# Binary formats and compatibility

---

# Kernel Support for miscellaneous Binary Formats (binfmt_misc)

_Peios Kernel / Administration / System administration / Binary formats and compatibility_

> This Kernel feature allows you to invoke almost (for restrictions see below) every program by simply typing its name in the shell. This includes for example compiled Java(TM), Python or Emacs programs.

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-kernel-support-for-miscellaneous-binary-formats-binfmt-misc"></a>

This Kernel feature allows you to invoke almost (for restrictions see below) every program by simply typing its name in the shell. This includes for example compiled Java(TM), Python or Emacs programs.

To achieve this you must tell binfmt_misc which interpreter has to be invoked with which binary. Binfmt_misc recognises the binary-type by matching some bytes at the beginning of the file with a magic byte sequence (masking out specified bits) you have supplied. Binfmt_misc can also recognise a filename extension aka `.com` or `.exe`.

First you must mount binfmt_misc:



```text
mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc
```

To actually register a new binary type, you have to set up a string looking like `:name:type:offset:magic:mask:interpreter:flags` (where you can choose the `:` upon your needs) and echo it to `/proc/sys/fs/binfmt_misc/register`.

Here is what the fields mean:

- - **`name`**

    is an identifier string. A new /proc file will be created with this name below `/proc/sys/fs/binfmt_misc`; cannot contain slashes `/` for obvious reasons.

- - **`type`**

    is the type of recognition. Give `M` for magic and `E` for extension.

- - **`offset`**

    is the offset of the magic/mask in the file, counted in bytes. This defaults to 0 if you omit it (i.e. you write `:name:type::magic...`). Ignored when using filename extension matching.

