1
0
Fork 0
mirror of git://git.code.sf.net/p/cdesktopenv/code synced 2025-02-15 04:32:24 +00:00
Commit graph

689 commits

Author SHA1 Message Date
Martijn Dekker
9ad9a1de44 github: Re-disable Mac CI runner (re: 5c389035)
The Mac runner is still broken: intermittent pipe- and
signal-related regressions that do not occur on any real Mac.
https://github.com/ksh93/ksh/runs/1892358749

.github/workflows/ci.yml:
- Remove the macOS runner.

src/cmd/ksh93/tests/pty.sh:
- Do not skip pty tests if there is no tty. (On FreeBSD with no
  tty, the tty builtin would need to be enabled in builtins.c.)

src/cmd/ksh93/tests/bracket.sh:
- Don't be noisy when skipping unavailable locales.
2021-02-13 06:58:30 +00:00
Martijn Dekker
5c389035d8 shtests: Stop requiring a tty
It is desirable to be able to run the tests on a system without
a functioning tty. Since this distribution comes with its own
pseudo-tty facility, pty, it should be possible to run the few
tests that require a tty on the pseudo-tty instead. I've verified
that they fail as expected on older ksh93.

Discussion: https://github.com/ksh93/ksh/pull/171

src/cmd/ksh93/tests/basic.sh,
src/cmd/ksh93/tests/bracket.sh:
- Remove tests that require a tty.

src/cmd/ksh93/tests/pty.sh:
- Put them here, adapted to work as interactive pty scripts.

src/cmd/ksh93/tests/shtests:
- No longer refuse to run if there is no functioning tty.

.github/workflows/ci.yml:
- Since the tests no longer require a tty, no longer use script(1)
  to get a pseudo-tty. Let's see if this works...
- Re-enable the Mac runner (re: 14632361). Maybe it has improved.
2021-02-13 05:55:27 +00:00
Lev Kujawski
a7121b6689
Implement leak detection on UnixWare (#172)
src/cmd/ksh93/tests/leaks.sh: Read vsz from UnixWare's ps

UnixWare's ps reports an accurate virtual size, so collecting that is
preferable to trying to parse the real resident size.
2021-02-13 00:52:54 +00:00
Martijn Dekker
2c04a88b37 shtests: actually test /dev/tty instead of checking for existence
The GitHub runners apparently provide a non-working /dev/tty. To
avoid failures and confusion, shtests shold refuse to run the tests
and tell people to use script(1) to simulate a tty. On Linux, it
goes like this:

	script -q -e -c 'bin/shtests --your-options-here'

On macOS and FreeBSD, the invocation is:

	script -q /dev/null bin/shtests --your-options-here

The NetBSD and OpenBSD variants of script(1) need different
invocations again. They also don't pass down the command's exit
status, so would need a workaround for that.

It would be nice if we could use pty for this as this comes with
the distribution, so would work the same on every OS, but it seems
to be broken for this use case.

src/cmd/ksh93/tests/shtest:
- Use 'test -t 1' with stdout (fd 1) redirected to /dev/tty to
  ensure the tty is actually on a terminal.

src/cmd/ksh93/tests/basic.sh:
- Remove superflous check for tty. All tests run through shtests.

Resolves: https://github.com/ksh93/ksh/pull/171
2021-02-13 00:50:46 +00:00
Martijn Dekker
6f6b22016a command -x: tweak args list size detection (re: 9ddb45b1)
src/cmd/ksh93/features/externs: ARG_EXTRA_BYTES detection:
- Improve detection of extra bytes per argument: on every loop
  iteration, recalculate the size of the environment while taking
  the amount extra bytes we're currently trying into account. Also
  count arguments (argv[]) as they are stored in the same buffer.
  On 64-bit Linux with glibc, this now detects 9 extra bytes per
  argument instead of 8. An odd number (literally and figuratively)
  but apparently it needs it; I do think my method is correct now.
  On 64-bit Solaris and macOS, this still detects 8 extra bytes.
  (On 64-bit Linux with musl C library, it detects 0 bytes. Nice.)

src/cmd/ksh93/sh/path.c: path_xargs():
- Remove the kludge subtracting twice the size of the environment.
  With the feature test fixed, this should no longer fail on Linux.
- Take into account the size of the final null element in the
  argument and environment lists.

src/cmd/ksh93/tests/path.sh:
- Do not use awk for the test due to breakage in the system awks
  on Solaris/Illumos (hangs) and AIX & UnixWare (drops arguments).
  Instead, use (wait for it...) ksh. It's a bit slower, but works.
2021-02-13 00:08:33 +00:00
Martijn Dekker
8c1e9971a7 tests/jobs.sh: suppress error msg on noncompliant 'ps' 2021-02-12 23:56:58 +00:00
Martijn Dekker
dec10fee6a package: compat: no $PWD on Bourne shell (re: 6cc2f6a0, f5eaf217) 2021-02-12 15:21:38 +00:00
Lev Kujawski
a9e7012dfd Fix a potential read of uninitialized memory through a pointer
src/lib/libast/misc/magic.c:
- Use strncpy instead of memcpy to avoid reading past the null
  terminator of the string pointed to by p.
2021-02-12 13:46:07 +00:00
Lev Kujawski
3224b79083 Forestall spurious test failures by skipping unavailable locales
src/cmd/ksh93/tests/bracket.sh:
- Read the list of installed locales to ensure the locale to be tested
  actually exists on the system under test.
- Produce a warning diagnostic for skipped locales.
- Additionally test the en_US.ISO8859-1 and en_US.UTF-8 locales.

Co-authored-by: Martijn Dekker <martijn@inlv.org>
2021-02-12 13:43:50 +00:00
Lev Kujawski
d5a94b3722 Produce IEEE compliant output from pow() despite platform deviations
src/cmd/ksh93/features/math.sh:
- Specify ast_float.h within iffehdrs instead of math.h, so that iffe
  will pick up on macro substitutions within libast. This should make
  any future efforts to remedy floating point behavior easier as well.
- Always include ast_float.h within the generated math header file,
  not just on IA64 platforms.

src/cmd/ksh93/tests/arith.sh:
- Test pow(1.0,-Inf) and pow(1.0,NaN) for IEEE compliance as well.
- Test the exponentiation operator (**) in addition, as streval.c,
  which processes the same, calls pow() separately.

src/lib/libast/features/float:
- Test the IEEE compliance of the underlying math library's pow()
  function and substitute macros producing compliant behavior if
  necessary.
2021-02-12 13:23:16 +00:00
Martijn Dekker
0f92d63823 tests/attributes.sh: fix spurious fail if any env var contains 'foo' 2021-02-12 12:45:47 +00:00
Martijn Dekker
41ebb55a3a Fix most of job control (-m/-o monitor) in scripts
If I haven't missed anything, this should make the non-interactive
aspects of job control in scripts work as expected, except for the
"<command unknown>" issue in the output of 'bg', 'fg' and 'jobs'
(which is not such a high priority as those commands are really
designed for interactive use).

Plus, I believe I now finally understand what these three are for:
* The job.jobcontrol variable is set to nonzero by job_init() in
  jobs.c if, and only if, the shell is interactive *and* managed to
  get control of the terminal. Therefore, any changing of terminal
  settings (tcsetpgrp(3), tty_set()) should only be done if
  job.jobcontrol is nonzero. This commit changes several checks for
  sh_isoption(SH_INTERACTIVE) to checks for job.jobcontrol for
  better consistency with this.
* The state flag, sh_isstate(SH_MONITOR), determines whether the
  bits of job control that are relevant for both scripts and
  interactive shells are active, which is mostly making sure that a
  background job gets its own process group (setpgid(3)).
* The shell option, sh_isoption(SH_MONITOR), is just that. When the
  user turns it on or off, the state flag is synched with it. It
  should usually not be directly checked for, as the state may be
  temporarily turned off without turning off the option.

Prior discussion:
https://www.mail-archive.com/austin-group-l@opengroup.org/msg06456.html

src/cmd/ksh93/bltins/typeset.c, src/cmd/ksh93/sh/args.c:
- Move synching the SH_MONITOR state flag with the SH_MONITOR
  shell option from b_set() (the 'set' builtin) to sh_applyopts()
  which is indirectly called from b_set() and is also used when
  parsing the shell invocation command line. This ensures -m is
  properly enabled in both scenarios.

src/cmd/ksh93/sh/jobs.c:
- job_init(): Do not refuse to initialise job control on
  non-interactive shells. Instead, skip everything that should only
  be done on interactive shells (i.e., everything to do with the
  terminal). This function is now even more of a mess than it was
  before, so refactoring may be desirabe at some point.
- job_close(), job_set(), job_reset(), job_wait(): Do not reset the
  terminal process group (tcsetpgrp()) if job.jobcontrol isn't on.

src/cmd/ksh93/sh/xec.c:
- sh_exec(): TFORK: For SIGINT handling, check the SH_MONITOR
  state flag, not the shell option.
- sh_exec(): TFORK: Do not turn off the SH_MONITOR state flag in
  forked children. The non-interactive part of job control should
  stay active. Instead, turn off the SH_INTERACTIVE state flag so
  we don't get interactive shell behaviour (i.e. job control noise
  on the terminal) in forked subshells.
- _sh_fork(), sh_ntfork(): Do not reset the terminal process group
  (tcsetpgrp()) if job.jobcontrol isn't on. Do not turn off the
  SH_MONITOR state flag in forked children.

src/cmd/ksh93/sh/subshell.c: sh_subfork():
- Do not turn off the monitor option and state in forked subshells.
  The non-interactive part of job control should stay active.

src/cmd/ksh93/bltins/misc.c: b_bg():
- Check isstate(SH_MONITOR) instead of sh_isoption(SH_MONITOR) &&
  job.jobcontrol before throwing a 'no job control' error.
  This fixes a minor bug: fg, bg and disown could quietly fail.

src/cmd/ksh93/tests/jobs.sh:
- Add tests for 'fg' with job control IDs (%%, %1) in scripts.
- Add test checking that a background job launched from a subsell
  with job control enabled correctly becomes the leader of its own
  process group.

Makes progress on: https://github.com/ksh93/ksh/issues/119
2021-02-12 06:51:27 +00:00
Martijn Dekker
37a18bab71 Fix ${ comsub; } killing job control
Another longstanding whopper of a bug in basic ksh93 functionality:
run a ${ shared-state; } command substitution twice and job control
promptly loses track of all your running jobs. New jobs are tracked
again until you run another two shared-state command substitutions.
This is in at least 93t+, 93u-, 93u+, 93v- and ksh2020.

$ sleep 300 &
[1]	56883
$ jobs						# OK
[1] +  Running                 sleep 300 &
$ v=${ echo hi1; }
$ jobs						# OK
[1] +  Running                 sleep 300 &
$ v=${ echo hi2; }
$ jobs						# Nothing!
$ fg
ksh: fg: no such job

src/cmd/ksh93/sh/subshell.c: sh_subshell():
- The current environment number shp->curenv (a.k.a. sh.curenv) was
  not being restored if the virtual subshell we're leaving is of
  the shared-state command substitution variety as it was wrongly
  considered to be part of the environment that didn't need
  restoring. This caused it to be out of sync with shp->jobenv
  (a.k.a. sh.jobenv) which did get restored from savedcurenv.
  Restore both from savedcurenv at the same time for any subshell.
  (How these numbers are used exactly remains to be discovered.)

src/cmd/ksh93/tests/jobs.sh:
- Added, with a test for this bug to start it off. There is no
  other test script where job control fits, and a lot more related
  fixes are anticipated: https://github.com/ksh93/ksh/issues/119
2021-02-11 13:41:40 +00:00
Martijn Dekker
2996d7ae7c Fix typos in <customtypecommand> --man self-documentation
src/cmd/ksh93/bltins/enum.c:
- enum_type[]: Fix typos; minor edit for style.
- enum_type[], enuminfo(): Make the list of supported values
  comma-separated, instead of using a comma at the start of each.

src/cmd/ksh93/sh/nvtype.c:
- sh_opttype[]: Fix typos.
2021-02-10 16:25:11 +00:00
Martijn Dekker
76ea18dcbd Fix disabling SHOPT_FIXEDARRAY (re: 2182ecfa)
It was easier than expected to fix this one. The many regression
test failures caused by disabling it were all due to one bug:
'typeset -p' output broke when building without this option.

src/cmd/ksh93/sh/nvtree.c: nv_attribute():
- In this function to print the attributes of a name-value pair,
  move four lines of code out of #if SHOPT_FIXEDARRAY...#endif that
  were inadvertently moved into the #if block in ksh93 2012-05-18.
  See the changes to nvtree.c in this multishell repo commit:
  https://github.com/multishell/ksh93/commit/aabab56a

src/cmd/ksh93/data/builtins.c:
- Update/rewrite 'typeset -a' documentation.
- Make it adapt to SHOPT_FIXEDARRAY.
- Fix a few typos.

src/cmd/ksh93/tests/arrays2.sh:
- Only one regression test needs a SHOPT_FIXEDARRAY check.

.github/workflows/ci.yml:
- Disable SHOPT_FIXEDARRAY when regression-testing without SHOPTs.
- Enable xtrace, add ':' commands for traced comments. This should
  make the CI runner output logs a little more readable.
2021-02-10 04:48:56 +00:00
Martijn Dekker
2182ecfa08 Fix compile/regress fails on compiling without SHOPT_* options
Many compile-time options were broken so that they could not be
turned off without causing compile errors and/or regression test
failures. This commit now allows the following to be disabled:

SHOPT_2DMATCH    # two dimensional ${.sh.match} for ${var//pat/str}
SHOPT_BGX        # one SIGCHLD trap per completed job
SHOPT_BRACEPAT   # C-shell {...,...} expansions (, required)
SHOPT_ESH        # emacs/gmacs edit mode
SHOPT_HISTEXPAND # csh-style history file expansions
SHOPT_MULTIBYTE  # multibyte character handling
SHOPT_NAMESPACE  # allow namespaces
SHOPT_STATS      # add .sh.stats variable
SHOPT_VSH        # vi edit mode

The following still break ksh when disabled:

SHOPT_FIXEDARRAY # fixed dimension indexed array
SHOPT_RAWONLY    # make viraw the only vi mode
SHOPT_TYPEDEF    # enable typeset type definitions

