1
0
Fork 0
mirror of git://git.code.sf.net/p/cdesktopenv/code synced 2025-02-13 11:42:21 +00:00
No description
Find a file
Martijn Dekker ffee9100d5 Robustify ${.sh.level} scope switching (re: 69d37d5e, e1c41bb2)
Switching the function scope to a parent scope by assigning to
.sh.level (SH_LEVELNOD) leaves the shell in an inconsistent state,
causing invalid-free and/or use-after-free bugs. The intention of
.sh.level was always to temporarily switch scopes inside a DEBUG
trap, so this commit minimises the pitfalls and instability by
imposing some sensible limitations:
1. .sh.level is now a read-only variable except while executing a
   DEBUG trap;
2. while it's writeable, attempts to unset .sh.level or to change
   its attributes are ignored;
3. attempts to set a discipline function for .sh.level are ignored;
4. it is an error to set a level < 0 or > the current scope.

Even more crashing bugs are fixed by simplifiying the handling and
initialisation of .sh.level and by exempting it completely from
virtual subshell scoping (to which it's irrelevant).

TODO: one thing remains: scope corruption and use-after-free happen
when using the '.' command inside a DEBUG trap with ${.sh.level}
changed. Behaviour same as before this commit. To be investigated.

All changed files:
- Consistently use the int16_t type for level values as that is the
  type of its non-pointer storage in SH_LEVELNOD.
- Update .sh.level by using an update_sh_level() macro that assigns
  directly to the node value, then restores the scope if needed.
- To eliminate implicit typecasts, use the same int16_t type (the
  type used by short ints such as SH_LEVELNOD) for all variables
  containing a function and/or dot script level.

src/cmd/ksh93/include/variables.h:
- Add update_sh_level() macro.

src/cmd/ksh93/include/name.h,
src/cmd/ksh93/sh/macro.c:
- Add a nv_nonptr() macro that checks attributes for a non-pointer
  value -- currently only signed or unsigned short integer value,
  accessed via the 's' member of 'union Value' (e.g. np->nvalue.s).
- nv_isnull(): To avoid undefined behaviour, check for attributes
  indicating a non-pointer value before accessing the nvalue.cp
  pointer (re: 5aba0c72).
- varsub(): In the set/unset check, remove the now-redundant
  exception for SH_LEVELNOD.

src/cmd/ksh93/data/variables.c,
src/cmd/ksh93/sh/init.c:
- shtab_variables[]: Make .sh.level a read-only short integer.
- sh_inittree(): To avoid undefined behaviour, do not assign to the
  'union Value' char pointer if the attribute indicates a non-
  pointer short integer value. Instead, the table value is ignored.

src/cmd/ksh93/sh/subshell.c: sh_assignok():
- Never create a subshell scope for SH_LEVELNOD.

src/cmd/ksh93/sh/xec.c:
- Get rid of 'struct Level' and its maxlevel member. This was only
  used in put_level() to check for an out of range assignment, but
  this can be trivially done by checking sh.fn_depth+sh.dot_depth.
- This in turn allows further simplification that reduces init for
  .sh.level to a single nv_disc() call in sh_debug(), so get rid of
  init_level().
- put_level(): Throw a "level out of range" error if assigned a
  wrong level.
- sh_debug():
  - Turn off the NV_RDONLY (read-only) attribute for SH_LEVELNOD
    while executing the DEBUG trap.
  - Restore the current scope when trap execution is finished.
- sh_funct(): Remove all .sh.level handling. POSIX functions (and
  dot scripts) already handle it in b_dot_cmd(), so sh_funct(),
  which is used by both, is the wrong place to do it.
- sh_funscope(): Update .sh.level for ksh syntax functions here
  instead. Also, do not bother to initialise its discipline here,
  as it can now only be changed in a DEBUG trap.

src/cmd/ksh93/bltins/typeset.c: setall():
- When it's not read-only, ignore all attribute changes for
  .sh.level, as changing the attributes would crash the shell.

src/cmd/ksh93/sh/nvdisc.c: nv_setdisc():
- Ignore all attempts to set a discipline function for .sh.level,
  as doing this would crash the shell.

src/cmd/ksh93/bltins/misc.c: b_dot_cmd():
- Bug fix: also update .sh.level when quitting a dot script.

src/cmd/ksh93/sh/name.c:
- _nv_unset():
  - To avoid an inconsistent state, ignore all attempts to unset
    .sh.level.
  - To avoid undefined behaviour, do not zero np->nvalue.cp if
    attributes for np indicate a non-pointer value (the actual bit
    value of a null pointer is not defined by the standard, so
    there is no guarantee that zeroing .cp will zero .s).
- sh_setscope(): For consistency, always set error_info.id (the
  command name for error messages) to the new scope's cmdname.
  Previously this was only done for two calls of this function.
- nv_name(): Fix a crashing bug by checking that np->nvname is a
  non-null pointer before dereferencing it.

src/cmd/ksh93/include/nval.h:
- The NV_UINT16P macro (which is unsigned NV_INT16P) had a typo in
  it, which went unnoticed for many years because it's not directly
  used (though its bit flags are set and used indirectly). Let's
  fix it anyway and keep it for completeness' sake.
2022-07-13 23:11:18 +02:00
.github/workflows Fix multiple bugs in .sh.match (#455) 2022-02-10 21:04:23 +00:00
bin Another build system overhaul (re: 35672208, 580ff616, 6cc2f6a0) 2022-06-12 05:47:02 +01:00
docs Various minor capitalization and typo fixes (#371) 2021-12-13 01:49:42 +01:00
src Robustify ${.sh.level} scope switching (re: 69d37d5e, e1c41bb2) 2022-07-13 23:11:18 +02:00
.gitignore package: more flat view fixes (re: 336e82f9, aeda3502) 2022-01-07 15:56:15 +00:00
ANNOUNCE Add --functrace shell option (re: 2a835a2d) 2022-06-04 17:27:27 +01:00
COPYRIGHT Fix incorrect typeset -L/-R/-Z on input with spaces (re: bdb99741) 2022-05-26 00:08:45 +01:00
LICENSE.md Top-level documentation tweaks 2021-02-20 23:19:50 +00:00
NEWS Robustify ${.sh.level} scope switching (re: 69d37d5e, e1c41bb2) 2022-07-13 23:11:18 +02:00
README.md Fix a few minor issues (#473) 2022-03-11 21:18:42 +01:00
TODO Release 1.0.0-beta.2 2021-12-17 04:20:04 +01:00

KornShell 93u+m

This repository is used to develop bugfixes to the last stable release (93u+ 2012-08-01) of ksh93, formerly developed by AT&T Software Technology (AST). The sources in this repository were forked from the GitHub AST repository which is no longer under active development.

For user-visible fixes, see NEWS and click on commit messages for full details. For all fixes, see the commit log. To see what's left to fix, see the issue tracker.

Policy

  1. Fixing bugs is main focus of the 1.x series. Major feature development is for future versions (2.x and up).
  2. No major rewrites. No refactoring code that is not fully understood.
  3. No changes in documented behaviour, except if required for compliance with the POSIX shell language standard which David Korn intended for ksh to follow.
  4. No 100% bug compatibility. Broken and undocumented behaviour gets fixed.
  5. No bureaucracy, no formalities. Just fix it, or report it: create issues, send pull requests. Every interested party is invited to contribute.
  6. To help increase everyone's understanding of this code base, fixes and significant changes should be fully documented in commit messages.
  7. Code style varies somewhat in this historic code base. Your changes should match the style of the code surrounding them. Indent with tabs, assuming an 8-space tab width. Opening braces are on a line of their own, at the same indentation level as their corresponding closing brace. Comments always use /*...*/.
  8. Good judgment may override this policy.

Why?

Between 2017 and 2020 there was an ultimately unsuccessful attempt to breathe new life into the KornShell by extensively refactoring the last unstable AST beta version (93v-). While that ksh2020 effort is now abandoned and still has many critical bugs, it also had a lot of bugs fixed. More importantly, the AST issue tracker now contains a lot of documentation on how to fix those bugs, which made it possible to backport many of them to the last stable release instead. This ksh 93u+m reboot now incorporates many of these bugfixes, plus patches from OpenSUSE, Red Hat, and Solaris, as well as many new fixes from the community (1, 2). Though there are many bugs left to fix, we are confident at this point that 93u+m is already the least buggy version of ksh93 ever released. As of late 2021, distributions such as Debian and Slackware have begun to package it as their default version of ksh93.

Build

To build ksh with a custom configuration of features, edit src/cmd/ksh93/SHOPT.sh.

Then cd to the top directory and run:

bin/package make

The compiled binaries are stored in the arch directory, in a subdirectory that corresponds to your architecture. The command bin/package host type outputs the name of this subdirectory.

If you have trouble or want to tune the binaries, you may pass additional compiler and linker flags. It is usually best to export these as environment variables before running bin/package as they could change the name of the build subdirectory of the arch directory, so exporting them is a convenient way to keep them consistent between build and test commands. Note that this system uses CCFLAGS instead of the usual CFLAGS. An example that makes Solaris Studio cc produce a 64-bit binary:

export CCFLAGS="-m64 -O" LDFLAGS="-m64"
bin/package make

Alternatively you can append these to the command, and they will only be used for that command. You can also specify an alternative shell in which to run the build scripts this way. For example:

bin/package make SHELL=/bin/bash CCFLAGS="-O2 -I/opt/local/include" LDFLAGS="-L/opt/local/lib"

Note: Do not add compiler flags that cause the compiler to emit terminal escape codes, such as -fdiagnostics-color=always; this will cause the build to fail as the probing code greps compiler diagnostics.

For more information run

bin/package help

Many other commands in this repo self-document via the --help, --man and --html options; those that do have no separate manual page.

Test

After compiling, you can run the regression tests. To run the default test sets for ksh and the build system, use:

bin/package test

For ksh, use the shtests command directly to control the regression test runs. Start by reading the information printed by:

bin/shtests --man

Install

Automated installation is not supported yet. To install manually:

cp arch/$(bin/package host type)/bin/ksh /usr/local/bin/
cp src/cmd/ksh93/sh.1 /usr/local/share/man/man1/ksh.1

(adapting the destination directories as required).

What is ksh93?

The following is the official AT&T description from 1993 that came with the ast-open distribution. The text is original, but hyperlinks were added here.


KSH-93 is the most recent version of the KornShell Language described in "The KornShell Command and Programming Language," by Morris Bolsky and David Korn of AT&T Bell Laboratories, ISBN 0-13-182700-6. The KornShell is a shell programming language, which is upward compatible with "sh" (the Bourne Shell), and is intended to conform to the IEEE P1003.2/ISO 9945.2 Shell and Utilities standard. KSH-93 provides an enhanced programming environment in addition to the major command-entry features of the BSD shell "csh". With KSH-93, medium-sized programming tasks can be performed at shell-level without a significant loss in performance. In addition, "sh" scripts can be run on KSH-93 without modification.

The code should conform to the IEEE POSIX 1003.1 standard and to the proposed ANSI C standard so that it should be portable to all such systems. Like the previous version, KSH-88, it is designed to accept eight bit character sets transparently, thereby making it internationally compatible. It can support multi-byte characters sets with some characteristics of the character set given at run time.

KSH-93 provides the following features, many of which were also inherent in KSH-88:

  • Enhanced Command Re-entry Capability: The KSH-93 history function records commands entered at any shell level and stores them, up to a user-specified limit, even after you log off. This allows you to re-enter long commands with a few keystrokes - even those commands you entered yesterday. The history file allows for eight bit characters in commands and supports essentially unlimited size histories.
  • In-line Editing: In "sh", the only way to fix mistyped commands is to backspace or retype the line. KSH-93 allows you to edit a command line using a choice of EMACS-TC or "vi" functions. You can use the in-line editors to complete filenames as you type them. You may also use this editing feature when entering command lines from your history file. A user can capture keystrokes and rebind keys to customize the editing interface.
  • Extended I/O Capabilities: KSH-93 provides several I/O capabilities not available in "sh", including the ability to:
    • specify a file descriptor for input and output
    • start up and run co-processes
    • produce a prompt at the terminal before a read
    • easily format and interpret responses to a menu
    • echo lines exactly as output without escape processing
    • format output using printf formats.
    • read and echo lines ending in "\".
  • Improved performance: KSH-93 executes many scripts faster than the System V Bourne shell. A major reason for this is that many of the standard utilities are built-in. To reduce the time to initiate a command, KSH-93 allows commands to be added as built-ins at run time on systems that support dynamic loading such as System V Release 4.
  • Arithmetic: KSH-93 allows you to do integer arithmetic in any base from two to sixty-four. You can also do double precision floating point arithmetic. Almost the complete set of C language operators are available with the same syntax and precedence. Arithmetic expressions can be used to as an argument expansion or as a separate command. In addition, there is an arithmetic for command that works like the for statement in C.
  • Arrays: KSH-93 supports both indexed and associative arrays. The subscript for an indexed array is an arithmetic expression, whereas, the subscript for an associative array is a string.
  • Shell Functions and Aliases: Two mechanisms - functions and aliases - can be used to assign a user-selected identifier to an existing command or shell script. Functions allow local variables and provide scoping for exception handling. Functions can be searched for and loaded on first reference the way scripts are.
  • Substring Capabilities: KSH-93 allows you to create a substring of any given string either by specifying the starting offset and length, or by stripping off leading or trailing substrings during parameter substitution. You can also specify attributes, such as upper and lower case, field width, and justification to shell variables.
  • More pattern matching capabilities: KSH-93 allows you to specify extended regular expressions for file and string matches.
  • KSH-93 uses a hierarchical name space for variables. Compound variables can be defined and variables can be passed by reference. In addition, each variable can have one or more disciplines associated with it to intercept assignments and references.
  • Improved debugging: KSH-93 can generate line numbers on execution traces. Also, I/O redirections are now traced. There is a DEBUG trap that gets evaluated before each command so that errors can be localized.
  • Job Control: On systems that support job control, including System V Release 4, KSH-93 provides a job-control mechanism almost identical to that of the BSD "csh", version 4.1. This feature allows you to stop and restart programs, and to move programs between the foreground and the background.
  • Added security: KSH-93 can execute scripts which do not have read permission and scripts which have the setuid and/or setgid set when invoked by name, rather than as an argument to the shell. It is possible to log or control the execution of setuid and/or setgid scripts. The noclobber option prevents you from accidentally erasing a file by redirecting to an existing file.
  • KSH-93 can be extended by adding built-in commands at run time. In addition, KSH-93 can be used as a library that can be embedded into an application to allow scripting.

Documentation for KSH-93 consists of an "Introduction to KSH-93", "Compatibility with the Bourne Shell" and a manual page and a README file. In addition, the "New KornShell Command and Programming Language" book is available from Prentice Hall.