- - **`magic`**

    is the byte sequence binfmt_misc is matching for. The magic string may contain hex-encoded characters like `\x0a` or `\xA4`. Note that you must escape any NUL bytes; parsing halts at the first one. In a shell environment you might have to write `\\x0a` to prevent the shell from eating your `\`. If you chose filename extension matching, this is the extension to be recognised (without the `.`, the `\x0a` specials are not allowed). Extension    matching is case sensitive, and slashes `/` are not allowed\!

- - **`mask`**

    is an (optional, defaults to all 0xff) mask. You can mask out some bits from matching by supplying a string like magic and as long as magic. The mask is anded with the byte sequence of the file. Note that you must escape any NUL bytes; parsing halts at the first one. Ignored when using filename extension matching.

- - **`interpreter`**

    is the program that should be invoked with the binary as first argument (specify the full path)

- - **`flags`**

    is an optional field that controls several aspects of the invocation of the interpreter. It is a string of capital letters, each controls a certain aspect. The following flags are supported:

    > - **`P` - preserve-argv\[0\]**
    >
    >   Legacy behavior of binfmt_misc is to overwrite the original argv\[0\] with the full path to the binary. When this flag is included, binfmt_misc will add an argument to the argument vector for this purpose, thus preserving the original `argv[0]`. e.g. If your interp is set to `/bin/foo` and you run `blah` (which is in `/usr/local/bin`), then the kernel will execute `/bin/foo` with `argv[]` set to `["/bin/foo", "/usr/local/bin/blah", "blah"]`.  The interp has to be aware of this so it can execute `/usr/local/bin/blah` with `argv[]` set to `["blah"]`.
    >
    > - **`O` - open-binary**
    >
    >   Legacy behavior of binfmt_misc is to pass the full path of the binary to the interpreter as an argument. When this flag is included, binfmt_misc will open the file for reading and pass its descriptor as an argument, instead of the full path, thus allowing the interpreter to execute non-readable binaries. This feature should be used with care - the interpreter has to be trusted not to emit the contents of the non-readable binary.
    >
    > - **`C` - credentials**
    >
    >   Currently, the behavior of binfmt_misc is to calculate the credentials and security token of the new process according to the interpreter. When this flag is included, these attributes are calculated according to the binary. It also implies the `O` flag. In upstream Linux this can cause a root-owned set-user-ID binary to run its interpreter with elevated Unix credentials. In Peios, it does not mint native token authority; exec access, signing/PIP and PSB rules still apply.
    >
    > - **`F` - fix binary**
    >
    >   The usual behaviour of binfmt_misc is to spawn the binary lazily when the misc format file is invoked.  However, this doesn't work very well in the face of mount namespaces and changeroots, so the `F` mode opens the binary as soon as the emulation is installed and uses the opened image to spawn the emulator, meaning it is always available once installed, regardless of how the environment changes.

There are some restrictions:

> - the whole register string may not exceed 1920 characters
>
> - the magic must reside in the first 128 bytes of the file, i.e. offset+size(magic) has to be less than 128
>
> - the interpreter string may not exceed 127 characters

To use binfmt_misc you have to mount it first. You can mount it with `mount -t binfmt_misc none /proc/sys/fs/binfmt_misc` command, or you can add a line `none  /proc/sys/fs/binfmt_misc binfmt_misc defaults 0 0` to your `/etc/fstab` so it auto mounts on boot.

You may want to add the binary formats in one of your `/etc/rc` scripts during boot-up. Read the manual of your init program to figure out how to do this right.

Think about the order of adding entries\! Later added entries are matched first\!

A few examples (assumed you are in `/proc/sys/fs/binfmt_misc`):

- enable support for em86 (like binfmt_em86, for Alpha AXP only):



  ```text
  echo ':i386:M::\x7fELF\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x03:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff:/bin/em86:' > register
  echo ':i486:M::\x7fELF\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x06:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff:/bin/em86:' > register
  ```

- enable support for packed DOS applications (pre-configured dosemu hdimages):



  ```text
  echo ':DEXE:M::\x0eDEX::/usr/bin/dosexec:' > register
  ```

- enable support for Windows executables using wine:



  ```text
  echo ':DOSWin:M::MZ::/usr/local/bin/wine:' > register
  ```

For java support see [Documentation/admin-guide/java.rst](/kernel/administration/admin-guide/compatibility/java.md)

You can enable/disable binfmt_misc or one binary type by echoing 0 (to disable) or 1 (to enable) to `/proc/sys/fs/binfmt_misc/status` or `/proc/.../the_name`. Catting the file tells you the current status of `binfmt_misc/the_entry`.

You can remove one entry or all entries by echoing -1 to `/proc/.../the_name` or `/proc/sys/fs/binfmt_misc/status`.

<a id="rst-hints"></a>

## Hints

If you want to pass special arguments to your interpreter, you can write a wrapper script for it. See [Documentation/admin-guide/java.rst](</kernel/administration/admin-guide/compatibility/java.md>) for an example.

Your interpreter should NOT look in the PATH for the filename; the kernel passes it the full filename (or the file descriptor) to use.  Using `$PATH` can cause unexpected behaviour and can be a security hazard.

Richard Günther &lt;[rguenth@tat.physik.uni-tuebingen.de](<mailto:rguenth@tat.physik.uni-tuebingen.de>)&gt;

---

# Java(tm) Binary Kernel Support for Linux v1.03

_Peios Kernel / Administration / System administration / Binary formats and compatibility_

> Linux beats them ALL! While all other OS's are TALKING about direct support of Java Binaries in the OS, Linux is doing it!

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


<a id="rst-java-tm-binary-kernel-support-for-linux-v1-03"></a>

Linux beats them ALL\! While all other OS's are TALKING about direct support of Java Binaries in the OS, Linux is doing it\!

You can execute Java applications and Java Applets just like any other program after you have done the following:

1. You MUST FIRST install the Java Developers Kit for Linux. The Java on Linux HOWTO gives the details on getting and installing this. This HOWTO can be found at:

   > [ftp://sunsite.unc.edu/pub/Linux/docs/HOWTO/Java-HOWTO](<ftp://sunsite.unc.edu/pub/Linux/docs/HOWTO/Java-HOWTO>)

   You should also set up a reasonable CLASSPATH environment variable to use Java applications that make use of any nonstandard classes (not included in the same directory as the application itself).

2. You have to compile BINFMT_MISC either as a module or into the kernel (`CONFIG_BINFMT_MISC`) and set it up properly. If you choose to compile it as a module, you will have to insert it manually with modprobe/insmod, as kmod cannot easily be supported with binfmt_misc. Read the file 'binfmt_misc.txt' in this directory to know more about the configuration process.

3. Add the following configuration items to binfmt_misc (you should really have read `binfmt_misc.txt` now): support for Java applications:



   ```text
   ':Java:M::\xca\xfe\xba\xbe::/usr/local/bin/javawrapper:'
   ```

   support for executable Jar files:



   ```text
   ':ExecutableJAR:E::jar::/usr/local/bin/jarwrapper:'
   ```

   support for Java Applets:



   ```text
   ':Applet:E::html::/usr/bin/appletviewer:'
   ```

   or the following, if you want to be more selective:



   ```text
   ':Applet:M::<!--applet::/usr/bin/appletviewer:'
   ```

   Of course you have to fix the path names. The path/file names given in this document match the Debian 2.1 system. (i.e. jdk installed in `/usr`, custom wrappers from this document in `/usr/local`)

   Note, that for the more selective applet support you have to modify existing html-files to contain `<!--applet-->` in the first line (`<` has to be the first character\!) to let this work\!

   For the compiled Java programs you need a wrapper script like the following (this is because Java is broken in case of the filename handling), again fix the path names, both in the script and in the above given configuration string.

   You, too, need the little program after the script. Compile like:



   ```text
   gcc -O2 -o javaclassname javaclassname.c
   ```

   and stick it to `/usr/local/bin`.

   Both the javawrapper shellscript and the javaclassname program were supplied by Colin J. Watson &lt;[cjw44@cam.ac.uk](<mailto:cjw44@cam.ac.uk>)&gt;.

Javawrapper shell script:



```sh
#!/bin/bash
# /usr/local/bin/javawrapper - the wrapper for binfmt_misc/java