Compiling without SHOPT_RAWONLY just gives four regression test
failures in pty.sh, but turning off SHOPT_FIXEDARRAY and
SHOPT_TYPEDEF causes compilation to fail. I've managed to tweak the
code to make it compile without those two options, but then dozens
of regression test failures occur, often in things nothing directly
to do with those options. It looks like the separation between the
code for these options and the rest was never properly maintained.
Making it possible to disable SHOPT_FIXEDARRAY and SHOPT_TYPEDEF
may involve major refactoring and testing and may not be worth it.

This commit has far too many tweaks to list. Notables fixes are:

src/cmd/ksh93/data/builtins.c,
src/cmd/ksh93/data/options.c:
- Do not compile in the shell options and documentation for
  disabled features (braceexpand, emacs/gmacs, vi/viraw), so the
  shell is not left with no-op options and inaccurate self-doc.

src/cmd/ksh93/data/lexstates.c:
- Comment the state tables to associte them with their IDs.
- In the ST_MACRO table (sh_lexstate9[]), do not make the S_BRACE
  state for position 123 (ASCII for '{') conditional upon
  SHOPT_BRACEPAT (brace expansion), otherwise disabling this causes
  glob patterns of the form {3}(x) (matching 3 x'es) to stop
  working as well -- and that is ksh globbing, not brace expansion.

src/cmd/ksh93/edit/edit.c: ed_read():
- Fixed a bug: SIGWINCH was not handled by the gmacs edit mode.

src/cmd/ksh93/sh/name.c: nv_putval():
- The -L/-R left/right adjustment options to typeset do not count
  zero-width characters. This is the behaviour with SHOPT_MULTIBYTE
  enabled, regardless of locale. Of course, what a zero-width
  character is depends on the locale, but control characters are
  always considered zero-width. So, to avoid a regression, add some
  fallback code for non-SHOPT_MULTIBYTE builds that skips ASCII
  control characters (as per iscntrl(3)) so they are still
  considered to have zero width.

src/cmd/ksh93/tests/shtests:
- Export the SHOPT_* macros from SHOPT.sh to the tests as
  environment variables, so the tests can check for them and decide
  whether or how to run tests based on the compile-time options
  that the tested binary was presumably compiled with.
- Do not run the C.UTF-8 tests if SHOPT_MULTIBYTE is not enabled.

src/cmd/ksh93/tests/*.sh:
- Add a bunch of checks for SHOPT_* env vars. Since most should
  have a value 0 (off) or 1 (on), the form ((SHOPT_FOO)) is a
  convenient way to use them as arithmetic booleans.

.github/workflows/ci.yml:
- Make GitHub do more testing: run two locale tests (Dutch and
  Japanese UTF-8 locales), then disable all the SHOPTs that we can
  currently disable, recompile ksh, and run the tests again.
2021-02-08 22:02:45 +00:00
Martijn Dekker
a9d77bba40 libast: optget(): emphasis: add screen/tmux, dtterm (re: ec79563b)
src/lib/libast/misc/optget.c:
- Add screen* (which includes tmux) and dtterm* (CDE terminal) to
  the glob pattern deciding whether to use ANSI boldface sequences.
- Don't bother parsing the env var if stderr is not on a terminal.

src/cmd/ksh93/sh.1:
- Extend self-documentation documentation; document how optget(3)
  uses the ERROR_OPTIONS env var to control boldface output.
- Tweaks and minor edits.
2021-02-07 20:42:52 +00:00
Martijn Dekker
ec79563b8f libast: optget(): fix emphasis state initialisation
This fixes a bug in libast optget()'s use of emphasis in the
display of --man(uals) via standard error on a terminal.

Symptom:

$ printf --man 2>&1 | more
(ok; emphasis disabled, no escape codes shown)
$ printf --man
(ok; emphasis correctly displayed)
$ printf --man 2>&1 | more
(whoops; emphasis not disabled; escape codes garble 'more' output)

The problem was that the state.emphasis variable was not
initialised and, when set to one, was never reset again
(except through the use of the --api, --html or --nroff option).

The source code also reveals an undocumented feature: if the
environment variable $ERROR_OPTIONS contains 'noemphasi', emphasis
is forced off, else if it contains 'emphasi', it's forced on.
Other characters (such as the final 's' of emphasis) are ignored.
This was also broken (forcing off didn't work) and is now fixed.

src/lib/libast/misc/optget.c:
- Do not assume that enabling emphasis is forever; re-initialise
  the state on every relevant getopts invocation.
- Increase the number of terminals on which emphasis is displayed
  using ANSI escape codes. (This is a hack and we should ask the OS
  for the correct codes, but never mind -- ANSI is now universal.)
2021-02-07 05:53:48 +00:00
Martijn Dekker
403e864ac8 Disallow >;word and <>;word for 'redirect' (re: 7b59fb80, 7b82c338)
The >;word and <>;word redirection operators cannot be used with
the 'exec' builtin, but the 'redirect' builtin (which used to be
an alias of 'command exec') permitted them. However, they do not
have the documented effect of the added ';'. So this commit blocks
those operators for 'redirect' as they are blocked for 'exec'.

It also tweaks redirect's error message if a non-redirection
argument is encountered.

src/cmd/ksh93/sh/parse.c: simple():
- Set the lexp->inexec flag for SYSREDIR (redirect) as well as
  SYSEXEC (exec). This flag is checked for in sh_lex() (lex.c) to
  throw a syntax error if one of these two operators is used.

src/cmd/ksh93/sh.1, src/cmd/ksh93/data/builtins.c:
- Documentation tweaks.

src/cmd/ksh93/sh/xec.c, src/cmd/ksh93/bltins/misc.c:
- When 'redirect' gives an 'incorrect syntax' (e_badsyntax) error
  message, include the first word that was found not to be a valid
  redirection. This is simply the first argument, as redirections
  are removed from the arguments list.

src/cmd/ksh93/tests/io.sh:
- Update test to reflect new error message format.
2021-02-07 03:23:56 +00:00
Martijn Dekker
43dfe3c8fa build system: rm unused variable declarations from Mamfiles
Now that the Make Abstract Machine files are maintained manually
and not generated automatically, unused variables are an annoying
distraction -- and there are many.

But the language/format is very simple and very parseable using
shell, awk, etc. -- so this was easy to automate. All variables are
declared with 'setv' and they are used if an expansion of the form
${varname} exists (the braces are mandatory in Mamfiles).

bin/Mamfile_rm_unused_vars:
- Added for reference and future use.

src/*/*/Mamfile:
- Remove all unused 'setv' variable declarations.
2021-02-05 15:39:31 +00:00
Martijn Dekker
7b59fb805c Fix 'redirect {var}>file' in subshell (re: 7b82c338)
Permanent redirections of that form broke in subshells when used
with the 'redirect' command, because I had overlooked one instance
where the new 'redirect' builtin needs to match the behaviour of
the 'exec' builtin.

src/cmd/ksh93/tests/io.sh: sh_exec():
- Do not restore file descriptors in (virtual) subshells for
  'redirect' just as this isn't done for 'exec'.

src/cmd/ksh93/tests/io.sh:
- Add regression test for this bug.
- Complete the test for f9427909 which I committed prematurely.

Fixes: https://github.com/ksh93/ksh/issues/167
2021-02-05 05:38:38 +00:00
Martijn Dekker
f9427909dc Make redirections like {varname}>file work with brace expansion off
This is some nonsense: redirections that store a file descriptor
greater than 9 in a variable, like {var}<&2 and the like, stopped
working if brace expansion was turned off. '{var}' is not a brace
expansion as it doesn't contain ',' or '..'; something like 'echo
{var}' is always output unexpanded. And redirections and brace
expansion are two completely unrelated things. It wasn't documented
that these redirections require the -B/braceexpand option, either.

src/cmd/ksh93/sh/lex.c: sh_lex():
- Remove incorrect check for braceexpand option before processing
  redirections of this form.

src/cmd/ksh93/COMPATIBILITY:
- Insert a brief item mentioning this.

src/cmd/ksh93/sh.1:
- Correction: these redirections do not yield a file descriptor >
  10, but > 9, a.k.a. >= 10.
- Add a brief example showing how these redirections can be used.

src/cmd/ksh93/tests/io.sh:
- Add a quick regression test.
2021-02-05 05:08:39 +00:00
Martijn Dekker
c709868572 process substitution: improve fifo error handling (re: ab5dedde)
src/cmd/ksh93/sh/args.c: sh_argprocsub():
- Fix compiler warnings with SHOPT_DEVFD on by including "io.h".
- Without SHOPT_DEVFD, the FIFO code didn't consider that libast's
  pathtemp(3) may also fail and return null. Add a check for this.
2021-02-04 20:47:45 +00:00
Martijn Dekker
cea04c4a6f Add missing NEWS entries (re: a410bc48, 6f3b23e6); update README.md 2021-02-04 17:31:22 +00:00
Martijn Dekker
a410bc480f autoload: Add loop detection
It was trivial to crash ksh by making an autoloaded function
definition file autoload itself, causing a stack overflow due to
infinite recursion. This commit adds loop detection that stops a
function that is being autoloaded from autoloading itself either
directly or indirectly, without removing the ability of autoloaded
function definition files to autoload other functions.

src/cmd/ksh93/sh/path.c: funload():
- Detect loops by checking if the path of a function to be
  autoloaded was already added to a new internal static tree,
  and if not, adding it while the function is being loaded.

src/cmd/ksh93/tests/path.sh:
- Add regression test.
- Tweak a couple of others to be freeze- and crash-proof.

NEWS:
- Add this fix + a forgotten entry for the previous fix (6f3b23e6).

Fixes: https://github.com/ksh93/ksh/issues/136
2021-02-04 16:28:19 +00:00
Martijn Dekker
6f3b23e6f4 Fix crash on trying a very long nonexistent command
Reproducer from @Saikiran-m:
| ~# sh -c `perl -e 'print "a"x100000'`
|  genunix: NOTICE: core_log: sh[1221] core dumped: /var/cores/core.sh.0.1602153496
| Memory fault(coredump)

The crash was in trying to decide whether the name was suitable for
autoloading as a function on $FPATH. This calls strmatch() to check
the name against a regex for valid function name. But the libast
regex code is not designed optimally and uses too much recursion,
limiting the length of the strings it's able to cope with.

src/cmd/ksh93/sh/path.c: path_search():
- Before calling strmatch(), check that the name is shorter than
  256 bytes. The maximum length of file names on Linux and macOS is
  255 bytes, so an autoload function can't have a name longer than
  that anyway.

src/cmd/ksh93/tests/path.sh:
- Add test for this bug.
- Tweak 'command -x' test to not leave a hanging process on Ctrl+C.

Fixes: https://github.com/ksh93/ksh/issues/144
2021-02-04 05:03:40 +00:00
Martijn Dekker
32cff97b24 tests/*.sh: fix indentation of warnings 2021-02-04 02:22:46 +00:00
Martijn Dekker
e220445265 Re-allow disabling vmalloc for release builds (re: 399886da)
Well, that commit was based on a silly oversight: of course it's
necessary to pass ${KSH_RELFLAGS} to the feature tests too as they
use this flag to determine whether to enable or disable vmalloc.

On further analysis I think the annoying warnings can be solved in
a different way. Quotes (single or double) in 'exec -' commands
don't seem to be special to mamake at all; it looks like they are
passed on to the shell as is. So Mamfile variables are expanded and
the expansions backslash-escaped the same way regardless of quotes.
Which means we can make the shell remove the unwanted level of
backslashes by using double instead of single quotes.

src/*/*/Mamfile:
- On iffe commands, restore ${KSH_RELFLAGS}, using double quotes to
  group the compiler command as one argument to iffe.
2021-02-04 01:40:53 +00:00
Martijn Dekker
824a85e38e ksh93/README: Void Linux (musl) successfully tested 2021-02-03 23:08:34 +00:00
Martijn Dekker
7dbcbce407 Revert 7a6980a3, restoring build on Alpine Linux
This reverts an OpenSUSE patch ("libast/comp/conf.sh: apply limits
detection fixes for Linux"). It broke the build on Alpine Linux
with the musl C library (see also e245856f).
2021-02-03 21:44:55 +00:00
Martijn Dekker
9ddb45b12d command -x: fix 'args list too long' on Linux, again (re: 8f5235a5)
This time it was failing on a 64-bit Debian Linux system with very
few and short environment variables. Sigh.

src/cmd/ksh93/sh/path.c:
- Combine the strategy from 63979488 with that of 8f5235a5.
2021-02-03 20:07:47 +00:00
Martijn Dekker
8f5235a53f fix 'args list too long' on Linux, again (re: 63979488)
That fix turned out to be insufficient as NixOS has huge
environment variable lists because (due to each software package
being installed in its own directory tree) it has to keep dozens
of directories in variables like XDG_CONFIG_DIRS and others.
The 'command -x' regression test was failing on NixOS.

src/cmd/ksh93/sh/path.c:
- Different strategy. Leave twice the size of the existing
  environment free.
2021-02-03 19:22:35 +00:00
Martijn Dekker
7ff6b73bdb emacs.c: fix 2 causes of crash
Hopefully this will deal with ksh crashing in macOS Terminal.app
once and for all. Trigger: press Command-F to open the find bar,
then press Esc to close it, then press Esc again. Result: crash
somewhere random in the job control code.

Turns out macOS Terminal.app apparently (and wrongly) sends <Esc>
followed by <Ctrl+L> to the terminal, which ksh takes as a sequence
for clearing the screen. The related crash ultimately traced back
to the code for that in emacs.c. The other crash was in the code
for double-ESC file name completion.

This commit also fixes a non-robust invocation of the 'tput'
command by using the direct path found in $(getconf PATH).

src/cmd/ksh93/features/cmds:
- Remove unused tests for the presence of commands
  (newgrp,test,id,wc,cut,logname,pfexec).
- Replace 'cmd tput' test by 'pth tput' which will find its path
  in $(getconf PATH) and store that path as the macro value.
- Add two tests to determine if 'tput' supports terminfo and/or
  termcap codes. (FreeBSD still requires old termcap codes.)

src/cmd/ksh93/edit/emacs.c: escape():
- Fix a crash in the code for double-ESC completion. Check if the
  cursor is on a non-zero position; this caused a bus error
  (invalid address access) in the subsequent ed_expand call.
- For <Esc><Ctrl+L> (clear screen), fix the strange crash in macOS
  Terminal by not using sh_trap() to invoke "tput clear", which
  causes ksh itself to invoke that command. ksh apparently doesn't
  cope with doing this while SIGWINCH (window size change signal)
  is sent by Terminal. The fix is to just use the C standard
  system(3) function to invoke tput. This invokes tput via /bin/sh,
  but what the hey. (Note that ksh also ran any function or alias
  called 'tput' instead of the real command, and that is now also
  fixed.)
- Use the new _pth_tput test result to invoke tput with the
  hardcoded default system path, increasing robustness.

src/cmd/ksh93/edit/edit.c: ed_setup():
- Use the new _pth_tput test result to invoke tput with the
  hardcoded default system path, increasing robustness.
- When getting the escape code for "cursor up", use the new
  _tput_terminfo and _tput_termcap test results to determine which
  kind of command code to send. This fixes it on FreeBSD.
2021-02-03 17:55:03 +00:00
Martijn Dekker
f5eaf217ed build system: fix detection of default system directories
src/cmd/INIT/iffe.sh:
- Fix "standard system directories" for the cmd test, which were
  hardcoded as bin, /etc, /usr/bin, /usr/etc, /usr/ucb. That's both
  unportable and antiquated. Replace this with the path output by
  'getconf PATH'.
- Add fixes from modernish for 'getconf PATH' output to compensate
  for bugs/shortcomigns in NixOS and AIX. Source:
  https://github.com/modernish/modernish/blob/9e4bf5eb/lib/modernish/aux/defpath.sh
  Ref.: https://github.com/NixOS/nixpkgs/issues/65512

src/lib/libast/comp/conf.tab: PATH:
- Add the NixOS and AIX default path fixes here too; this fixes
  'command -p' and the builtin 'getconf PATH' on these systems.

bin/package, src/cmd/INIT/package.sh:
- Re-support being launched with just the command name 'package' in
  the command line (if the 'package' command is in $PATH). At least
  one other script in the build system does this. (re: 6cc2f6a0)
- Go back three levels (../../..) if we were invoked from
  arch/*/bin/package, otherwise we won't find src/cmd/ksh93/SHOPT.sh.
2021-02-03 17:49:00 +00:00
Martijn Dekker
be33942415 Some more build fixes from OpenSUSE
These update some outdated library path searches as well as
a couple of gcc-specific improvements.

Original patch:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-compat.dif
2021-02-02 21:03:01 +00:00
Martijn Dekker
52067c3d37 Backport atomic job locking from ksh 93v- beta
Something similar was previously done in 07cc71b8 from a Debian
patch, and eventually reverted; it redefined the ast atomic
functions asoincint() and asodecint() to be gcc-specific. This
imports the upstream version from the ksh 93v- beta instead.

This commit is based on an OpenSUSE patch:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-joblock.dif

src/cmd/ksh93/include/jobs.h:
- Replace job locking mechanism with the 93v- version which uses
  the atomic libast functions asoincint(), asogetint() and
  asodecint(). See: src/lib/libast/man/aso.3

src/cmd/ksh93/sh/jobs.c: job_subsave():
- Revert gcc optimiser bug workaround from c258a04f.
  It should now be unnecessary.
2021-02-02 17:38:19 +00:00
Martijn Dekker
1bd0620708 libast: sfio(3) fixes from ksh 93v- beta
These fixes were backported by OpenSUSE. Original patch:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-sfio.dif
2021-02-02 16:20:59 +00:00
Martijn Dekker
63979488e6 command -x: fix 'arg list too long' on Linux (re: 66e1d446)
I got one intermittent regression test failure due to 'argument
list too long' on a Debian x86_64 system.

src/cmd/ksh93/sh/path.c: path_xargs():
- Leave extra argument space for systems that need extra bytes:
  1KiB per extra byte, with a minimum of 2KiB (the old value).
2021-02-02 15:23:21 +00:00
Martijn Dekker
db71b3ad43 libast: robustness fixes for temporary files and streams
From an OpenSUSE patch:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-pathtemp.dif

See src/lib/libast/man/path.3 for pathtemp()
and src/lib/libast/man/sfio.3 for sftmp()

src/lib/libast/path/pathtemp.c:
- Error check fix: add an access check wrapper function that checks
  if a path was given and if there is enough free space on the
  device, setting errno appropriately in case of trouble.

src/lib/libast/sfio/sftmp.c:
- On Linux, use the /dev/shm shared memory objects for the new
  temporary file descriptor -- that is, do not access HD or SSD but
  only the memory based tmpfs of the POSIX SHM.
2021-02-02 14:44:34 +00:00
Martijn Dekker
b12be093d7 typeset: print_value(): save/restore last_table
This fix comes via an OpenSUSE patch but also exists in 93v- beta.
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-typedef.dif
(only the printvalue() diff was still applicable to 93u+m;
the setall() fix was done differently and better in a2f13c19)
2021-02-02 14:31:35 +00:00
Martijn Dekker
4645e6ad33 job_reset(): fix for resetting foreground process group
Patch from OpenSUSE:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-foreground-prgrp.dif

src/cmd/ksh93/sh/jobs.c: job_reset():
- Only reset the foreground process group associated with the
  current job if the current job's process ID is different from the
  terminal's foreground process group ID.
2021-02-02 12:49:00 +00:00
Martijn Dekker
9f980ba65a sh_setmatch(): fix node size calculation
This fixes the function that sets ${.sh.match}. Patch from OpenSUSE:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-limit-name-len.dif

src/cmd/ksh93/sh/init.c: sh_setmatch():
- Fix node size calculation, possibly preventing data corruption.

src/cmd/ksh93/include/ulimit.h: Limit_t:
- Defining the 'name' struct member as 'char name[16]' makes
  no sense as the name is being initialised statically in
  data/limits.c; just make it a 'char *name' pointer.
2021-02-02 11:52:54 +00:00
Martijn Dekker
3002c4113e vmalloc: better detect default region size on Linux
This is a Linux-specific fix for vmalloc from OpenSUSE, for what
that's still worth; we're not going to keep using vmalloc long term.
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-vm.dif
2021-02-02 11:32:37 +00:00
Martijn Dekker
e2c2753ee8 libast: Fix detection of GCC 4.1+ 64/32-bit atomic operations model
This fix to the atomic scalar operations feature tests is from OpenSUSE:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-aso.dif
2021-02-02 05:27:08 +00:00
Martijn Dekker
69e18de58f edit.c: Fix history generation if there are zero arguments
This applies a fix from OpenSUSE:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-reg.dif
2021-02-02 05:24:11 +00:00
Martijn Dekker
627df2b19a libast: optget(3): fix some uninitialised variables
This is a part of this OpenSUSE patch:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-gcc.dif
2021-02-02 05:17:52 +00:00
Martijn Dekker
0684806d47 feature tests: signbit detection fix for ia64
An Intel Itanium fix from OpenSUSE:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-ia64.dif
2021-02-02 04:40:09 +00:00
Martijn Dekker
7a6980a380 libast/comp/conf.sh: apply limits detection fixes for Linux
This is another patch from OpenSUSE:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-limits.dif
2021-02-02 04:35:54 +00:00
Martijn Dekker
fa3a3d7955 sh_ntfork(): handle SIGTSTP along with SIGTTIN and SIGTTOU
This applies a patch from OpenSUSE that makes SIGTSTP handling
consistent with that of SIGTTIN and SIGTTOU.
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-signals.dif
2021-02-02 04:25:46 +00:00
Martijn Dekker
8a58166bc4 Add OpenSUSE fixes for the uname builtin on Linux
Original patches:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-uname.dif
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-no-sysctl.dif
2021-02-02 03:31:21 +00:00
Martijn Dekker
0e4c4d619d Fix minor typeset attribute regressions (re: 95fe07d8, fdb9781e)
This fixes the following regressions marked TODO in attributes.sh:

$ typeset -L 13 bar; readonly bar; typeset -p bar
typeset -r -L 0 foo		# exp.: typeset -r -L 13 foo
$ typeset -R 13 bar; readonly bar; typeset -p bar
typeset -r -R 0 bar		# exp.: typeset -r -R 13 bar
$ typeset -Z 13 baz; readonly baz; typeset -p baz
typeset -r -Z 0 -R 0 baz	# exp.: typeset -r Z 13 -R 13 baz

I've discovered that these were briefly fixed between fdb9781e (Red
Hat patch for typeset -xu/-xl) and 95fe07d8 (reversal of patch,
different -xu/-xl fix, but reintroduced these regressions).

src/cmd/ksh93/sh/name.c: nv_newattr():
- Replace check from 95fe07d8 with a new one that combines its
  approach with that of fdb9781e: do not change size (and hence
  return early) if NV_RDONLY and/or NV_EXPORT are the only
  attributes that are changing.

src/cmd/ksh93/tests/attributes.sh:
- Enable the TODO regression tests.
2021-02-02 02:20:37 +00:00
hyenias
fe05350f2d
typeset: fix short integer restriction (#166)
This commit corrects how shortint was being applied to various
possible typeset variables in error. The short integer option
modifier 'typeset -s' should only be able to be applied if the
the variable is also an integer. Several issues were resolved
with this fix:
- 'typeset -s': created a short integer having an invalid base
  of zero. 'typeset -s foo' created 'typeset -s -i 0 foo=0' and
  now will result in an empty string.
- 'typeset -sL': previously resulted in a segmentation fault.

The following are the various incorrect 'typeset' instances
that have been fixed:

$ 'export foo; typeset -s foo; readonly foo; typeset -p foo'
(before) typeset -x -r -s -i 0 foo=0
( after) typeset -x -r foo

$ 'typeset -sL foo=1*2; typeset -p foo'
(before) Segmentation fault (core dumped)
( after) typeset -L 3 foo='1*2'

$ 'typeset -sR foo=1*2; typeset -p foo'
(before) typeset -s -i foo=2
( after) typeset -R 3 foo='1*2'

$ 'typeset -sZ foo=1*2; typeset -p foo'
(before) typeset -F 0 foo=2
( after) typeset -Z 3 -R 3 foo='1*2'

src/cmd/ksh93/bltins/typeset.c: b_typeset():
- Add conditional check within the 's' option to only
  apply NV_SHORT as well as remove any NV_LONG flag
  if NV_INTEGER flag was set.
- Relocate shortint conditional logic to the 'i' option.

src/cmd/ksh93/tests/attributes.sh:
- Adjust regression tests for '-s' and add '-si' check.
2021-02-01 23:35:18 +00:00
Martijn Dekker
5491fe9724 Correctly block invalid values for arrays of an enum type
This fixes part of https://github.com/ksh93/ksh/issues/87:

Scalar arrays (-a) and associative arrays (-A) of a type created by
'enum' did not consistently block values not specified by the enum
type, yielding corrupted results.

An expansion of type "${array[@]}" yielded random numbers instead
of values for associative arrays of a type created by 'enum'.

This does not yet fix another problem: ${array[@]} does not yield
all values for associative enum arrays.

src/cmd/ksh93/bltins/enum.c: put_enum():
- Always throw an error if the value is not in the list of possible
  values for an enum type. Remove incorrect check for the NV_NOFREE
  flag. Whatever that was meant to accomplish, I've no idea.

src/cmd/ksh93/sh/array.c: nv_arraysettype():
- Instead of sh_eval()ing a shell assignment, use nv_putval()
  directly. Also use the stack (see src/lib/libast/man/stk.3)
  instead of malloc to save the value; it's faster and will be
  auto-freed at some point. This shortens the function and makes it
  faster by not entering into a whole new shell context -- which
  also fixes another problem: the error message from put_enum()
  didn't cause the shell to exit for indexed enum arrays.

src/cmd/ksh93/sh/name.c: nv_setlist():
- Apply a patch from David Korn that correctly sets the data type
  for associative arrays, fixing the ${array[@]} expansion yielding
  random numbers. Thanks to @JohnoKing for the pointer.
  https://github.com/ksh93/ksh/issues/87#issuecomment-662613887
  https://www.mail-archive.com/ast-developers@lists.research.att.com/msg00697.html

src/cmd/ksh93/tests/enum.sh:
- Add tests checking that invalid values are correctly blocked for
  indexed and associative arrays of an enum type.

Makes progress on: https://github.com/ksh93/ksh/issues/87
2021-02-01 16:57:43 +00:00
Martijn Dekker
6a0e9a1a75 Tweak and regress-test 'command -x' (re: 66e1d446)
Turns out the assumption I was operating on, that Linux and macOS
align arguments on 32 or 64 bit boundaries, is incorrect -- they
just need some extra bytes per argument. So we can use a bit more
of the arguments buffer on these systems than I thought.

src/cmd/ksh93/features/externs:
- Change the feature test to simply detect the # of extra bytes per
  argument needed. On *BSD and commercial Unices, ARG_EXTRA_BYTES
  shows as zero; on Linux and macOS (64-bit), this yields 8. On
  Linux (32-bit), this yields 4.

src/cmd/ksh93/sh/path.c: path_xargs():
- Do not try to calculate alignment, just add ARG_EXTRA_BYTES to
  each argument.
- Also add this when substracting the length of environment
  variables and leading and trailing static command arguments.

src/cmd/ksh93/tests/path.sh:
- Test command -v/-V with -x.
- Add a robust regression test for command -x.

src/cmd/ksh93/data/builtins.c, src/cmd/ksh93/sh.1:
- Tweak docs. Glob patterns also expand to multiple words.
2021-02-01 02:19:02 +00:00
Martijn Dekker
f37098f177 Build fix for Linux i386
iffe feature test that add a -D_LARGEFILE64_SOURCE compiler flag to
detect the presence of 64-bit types like off64_t are very
incorrect; they always find the type even if the rest of the source
is not compiled with that flag, causing an inconsistent compilation
environment. This was the cause of mysterious failures to compile
some feature tests on Linux i386 -- it tried to use an off64_t type
that was wrongly detected.

A flag like -D_LARGEFILE64_SOURCE needs to be added to the compiler
flags consistently so it is used for compiling all files and tests.

src/lib/libast/features/dirent,
src/lib/libast/features/fs,
src/lib/libast/features/lib,
src/lib/libast/features/mmap,
src/cmd/ksh93/features/rlimits:
- Remove the -D_LARGEFILE64_SOURCE flag from all the tests that
  used it.
- Fix some preprocessor directives for compiling without
  _LARGEFILE64_SOURCE. We cannot rely on the result of the _lib_*64
  tests because those functions are still found in glibc even if
  _LARGEFILE64_SOURCE is not defined; we have to check for the
  existence of the type definitions before using them.

src/cmd/INIT/cc.linux.i386,
src/cmd/INIT/cc.linux.i386-icc:
- Add/update compiler wrappers to hardcode -D_LARGEFILE64_SOURCE
  in the flags for the default compiler. If it is overriden with
  $CC, then it needs to be added manually if desired.
2021-01-31 23:47:43 +00:00
Martijn Dekker
a1f727749a tests/locale.sh: disable en_US.UTF-8 spaces test
This test depends on the correctness of the locale data provided
by the OS, and some installations are broken. Failures of this test
most likely do not represent a bug in ksh or libast.
2021-01-31 20:50:03 +00:00
Martijn Dekker
ede479967f resolve/remove USAGE_LICENSE macros; remove repetitive (c) strings
This takes another small step towards disentangling the build
system from the old AT&T environment. The USAGE_LICENSE macros with
author and copyright information, which was formerly generated
dynamically for each file from a database, are eliminated and the
copyright/author information is instead inserted into the AST
getopt usage strings directly.

Repetitive license/copyright information is also removed from the
getopt strings in the builtin commands (src/lib/libcmd/*.c and
src/cmd/ksh93/data/builtins.c). There's no need to include 55
identical license/copyright strings in the ksh binary; one (in the
main ksh getopt string, shown by ksh --man) ought to be enough!
This makes the ksh binary about 10k smaller.

It does mean that something like 'enum --author', 'typeset
--license' or 'shift --copyright' will now not show those notices
for those builtins, but I doubt anyone will care.
2021-01-31 11:00:49 +00:00
Martijn Dekker
66e1d44642 command -x: fix efficiency; always run external cmd (re: acf84e96)
This commit fixes 'command -x' to adapt to OS limitations with
regards to data alignment in the arguments list. A feature test is
added that detects if the OS aligns the argument on 32-bit or
64-bit boundaries or not at all, allowing 'command -x' to avoid
E2BIG errors while maximising efficiency.

Also, as of now, 'command -x' is a way to bypass built-ins and
run/query an external command. Built-ins do not limit the length of
their argument list, so '-x' never made sense to use for them. And
because '-x' hangs on Linux and macOS on every ksh93 release
version to date (see acf84e96), few use it, so there is little
reason not to make this change.

Finally, this fixes a longstanding bug that caused the minimum exit
status of 'command -x' to be 1 if a command with many arguments was
divided into several command invocations. This is done by replacing
broken flaggery with a new SH_XARG state flag bit.

src/cmd/ksh93/features/externs:
- Add new C feature test detecting byte alignment in args list.
  The test writes a #define ARG_ALIGN_BYTES with the amount of
  bytes the OS aligns arguments to, or zero for no alignment.

src/cmd/ksh93/include/defs.h:
- Add new SH_XARG state bit indicating 'command -x' is active.

src/cmd/ksh93/sh/path.c: path_xargs():
- Leave extra 2k in the args buffer instead of 1k, just to be sure;
  some commands add large environment variables these days.
- Fix a bug in subtracting the length of existing arguments and
  environment variables. 'size -= strlen(cp)-1;' subtracts one less
  than the size of cp, which makes no sense; what is necessary is
  to substract the length plus one to account for the terminating
  zero byte, i.e.: 'size -= strlen(cp)+1'.
- Use the ARG_ALIGN_BYTES feature test result to match the OS's
  data alignment requirements.
- path_spawn(): E2BIG: Change to checking SH_XARG state bit.

src/cmd/ksh93/bltins/whence.c: b_command():
- Allow combining -x with -p, -v and -V with the expected results
  by setting P_FLAG to act like 'whence -p'. E.g., as of now,
	command -xv printf
  is equivalent to
	whence -p printf
  but note that 'whence' has no equivalent of 'command -pvx printf'
  which searches $(getconf PATH) for a command.
- When -x will run a command, now set the new SH_XARG state flag.

src/cmd/ksh93/sh/xec.c: sh_exec():
- Change to using the new SH_XARG state bit.
- Skip the check for built-ins if SH_XARG is active, so that
  'command -x' now always runs an external command.

src/lib/libcmd/date.c, src/lib/libcmd/uname.c:
- These path-bound builtins sometimes need to run the external
  system command by the same name, but they did that by hardcoding
  an unportable direct path. Now that 'command -x' runs an external
  command, change this to using 'command -px' to guarantee using
  the known-good external system utility in the default PATH.
- In date.c, fix the format string passed to 'command -px date'
  when setting the date; it was only compatible with BSD systems.
  Use the POSIX variant on non-BSD systems.
2021-01-30 06:53:19 +00:00
Martijn Dekker
005d38f410 tests/leaks.sh: add procfs method for Linux
This allows faster testing for memory leaks on Linux if
ksh is compiled without vmalloc.
2021-01-28 21:59:27 +00:00
Martijn Dekker
ab6b483b17 features/pty: restore build on AIX by reordering #includes 2021-01-28 07:19:07 +00:00
Martijn Dekker
674a0c3559 Another lexical fix for here-documents (re: 6e515f1d)
OpenSUSE patch from:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-heredoc.dif

src/cmd/ksh93/sh/lex.c: here_copy():
- Do not potentially seek back a zero or negative length.
2021-01-28 06:32:42 +00:00
Martijn Dekker
4604df9ada Stack robustness fixes from OpenSUSE
Three OpenSUSE patches from:
https://build.opensuse.org/package/show/shells/ksh

As usual, the relevant bug is not currently public:
https://bugzilla.opensuse.org/show_bug.cgi?id=844071

src/cmd/ksh93/sh/xec.c: sh_debug()/sh_exec():
- Fix stk restoration. [bnc#844071]

src/lib/libast/misc/stk.c:
- Fix stk aliasing code. [bnc#844071]
  (ksh93-stkalias.dif)
- Make a unknown location fatal in stkset() so that we get a core
  dump right away instead of later in an unrelated part of code.
  (ksh93-stkset-abort.dif)

src/lib/libast/man/stk.3,
src/lib/libast/man/stak.3:
- Update manual with new stkset() behaviour. (93u+m addition)
  (Note that stak is implemented as macros that translate to stk)
2021-01-28 06:18:44 +00:00
Martijn Dekker
c5bd6874ef test -p: fix bug due to wrong parentheses
Patch from OpenSUSE:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-test.dif

src/cmd/ksh93/bltins/test.c:
- Fix parentheses in the isapipe() macro.
- test_binop(): Initialise variables.
2021-01-28 05:16:49 +00:00
Martijn Dekker
288b6c6517 Fix various possible uses of uninitialised variables
Patch from OpenSUSE, slightly adapted for 93u+m. Source:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-uninitialized.dif
2021-01-28 04:54:41 +00:00
Martijn Dekker
c52cb93999 sh_funscope(): Fix possible dereference of null pointer
Patch from OpenSUSE:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-unset-f.dif
2021-01-28 04:38:48 +00:00
Martijn Dekker
129614b99f edit/vi.c: sanity checks from OpenSUSE
Source: https://build.opensuse.org/package/view_file/shells/ksh/ksh93-vi.dif
Patch from 2007, apparently never upstreamed.
2021-01-28 04:35:46 +00:00
Martijn Dekker
3ad4307054 name.c: fix possible crash in attstore()
From OpenSUSE:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-env.dif
(the init.c fix there is already done differently in 3654ee73)

src/cmd/ksh93/sh/name.c: attstore():
- Check nv_mapchar() returns a non-null pointer before using it.
2021-01-28 04:01:49 +00:00
Martijn Dekker
cc4927529b libast: Update cdt(3): Allow empty strings in (dt)trees
This backports most of the Cdt (container data types) mechanism
from the ksh 93v- beta, based on ground work done by OpenSUSE:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-dttree-crash.dif
plus adaptations to match ksh 93u+m and an updated manual page
(src/lib/libast/man/cdt.3) added directly from the 93v- sources.

| Thu Dec 20 12:48:02 UTC 2012 - werner@suse.de
|
| - Add ksh93-dttree-crash.dif - Allow empty strings in (dt)trees
|   (bnc#795324)
|
| Fri Oct 25 14:07:57 UTC 2013 - werner@suse.de
|
| - Rework patch ksh93-dttree-crash.dif

As usual, precious little information is available because the
OpenSUSE bug report is currently closed to the public:
https://bugzilla.opensuse.org/show_bug.cgi?id=795324

However, a cursory inspection suggests that this code contains
improvements to do with concurrent processing and related
robustness. The new cdt.3 manual page adds a lot about that.

This has been in production use on OpenSUSE for a long time,
so hopefully this will make ksh a little more stable again.
Only one way to find out: let's commit and test this...

BTW, to get a nice manual, use groff and ghostscript's ps2pdf:
$ groff -tman src/lib/libast/man/cdt.3 | ps2pdf - cdt.3.pdf
2021-01-28 02:44:52 +00:00
Martijn Dekker
aa2644ab84 build: add missing version.h dependencies (re: 7fdeadd4)
src/cmd/ksh93/Mamfile:
- parse.c and shcomp.c now depend on version.h; this makes sure
  they are rebuilt if version.h changes.
2021-01-28 00:47:35 +00:00
Martijn Dekker
77ab60a149 iffe: revert <stdio.h> removal, add different fix (re: 308696ec)
Commit 308696ec caused the build to fail on macOS Catalina.

src/cmd/INIT/iffe.sh:
- Fix a blatantly unportable practice of passing multiple
  "|"-separated 'case' patterns through a variable. This was a way
  of grepping for some headers including stdio.h, but it only works
  this way on ksh93 and possibly the original Bourne shell, and not
  on *any* other shell (not even pdksh or mksh) -- and the fact
  that it works on ksh93 is arguably a bug. Fix by eliminating the
  "noext" variable (which is init'ed once and never changes) and
  using the pattern in the relevant 'case' statement directly.

src/cmd/builtin/features/pty:
- No matter what I try, including <stdio.h> causes the build to
  fail on Gentoo Linux (i386) with mysterious "invalid identifier:
  off64_t" errors -- this is probably some AST preprocessor hackery
  gone awry, but I've no idea where to even begin with that. This
  works around the problem by using AST sfio instead, which is
  built and functional by the time this feature test is run.
- Remove explicit extern declaration for ptsname(2) that was never
  used because it depended on an npt_ptsname feature test that
  doesn't exist (or no longer exists).
- Add missing <fcntl.h>, <stdlib.h>, and <unistd.h> for open(2),
  ptsname(2) and close(2), respectively.

src/lib/libast/features/float,
src/lib/libast/features/sfio,
src/lib/libast/features/stdio:
- Re-include <stdio.h>.

Fixes: https://github.com/ksh93/ksh/issues/164 (I hope)
2021-01-27 15:30:16 +00:00
Martijn Dekker
399886daa9 **/Mamfile: iffe: rm irrelevant flags (re: 580ff616, 6cc2f6a0)
This fixes annoying warnings from feature tests that show up when
building with IFFEFLAGS=-d1 (show compiler output from iffe), e.g.:

| In file included from <built-in>:367:
| <command line>:3:26: warning: missing terminating '"' character [-Winvalid-pp-token]
| #define _AST_git_commit \"a5c53a59\"
|                          ^
| 1 warning generated.

This means the double quotes were incorrectly escaped, which is
probably a bug in mamake -- but they're done correctly for the .c
files that actually need these flags. I may or may not trace the
mamake bug sometime.

src/*/*/Mamfile:
- Remove ${KSH_SHOPTFLAGS} en ${KSH_RELFLAGS} from the iffe
  invocations; they are not relevant for feature tests, only when
  actually compiling .c files (the $CC commands).
2021-01-27 14:54:53 +00:00
Martijn Dekker
db5621dbf8 Fix editor prediction code garbling input
This applies a patch from OpenSUSE. Source:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-edpredict.dif

| Tue Jul  5 14:49:03 CEST 2016 - mls@suse.de
|
| - fix editor prediction code garbling input [bnc#964966]
|   new patch: ksh93-edpredict.dif

Unfortunately the bug report is not currently public:
https://bugzilla.opensuse.org/show_bug.cgi?id=964966
but this one seems sensible enough and is in production use,
so I'll take it on faith.
2021-01-27 05:56:12 +00:00
Martijn Dekker
9b5ff0f833 Fix leak in optimize processing
This applies a patch from OpenSUSE. Source:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-optimizeleak.dif

| Tue Jul  5 14:49:03 CEST 2016 - mls@suse.de
|
| - fix leak in optimize processing [bnc#982423]
|   new patch: ksh93-optimizeleak.dif

Unfortunately the bug report is not currently public:
https://bugzilla.opensuse.org/show_bug.cgi?id=982423
but this one seems sensible enough and is in production use,
so I'll take it on faith.
2021-01-27 05:51:47 +00:00
Martijn Dekker
6d1352699e Fix locking error in spawn implementation
This applies a patch from OpenSUSE. Source:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-spawnlock.dif

| Wed Oct 12 13:23:14 CEST 2016 - mls@suse.de
|
| - fix locking error in spawn implementation [bnc#988213]
|   new patch: ksh93-spawnlock.dif

Unfortunately the bug report is not currently public:
https://bugzilla.opensuse.org/show_bug.cgi?id=988213
but this one seems sensible enough and is in production use,
so I'll take it on faith.
2021-01-27 05:32:24 +00:00
Martijn Dekker
a5c53a59e1 pty: more tweaks (re: 206bba4f, 5a2e7dae)
src/cmd/builtin/pty.c:
- Add missing #include <signal.h>.
- No need to limit SIGTTOU handling to Linux only -- it is POSIX
  compliant. Change #ifdef __linux__ to #ifdef SIGTTOU.
- The ECHOKE flag is not POSIX, so protect it with an #ifdef.
- s/slave/minion/g because minions are way more fun.
2021-01-27 04:51:01 +00:00
Martijn Dekker
206bba4f2e pty.c: Restore build on systems without cfmakeraw(3) (re: 5a2e7dae)
The OpenSUSE patch uses cfmakeraw(3) which is on Linux, BSD and
macOS, but not portable. The build failed on Solaris and variants.

src/cmd/builtin/features/pty:
- Add simple test for the presence of cfmakeraw(3). I love iffe.

src/cmd/builtin/pty.c:
- Add POSIX compliant fallback flaggery for systems without it.
2021-01-27 02:54:25 +00:00
Martijn Dekker
8e45daeaf1 ksh93/README: we now build on Alpine, 0 regress fails (re: e245856f) 2021-01-27 01:14:13 +00:00
Martijn Dekker
eaacfbb929 tests/pty.sh: Re-disable the process group exercise test
It freezes the 'less' pager on OpenBSD, which is not a ksh bug.
2021-01-27 00:55:20 +00:00
Martijn Dekker
28f97ba85c Allow building on AIX
This makes ksh build at least on AIX 7.1 on RISC (PowerPC).

There are 4 regression test failures:

        leaks.sh[159]: memory leak on PATH reset before PATH search
        (leaked approx 220 KiB after 16384 iterations)

        pty.sh[351]: POSIX sh 104(C): line 364: expected
        "^done\r?\n$", got EOF

        signal.sh[280]: subshell ignoring signal does not send
        signal to parent (expected 'SIGUSR1', got 'done')

        signal.sh[282]: parent does not wait for child to complete
        before handling signal

src/cmd/INIT/iffe.sh:
- Unset LIBPATH on AIX. The features/pty output{ ... }end will fail
  to link to libiconv otherwise, causing a build failure. See:
  https://www.ibm.com/support/pages/member-libiconvso2-not-found-archive

src/cmd/builtin/pty.c:
- CMIN is not defined on AIX, so set it to 1 if it's not defined.

src/cmd/ksh93/README:
- Update list of tested OSs.
2021-01-27 00:44:26 +00:00
Martijn Dekker
308696ec95 feature tests: do not re-include <stdio.h>
iffe --man documents that stdio.h is automatically pre-included for
all feature tests. Including it in the test code is not needed.

You'd think it shouldn't do any harm, but on a Gentoo i386 system,
this include turned out to be the cause of a mysterious 'unknown
type: off64_t' error while compiling the output{ ... }end block in
features/pty. I'm not going to bother with further tracing the
cause of that -- there is some hackery with off64_t defines in the
AST headers that probably has something to do with it.

src/cmd/builtin/features/pty,
src/lib/libast/features/float,
src/lib/libast/features/sfio,
src/lib/libast/features/stdio:
- Remove '#include <stdio.h>' from output{ ... }end blocks.
2021-01-26 21:53:48 +00:00
Martijn Dekker
b6bd9815a4 **/Mamfile: Use IFFEFLAGS variable to add iffe flags like -d1
It was unreasonably hard to debug problems with iffe tests that
fail to compile where they should (particularly output{ ... }end
blocks that write esserntial headers).

In e72543a9 the problem was already somewhat mitigated by making
some of the failing output{ ... }end blocks emit #error directives
so that invalid/incomplete headers would cause an error at a
sensible point, and not a much harder to track error later.

This commit further mitigates the problem by making the Mamfiles
respect an IFFEFLAGS environmenet variable that is prefixed to
every iffe command's arguments. The typical use would be to export
IFFEFLAGS=-d1 to enable debug level 1: show compiler output for all
iffe tests. This now makes it reasonably feasible to detect
problems in the feature tests themselves.

src/**/Mamfile:
- Import IFFEFLAGS environment variable using setv.
- Prefix ${IFFEFLAGS} to every iffe command.

src/**/features/*:
- Amend the new fail error messages to recommend exporting
  IFFEFLAGS=-d1 to show the cause of the failure.

README.md, TODO:
- Updates.
2021-01-26 17:21:20 +00:00
Martijn Dekker
f033bb0351 alarm: don't save sh.ifstable (re: 18b3f4aa)
It is not correct to save sh.ifstable (a.k.a. shp->ifstable) before
calling a function and then restore it after; this can cause field
splitting to malfunction. See 70368c57.

The change to init.c in the Red Hat patch applied in 18b3f4aa
(shp->ifstable[0] = S_EOF) appears to be sufficient.

src/cmd/ksh93/bltins/alarm.c:
- Revert save/restore of sh.ifstable.

src/cmd/ksh93/tests/builtins.sh:
- Tweak the regression test to work correctly on a slower machine,
  i.e. a Raspberry Pi running FreeBSD 12.2 arm64 (thanks to hyenias
  for providing testing access).
2021-01-26 15:48:38 +00:00
Martijn Dekker
e72543a9fa Build system tweaks; fix use of brk(2)/sbrk(2) feature test
There is a feature test for brk(2)/sbrk(2), but it was not checked
for in one place in vmbest.c, causing libdll to fail to build on
FreeBSD aarch64 because the features/dll output{...}end block
failed to link. This commit allows libdll to build on that system,
though another mysterious build failure apparently remains.
https://github.com/ksh93/ksh/issues/154

src/lib/libast/include/vmalloc.h,
src/lib/libast/vmalloc/vmbest.c:
- Add missing '#if _mem_sbrk' directives to disable uses of sbrk(2)
  on systems that have removed this deprecated interface.

src/cmd/builtin/features/pty,
src/lib/libast/features/common,
src/lib/libast/features/float,
src/lib/libast/features/lib,
src/lib/libast/features/sfio,
src/lib/libast/features/sizeof:
- Add a fail clause to more 'tst - output{' blocks so they write an
  informative #error directive if they fail to compile and write
  required header identifiers. This should avoid much more obscure
  compile errors later on. (re: e20c0c6b)

.gitignore:
- Add pattern for emacs #backup# files.
2021-01-26 09:59:11 +00:00
Martijn Dekker
856a2bb253 **/Mamfile: add header comment pointing to MAM docs (re: 6cc2f6a0)
The only proper documentation of the MAM language is in Glenn
Fowler's paper, which is unfortunately copyrighted so we can't
include it. But we can at least provide a link to it.

src/**/Mamfile:
- Add header comment.

src/cmd/INIT/mamake.c:
- Re-enable clang warnings on unused values (there aren't any).
2021-01-25 14:38:58 +00:00
hyenias
19c427435b
typeset: Correct numeric attribute change for floating points (#163)
This commit resolves the following incorrect variable assignments:
$ unset a; typeset -uF a=2; typeset -p a
typeset -X a=0x1.0000000000p+1
$ unset a; typeset -Fu a=2; typeset -p a
typeset -X a=0x1.0000000000p+1
$ unset a; typeset -ulF a=2; typeset -p a
typeset -l -X a=0x1.0000000000p+1
$ unset a; typeset -Ful a=2; typeset -p a
typeset -l -X a=0x1.0000000000p+1
$ unset a; typeset -Eu a=2; typeset -p a
typeset -E -X a=2
$ unset a; typeset -Eul a=2; typeset -p a
typeset -l -E -X a=2

src/cmd/ksh93/bltins/typeset.c:
- If the unsigned option (-u) was provided in conjunction with a
  floating point (-F) then due to a flag collision with NV_UNSIGN
  and NV_HEXFLOAT both having the value of NV_LTOU caused the
  floating point to become a hexadecimal floating point (-X) in
  error. Also, if a -E option flag was followed with a -u option
  then the resulting variable would be both a scientific notation
  and a hexadecimal floating point at the same time.

src/cmd/ksh93/tests/attributes.sh:
- Add regression tests.

Co-authored-by: Martijn Dekker <martijn@inlv.org>
2021-01-24 22:45:08 +00:00
Martijn Dekker
5a2e7dae67 pty: Fix signal handling (re: 1ca9286a)
This applies the OpenSUSE changes to pty.c from:
https://build.opensuse.org/package/view_file/shells/ksh/ksh93-builtin.dif

src/cmd/builtin/pty.c:
- Add a patch from OpenSUSE with a fix for signal handling.

src/cmd/ksh93/tests/pty.sh:
- Re-enable the process group exercise test.

Resolves: https://github.com/ksh93/ksh/issues/61
2021-01-24 18:57:27 +00:00
Martijn Dekker
70368c57d6 Fix field splitting bug triggered by DEBUG trap
An unquoted variable expansion evaluated in a DEBUG trap action
caused IFS field splitting to be deactivated in code executed after
the trap action. Thanks to Koichi Nakashima for the reproducer:

| v=''
| trap ': $v' DEBUG
| A="a b c"
| set -- $A
| printf '%s\n' "$@"
|
| Expected
|
| a
| b
| c
|
| Actual
|
| a b c

src/cmd/ksh93/sh/fault.c: sh_trap():
- Remove incorrect save/restore of sh.ifstable, the internal state
  table for field splitting. This reverts three lines added in ksh
  93t+ 2009-11-30. Analysis: As an expansion is split into fields
  (macro.c, lines 2367-2471), sh.ifstable is modified. If that
  happens within a DEBUG trap, any modifications in ifstable are
  undone by the restoring memccpy, leaving an inconsistent state.

src/cmd/ksh93/COMPATIBILITY:
- Document the DEBUG trap fixes, particularly the incorrect
  inheritance by subshells and functions that some scripts may now
  rely on because this bug is so longstanding. (re: 2a835a2d)

src/cmd/ksh93/tests/basic.sh:
- Add relevant tests.

Resolves: https://github.com/ksh93/ksh/issues/155

TODO: add a -T (-o functrace) option as in bash, which should allow
subshells and ksh-style functions to inherit DEBUG traps.

P.S.: The very handy multishell repo allows us to use 'git blame'
to trace the origin of the recently fixed DEBUG trap bugs.

The off-by-one error causing various bugs, reverted in 2a835a2d,
was introduced in ksh 93t 2008-07-25:
https://github.com/multishell/ksh93/commit/8e947ccf
(fault.c, line 321)

The incorrect check causing the exit status bug, reverted in
d00b4b39, was introduced in ksh 93t 2008-11-04:
https://github.com/multishell/ksh93/commit/b1ade268
(fault.c, line 459)

The ifstable save/restore causing the field splitting bug, reverted
in this commit, was introduced in ksh 93t+ 2009-11-30:
https://github.com/multishell/ksh93/commit/53d9f009
(fault.c, lines 440, 444, 482)

So all the bugs reported in #155 were fixed by simply reverting
these specific changes. I think that they are some experiments that
the developers simply forgot to remove. I've suspected such a thing
multiple times before. ksh93 was developed by researchers who were
genius innovators, but incredibly sloppy maintainers.
2021-01-24 16:09:02 +00:00
Martijn Dekker
e664b78f98 Add regress test for redirection in DEBUG trap action (re: 2a835a2d)
Turns out the previous commit also fixed the bug that disables the
DEBUG trap if a redirection is used in a DEBUG trap action -- in
other words, that's the same bug.

src/cmd/ksh93/tests/basic.sh:
- Add test from the reproducer in the bug report.

Makes progress on: https://github.com/ksh93/ksh/issues/155
2021-01-24 03:51:00 +00:00
Martijn Dekker
2a835a2d8a Fix restoring DEBUG trap upon exiting virtual subshell
This trap failed to be restored correctly when being trapped in
a subshell, causing corruption or a crash when restoring the
parent shell environment's trap upon leaving the subshell.

Thanks to Koichi Nakashima for the report and reproducer.

src/cmd/ksh93/sh/fault.c: sh_sigreset():
- Fix an off-by-one error in the loop that restores the
  pseudosignal traps.

src/cmd/ksh93/tests/basic.sh:
- Test overwriting the main shell trap in a subshell for all
  pseudosignals.

Makes progress on: https://github.com/ksh93/ksh/issues/155
2021-01-24 01:06:11 +00:00
Martijn Dekker
ac8e702ef2 sh.1: rm Solaris-specific SHOPT_PFSH info (re: f089d799)
The -P option only ever worked on Solaris so it's questionable it
should have been in the general-purpose manual to begin with. And
now it doesn't even work on Solaris as it disable SHOPT_PFSH with a
patch (that functionality is now provided by a wrapper that works
with all shells). So it's long past time to stop documenting it.

For the same reason, this also removes the info about invoking ksh
as pfksh, etc. -- this is still possible on Solaris with the new
method, but the functionality is no longer actually provided by
ksh. If the Solaris maintainers want it back in the man page, that
should be done by adding a patch to their build system.
2021-01-23 22:52:31 +00:00
Lev Kujawski
e73696fd87
Reenable the clobber method on UnixWare. (#160)
UnixWare's ps prefers to read psinfo (from the proc structure in
kernel memory) within /proc as an anti-Trojan horse measure.
Updates to argv[0] are still reflected within /proc/$pid/cmdline,
which is useful for diagnostic purposes.

src/cmd/ksh93/sh/main.c:
- Remove __USLC__ from the list of platforms excluded from the
  fixargs method.

src/cmd/ksh93/tests/basic.sh:
- Read /proc/$pid/cmdline instead of ps on UnixWare.
2021-01-23 21:31:47 +00:00
Martijn Dekker
d2cc520883 Disable SHOPT_KIA (ksh -R) by default
SHOPT_KIA enables the -R option that generates a cross-reference
database from a script. However, no tool to analyse this database
is shipped or seems to be available anywhere (in spite of multiple
people looking for one), and the format is very opaque. No usage
examples are known or findable on the internet. This seems like it
should not be compiled in by default, although we'll keep the code
in case some way to use it is found.

src/cmd/ksh93/SHOPT.sh:
- Disable SHOPT_KIA by default by removing the default 1 value.

src/cmd/ksh93/sh/args.c, src/cmd/ksh93/sh/parse.c:
- Fix a couple of preprocessor logic bugs that made it impossible
  to compile ksh without SHOPT_KIA.

src/cmd/ksh93/data/builtins.c:
- Fix typo in -R doc in ksh --man (in case SHOPT_KIA is enabled).

src/cmd/ksh93/sh.1:
- Since sh.1 is not generated dynamically, remove the -R doc.
2021-01-23 18:26:38 +00:00
Martijn Dekker
0a9c6fd771 Revert GNU __malloc_initialize_hook(3) change (re: e8b3274a)
This post-Korn AT&T commit from Feburary 2020 broke the build at
least on Slackware 14.2 with gcc 5.5.0 and glibc 2.23 if vmalloc
was disabled by defining _std_malloc or _AST_ksh_release (see
35672208). So building with vmalloc disabled has always been broken
on 93u+m on at least this version of Linux.

As usual, AT&T did not document the reason for applying this
change. It was also part of a commit that I already have little
trust in (I reverted another part of it in 16e4824c). So let's just
revert this and see what happens.

Hmm. The Linux __malloc_initialize_hook(3) manual page says it's
deprecated and was to be removed from glibc as of 2.24, whereas
Slackware 14.2 uses glibc 2.23. This would explain why this change
didn't break Linux with newer glibc versions, as the feature test
won't detect it and it won't be used at all.

src/lib/libast/features/vmalloc, src/lib/libast/vmalloc/malloc.c:
- Revert change in definition of __malloc_initialize_hook. It now
  conforms again with the spec in the Linux man page.

The build error caused by this change was:
| + cc -D_BLD_DLL -fPIC -D_BLD_ast '-D_AST_git_commit="e3f6d2d0"' -Os -g -D_std_malloc -I. -I/usr/local/src/ksh/src/lib/libast -Icomp -I/usr/local/src/ksh/src/lib/libast/comp -Ivmalloc -I/usr/local/src/ksh/src/lib/libast/vmalloc -Iinclude -I/usr/local/src/ksh/src/lib/libast/include -Istd -I/usr/local/src/ksh/src/lib/libast/std -D_PACKAGE_ast -c /usr/local/src/ksh/src/lib/libast/vmalloc/malloc.c
| /usr/local/src/ksh/src/lib/libast/vmalloc/malloc.c: In function '_ast_mallopt':
| /usr/local/src/ksh/src/lib/libast/vmalloc/malloc.c:1089:58: warning: implicit declaration of function 'mallopt' [-Wimplicit-function-declaration]
|  extern int F2(_ast_mallopt, int,cmd, int,value) { return mallopt(cmd, value); }
|                                                           ^
| /usr/local/src/ksh/src/lib/libast/vmalloc/malloc.c: At top level:
| /usr/local/src/ksh/src/lib/libast/vmalloc/malloc.c:1093:22: error: return type is an incomplete type
|  extern Mallinfo_t F0(_ast_mallinfo, void) { return mallinfo(); }
|                       ^
| /usr/local/src/ksh/src/lib/libast/vmalloc/malloc.c:72:19: note: in definition of macro 'F0'
|  #define F0(f,t0)  f(t0)
|                    ^
| /usr/local/src/ksh/src/lib/libast/vmalloc/malloc.c: In function '_ast_mallinfo':
| /usr/local/src/ksh/src/lib/libast/vmalloc/malloc.c:1093:52: warning: implicit declaration of function 'mallinfo' [-Wimplicit-function-declaration]
|  extern Mallinfo_t F0(_ast_mallinfo, void) { return mallinfo(); }
|                                                     ^
| /usr/local/src/ksh/src/lib/libast/vmalloc/malloc.c:1093:52: warning: 'return' with a value, in function returning void
| mamake [lib/libast]: *** exit code 1 making malloc.o
2021-01-23 15:44:55 +00:00
Martijn Dekker
c2108888df bin/package: reallow building old ksh versions (re: 6cc2f6a0)
When building old code for debugging purposes (e.g. when doing 'git
bisect' runs), it's best to use the current build system even with
the old code, because the old build system was very broken. E.g.:

	git checkout (some old commit)
	git checkout master bin src/cmd/INIT # use new build system
	bin/package make

However, that became impossible in 6cc2f6a0 because the new
SHOPT.sh script was unconditionally sourced. The error caused the
script to exit because '.' is a special builtin.

bin/package, src/cmd/INIT/package.sh:
- If src/cmd/ksh93/SHOPT.sh doesn't exist, issue a warning instasd
  of trying to source it.
2021-01-23 14:42:52 +00:00
Martijn Dekker
e3f6d2d0e6 Fix build on systems without O_CLOEXEC (re: 9f43f8d1)
A build failure on HP-UX B.11.11 was introduced when O_cloexec was
changed to O_CLOEXEC (which is POSIX standard) in the backported
93v- code. The lowercase variant is conditionally defined by libast
in src/lib/libast/features/fcntl.c precisely for compatibility with
systems that do not have O_CLOEXEC.

src/lib/libast/tm/tvtouch.c:
- Revert to using the AST O_cloexec flag when calling open(2).
2021-01-23 00:40:00 +00:00
Martijn Dekker
6cc2f6a0af Build system: make SHOPT_* editable again; allow indenting Mamfiles
The build system is adapted to make SHOPT_* compile-time options
editable without nmake. We can now easily change ksh's compile-time
options by editing src/cmd/ksh93/SHOPT.sh. The bin/package script
is adapted to turn these into compile flags. This resolves the most
important drawback of not using nmake.

Also, mamake now has support for indented Mam (Make Abstract
Machine) code. Only one type of block (make...done) is supported in
Mamfiles, so they are easy to indent automatically. A script to
(re)do this is included.

Since nmake is not going to be restored (it has too many problems
that no one is interested in fixing), this at least makes mamake
significantly easier to work with.

The Makefiles are deleted. They may still be handy for reference to
understand the Mamfiles, but they haven't actually matched the
Mamfiles for a while -- and you can still look in the git history.

Deleting them requires some adaptations to bin/package and mamake.c
because, even though they do not use those files, they still looked
for them to decide whether to build code in a directory.

Finally, this commit incorporates some #pragmas for clang to
suppress annoying warnings about the coding style used in this
historic code base. (gcc does not complain so much.)

src/cmd/ksh93/SHOPT.sh:
- Added.

bin/package, src/cmd/INIT/package.sh:
- cd into our own directory in case we were run from another dir.
- $makefiles: only look for Mamfiles.
- Add ksh compile-options via KSH_SHOPTFLAGS. Include SHOPT.sh.
- make_recurse(): Do not write a missing Makefile.
- finalize environment: Look for Mamfiles instead of Makefiles.

src/cmd/INIT/mamake.c:
- Tell clang to suppress annoying warnings about coding style.
- Update version string and self-documentation.
- input(): Add support for indented Mam code by skipping initial
  whitespace on each input line.
- files[]: Instead of looking for various of Makefiles to decide
  where to build, only look for Mamfiles.

src/Makefile, src/cmd/INIT/Makefile, src/cmd/Makefile,
src/cmd/builtin/Makefile, src/cmd/ksh93/Makefile, src/lib/Makefile,
src/lib/libast/Makefile, src/lib/libcmd/Makefile,
src/lib/libdll/Makefile, src/lib/libsum/Makefile:
- Removed.

src/Mamfile, src/cmd/INIT/Mamfile, src/cmd/Mamfile,
src/cmd/builtin/Mamfile, src/cmd/ksh93/Mamfile, src/lib/Mamfile,
src/lib/libast/Mamfile, src/lib/libcmd/Mamfile,
src/lib/libdll/Mamfile, src/lib/libsum/Mamfile:
- Indent the code with tabs.
- In ksh93/Mamfile, add ${KSH_SHOPT_FLAGS} to every $CC command.
- In ksh93/Mamfile, add "prev SHOPT.sh" for every *.o file
  so they are rebuilt whenever SHOPT.sh changes.

bin/Mamfile_indent:
- Added, in case someone wants to re-indent a Mamfile.

src/cmd/INIT/proto.c, src/cmd/INIT/ratz.c, src/cmd/INIT/release.c,
src/lib/libast/features/common, src/lib/libast/include/ast.h:
- Tell clang to suppress annoying warnings about coding style that
  it disapproves of (mainly concerning the use of parentheses).

src/cmd/INIT/cc.darwin, src/cmd/INIT/cc.freebsd,
src/cmd/INIT/cc.openbsd:
- Remove now-redundant clang warning suppression flags.

Resolves: https://github.com/ksh93/ksh/issues/60
2021-01-22 23:39:59 +00:00
Martijn Dekker
47468f56c2 main.c: fixargs(): add support for *BSD using setproctitle(3)
What is this for? See cefe087d

src/cmd/ksh93/Mamfile:
- Make iffe generate a test for the presence of setproctitle(3).

src/cmd/ksh93/sh/main.c:
- Include setproctitle test result.
- Re-enable fixargs() for FreeBSD and DragonFly BSD.
  Disable it for UnixWare.
- fixargs(): Add _lib_setproctitle version. Keep it simple with a
  128-character buffer array -- should be plenty for 'ps' output.
- fixargs(): Fix an off-by-one in zeroing the rest of the buffer.

src/cmd/ksh93/tests/basic.sh:
- Update the relevant regression test to run on FreeBSD/DragonFly
  and tolerate the "ksh: " prefix added by setproctitle(3).
2021-01-21 22:59:31 +01:00
Martijn Dekker
7fdeadd4f1 Increase shcomp bytecode header version; doc updates
src/cmd/ksh93/include/version.h:
- Centrally define the 93u+m copyright (SH_RELEASE_CPYR) for adding
  to the original AT&T copyright in 'ksh --man' and 'shcomp --man'.
- Centrally define the binary header version number for bytecode
  generated by shcomp: SHCOMP_HDR_VERSION.
- Bump SHCOMP_HDR_VERSION from 3 to 4. Converting all the preset
  aliases to builtin commands has caused new bytecode to be
  incompatible with old ksh. (However, old bytecode runs fine on
  93u+m, because shcomp pre-expands the preset aliases.)

src/cmd/ksh93/sh/shcomp.c:
- Instead of keeping its own version date (not changed since 2003),
  use the same version string as ksh itself (SH_RELEASE).
- Use SH_RELEASE_CPYR for the extra 93u+m copyright string.
- Use SHCOMP_HDR_VERSION for the bytecode header.

src/cmd/ksh93/sh/parse.c: sh_parse():
- Use SHCOMP_HDR_VERSION for the bytecode version check.

src/cmd/ksh93/data/builtins.c: opt_ksh[]:
- Use SH_RELEASE_CPYR for the extra 93u+m copyright string.

src/cmd/ksh93/COMPATIBILITY:
- Mention that 93u+m shcomp bytecode won't run on older ksh.
- Document changes in printf %T (re: 9526b3fa).

src/cmd/ksh93/README:
- Mention that we run on UnixWare (with major regressions).
  https://github.com/ksh93/ksh/pull/159#issuecomment-764667929
2021-01-21 17:04:14 +00:00
Martijn Dekker
9f43f8d10b Backport changes to AST time library from ksh 93v- beta
This incorporates the last changes in the tm library before AT&T
laid off the AST developers. It contains mostly time zone and
locale related changes/fixes.

I was hoping these would fix #52 (locale-based 'printf %T' output
is broken), but no such luck. This is probably good to have anyway.
2021-01-21 13:58:30 +00:00
Martijn Dekker
0a10e76ccc typeset: add error msgs for incompatible options; improve usage msg
This adds informative error messages if incompatible options are
given. It also documents the exclusive -m, -n and -T options on
separate usage lines, as was already done with -f. The usage
message for incompatible options now looks something like this:

| $ ksh -c 'typeset -L10 -F -f -i foo'
| ksh: typeset: -i/-F/-E/-X cannot be used with -L/-R/-Z
| ksh: typeset: -f cannot be used with other options
| Usage: typeset [-bflmnprstuxACHS] [-a[type]] [-i[base]] [-E[n]]
|                [-F[n]] [-L[n]] [-M[mapping]] [-R[n]] [-X[n]]
|                [-h string] [-T[tname]] [-Z[n]] [name[=value]...]
|    Or: typeset -f [name...]
|    Or: typeset -m [name=name...]
|    Or: typeset -n [name=name...]
|    Or: typeset -T [tname[=(type definition)]...]
|  Help: typeset [ --help | --man ] 2>&1

(see also the previous commit, e21a053e)

Unfortunately the first "Usage" line has some redundancies with the
"Or:" lines showing separate usages. It doesn't seem to be possible
to avoid this; it's a flaw in how libast generates everything
(usage, help, manual) from one huge getopt(3) string. I still think
the three added "Or:" lines are an improvement as it wasn't
previously shown that these options need to be used on their own.

src/cmd/ksh93/bltins/typeset.c: b_typeset():
- Instead of only showing a generic usage message, add an
  informative error message if incompatible options were given.
- Conflicting options detection was failing because NV_LJUST and
  NV_EXPNOTE have the same bitmask value. Use a new 'isadjust'
  flag for -L/-R/-Z to remember if one of these was set.
- Detect conflict between -L/-R/-Z and a float option, not just -i.

src/cmd/ksh93/include/name.h, src/cmd/ksh93/data/msg.c:
- Add the two new error messages for incompatible options.

src/cmd/ksh93/data/builtins.c: sh_opttypeset[]:
- Add a space after 'float' in in "[+float?\btypeset -lE\b]" as
  this makes 'float' appear on its own line, improving formatting.
- Show -m, -n, -T on separate usage lines like -f, as none of these
  can be combined with other options.
- Remove "cannot be combined with other options" from -m and -n
  descriptions, as that should now be clear from the separate usage
  lines -- and even if not, the error message is now informative.

src/cmd/ksh93/sh.1, src/cmd/ksh93/COMPATIBILITY:
- Update.

src/cmd/ksh93/tests/types.sh:
- Remove obsolete test: 'typeset -RF' is no longer accepted.
  (It crashed in 93u+, so this is not an incompatibility...)

Resolves: https://github.com/ksh93/ksh/issues/48
2021-01-21 09:36:10 +00:00
Martijn Dekker
e21a053e19 libast: optget: improve usage messages, adding help info line
For example, this changes 'typeset -Q' (a bad option) from:

| ksh: typeset: -Q: unknown option
| Usage: typeset [-bflmnprstuxACHS] [-a[type]] [-i[base]] [-E[n]]
|                [-F[n]] [-L[n]] [-M[mapping]] [-R[n]] [-X[n]]
|                [-h string] [-T[tname]] [-Z[n]] [name[=value]...]
|    Or: typeset [ options ] -f [name...]

to:

| ksh: typeset: -Q: unknown option
| Usage: typeset [-bflmnprstuxACHS] [-a[type]] [-i[base]] [-E[n]]
|                [-F[n]] [-L[n]] [-M[mapping]] [-R[n]] [-X[n]]
|                [-h string] [-T[tname]] [-Z[n]] [name[=value]...]
|    Or: typeset -f [name...]
|  Help: typeset [ --help | --man ] 2>&1

src/lib/libast/misc/optget.c: args():
- Revert the changes done in 6916a873 and ae92cd89. The --help and
  --man labels weren't added consistently (they did not show up in
  the example above) whereas they did show up unnecessarily in the
  manual page itself.
- In the usage section and usage messges, only show an [ options ]
  label on the first usage line; don't redundantly repeat on second
  and further ("Or:") lines.
- In usage and --help (but not --man), add a new "Help:" line
  telling the user about the --help and --man options. This
  replaces the reverted changes. Show the 2>&1 redirection as a
  reminder that you need to do this to pipe it into a pager, as
  everything is written to standard error!
- Add some comments clarifying what I think this code does...

src/cmd/ksh93/tests/builtins.sh:
- Update to match changes in getopts usage output.
2021-01-21 08:55:12 +00:00
Martijn Dekker
6445573d24 typeset: only alloc stack space if needed (re: ff70c27f)
src/cmd/ksh93/bltins/typeset.c:
- Don't call stakalloc(3) unless/until we actually need it to
  construct a new list of arguments.
2021-01-21 08:39:10 +00:00
Lev Kujawski
ff70c27f24
typeset: Fix stack fencepost error, ISO C90 compat (#159)
src/cmd/ksh93/bltins/typeset.c:
- The new_argv[] array was one item too short (should be argc+2).
- Use AST stakalloc(3) to allocate it instead of a dynamic array;
  this restores compatibility with ISO C90.

src/lib/libast/features/standards, src/cmd/INIT/cc.unixware.i386:
- Add support for UnixWare.
- Do not define any standards macros on this system, as on FreeBSD
  and DragonFly BSD.
2021-01-21 07:50:07 +00:00
Martijn Dekker
bb4d6a2ee5 cd: add missing "test.h" include (re: 5ee290c7)
Fixes: https://github.com/ksh93/ksh/issues/158
2021-01-20 22:13:32 +00:00
Martijn Dekker
8cd4bc1690 conf.sh: correct embarrassing typo (re: a75d0dfa) 2021-01-20 22:05:22 +00:00
Martijn Dekker
d00b4b39f6 Fix side effect to exit status of DEBUG trap in comsub
This fixes the following:

trap ':' DEBUG
r=$(exit 123)
echo $? # Expected 123, but actually 0.

Thanks to Koichi Nakashima for the report and reproducer.

src/cmd/ksh93/sh/fault.c: sh_trap():
- Restore the saved current exit status (exitval) for all traps.
  Do not except the DEBUG trap from doing that. I've no idea why
  this exception was made, but it's not correct.

src/cmd/ksh93/tests/basic.sh:
- Add tests.

Makes progress on: https://github.com/ksh93/ksh/issues/155
2021-01-20 17:48:09 +00:00
Martijn Dekker
5ee290c7a8 cd: Fork if $PWD exists but is not actually the PWD (re: d1483150)
Commit d1483150 did not fully fix #153.
Test case from Harald van Dijk that was still failing:

$ mkdir test
$ cd test
$ rmdir $PWD
$ mkdir $PWD
$ ksh -c "(cd /); pwd"
/

Forking a virtual subshell in that case is needed to avoid ending
up in a directory that replaced the PWD, because it will not be
possible for a process to change back to the original directory.

src/cmd/ksh93/bltins/cd_pwd.c:
- When deciding whether to fork, instead of attempting to opendir
  the PWD, compare the inodes $PWD and "." to determine if $PWD
  still actually refers to the current directory. This uses the
  test_inode() function which is also used by 'test foo -ef bar'.

src/cmd/ksh93/tests/subshell.sh:
- Add test based on the above.

Progresses: https://github.com/ksh93/ksh/issues/153
2021-01-20 05:56:38 +00:00
Martijn Dekker
ec0155ee65 tests/variables.sh: tweaks for special and locale variable tests
src/cmd/ksh93/tests/variables.sh:
- Fork the subshell with the test that includes unsetting LINENO
  and changing its type. Otherwise, some side effect of that leaks
  out of the subshell, messing up $LINENO. This is a bug, but it's
  low priority -- we may get to it someday. Marked with a TODO.
- Do the LC_* tests in their own subshell. Skip them if changing
  LANG to an invalid value does not produce a diagnostic message.
  This occurs on OpenBSD and Alpine Linux (with musl libc). It
  looks like their C libraries do not verify the locale, so
  failures here are not a ksh problem; skip the tests in that case.
2021-01-20 05:38:55 +00:00
Martijn Dekker
21c42fcef8 tests/pty.sh: skip 4 tests when running as root 2021-01-20 05:01:57 +00:00
lev105
e245856fd2
Fix incompatibilities with the musl C library (#156)
This makes ksh build on Alpine Linux which uses this C library.

src/lib/libast/include/ast_std.h:
- Define __DEFINED_FILE to hide FILE internals from the Korn
  shell's SFIO.

src/lib/libast/features/wchar:
- Include wchar.h before redefining iswalpha() to avoid mangling
  the C library's declaration.

src/lib/libast/features/lib:
- Test whether off64_t and off_t are actually distinct types before
  using the former.

Fixes: #3
2021-01-20 04:02:00 +00:00
Martijn Dekker
699965fe41 tests/builtins.sh: don't test for x perm check as root 2021-01-20 03:54:23 +00:00
Martijn Dekker
a75d0dfa18 conf.sh: avoid pointless reruns (re: 33b6718b)
Same idea as in the referenced commit.

src/lib/libast/comp/conf.sh:
- If an output header file has not changed after rerunning conf.sh,
  still update the output file's timestamp using touch(1) to signal
  that the test has already been run.
2021-01-19 23:05:39 +00:00
Martijn Dekker
3b19944e07 tweak for compat with broken /bin/sh on AIX ibm.risc
AIX on ibm.risc comes with a broken version of ksh88 as /bin/sh
where the following causes breakage in the parser (spurious syntax
errors):

	(set -o posix) 2>/dev/null && set -o posix

However, prefixing it with 'command' (while keeping the subshell)
circumvents the problem. So, why not.

	(command set -o posix) 2>/dev/null && set -o posix
2021-01-19 22:38:27 +00:00
Martijn Dekker
e20c0c6b5d dll feature test: output #error directive on failure
A common cause of build failures on some systems is that the output
block in the dll feature test silently fails to compile. This leads
to very-hard-to-trace compiler errors about missing identifiers
later on. iffe syntax does not allow aborting compilation if a
block does not compile, however, it does let us produce alternative
output from a shell script if compilation fails. This can be used
to generate an informative #error directive that is inserted in
place of the missing identifiers.

src/lib/libdll/features/dll:
- Add fail block to output block that produces an #error directive.
2021-01-19 22:19:54 +00:00
Martijn Dekker
820bb6a04b make.probe: probe_optimize: remove -O2
Solaris Studio 12.5 cc seems to produce incorrect code at -O2
(a.k.a. -xO2) optimisation level; integer variables initialise at
random values, and the behaviour of the shell is so incorrect it
can't even run the test scripts. It does not support -Os so that
is skipped for that compiler. At -O it works fine.

src/cmd/INIT/make.probe:
- By default, only try -Os and -O optimisation flags.
2021-01-19 22:13:59 +00:00
Martijn Dekker
7bab9508aa Fix crash on subshell exit if PWD is inaccessible (re: dd9bc229)
This commit also further mitigates the problems with restoring an
inaccessible or nonexistent PWD on exiting a virtual subshell.

Harald van Dijk writes:
> On a build of ksh with -fsanitize=undefined to help diagnose
> problems:
>
> $ mkdir deleted
> $ cd deleted
> $ rmdir ../deleted
> $ ksh -c '(cd /; (cd /)); :'
> /home/harald/ksh/src/cmd/ksh93/sh/subshell.c:561:22: runtime
> error: null pointer passed as argument 1, which is declared to
> never be null
> Segmentation fault (core dumped)
>
> Note that it segfaults the same with default compilation flags,
> but it does not print out the useful extra message. The code
> assumes that pwd is non-null and passes it to strcmp without
> checking, but it will be null if the current directory cannot be
> determined, for instance because it has been deleted.

src/cmd/ksh93/sh/subshell.c: sh_subshell():
- Avoid the null pointer dereference reported above.

src/cmd/ksh93/bltins/cd_pwd.c: b_cd():
- Fork a virtual subshell even on systems with fchdir(2) if the
  present working directory tests as inaccessible on invoking 'cd';
  it may no longer exist and fchdir would fail to get a handle.
  (For the test we have to opendir(3) the full path to the PWD and
  not ".", as the latter may succeed even if the PWD is gone.)

src/cmd/ksh93/data/builtins.c:
- Update 'cd' version string.

Fixes:   https://github.com/ksh93/ksh/issues/153
Related: https://github.com/ksh93/ksh/issues/141
2021-01-19 18:47:41 +00:00
Martijn Dekker
82847bba3f sh_main(): do not decrease null pointer
src/cmd/ksh93/sh/main.c: sh_main():
- Reading the code makes it obvious that the shp->comdiv-- decrease
  in the 'else' block is never reached unless that pointer is still
  null, in which case it makes no sense to decrease it. Must be
  some kind of missed leftover from old code. Remove the decrease.
2021-01-19 18:39:43 +00:00
Martijn Dekker
de7eb85255 sh_subsavefd(): avoid a negative shift operand
This change is backported from the abandoned ksh 93v- beta.

src/cmd/ksh93/sh/subshell.c: sh_subsavefd():
- Do not subtract 1 from fd, as this would cause a negative shift
  operand for stdin (fd==0).
2021-01-19 18:30:10 +00:00
Martijn Dekker
ccd98fe754 src/cmd/ksh93/{COMPATIBILITY,README}: updates in prep for release 2021-01-19 01:12:04 +00:00
Martijn Dekker
33b6718bf2 iffe: avoid pointless reruns: update result timestamp if unchanged
If iffe re-ran a test because the source test script changed, but
the result file is unchanged, it didn't update the timestamp of the
result, so the source script remained newer. The build system then
kept pointlessly re-running the test on each rebuild. If a central
test script such as src/lib/libast/features/standards was changed,
this had cascading effects, e.g., causing libast to be rebuilt over
and over as I recompiled small changes elsewhere. Until now, my
workaround was to delete the entire 'arch' directory and start
over. Hopefully that will now no longer be needed.

src/cmd/INIT/iffe.sh:
- If a test output file has not changed after rerunning a test that
  has changed, still update the output file's timestamp using
  touch(1) to signal that the test has already been run.
2021-01-18 21:55:57 +00:00
Martijn Dekker
dd0d03b973 Eliminate LDFLAGS hack to compile on certain OSs
Instead, we now link to the libm system math library where needed
by adding -lm to the relevant compile commands in the Mamfiles.
This is not needed on every system but never does any harm.

(This adds more custom edits to the Mamfiles, which were originally
generated from the nmake Makefiles. This takes us further from
restoring nmake, but that already wasn't going to happen anyway,
due to its many problems... the path forward will be to translate
the Mamfiles to some other, current make system such as GNU make.)

bin/package, src/cmd/INIT/package.sh:
- Remove LDFLAGS=-lm hack for DragonFly BSD, NetBSD and Solaris.

src/cmd/builtin/Mamfile,
src/cmd/ksh93/Mamfile,
src/lib/libdll/Mamfile:
- Add -lm where linking failed on any of the three mentioned OSs.

src/lib/libdll/features/dll:
- In the output test program, add missing #include <math.h>, fixing
  unknown identifier errors on NetBSD (ldexp, ldexpl).

src/cmd/builtin/features/pty:
- Add missing #include <stdio.h> to make printf work on all systems
  (this is just a feature test, no need to bother with sfio here).

src/lib/libast/features/stdio:
- Undef __FILE_T to avoid interference from system headers on QNX.
  (There are still other problems preventing a build on QNX 6.5.0.
  The shipped version of gcc seems to be broken.)
2021-01-18 19:16:17 +00:00
Martijn Dekker
5f6371f078 main.c: tweak fixargs() macros: single point of truth 2021-01-18 09:33:26 +00:00
Martijn Dekker
4dcf5c5066 Apply patches to build on DragonFly BSD and (older) FreeBSD
This now makes ksh build on DragonFly BSD.

bin/package, src/cmd/INIT/package.sh:
- DragonFly also needs the -lm hack for LDFLAGS.

src/cmd/ksh93/sh/main.c, src/cmd/ksh93/tests/basic.sh:
- fixargs() doesn't work on DragonFly either
  (re: 9b7c392a, 159fb9ee, cefe087d).

The following are backported from:
https://github.com/att/ast/issues/26#issuecomment-313927854
https://github.com/att/ast/pull/19

src/lib/libast/comp/setlocale.c:
- Add missing #include <errno.h> since errno is used.

src/lib/libast/features/standards:
- Do not set any standards macros (_POSIX_SOURCE etc) on FreeBSD or
  DragonflyBSD; they disable too much functionality on those.

src/lib/libast/features/wchar:
- Set _STDFILE_DECLARED on DragonFly, too.

src/lib/libast/include/sfio.h, src/lib/libast/include/sfio_t.h,
src/lib/libast/sfio/_sfopen.c, src/lib/libast/sfio/sfclrlock.c,
src/lib/libast/sfio/sfhdr.h, src/lib/libast/sfio/sfnew.c,
src/lib/libast/sfio/sfset.c:
- Rename SF_* macros to SFIO_* to avoid a conflict with system
  headers.

src/lib/libast/string/strexpr.c:
- Rename error() to err() to avoid a conflict.
2021-01-18 09:08:48 +00:00
Martijn Dekker
8633290e63 Fix build failure on certain versions of glibc
Patch from:
https://bugzilla.redhat.com/show_bug.cgi?id=1477082

See also:
https://github.com/att/ast/pull/63
https://bugs.debian.org/887743
2021-01-18 07:48:15 +00:00
Martijn Dekker
8361e065e6 job_unpost(): fix segfault
This function could segfault under certain conditions (in macOS
Terminal, when ksh received SIGWINCH and a complex PS1 prompt is
defined; see 61437b27)

0   ksh            job_unpost + 49 (jobs.c:1703)
1   ksh            job_reap + 1632 (jobs.c:468)
2   ksh            job_wait + 942 (jobs.c:1525)
3   ksh            sh_exec + 19579 (xec.c:1627)
4   ksh            sh_eval + 545 (xec.c:763)
5   ksh            sh_trap + 427
6   ksh            ed_emacsread + 3598 (emacs.c:1072)
7   ksh            slowread + 489 (io.c:1962)
8   ksh            sfrd + 1026 (sfrd.c:253)
9   ksh            _sffilbuf + 587 (sffilbuf.c:105)
10  ksh            sfreserve + 662
11  ksh            exfile + 1922 (main.c:527)
12  ksh            sh_main + 1071 (main.c:351)
13  libdyld.dylib  start + 1

src/cmd/ksh93/sh/jobs.c: job_unpost():
- Fix a dereference of a possible null pointer returned by
  job_byjid(). Add a check and return if that pointer is null.
2021-01-18 07:14:06 +00:00
Martijn Dekker
7222ba3af7 tests/basic.sh: fix intermittent spurious regress fail
~- and ~+ are ksh93-specific tilde expansions that expand to
$OLDPWD and $PWD, respectively. On some systems, $OLDPWD is not set
on entry to the test script, because it is not exported to the
environment. This made it unset before any 'cd' was executed,
which (correctly) disabled ~- expansion.

src/cmd/ksh93/tests/basic.sh:
- Before testing 'cd ~-', make sure $OLDPWD is set by cd'ing to
  /dev first (a directory guaranteed by POSIX).
2021-01-18 06:27:08 +00:00
Martijn Dekker
8e8ff5f6f6 Disable SHOPT_PFSH in feature test (re: f089d799)
src/cmd/ksh93/features/options:
- To make sure SHOPT_PFSH stays disabled on Solaris, we
  also need to stop this feature test from re-enabling it.
2021-01-18 06:11:45 +00:00
Martijn Dekker
f089d7990a Solaris: disable deprecated SHOPT_PFSH by default
Solaris /bin/ksh disables the SHOPT_PFSH compile option ("solaris
exec_attr(4) profile execution") with a patch. Since this option
applies to Solaris and variants only, let's upstream that change.

(Solaris now provides pfksh93 as a wrapper around ksh93, and does
the same for other shells, so profiling functionality is no longer
ksh-specific.)

If you want to re-enable it, add -DSHOPT_PFSH to your $CCFLAGS.

Original patch:
https://github.com/oracle/solaris-userland/blob/master/components/ksh93/patches/150-CR7168611.patch

src/cmd/ksh93/Makefile:
- Add note that edits in Makefile are ineffective as we do not ship
  nmake.
- Disable SHOPT_PFSH, cosmetically.

src/cmd/ksh93/Mamfile:
- Remove -DSHOPT_PFSH from all compiler commands.
2021-01-18 05:29:09 +00:00
Martijn Dekker
4cfe49aebb package: involve $CCFLAGS when determing 64-bit arch (re: 9a48ba15)
bin/package, src/cmd/INIT/package.sh:
- It can depend on the compiler flags passed whether the compiler
  produces code for a 64-bit architecture, so pass $CCFLAGS to
  the compiler when testing whether it creates 64-bit object code.

README.md:
- Copy-edit of build instructions.
2021-01-18 03:56:03 +00:00
Martijn Dekker
580ff61617 Fix release and standards build flags (re: 35672208, aa4669ad)
bin/package, src/cmd/INIT/package.sh:
- CCFLAGS overwrites the autodetected optimisation flags (e.g. -Os)
  if set. Unfortunately, that also happened when we added something
  to CCFLAGS for a release build or to add an extra flag needed by
  Solaris. The fix is to use a new flags variable (KSH_RELFLAGS)
  instead. This needs to be done in a different place as it needs
  to be added to the mamake command as an assignment argument.
- Remove the Solaris CCFLAGS hack; see features/common below.

src/*/*/Mamfile:
- Add ${KSH_RELFLAGS} to all the compiler commands.

src/lib/libast/features/common:
- Enable POSIX standard on Solaris (i.e.: if __sun is defined) by
  defining _XPG6 directly in the feature test that generates
  ast_std.h, which is indirectly included by everything. This
  removes the need to pass -D_XPG6 via CCFLAGS. (Doing so
  automatically with gcc was not otherwise possible.)

src/cmd/INIT/cc.sol11.*:
- No longer pass -D_XPG6, as per above.
2021-01-18 01:07:45 +00:00
Martijn Dekker
e25d9f4190 nv_newattr(): fix potential invalid free
src/cmd/ksh93/sh/name.c:
- Zero the 'cp' pointer after freeing it, as the next loop
  iteration may otherwise re-use the old address.
2021-01-17 03:55:46 +00:00
Martijn Dekker
9a48ba1557 package: fix code for detecting 64-bit compiler
bin/package, src/cmd/INIT/package.sh:
- The code for detecting a 64-bit object file was seriously broken:
  the temporary file name could contain '64' because it included $$,
  the current PID, and 64-bit was detected if the output of 'file'
  (which includes the complete file name) contained '64'. Fix by
  removing the file name from 'file' output before testing.
- Also refactor that code a bit and remove the nonsensical test if
  /bin/sh is a 64-bit binary, which is neither here nor there. It's
  what the compiler produces that we need to care about.
2021-01-16 22:53:35 +00:00
Martijn Dekker
6025c8125e make.probe: add fallback optimisation flags
src/cmd/INIT/make.probe:
- probe_optimize: Also try -O2 and -O, for compilers (such as
  Solaris Studio cc) that do not support -Os.
- Use more robust code to loop through possible optimiser flags.
2021-01-16 22:01:07 +01:00
Martijn Dekker
1554ec2cdd libast: Revert conf.sh changes (re: 2e839d87, 3aa01a95)
These caused a compilation failure in the generated conftab.c
file while compiling on Solaris with gcc.
2021-01-16 19:27:48 +01:00
Martijn Dekker
68a6f9a6e2 Fix Solaris cc wrappers (re: 4e67234a)
The versions from the Solaris patch require $CC_EXPLICIT to be set,
which is specific to the internal Solaris build environment.

src/cmd/INIT/cc.sol11.*:
- Cope without $CC_EXPLICIT set in environment; fall back to $CC
  and if that is not set either, detect whether to use cc or gcc.
- Set appropriate flags for cc (Solaris Studio) or gcc, including
  the necessary -D_XPG6 flag, without which ksh crashes on Solaris.

bin/package, src/cmd/INIT/package.sh:
- Update hack to add the -D_XPG6 flag so it applies to gcc only
  (note: the src/cmd/INIT/cc.* scripts are never used for gcc).
2021-01-16 19:25:39 +01:00
Martijn Dekker
2e839d8775 getconf detection: fix compiler error msg extraction (re: 3aa01a95)
That patch didn't work for non-gcc, non-clang compilers -- at least
Solaris Studio cc. It doesn't prefix error messages with "error:".
As a result, it caused the build to fail on Solaris with native cc.

src/lib/libast/comp/conf.sh:
- Use a sed formula that should catch error messages prefixed by
  "line xx:" while still removing warnings and suggestions. This
  works on at least clang, gcc, Solaris Studio cc.
2021-01-16 14:43:22 +00:00
Martijn Dekker
2f7918deec libast: backport tvsleep(3) from ksh 93v- (re: 2db9953a)
src/lib/libast/tm/tvsleep.c:
- Since the 'sleep' builtin was backported/fixed from ksh93v- and
  ksh2020, it makes sense to use the latest/last tvsleep(3), too.
  Looks like this added an interrupt check (errno == EINTR).
  Also, new fallback versions for systems without nanosleep(2).

Documentation: src/lib/libast/man/tv.3 (unchanged)
2021-01-15 19:05:32 +00:00
Martijn Dekker
a3f4ef7adf libast: fix detection of long double NaN/INF signatures
src/lib/libast/features/float:
- libast attempts to determine the binary representation of Inf and
  NaN to use as a fall-back code path for systems that do not
  support fpclassify(). The libast feature detection did not get
  consistent signatures between builds. To fix this, zero the
  memory before determining the signature.

src/lib/libast/sfio/sfcvt.c:
- The fall-back code path is broken because there are multiple
  representations for NaN - the important thing is to check the
  exponent and for a non-zero significand. The trailing bits can be
  random or left over from interim operations. For that reason, to
  ensure we never end up using the fall-back code path, explicitly
  generate a compile error if we end up there.

Based on a patch from @citrus-it:
8bf59a9a8f
but uses POSIX memset(3) instead of deprecated bzero(3).
2021-01-15 15:40:12 +00:00
Martijn Dekker
3aa01a95ee getconf detection: cope with new compiler messages
conf.sh checks for undefined symbols by parsing compiler output and
looking for strings of capital letters and underscores. Modern gcc
produces suggestions for replacement variables too, for example:

error: '_SC_CLOCKRES_MIN' undeclared here (not in a function); did you mean _POSIX_CLOCKRES_MIN?
 _SC_CLOCKRES_MIN,
 ^~~~~~~~~~~~~~~~
 _POSIX_CLOCKRES_MIN

This causes good variables to be excluded along with bad, causing differences
between the builtin and system getconf commands.

src/lib/libast/comp/conf.sh:
- Only use lines containing 'error:' and ignore everything starting
  from 'did you mean:'. (Note this scripts sets the locale to C.)

Patch from @citrus-it:
061a4b1da1
2021-01-15 15:38:14 +00:00
Martijn Dekker
649f4b047b tests/builtins.sh: tweak for HP-UX 2021-01-12 18:18:39 +00:00
Martijn Dekker
4d5e21de80 Fix for compiling with SHOPT_DYNAMIC disabled
src/cmd/ksh93/bltins/typeset.c:
- Correct faulty preprocessor directive logic causing a build
  failure if SHOPT_DYNAMIC is disabled.
2021-01-10 23:02:15 +00:00
Martijn Dekker
e981f7c8b8 Regression test tweaks to avoid false fails on Solaris
src/cmd/ksh93/tests/path.sh:
- Re-export PATH after unsetting it.

src/cmd/ksh93/tests/pty.sh:
- Increase some delays.
2021-01-10 20:53:41 +01:00
Martijn Dekker
9b7c392a7c Disable fixargs() on Solaris (re: 159fb9ee, cefe087d)
It doesn't work on Solaris either.
2021-01-10 18:47:12 +00:00
Martijn Dekker
159fb9ee27 main.c: Tweak fixargs() (re: cefe087d)
src/cmd/ksh93/sh/main.c: fixargs():
- Erase the entire length of the command arguments buffer (the
  space from argv[0] until environ[0]) so that remnants of longer
  command arguments aren't left in 'ps' output when executing a
  hashbang-ess script with a shorter command line.
- Disable fixargs() on FreeBSD. It has never had any effect on that
  system; apparently it either requires another method to rewrite
  arguments for 'ps' output purposes (which?) or it's not possible.

src/cmd/ksh93/tests/basic.sh:
- Skip the test if running on FreeBSD.
2021-01-10 06:34:49 +00:00
Martijn Dekker
e7202832fd Revert "bin/package: don't test-compile using possibly broken dev shell"
This reverts commit 600cb182.
$cc may be a system compiler binary, it is not necessarily a
src/cmd/INIT/cc.* wrapper script; so prefixing 'sh' is wrong.
2021-01-09 16:16:28 +00:00
Martijn Dekker
4d0b77d398 Revert "Fix SIGALRM core dump (Solaris patch 230-18229654)"
This reverts commit 13e7b262. It caused the regression test for the
'alarm' builtin, introduced in 18b3f4aa, to hang on FreeBSD.
2021-01-09 13:18:00 +00:00
Martijn Dekker
7d2bb8fdd9 libast: fix exec fail on interactive (Solaris patch 315-26773587)
This upstreams a Solaris patch:
https://github.com/oracle/solaris-userland/blob/master/components/ksh93/patches/315-26773587.patch
which ostensibly fixes this bug filed in Oracle's closed system:
26773587 interactive ksh exec failure in while read loop

src/lib/libast/comp/spawnveg.c:
- If posix_spawn(3) fails with an error other than EPERM, retry,
  but without attributes.
2021-01-09 01:58:23 +00:00
Martijn Dekker
4e67234ae8 INIT: Add Solaris 11 compiler wrappers (Solaris patch 005-compiler)
This upstreams a Solaris patch:
https://github.com/oracle/solaris-userland/blob/master/components/ksh93/patches/005-compiler.patch
2021-01-09 01:03:08 +00:00
Martijn Dekker
e03c010c4d Fix for non-UTF-8 wide charsets (Solaris patch 050-CR7065478)
This upstreams a Solaris patch:
https://github.com/oracle/solaris-userland/blob/master/components/ksh93/patches/050-CR7065478.patch

src/lib/libast/comp/setlocale.c:
- Add wide_wctomb() wrapper for wctomb(3). It changes an invalid
  character (wctomb returns -1) to a single byte with length 1.
- set_ctype(): Use wide_wctomb() instead of wctomb(3) as the
  conversion discipline function (ast.mb_conv). Effectively this
  means there are no invalid characters. Perhaps this is necessary
  for compatibility with ASCII. Sadly, no public info available.
2021-01-09 00:45:51 +00:00
Martijn Dekker
096f46eee5 Fix for memory mgmt in variable expansion (Solaris 105-CR7032068)
This upstreams a Solaris patch:
https://github.com/oracle/solaris-userland/blob/master/components/ksh93/patches/105-CR7032068.patch

No other information is publicly available but this has been in
production use on Solaris for a long time. It looks like this is
intended to avoid an invalid free().
2021-01-09 00:28:11 +00:00