if [ -z "$1" ]; then
      exec 1>&2
      echo Usage: $0 class-file
      exit 1
fi

CLASS=$1
FQCLASS=`/usr/local/bin/javaclassname $1`
FQCLASSN=`echo $FQCLASS | sed -e 's/^.*\.\([^.]*\)$/\1/'`
FQCLASSP=`echo $FQCLASS | sed -e 's-\.-/-g' -e 's-^[^/]*$--' -e 's-/[^/]*$--'`

# for example:
# CLASS=Test.class
# FQCLASS=foo.bar.Test
# FQCLASSN=Test
# FQCLASSP=foo/bar

unset CLASSBASE

declare -i LINKLEVEL=0

while :; do
      if [ "`basename $CLASS .class`" == "$FQCLASSN" ]; then
              # See if this directory works straight off
              cd -L `dirname $CLASS`
              CLASSDIR=$PWD
              cd $OLDPWD
              if echo $CLASSDIR | grep -q "$FQCLASSP$"; then
                      CLASSBASE=`echo $CLASSDIR | sed -e "s.$FQCLASSP$.."`
                      break;
              fi
              # Try dereferencing the directory name
              cd -P `dirname $CLASS`
              CLASSDIR=$PWD
              cd $OLDPWD
              if echo $CLASSDIR | grep -q "$FQCLASSP$"; then
                      CLASSBASE=`echo $CLASSDIR | sed -e "s.$FQCLASSP$.."`
                      break;
              fi
              # If no other possible filename exists
              if [ ! -L $CLASS ]; then
                      exec 1>&2
                      echo $0:
                      echo "  $CLASS should be in a" \
                           "directory tree called $FQCLASSP"
                      exit 1
              fi
      fi
      if [ ! -L $CLASS ]; then break; fi
      # Go down one more level of symbolic links
      let LINKLEVEL+=1
      if [ $LINKLEVEL -gt 5 ]; then
              exec 1>&2
              echo $0:
              echo "  Too many symbolic links encountered"
              exit 1
      fi
      CLASS=`ls --color=no -l $CLASS | sed -e 's/^.* \([^ ]*\)$/\1/'`
done

if [ -z "$CLASSBASE" ]; then
      if [ -z "$FQCLASSP" ]; then
              GOODNAME=$FQCLASSN.class
      else
              GOODNAME=$FQCLASSP/$FQCLASSN.class
      fi
      exec 1>&2
      echo $0:
      echo "  $FQCLASS should be in a file called $GOODNAME"
      exit 1
fi

if ! echo $CLASSPATH | grep -q "^\(.*:\)*$CLASSBASE\(:.*\)*"; then
      # class is not in CLASSPATH, so prepend dir of class to CLASSPATH
      if [ -z "${CLASSPATH}" ] ; then
              export CLASSPATH=$CLASSBASE
      else
              export CLASSPATH=$CLASSBASE:$CLASSPATH
      fi
fi

shift
/usr/bin/java $FQCLASS "$@"
```

javaclassname.c:



```c
/* javaclassname.c
 *
 * Extracts the class name from a Java class file; intended for use in a Java
 * wrapper of the type supported by the binfmt_misc option in the Linux kernel.
 *
 * Copyright (C) 1999 Colin J. Watson <cjw44@cam.ac.uk>.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <sys/types.h>

/* From Sun's Java VM Specification, as tag entries in the constant pool. */

#define CP_UTF8 1
#define CP_INTEGER 3
#define CP_FLOAT 4
#define CP_LONG 5
#define CP_DOUBLE 6
#define CP_CLASS 7
#define CP_STRING 8
#define CP_FIELDREF 9
#define CP_METHODREF 10
#define CP_INTERFACEMETHODREF 11
#define CP_NAMEANDTYPE 12
#define CP_METHODHANDLE 15
#define CP_METHODTYPE 16
#define CP_INVOKEDYNAMIC 18

/* Define some commonly used error messages */

#define seek_error() error("%s: Cannot seek\n", program)
#define corrupt_error() error("%s: Class file corrupt\n", program)
#define eof_error() error("%s: Unexpected end of file\n", program)
#define utf8_error() error("%s: Only ASCII 1-255 supported\n", program);

char *program;

long *pool;

u_int8_t read_8(FILE *classfile);
u_int16_t read_16(FILE *classfile);
void skip_constant(FILE *classfile, u_int16_t *cur);
void error(const char *format, ...);
int main(int argc, char **argv);

/* Reads in an unsigned 8-bit integer. */
u_int8_t read_8(FILE *classfile)
{
      int b = fgetc(classfile);
      if(b == EOF)
              eof_error();
      return (u_int8_t)b;
}

/* Reads in an unsigned 16-bit integer. */
u_int16_t read_16(FILE *classfile)
{
      int b1, b2;
      b1 = fgetc(classfile);
      if(b1 == EOF)
              eof_error();
      b2 = fgetc(classfile);
      if(b2 == EOF)
              eof_error();
      return (u_int16_t)((b1 << 8) | b2);
}

/* Reads in a value from the constant pool. */
void skip_constant(FILE *classfile, u_int16_t *cur)
{
      u_int16_t len;
      int seekerr = 1;
      pool[*cur] = ftell(classfile);
      switch(read_8(classfile))
      {
      case CP_UTF8:
              len = read_16(classfile);
              seekerr = fseek(classfile, len, SEEK_CUR);
              break;
      case CP_CLASS:
      case CP_STRING:
      case CP_METHODTYPE:
              seekerr = fseek(classfile, 2, SEEK_CUR);
              break;
      case CP_METHODHANDLE:
              seekerr = fseek(classfile, 3, SEEK_CUR);
              break;
      case CP_INTEGER:
      case CP_FLOAT:
      case CP_FIELDREF:
      case CP_METHODREF:
      case CP_INTERFACEMETHODREF:
      case CP_NAMEANDTYPE:
      case CP_INVOKEDYNAMIC:
              seekerr = fseek(classfile, 4, SEEK_CUR);
              break;
      case CP_LONG:
      case CP_DOUBLE:
              seekerr = fseek(classfile, 8, SEEK_CUR);
              ++(*cur);
              break;
      default:
              corrupt_error();
      }
      if(seekerr)
              seek_error();
}

void error(const char *format, ...)
{
      va_list ap;
      va_start(ap, format);
      vfprintf(stderr, format, ap);
      va_end(ap);
      exit(1);
}

int main(int argc, char **argv)
{
      FILE *classfile;
      u_int16_t cp_count, i, this_class, classinfo_ptr;
      u_int8_t length;

      program = argv[0];

      if(!argv[1])
              error("%s: Missing input file\n", program);
      classfile = fopen(argv[1], "rb");
      if(!classfile)
              error("%s: Error opening %s\n", program, argv[1]);

      if(fseek(classfile, 8, SEEK_SET))  /* skip magic and version numbers */
              seek_error();
      cp_count = read_16(classfile);
      pool = calloc(cp_count, sizeof(long));
      if(!pool)
              error("%s: Out of memory for constant pool\n", program);

      for(i = 1; i < cp_count; ++i)
              skip_constant(classfile, &i);
      if(fseek(classfile, 2, SEEK_CUR))       /* skip access flags */
              seek_error();

      this_class = read_16(classfile);
      if(this_class < 1 || this_class >= cp_count)
              corrupt_error();
      if(!pool[this_class] || pool[this_class] == -1)
              corrupt_error();
      if(fseek(classfile, pool[this_class] + 1, SEEK_SET))
              seek_error();

      classinfo_ptr = read_16(classfile);
      if(classinfo_ptr < 1 || classinfo_ptr >= cp_count)
              corrupt_error();
      if(!pool[classinfo_ptr] || pool[classinfo_ptr] == -1)
              corrupt_error();
      if(fseek(classfile, pool[classinfo_ptr] + 1, SEEK_SET))
              seek_error();

      length = read_16(classfile);
      for(i = 0; i < length; ++i)
      {
              u_int8_t x = read_8(classfile);
              if((x & 0x80) || !x)
              {
                      if((x & 0xE0) == 0xC0)
                      {
                              u_int8_t y = read_8(classfile);
                              if((y & 0xC0) == 0x80)
                              {
                                      int c = ((x & 0x1f) << 6) + (y & 0x3f);
                                      if(c) putchar(c);
                                      else utf8_error();
                              }
                              else utf8_error();
                      }
                      else utf8_error();
              }
              else if(x == '/') putchar('.');
              else putchar(x);
      }
      putchar('\n');
      free(pool);
      fclose(classfile);
      return 0;
}
```

jarwrapper:



```text
#!/bin/bash
# /usr/local/java/bin/jarwrapper - the wrapper for binfmt_misc/jar

java -jar $1
```

Now simply `chmod +x` the `.class`, `.jar` and/or `.html` files you want to execute.

To add a Java program to your path best put a symbolic link to the main .class file into /usr/bin (or another place you like) omitting the .class extension. The directory containing the original .class file will be added to your CLASSPATH during execution.

To test your new setup, enter in the following simple Java app, and name it "HelloWorld.java":



```java
class HelloWorld {
        public static void main(String args[]) {
                System.out.println("Hello World!");
        }
}
```

Now compile the application with:



```text
javac HelloWorld.java
```

Set the executable permissions of the binary file, with:



```text
chmod 755 HelloWorld.class
```

And then execute it:



```text
./HelloWorld.class
```

To execute Java Jar files, simple chmod the `*.jar` files to include the execution bit, then just do:



```text
./Application.jar
```

To execute Java Applets, simple chmod the `*.html` files to include the execution bit, then just do:



```text
./Applet.html
```

originally by Brian A. Lantz, [brian@lantz.com](<mailto:brian@lantz.com>) heavily edited for binfmt_misc by Richard Günther new scripts by Colin J. Watson &lt;[cjw44@cam.ac.uk](<mailto:cjw44@cam.ac.uk>)&gt; added executable Jar file support by Kurt Huwig &lt;[kurt@iku-netz.de](<mailto:kurt@iku-netz.de>)&gt;

---

# Mono(tm) Binary Kernel Support for Linux

_Peios Kernel / Administration / System administration / Binary formats and compatibility_

> To configure Linux to automatically execute Mono-based .NET binaries (in the form of .exe files) without the need to use the mono CLR wrapper, you can use the BINFMT_MISC kernel support.

<a id="rst-mono-tm-binary-kernel-support-for-linux"></a>

To configure Linux to automatically execute Mono-based .NET binaries (in the form of .exe files) without the need to use the mono CLR wrapper, you can use the BINFMT_MISC kernel support.

This will allow you to execute Mono-based .NET binaries just like any other program after you have done the following:

1. You MUST FIRST install the Mono CLR support, either by downloading a binary package, a source tarball or by installing from Git. Binary packages for several distributions can be found at:

   > [https://www.mono-project.com/download/](<https://www.mono-project.com/download/>)

   Instructions for compiling Mono can be found at:

   > [https://www.mono-project.com/docs/compiling-mono/linux/](<https://www.mono-project.com/docs/compiling-mono/linux/>)

   Once the Mono CLR support has been installed, just check that `/usr/bin/mono` (which could be located elsewhere, for example `/usr/local/bin/mono`) is working.

2. You have to compile BINFMT_MISC either as a module or into the kernel (`CONFIG_BINFMT_MISC`) and set it up properly. If you choose to compile it as a module, you will have to insert it manually with modprobe/insmod, as kmod cannot be easily supported with binfmt_misc. Read the file `binfmt_misc.txt` in this directory to know more about the configuration process.

3. Add the following entries to `/etc/rc.local` or similar script to be run at system startup:



   ```sh
   # Insert BINFMT_MISC module into the kernel
   if [ ! -e /proc/sys/fs/binfmt_misc/register ]; then
       /sbin/modprobe binfmt_misc
       # Some distributions, like Fedora Core, perform
       # the following command automatically when the
       # binfmt_misc module is loaded into the kernel
       # or during normal boot up (systemd-based systems).
       # Thus, it is possible that the following line
       # is not needed at all.
       mount -t binfmt_misc none /proc/sys/fs/binfmt_misc
   fi

   # Register support for .NET CLR binaries
   if [ -e /proc/sys/fs/binfmt_misc/register ]; then
       # Replace /usr/bin/mono with the correct pathname to
       # the Mono CLR runtime (usually /usr/local/bin/mono
       # when compiling from sources or CVS).
       echo ':CLR:M::MZ::/usr/bin/mono:' > /proc/sys/fs/binfmt_misc/register
   else
       echo "No binfmt_misc support"
       exit 1
   fi
   ```

4. Check that `.exe` binaries can be ran without the need of a wrapper script, simply by launching the `.exe` file directly from a command prompt, for example:



   ```text
   /usr/bin/xsd.exe
   ```

   > [!NOTE]
   >
   > If this fails with a permission denied error, check that the `.exe` file has execute permissions.

---

# Syscall User Dispatch

_Peios Kernel / Administration / System administration / Binary formats and compatibility_

> Compatibility layers like Wine need a way to efficiently emulate system calls of only a part of their process - the part that has the incompatible code - while being able to execute native syscalls without a high performance penalty on the…

<a id="rst-syscall-user-dispatch"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-background"></a>

## Background

Compatibility layers like Wine need a way to efficiently emulate system calls of only a part of their process - the part that has the incompatible code - while being able to execute native syscalls without a high performance penalty on the native part of the process.  Seccomp falls short on this task, since it has limited support to efficiently filter syscalls based on memory regions, and it doesn't support removing filters.  Therefore a new mechanism is necessary.

Syscall User Dispatch brings the filtering of the syscall dispatcher address back to userspace.  The application is in control of a flip switch, indicating the current personality of the process.  A multiple-personality application can then flip the switch without invoking the kernel, when crossing the compatibility layer API boundaries, to enable/disable the syscall redirection and execute syscalls directly (disabled) or send them to be emulated in userspace through a SIGSYS.

The goal of this design is to provide very quick compatibility layer boundary crosses, which is achieved by not executing a syscall to change personality every time the compatibility layer executes.  Instead, a userspace memory region exposed to the kernel indicates the current personality, and the application simply modifies that variable to configure the mechanism.

There is a relatively high cost associated with handling signals on most architectures, like x86, but at least for Wine, syscalls issued by native Windows code are currently not known to be a performance problem, since they are quite rare, at least for modern gaming applications.

Since this mechanism is designed to capture syscalls issued by non-native applications, it must function on syscalls whose invocation ABI is completely unexpected to Linux.  Syscall User Dispatch, therefore doesn't rely on any of the syscall ABI to make the filtering.  It uses only the syscall dispatcher address and the userspace key.

As the ABI of these intercepted syscalls is unknown to Linux, these syscalls are not instrumentable via ptrace or the syscall tracepoints.

<a id="rst-interface"></a>

## Interface

A thread can setup this mechanism on supported kernels by executing the following prctl:

> prctl(PR_SET_SYSCALL_USER_DISPATCH, &lt;op&gt;, &lt;offset&gt;, &lt;length&gt;, \[selector\])

&lt;op&gt; is either PR_SYS_DISPATCH_EXCLUSIVE_ON/PR_SYS_DISPATCH_INCLUSIVE_ON or PR_SYS_DISPATCH_OFF, to enable and disable the mechanism globally for that thread.  When PR_SYS_DISPATCH_OFF is used, the other fields must be zero.

For PR_SYS_DISPATCH_EXCLUSIVE_ON \[&lt;offset&gt;, &lt;offset&gt;+&lt;length&gt;) delimit a memory region interval from which syscalls are always executed directly, regardless of the userspace selector.  This provides a fast path for the C library, which includes the most common syscall dispatchers in the native code applications, and also provides a way for the signal handler to return without triggering a nested SIGSYS on (rt\_)sigreturn.  Users of this interface should make sure that at least the signal trampoline code is included in this region. In addition, for syscalls that implement the trampoline code on the vDSO, that trampoline is never intercepted.

For PR_SYS_DISPATCH_INCLUSIVE_ON \[&lt;offset&gt;, &lt;offset&gt;+&lt;length&gt;) delimit a memory region interval from which syscalls are dispatched based on the userspace selector. Syscalls from outside of the range are always executed directly.

\[selector\] is a pointer to a char-sized region in the process memory region, that provides a quick way to enable disable syscall redirection thread-wide, without the need to invoke the kernel directly.  selector can be set to SYSCALL_DISPATCH_FILTER_ALLOW or SYSCALL_DISPATCH_FILTER_BLOCK. Any other value should terminate the program with a SIGSYS.

Additionally, a tasks syscall user dispatch configuration can be peeked and poked via the PTRACE\_(GET\|SET)\_SYSCALL_USER_DISPATCH_CONFIG ptrace requests. This is useful for checkpoint/restart software.

<a id="rst-security-notes"></a>

## Security Notes

Syscall User Dispatch provides functionality for compatibility layers to quickly capture system calls issued by a non-native part of the application, while not impacting the Linux native regions of the process.  It is not a mechanism for sandboxing system calls, and it should not be seen as a security mechanism, since it is trivial for a malicious application to subvert the mechanism by jumping to an allowed dispatcher region prior to executing the syscall, or to discover the address and modify the selector value.  If the use case requires any kind of security sandboxing, Seccomp should be used instead.

Any fork or exec of the existing process resets the mechanism to PR_SYS_DISPATCH_OFF.
