diff --git a/.gitattributes b/.gitattributes index b6c1a288..17dd0bdd 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,3 +4,23 @@ ci_*.sh text eol=lf .github/workflows/*.yml text eol=lf test/** binary diff +scripts/*.sh text eol=lf +build/Containerfile text eol=lf +tests/lfn/*.sh text eol=lf +tests/mdvmm/*.sh text eol=lf +tests/uefi/*.sh text eol=lf +mdvmm/** text eol=lf +release/*.sh text eol=lf +tests/iso/*.sh text eol=lf +gui/** text eol=lf +tests/gui/*.py text eol=lf +build/*.sh text eol=lf +tests/net/*.sh text eol=lf +tests/ssh/*.sh text eol=lf +net/** text eol=lf +tests/usb/*.sh text eol=lf +tests/install/*.sh text eol=lf +tests/install/*.py text eol=lf +mdvmm/ipxe/** text eol=lf +tests/pkg/*.sh text eol=lf +net/pkg/*.sh text eol=lf diff --git a/.gitignore b/.gitignore index fb8a43e0..7d5949d2 100644 --- a/.gitignore +++ b/.gitignore @@ -58,3 +58,15 @@ _downloads/** _output/** _watcom/** kernel/exeflat.rsp + +# modernDOS build/test artifacts +test/*.img +test/fdconfig.sys +test/result.txt + +# MDVMM build output +mdvmm/build/ +gui/build/ +net/ssh/build/ +net/pkg/build/ +__pycache__/ diff --git a/.gitmodules b/.gitmodules index 77e0176b..bc3b69e2 100644 --- a/.gitmodules +++ b/.gitmodules @@ -5,3 +5,4 @@ [submodule "country"] path = country url = https://github.com/FDOS/country.git + ignore = untracked diff --git a/README.md b/README.md index 23e905a5..4ff2e304 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,54 @@ +modernDOS +========= + +**DOS, reimagined as if it never faded.** modernDOS is a fork of the FreeDOS kernel that imagines DOS kept evolving for 40 years: an original desktop GUI, modern native and networked applications, and booting on modern UEFI PCs. Every existing DOS program keeps working. + +### Compatibility contract +INT 21h, INT 2Fh, program loading (EXEC) and the DOS version numbers reported by INT 21h/30h are frozen. New features are added on top of them and never change their existing behavior. + +### Editions + +- **UEFI** (`modernDOS-.iso`, CD or USB stick): for current + machines. The monitor brings its own BIOS and drivers (AHCI, NVMe, USB, + graphics). +- **BIOS** (`modernDOS--bios.img`, a disk image for a USB stick + or hard disk): for older machines; disks, screen and keyboard go through + the machine's BIOS. The ISO also boots a small floppy image from CD on a + BIOS. + +Both install on the machine's disk: the UEFI loader offers it (personal +images), the BIOS edition has `INSTALL` (FDISK, FORMAT, SYS and a copy). + +Both have the same monitor, network card drivers (iPXE's), SSH, package +manager and desktop with the browser. + +## Roadmap +| # | Milestone | Status | +|---|---|---| +| M1 | Kernel modernization: reproducible container build, QEMU boot tests, native long-filename (LFN) API in the kernel (`docs/lfnapi.txt`) | done | +| M2 | MDVMM supervisor: 32-bit V86 monitor + DPMI host, multiple DOS sessions (`docs/mdvmm.md`) | done | +| M3 | UEFI boot with native drivers (GOP display, AHCI/NVMe disks, USB input) | done: DOS boots on UEFI with a virtual BIOS, XMS, DPMI, sessions, AHCI/NVMe disks, USB keyboards (`docs/mdvmm.md`) | +| M4 | Original desktop GUI + widget toolkit (32-bit DPMI) | done: VBE graphics, mouse, window manager, widget toolkit, desktop shell MDDESK on both boot paths (`docs/gui.md`) | +| M5 | Native apps: file manager, editor, settings, terminal (DOS session in a window) | done: file manager, text editor, settings, terminal (`docs/apps.md`) | +| M6 | Networking: TCP/IP, sockets API, package manager, browser | done (first versions): network cards through iPXE's drivers, packet driver, Watt-32 TCP/IP and sockets, SSH server and client (shell, sftp, scp), install on a disk and remote updates, package manager `PKG` with signed repositories, a text-layout web browser in the desktop (http only) (`docs/network.md`, `docs/apps.md`) | + +### Trying it +Releases have a bootable ISO (alpha, tested in QEMU only): write it to a +USB stick with a raw image writer and boot a UEFI PC with Secure Boot +off, or boot it from CD on a BIOS PC. See `release/README.TXT`. + +### Building (Linux, needs podman) +``` +scripts/mdbuild.sh # builds the GCC (reference) and Open Watcom kernels, MDVMM.COM, BOOTX64.EFI, mdgui +scripts/mkiso.sh # the release ISO: _output/release/modernDOS-.iso +scripts/mdtest.sh # QEMU: boot tests, LFN API + DJGPP libc, MDVMM (DPMI, sessions, graphics), UEFI boot, + # USB, network, SSH, install and update, ISO +``` + +The upstream FreeDOS README follows. + +--- + fd kernel ========= diff --git a/build/Containerfile b/build/Containerfile new file mode 100644 index 00000000..d756eee7 --- /dev/null +++ b/build/Containerfile @@ -0,0 +1,73 @@ +# modernDOS build/test environment +# Mirrors the cross-build parts of ci_prereq.sh (no dosemu / DOS-hosted builds). +FROM docker.io/library/ubuntu:24.04 + +ENV DEBIAN_FRONTEND=noninteractive + +RUN apt-get update \ + && apt-get install -y --no-install-recommends software-properties-common gpg-agent ca-certificates \ + && add-apt-repository -y ppa:tkchia/build-ia16 \ + && apt-get update \ + && apt-get install -y --no-install-recommends \ + gcc libc6-dev gcc-ia16-elf libi86-ia16-elf nasm upx-ucl make git python3 \ + qemu-system-x86 mtools dosfstools util-linux bash procps coreutils \ + curl xz-utils bzip2 unzip gcc-i686-linux-gnu binutils-i686-linux-gnu \ + && rm -rf /var/lib/apt/lists/* + +# Open Watcom v2 (same snapshot upstream CI uses) -> /opt/watcom +RUN mkdir -p /opt/watcom \ + && curl -fsSL https://github.com/open-watcom/open-watcom-v2/releases/download/Current-build/ow-snapshot.tar.xz \ + | tar -C /opt/watcom -xJ +ENV WATCOM=/opt/watcom + +# DJGPP cross compiler (GCC 12.2, build-djgpp v3.4) -> /opt/djgpp +RUN curl -fsSL https://github.com/andrewwutw/build-djgpp/releases/download/v3.4/djgpp-linux64-gcc1220.tar.bz2 \ + | tar -C /opt -xj + +# CWSDPMI r7 DPMI host for running DJGPP programs -> /opt/cwsdpmi +RUN mkdir -p /opt/cwsdpmi && cd /opt/cwsdpmi \ + && curl -fsSL -o csdpmi7b.zip https://www.delorie.com/pub/djgpp/current/v2misc/csdpmi7b.zip \ + && unzip -q csdpmi7b.zip && rm csdpmi7b.zip + +# FreeDOS 1.4 FreeCOM shell, HIMEMX XMS driver, CTMOUSE mouse driver -> /opt/fdos +RUN mkdir -p /opt/fdos && cd /opt/fdos \ + && for p in freecom himemx ctmouse; do \ + curl -fsSL -o $p.zip https://www.ibiblio.org/pub/micro/pc-stuff/freedos/files/repositories/1.4/base/$p.zip \ + && unzip -q -o -LL $p.zip && rm $p.zip; done + +# UEFI firmware for the UEFI boot tests (x64 OVMF), xorriso for the release +# ISO; libfl2 for DJGPP's ar, libslang2-dev for building Watt-32's tools; +# OpenSSH client and server for the SSH tests +RUN apt-get update \ + && apt-get install -y --no-install-recommends ovmf xorriso libfl2 libslang2-dev \ + openssh-client openssh-server \ + && rm -rf /var/lib/apt/lists/* + +# Watt-32 TCP/IP for DJGPP -> /opt/watt32 (pinned, checked; see watt32.sh) +COPY watt32.sh /tmp/watt32/ +COPY watt32/ /tmp/watt32/watt32/ +RUN bash /tmp/watt32/watt32.sh && rm -rf /tmp/watt32 /opt/watt32/bin + +# iPXE source -> /opt/ipxe: the monitor's network card drivers (pinned, +# checked; see ipxe.sh and mdvmm/ipxe) +COPY ipxe.sh /tmp/ +RUN bash /tmp/ipxe.sh && rm /tmp/ipxe.sh + +# BearSSL -> /opt/bearssl: TLS for the browser and the package manager +# (pinned, checked; see bearssl.sh) +COPY bearssl.sh /tmp/ +RUN bash /tmp/bearssl.sh && rm /tmp/bearssl.sh + +# FreeDOS 1.4 FDISK, FORMAT, XCOPY -> /opt/fdos: for the BIOS edition's +# INSTALL (the disk tools on its boot disk) +RUN cd /opt/fdos \ + && for p in fdisk format xcopy; do \ + curl -fsSL -o $p.zip https://www.ibiblio.org/pub/micro/pc-stuff/freedos/files/repositories/1.4/base/$p.zip \ + && unzip -q -o -LL $p.zip && rm $p.zip; done + +# a DOS game for the compatibility tests -> /opt/games (pinned, checked; +# see games.sh) +COPY games.sh /tmp/ +RUN bash /tmp/games.sh && rm /tmp/games.sh + +WORKDIR /src diff --git a/build/bearssl.sh b/build/bearssl.sh new file mode 100755 index 00000000..1e2c0778 --- /dev/null +++ b/build/bearssl.sh @@ -0,0 +1,54 @@ +#!/bin/bash +# Build the BearSSL TLS library into /opt/bearssl (used by the +# Containerfile): TLS 1.2 for the browser and the package manager. +# - the pinned release, checked against its SHA-256 +# - lib/libbearssl.a for DJGPP (DOS programs), lib/host/libbearssl.a for +# the build host (tests) +# - trust_anchors.h: the certificate authorities of the build image's +# ca-certificates package (Mozilla's list), converted with BearSSL's +# own tool +# +# Usage: build/bearssl.sh [tarball] (default: download the pinned one) + +set -e +VERSION=0.6 +SHA256=6705bba1714961b41a728dfc5debbe348d2966c117649392f8c8139efc83ff14 +URL=https://bearssl.org/bearssl-$VERSION.tar.gz +DEST=${BEARSSL_DEST:-/opt/bearssl} +DJ=/opt/djgpp/bin/i586-pc-msdosdjgpp- + +TAR=$1 +if [ -z "$TAR" ]; then + TAR=$(mktemp) + curl -fsSL --retry 5 --retry-delay 5 -o "$TAR" "$URL" +fi +echo "$SHA256 $TAR" | sha256sum -c - +rm -rf "$DEST" +mkdir -p "$DEST" +tar -xzf "$TAR" -C "$DEST" --strip-components=1 +cd "$DEST" +mkdir -p lib/host obj/dj obj/host + +# the library, for DOS and for the host. No system random source, no +# system time on DOS: the programs give both (BR_USE_* off). +SRCS=$(find src -name '*.c' | sort) +build() { # build compiler ar objdir out flags... + local cc=$1 ar=$2 dir=$3 out=$4 f o; shift 4 + for f in $SRCS; do + o=$dir/$(echo "${f#src/}" | tr / _); o=${o%.c}.o + echo "$cc -O2 -w -Isrc -Iinc $* -c -o $o $f" + done | xargs -P "$(nproc)" -I{} sh -c '{}' + rm -f "$out" + "$ar" rcs "$out" "$dir"/*.o +} +build "${DJ}gcc" "${DJ}ar" obj/dj lib/libbearssl.a -march=i586 \ + -DBR_USE_URANDOM=0 -DBR_USE_UNIX_TIME=0 -DBR_USE_WIN32_TIME=0 -DBR_USE_WIN32_RAND=0 \ + -DBR_RDRAND=0 -DBR_AES_X86NI=0 -DBR_SSE2=0 -DBR_64=0 -DBR_INT128=0 -DBR_LE_UNALIGNED=1 +build gcc ar obj/host lib/host/libbearssl.a + +# the trust anchors, with BearSSL's tool (built for the host) +gcc -O1 -w -Isrc -Iinc -o obj/brssl tools/*.c lib/host/libbearssl.a +obj/brssl ta /etc/ssl/certs/ca-certificates.crt > trust_anchors.h 2> obj/ta.log +grep -c "^static const unsigned char TA[0-9]*_DN" trust_anchors.h | sed 's/^/trust anchors: /' +rm -rf obj test samples T0 mk conf build tools +ls -l lib/libbearssl.a lib/host/libbearssl.a trust_anchors.h diff --git a/build/games.sh b/build/games.sh new file mode 100755 index 00000000..44cec06a --- /dev/null +++ b/build/games.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# A game for the compatibility tests into /opt/games (used by the +# Containerfile): Kiloblaster, (c) 1992 Allen Pilgrim / Epic MegaGames, +# freeware since 2008 (its LICENSE.TXT comes along) - the package of the +# FreeDOS 1.4 games repository, checked against its SHA-256. Only the +# tests run it (tests/compat/game.sh); it is not part of modernDOS. +# +# Usage: build/games.sh [kiloblas.zip] (default: download it) + +set -e +SHA256=74b580c38063e21d749e76c0e087d069ce69b8ad68ae3c39d7c4ce2f6ded3da6 +URL=https://www.ibiblio.org/pub/micro/pc-stuff/freedos/files/repositories/1.4/games/kiloblas.zip +DEST=${GAMES_DEST:-/opt/games} + +ZIP=$1 +if [ -z "$ZIP" ]; then + ZIP=$(mktemp) + curl -fsSL --retry 5 --retry-delay 5 -o "$ZIP" "$URL" +fi +echo "$SHA256 $ZIP" | sha256sum -c - +rm -rf "$DEST/kiloblas" +mkdir -p "$DEST/kiloblas" +python3 - "$ZIP" "$DEST/kiloblas" <<'PY' +import os, sys, zipfile +z = zipfile.ZipFile(sys.argv[1]) +n = 0 +for i in z.infolist(): + name = i.filename.upper() + if name.startswith("GAMES/KILOBLAS/") and not name.endswith("/"): + open(os.path.join(sys.argv[2], os.path.basename(name)), "wb").write(z.read(i)) + n += 1 +print("kiloblas: %d files" % n) +PY diff --git a/build/ipxe.sh b/build/ipxe.sh new file mode 100755 index 00000000..01e0b66e --- /dev/null +++ b/build/ipxe.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# Put the iPXE source tree into /opt/ipxe (used by the Containerfile): the +# monitor's network card drivers are built from it (mdvmm/ipxe). A pinned +# snapshot, checked against its SHA-256; nothing of it is run here. +# +# Usage: build/ipxe.sh [tarball] (default: download the pinned one) + +set -e +COMMIT=4b7e1df9c513d43e9e79c63463aa2470f34de7e3 # 2026-10-24 +SHA256=a767f18394581a46e0cd2811166698bf65ee85c8de1b6b44be8558a6adc078ba +URL=https://github.com/ipxe/ipxe/archive/$COMMIT.tar.gz +DEST=${IPXE_DEST:-/opt/ipxe} + +TAR=$1 +if [ -z "$TAR" ]; then + TAR=$(mktemp) + curl -fsSL --retry 5 --retry-delay 5 -o "$TAR" "$URL" +fi +echo "$SHA256 $TAR" | sha256sum -c - +rm -rf "$DEST" +mkdir -p "$DEST" +# only the source and the licences (no tests, tools, documentation) +tar -xzf "$TAR" -C "$DEST" --strip-components=1 --wildcards \ + '*/src/include' '*/src/arch/x86' '*/src/arch/i386' '*/src/config' '*/src/core' \ + '*/src/net' '*/src/drivers' '*/COPYING*' +du -sh "$DEST" diff --git a/build/watt32-errnos.sh b/build/watt32-errnos.sh new file mode 100755 index 00000000..bc36c9b1 --- /dev/null +++ b/build/watt32-errnos.sh @@ -0,0 +1,53 @@ +#!/bin/bash +# Generate Watt-32's errno tables for DJGPP (runs inside the build container). +# +# Watt-32 needs build/djgpp/syserr.c and inc/sys/djgpp.err, made by its +# util/errnos.c compiled with DJGPP and run under DOS (it asks DJGPP's C +# library for its errno values and messages). This builds it, runs it in +# QEMU on the modernDOS kernel with CWSDPMI, and writes the two files to +# build/watt32/ (they are kept in the repository; rerun when DJGPP or the +# pinned Watt-32 changes). +# +# Usage: build/watt32-errnos.sh + +set -e +WATT=$(realpath "$1") +ROOT=$(cd "$(dirname "$0")/.." && pwd) +OUT="$ROOT/build/watt32" +KERNEL="$ROOT/_output/gcc/kgc8632.sys" +TEST="$ROOT/test" +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +. "$TEST/cfg.sh" +export MTOOLS_SKIP_CHECK=1 + +/opt/djgpp/bin/i586-pc-msdosdjgpp-gcc -s -I"$WATT/inc" -o "$WORK/dj_err.exe" "$WATT/util/errnos.c" +"$NASM" -f bin -o "$WORK/poweroff.com" "$ROOT/tests/mdvmm/poweroff.asm" + +cd "$WORK" +printf 'SHELL=A:\\COMMAND.COM A:\\ /E:512 /P\r\n' > fdconfig.sys +printf '@ECHO OFF\r\nA:\\DJ_ERR.EXE -s > A:\\SYSERR.C\r\nA:\\DJ_ERR.EXE -e > A:\\DJGPP.ERR\r\nA:\\POWEROFF.COM\r\n' > autoexec.bat +"$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_LBA=0 -D_USE_PART_INFO=0 -D_QUERY_GEOMETRY=0 \ + -D_FAT12 -D_UNIT=00h -o boot.bin +"$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,fdconfig.sys" \ + -D_BOOTPATCHFILE="'boot.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR_PART_TYPE=ptFAT12 -D_BPE=12 -D_SPC=1 -D_SPI=2880 \ + -D_SPF=9 -D_NUMROOT=224 -D_UNIT=00h -o disk.img +mcopy -i disk.img /opt/fdos/bin/command.com ::COMMAND.COM +mcopy -i disk.img autoexec.bat ::AUTOEXEC.BAT +mcopy -i disk.img dj_err.exe ::DJ_ERR.EXE +mcopy -i disk.img /opt/cwsdpmi/bin/CWSDPMI.EXE ::CWSDPMI.EXE +mcopy -i disk.img poweroff.com ::POWEROFF.COM + +timeout --foreground 120 "$QEMU" -m 32 -drive file=disk.img,format=raw,if=floppy \ + -display none -net none -no-reboot "$OUT/syserr.c" +mtype -i disk.img ::DJGPP.ERR | sed 's/\r$//' > "$OUT/djgpp.err" +wc -l "$OUT/syserr.c" "$OUT/djgpp.err" +grep -q "SYS_ERRLIST" "$OUT/syserr.c" && grep -q "define" "$OUT/djgpp.err" +echo "watt32 errno tables: done" diff --git a/build/watt32.sh b/build/watt32.sh new file mode 100755 index 00000000..c1572a22 --- /dev/null +++ b/build/watt32.sh @@ -0,0 +1,55 @@ +#!/bin/bash +# Build the Watt-32 TCP/IP library for DJGPP into /opt/watt32 (used by the +# Containerfile). Safe by construction: +# - a pinned snapshot, checked against its SHA-256 +# - Watt-32's makefile generators (mkmake, mkdep, bin2c) are compiled +# from their C source; the prebuilt binaries in the snapshot are not run +# - the DJGPP errno tables come from build/watt32/ (generated under DOS by +# build/watt32-errnos.sh) +# Result: /opt/watt32/lib/libwatt.a, headers in /opt/watt32/inc. +# +# Usage: build/watt32.sh [tarball] (default: download the pinned one) + +set -e +COMMIT=b619bfef4f9b4bcdaef20b18b3844d50f274af13 # 2026-10-14 +SHA256=c298cf1ba3b54b75b89cc6b7691b3e61e7cc70bb8c0e6b7999dc240f6bf254d6 +URL=https://github.com/gvanem/Watt-32/archive/$COMMIT.tar.gz +HERE=$(cd "$(dirname "$0")" && pwd) +DEST=${WATT_DEST:-/opt/watt32} +DJ=/opt/djgpp/bin/i586-pc-msdosdjgpp- + +TAR=$1 +if [ -z "$TAR" ]; then + TAR=$(mktemp) + curl -fsSL --retry 5 --retry-delay 5 -o "$TAR" "$URL" +fi +echo "$SHA256 $TAR" | sha256sum -c - +rm -rf "$DEST" +mkdir -p "$DEST" +tar -xzf "$TAR" -C "$DEST" --strip-components=1 + +# the generators, from source +cd "$DEST/util" +mkdir -p linux +gcc -O2 -w -o linux/mkmake mkmake.c -lslang # S-Lang's preprocessor +gcc -O2 -w -o linux/mkdep mkdep.c +gcc -O2 -w -o linux/bin2c bin2c.c + +# the errno tables for DJGPP +mkdir -p "$DEST/src/build/djgpp" +cp "$HERE/watt32/syserr.c" "$DEST/src/build/djgpp/syserr.c" +cp "$HERE/watt32/djgpp.err" "$DEST/inc/sys/djgpp.err" + +# what 'configur.sh djgpp' does, with the generators built above +cd "$DEST/src" +export WATT_ROOT="$DEST" +{ + echo "BIN_PREFIX = $DJ" + echo "W32_BIN2C_ = ../util/linux/bin2c" + echo "W32_NASM_ ?= nasm" + ../util/linux/mkmake -d build/djgpp makefile.all DJGPP FLAT +} > djgpp.mak +../util/linux/mkdep -s.o -p'$(OBJDIR)/' *.[ch] > build/djgpp/watt32.dep +echo "neterr.c: build/djgpp/syserr.c" >> build/djgpp/watt32.dep +make -f djgpp.mak -j4 +ls -l "$DEST/lib/libwatt.a" diff --git a/build/watt32/djgpp.err b/build/watt32/djgpp.err new file mode 100644 index 00000000..578f8589 --- /dev/null +++ b/build/watt32/djgpp.err @@ -0,0 +1,116 @@ +#ifndef __SYS_WERRNO_ERR +#define __SYS_WERRNO_ERR + +/* + * THIS FILE WAS GENERATED BY %WATT_ROOT%\a:/dj_err.exe + * at Mon Nov 23 12:05:22 2026. + * DO NOT EDIT. + * + * Watt-32 errnos are after vendor's errnos (1 - 41) + */ + +#ifndef __DJGPP__ +#error This file is only for use by "__DJGPP__" +#endif + +#define ERRNO_VENDOR_VERSION "2.05" + +#define EDOM 1 +#define ERANGE 2 +#define E2BIG 3 +#define EACCES 4 +#define EAGAIN 5 +#define EBADF 6 +#define EBUSY 7 +#define ECHILD 8 +#define EDEADLK 9 +#define EEXIST 10 +#define EFAULT 11 +#define EFBIG 12 +#define EINTR 13 +#define EINVAL 14 +#define EIO 15 +#define EISDIR 16 +#define EMFILE 17 +#define EMLINK 18 +#define ENAMETOOLONG 19 +#define ENFILE 20 +#define ENODEV 21 +#define ENOENT 22 +#define ENOEXEC 23 +#define ENOLCK 24 +#define ENOMEM 25 +#define ENOSPC 26 +#define ENOSYS 27 +#define ENOTDIR 28 +#define ENOTEMPTY 29 +#define ENOTTY 30 +#define ENXIO 31 +#define EPERM 32 +#define EPIPE 33 +#define EROFS 34 +#define ESPIPE 35 +#define ESRCH 36 +#define EXDEV 37 +#define ENMFILE 38 +#define ELOOP 39 +#define EOVERFLOW 40 +#define EILSEQ 41 +#define EWOULDBLOCK 42 +#define EINPROGRESS 43 +#define EALREADY 44 +#define ENOTSOCK 45 +#define EDESTADDRREQ 46 +#define EMSGSIZE 47 +#define EPROTOTYPE 48 +#define ENOPROTOOPT 49 +#define EPROTONOSUPPORT 50 +#define ESOCKTNOSUPPORT 51 +#define EOPNOTSUPP 52 +#define EPFNOSUPPORT 53 +#define EAFNOSUPPORT 54 +#define EADDRINUSE 55 +#define EADDRNOTAVAIL 56 +#define ENETDOWN 57 +#define ENETUNREACH 58 +#define ENETRESET 59 +#define ECONNABORTED 60 +#define ECONNRESET 61 +#define ENOBUFS 62 +#define EISCONN 63 +#define ENOTCONN 64 +#define ESHUTDOWN 65 +#define ETIMEDOUT 66 +#define ECONNREFUSED 67 +#define EHOSTDOWN 68 +#define EHOSTUNREACH 69 +#define ESTALE 70 +#define EREMOTE 71 +#define EBADRPC 72 +#define ERPCMISMATCH 73 +#define EPROGUNAVAIL 74 +#define EPROGMISMATCH 75 +#define EPROCUNAVAIL 76 +#define EINVFNC 77 +#define ENOPATH 78 +#define ECONTR 79 +#define EINVMEM 80 +#define EINVENV 81 +#define EINVFMT 82 +#define EINVACC 83 +#define EINVDAT 84 +#define EDEADLOCK 85 +#define ECURDIR 86 +#define ENOTSAM 87 +#define ETXTBSY 88 +#define ENOTBLK 89 +#define EUCLEAN 90 +#define ETOOMANYREFS 91 +#define EPROCLIM 92 +#define EUSERS 93 +#define EDQUOT 94 +#define EVDBAD 95 +#define ENORMTWD 96 +#define ECANCELED 97 + +#endif /* __SYS_WERRNO_ERR */ diff --git a/build/watt32/syserr.c b/build/watt32/syserr.c new file mode 100644 index 00000000..6f3e6970 --- /dev/null +++ b/build/watt32/syserr.c @@ -0,0 +1,134 @@ +/* + * THIS FILE WAS GENERATED BY %WATT_ROOT%\a:/dj_err.exe + * at Mon Nov 23 12:05:22 2026. + * DO NOT EDIT. + * + * The Watt-32 'sys_errlist[]' that replaces vendor's 'sys_errlist[]' + */ + +#ifndef __DJGPP__ +#error This file is only for use by "__DJGPP__" +#endif + +char __syserr000[] = "Unknown error"; +char __syserr001[] = "Input to function out of range (EDOM)"; +char __syserr002[] = "Output of function out of range (ERANGE)"; +char __syserr003[] = "Argument list too long (E2BIG)"; +char __syserr004[] = "Permission denied (EACCES)"; +char __syserr005[] = "Resource temporarily unavailable (EAGAIN)"; +char __syserr006[] = "Bad file descriptor (EBADF)"; +char __syserr007[] = "Resource busy (EBUSY)"; +char __syserr008[] = "No child processes (ECHILD)"; +char __syserr009[] = "Resource deadlock avoided (EDEADLK)"; +char __syserr010[] = "File exists (EEXIST)"; +char __syserr011[] = "Bad address (EFAULT)"; +char __syserr012[] = "File too large (EFBIG)"; +char __syserr013[] = "Interrupted system call (EINTR)"; +char __syserr014[] = "Invalid argument (EINVAL)"; +char __syserr015[] = "Input or output error (EIO)"; +char __syserr016[] = "Is a directory (EISDIR)"; +char __syserr017[] = "Too many open files (EMFILE)"; +char __syserr018[] = "Too many links (EMLINK)"; +char __syserr019[] = "File name too long (ENAMETOOLONG)"; +char __syserr020[] = "Too many open files in system (ENFILE)"; +char __syserr021[] = "No such device (ENODEV)"; +char __syserr022[] = "No such file or directory (ENOENT)"; +char __syserr023[] = "Unable to execute file (ENOEXEC)"; +char __syserr024[] = "No locks available (ENOLCK)"; +char __syserr025[] = "Not enough memory (ENOMEM)"; +char __syserr026[] = "No space left on drive (ENOSPC)"; +char __syserr027[] = "Function not implemented (ENOSYS)"; +char __syserr028[] = "Not a directory (ENOTDIR)"; +char __syserr029[] = "Directory not empty (ENOTEMPTY)"; +char __syserr030[] = "Inappropriate I/O control operation (ENOTTY)"; +char __syserr031[] = "No such device or address (ENXIO)"; +char __syserr032[] = "Operation not permitted (EPERM)"; +char __syserr033[] = "Broken pipe (EPIPE)"; +char __syserr034[] = "Read-only file system (EROFS)"; +char __syserr035[] = "Invalid seek (ESPIPE)"; +char __syserr036[] = "No such process (ESRCH)"; +char __syserr037[] = "Improper link (EXDEV)"; +char __syserr038[] = "No more files (ENMFILE)"; +char __syserr039[] = "Too many levels of symbolic links (ELOOP)"; +char __syserr040[] = "Value too large (EOVERFLOW)"; +char __syserr041[] = "Invalid or incomplete multibyte or wide character (EILSEQ)"; +char __syserr042[] = "Operation would block (EWOULDBLOCK)"; +char __syserr043[] = "Operation now in progress (EINPROGRESS)"; +char __syserr044[] = "Operation already in progress (EALREADY)"; +char __syserr045[] = "Socket operation on non-socket (ENOTSOCK)"; +char __syserr046[] = "Destination address required (EDESTADDRREQ)"; +char __syserr047[] = "Message too long (EMSGSIZE)"; +char __syserr048[] = "Protocol wrong type for socket (EPROTOTYPE)"; +char __syserr049[] = "Protocol option not available (ENOPROTOOPT)"; +char __syserr050[] = "Protocol not supported (EPROTONOSUPPORT)"; +char __syserr051[] = "Socket type not supported (ESOCKTNOSUPPORT)"; +char __syserr052[] = "Operation not supported on socket (EOPNOTSUPP)"; +char __syserr053[] = "Protocol family not supported (EPFNOSUPPORT)"; +char __syserr054[] = "Address family not supported by protocol (EAFNOSUPPORT)"; +char __syserr055[] = "Address already in use (EADDRINUSE)"; +char __syserr056[] = "Can't assign requested address (EADDRNOTAVAIL)"; +char __syserr057[] = "Network is down (ENETDOWN)"; +char __syserr058[] = "Network is unreachable (ENETUNREACH)"; +char __syserr059[] = "Network dropped connection on reset (ENETRESET)"; +char __syserr060[] = "Software caused connection abort (ECONNABORTED)"; +char __syserr061[] = "Connection reset by peer (ECONNRESET)"; +char __syserr062[] = "No buffer space available (ENOBUFS)"; +char __syserr063[] = "Socket is already connected (EISCONN)"; +char __syserr064[] = "Socket is not connected (ENOTCONN)"; +char __syserr065[] = "Can't send after socket shutdown (ESHUTDOWN)"; +char __syserr066[] = "Connection timed out (ETIMEDOUT)"; +char __syserr067[] = "Connection refused (ECONNREFUSED)"; +char __syserr068[] = "Host is down (EHOSTDOWN)"; +char __syserr069[] = "No route to host (EHOSTUNREACH)"; +char __syserr070[] = "Stale NFS file handle (ESTALE)"; +char __syserr071[] = "Too many levels of remote in path (EREMOTE)"; +char __syserr072[] = "RPC struct is bad (EBADRPC)"; +char __syserr073[] = "RPC version wrong (ERPCMISMATCH)"; +char __syserr074[] = "RPC prog. not avail (EPROGUNAVAIL)"; +char __syserr075[] = "RPC Program version wrong (EPROGMISMATCH)"; +char __syserr076[] = "Bad procedure for program (EPROCUNAVAIL)"; +char __syserr077[] = "Invalid function number (EINVFNC)"; +char __syserr078[] = "Path not found (ENOPATH)"; +char __syserr079[] = "Memory area destroyed (ECONTR)"; +char __syserr080[] = "Invalid memory block address (EINVMEM)"; +char __syserr081[] = "Invalid environment (EINVENV)"; +char __syserr082[] = "Invalid format (EINVFMT)"; +char __syserr083[] = "Invalid access code (EINVACC)"; +char __syserr084[] = "Invalid data (EINVDAT)"; +char __syserr085[] = "Locking violation (EDEADLOCK)"; +char __syserr086[] = "Attempt to remove current directory (ECURDIR)"; +char __syserr087[] = "Not same device (ENOTSAM)"; +char __syserr088[] = "Text file busy (ETXTBSY)"; +char __syserr089[] = "Block device required (ENOTBLK)"; +char __syserr090[] = "Structure needs cleaning (EUCLEAN)"; +char __syserr091[] = "Too many references (ETOOMANYREFS)"; +char __syserr092[] = "Too many processes (EPROCLIM)"; +char __syserr093[] = "Too many users (EUSERS)"; +char __syserr094[] = "Disc quota exceeded (EDQUOT)"; +char __syserr095[] = "RVD related disk error (EVDBAD)"; +char __syserr096[] = "Out of remote working directory stuctures (ENORMTWD)"; +char __syserr097[] = "Operation canceled (ECANCELED)"; + +char *SYS_ERRLIST[] = { + __syserr000, __syserr001, __syserr002, __syserr003, __syserr004, + __syserr005, __syserr006, __syserr007, __syserr008, __syserr009, + __syserr010, __syserr011, __syserr012, __syserr013, __syserr014, + __syserr015, __syserr016, __syserr017, __syserr018, __syserr019, + __syserr020, __syserr021, __syserr022, __syserr023, __syserr024, + __syserr025, __syserr026, __syserr027, __syserr028, __syserr029, + __syserr030, __syserr031, __syserr032, __syserr033, __syserr034, + __syserr035, __syserr036, __syserr037, __syserr038, __syserr039, + __syserr040, __syserr041, __syserr042, __syserr043, __syserr044, + __syserr045, __syserr046, __syserr047, __syserr048, __syserr049, + __syserr050, __syserr051, __syserr052, __syserr053, __syserr054, + __syserr055, __syserr056, __syserr057, __syserr058, __syserr059, + __syserr060, __syserr061, __syserr062, __syserr063, __syserr064, + __syserr065, __syserr066, __syserr067, __syserr068, __syserr069, + __syserr070, __syserr071, __syserr072, __syserr073, __syserr074, + __syserr075, __syserr076, __syserr077, __syserr078, __syserr079, + __syserr080, __syserr081, __syserr082, __syserr083, __syserr084, + __syserr085, __syserr086, __syserr087, __syserr088, __syserr089, + __syserr090, __syserr091, __syserr092, __syserr093, __syserr094, + __syserr095, __syserr096, __syserr097, +}; + diff --git a/docs/apps.md b/docs/apps.md new file mode 100644 index 00000000..d6d75453 --- /dev/null +++ b/docs/apps.md @@ -0,0 +1,126 @@ +# modernDOS applications (milestone M5) + +The applications are part of the desktop program, MDDESK (`gui/desk/`): +the DPMI host runs one 32-bit client at a time, so they are modules of +it, each in its own windows. They are started from the launcher. + +## Status + +| Part | State | +|---|---| +| M5.1 file manager | working: browse folders with long file names, open folders and programs, new folder, rename, delete | +| M5.2 text editor | working: multi-line editing widget, editor with File menu, Ctrl+S, opened from Files | +| M5.3 settings | working: background, accent colour, 12/24-hour clock, mouse speed; live, saved in MDDESK.CFG | +| M5.4 terminal (a DOS session in a window) | working on UEFI boots: a job slot's session runs COMMAND.COM, its text screen is drawn in the window, the window's keys are typed into it (`gui/desk/term.c`) | + +## Files + +`gui/desk/files.c`. A window per view, opened at the root of the +current drive: + +- Path: type a folder (or a drive, `C:`) and press Enter. +- Buttons: Up, Refresh, New folder, Rename, Delete, Open. +- The list: folders first, then files, by name (case-insensitive), with + the size and date; `..` in subfolders. Enter or a double click opens: + a folder is entered, a program (`.EXE`, `.COM`, `.BAT`) runs through + the desktop (text mode, back on a key), any other file opens in the + editor. +- New folder and Rename ask with `ui_ask_text()`; Delete asks with + `ui_confirm()` (folders must be empty). + +Toolkit additions for it: lists have an `activate` action (Enter, double +click) besides `action` (selection), and the dialogs `ui_ask_text()` and +`ui_confirm()`. + +## Editor + +`gui/desk/editor.c`, a window per file, from the launcher (a new text) +or from Files. + +- File menu: New, Open..., Save, Save as..., Close; Ctrl+S saves. +- Status line: line, column, modified. The title shows `*` while there + are unsaved changes; closing then asks first. +- Files are read with LF or CRLF line ends (up to 1 MB) and written with + CRLF. + +The text is the toolkit's `ui_edit()` widget: a line array; typing, +Enter splits a line, Backspace and Delete join lines, arrows, +Home/End, PgUp/PgDn, Ctrl+Home/End, Tab inserts spaces (to a multiple +of 4); the mouse places the caret, the scroll bar pages. +`edit_set_text()`, `edit_get_text()` (CRLF), `edit_modified()`, +`edit_caret()`. + +## Settings + +`gui/desk/settings.c`, from the launcher. Changes apply at once: + +- Background: Slate (default), Ocean, Forest, Plum, Charcoal (gradients). +- Accent colour: Teal (default), Blue, Orange, Purple, Green - active + title bars, focus, selection, the panel's highlights. +- 24-hour clock (off: 12-hour with AM/PM). +- Mouse speed: Slow, Normal, Fast (INT 33h function 0Fh, 16/8/4 mickeys + per 8 pixels). + +Save writes `MDDESK.CFG` (`key=value` lines) next to `MDDESK.EXE`; the +desktop reads it when it starts. On UEFI boots `A:` is a RAM copy, so a +saved file lasts until the next boot. + +The colours are `theme` in mdgui (`theme.c`); `wm_redraw_all()` sends +`EV_REDRAW` to every window so retained contents are drawn again in the +new colours. + +## Testing + +`tests/gui/deskdrive.py` (MDDESK /TEST, both boot paths), after the +desktop steps: opens Files, creates `Test Folder`, renames it to +`Renamed Dir`, opens it (only `..` inside), goes Up, deletes it. The +desktop logs every listing and operation; `deskcheck.py` checks them. +Then it opens `A:\Created On Linux.txt` from Files in the editor, adds +to the line and a second line, saves with Ctrl+S (53 bytes, CRLF) and +closes. On DOS boots the MDVMM test also reads the file back from the +disk image afterwards. Then Settings: Ocean, Orange, 12-hour clock, Save; +AUTOEXEC.BAT then starts `MDDESK /TEST /EXIT`, which must load the same +settings. `files.ppm`, `editor.ppm` and `settings.ppm` (with +`SHOTS=dir`) show the applications. + +## Terminal + +`gui/desk/term.c`. Launcher > Terminal opens a window with a DOS prompt. + +- MDVMM keeps the other DOS sessions running beside the desktop. The + terminal takes a *job slot*: a session started by + `SSHSLOT.COM` before the desktop (AUTOEXEC.BAT does), which waits for + work. The same slots serve remote shells of the SSH server. +- The window shows the session's 80x25 text screen (monitor call INT 2Fh + AX=DE08h, about 20 times a second, changed cells only) in CGA colours + with the cursor; keys go into the session's BIOS keyboard buffer + (AX=DE09h). `EXIT` closes the window; closing the window sends Ctrl+C + and `EXIT` to the shell. +- On both boots: a session that is not on the display writes its text + into its own screen memory (on DOS boots the monitor keeps it from the + video hardware). A program that sets a graphics mode waits until its + session is on the display (Ctrl+Alt+F2..). +- Programs in the terminal can be 32-bit DPMI programs: every session has + its own DPMI client. + +## Browser + +`gui/desk/browser.c`. Launcher > Browser. An address field with Go and +Back, the page below. + +- Pages are laid out as text in the window's fixed-width font: headings, + paragraphs, line breaks, lists, links (underlined, click to follow), + preformatted text, rules, table rows, placeholders for images and form + fields, character entities, UTF-8 shown in code page 437. Scripts and + style sheets are skipped. +- Keys in the page: Up, Down, PgUp, PgDn, Space, Home, End; Backspace + goes back. +- `http://` and `https://` (TLS 1.2 with BearSSL, `net/pkg/tls.c`; server + certificates are checked against Mozilla's list of authorities, built + in). No scripts run, so pages that scripts build stay empty; the start + page lists places that read well as text. +- The network is Watt-32 through the packet driver (`PKTDRV`, loaded by + AUTOEXEC.BAT before the desktop); loading a page blocks the desktop + until it is there. +- The page view is a `UI_CANVAS` widget (`ui_canvas()` in mdgui): an + area a program draws and handles itself. diff --git a/docs/gui.md b/docs/gui.md new file mode 100644 index 00000000..041f8315 --- /dev/null +++ b/docs/gui.md @@ -0,0 +1,174 @@ +# modernDOS desktop GUI (milestone M4) + +The modernDOS desktop is a 32-bit DPMI program (DJGPP), with its own +original look and widget toolkit. It runs on both boot paths: from DOS +on a PC BIOS, and on UEFI PCs, where the MDVMM monitor's virtual BIOS +provides the graphics mode. + +## Status + +| Part | State | +|---|---| +| M4.1 graphics foundation | working: VBE linear framebuffer (32 bpp) on both boot paths, `mdgui` library: back buffer, clipped drawing, 8x16 text, present | +| M4.2 mouse and events | working: INT 33h on both boot paths (UEFI: virtual BIOS driver, USB mice; DOS: CTMOUSE), `mdgui` events and mouse cursor | +| M4.3 window system | working: windows with frames, title bars and close buttons, z-order, focus, moving, damage repaint (`wm.c`) | +| M4.4 widget toolkit | working: labels, buttons, checkboxes, text fields, lists, menu bar with drop-down menus, keyboard focus (`ui.c`) | +| M4.5 desktop shell | working: MDDESK with a panel (launcher, window list, clock), About, running DOS programs | + +## Graphics modes + +Programs use VBE 2.0+ (INT 10h AX=4Fxxh) for a 32 bpp direct color mode +with a linear framebuffer, mapped with DPMI 0800h. + +- DOS boot: the real VBE BIOS (in QEMU: SeaBIOS VGA BIOS, mode 144h at + 1024x768). +- UEFI boot: the virtual BIOS (`mdvmm/core/bios.c`) offers VBE 3.0 with + one mode, 141h: the GOP framebuffer as the firmware set it up (QEMU: + 1280x800). 4F00h/4F01h/4F02h/4F03h, 4F06h (get), 4F07h (start 0,0). + While the mode is set the text console (`fbcon.c`) stops drawing; + INT 10h AH=00h or 4F02h with mode 3 returns to text mode, and the + console is redrawn. + +## mdgui library + +`gui/lib/`, built into `gui/build/mdgui.o` (one relocatable object: link +it like a .o). API in `gui/lib/mdgui.h`: + +- `gfx_open(w, h)` picks the mode (w x h if there is one, else the + largest that fits, else the smallest), maps the framebuffer and sets + the mode; `gfx_close()` returns to text mode. +- Drawing goes to surfaces in normal memory: `gfx_screen()` is the back + buffer. `gfx_present(x, y, w, h)` copies an area to the framebuffer, + converting the 0x00RRGGBB colors to the mode's layout when needed. +- `draw_*`: pixel, fill, lines, frame, vertical gradient, blit, all + clipped to the surface's clip rectangle (`surface_clip`). +- `draw_text`: the 8x16 code page 437 font (shared with the MDVMM text + console, `mdvmm/core/font.c`). + +## Input + +`input_open()` finds the INT 33h driver, sets its range to the screen, +1:1 motion (function 0Fh, 8 mickeys per 8 pixels) and no double speed. +`input_poll()` / `input_wait()` return events: mouse move, button down +and up (from the press/release counters, functions 05h/06h, so short +clicks between polls are not lost), and keys (INT 16h AH=10h/11h: scan +code, character, shift flags). `input_wait()` idles with INT 2Fh +AX=1680h, so other DOS sessions run. + +The mouse cursor is not in the back buffer: `gfx_cursor_move()` and +`gfx_present()` compose it over the presented rows. + +Mouse drivers: + +- DOS boot: any INT 33h driver; the tests use CTMOUSE (FreeDOS) with the + PS/2 mouse. CTMOUSE accelerates fast motion. +- UEFI boot: the virtual BIOS has a driver (`mdvmm/core/mouse.c`) fed by + USB boot protocol mice on xHCI root ports. DOS resets INT 33h while it + starts, so `MDVMM` (no arguments, in AUTOEXEC.BAT) installs it through + INT 2Fh AX=DE07h. In text mode the cursor is an inverted cell, drawn by + the console. Functions 00h-08h, 0Bh, 0Fh, 1Bh, 21h, 24h; not yet the + event handler (0Ch) or PS/2 mice. + +## Window manager + +`gui/lib/wm.c`. The desktop is one program; all its windows live in it, +much like the Windows 3.x GUI ran in one address space. + +- A window (`struct window`) has an outer rectangle, a title, and a + retained client surface the program draws into, then calls + `wm_invalidate()`. `wm_window_new()`, `wm_window_close()`, + `wm_window_move()`, `wm_raise()`. +- Repaint: changes add to a damaged rectangle (`wm_damage()`); + `wm_update()` draws the desktop and the windows bottom to top, clipped + to it, and presents only that area. +- Events (`wm_dispatch()`, or `wm_run()` as the whole loop): a mouse + press raises and focuses the window under the pointer; on the title bar + it starts a move, on the close button it sends `EV_CLOSE` (the window + closes unless the handler takes it); elsewhere the window gets the + event in client coordinates and keeps the mouse until the button is + released. Keys go to the focused (top) window. +- Look: slate title bars, teal for the active window, a red close button, + 1-pixel dark frames, a dark blue-grey gradient desktop. + +## Widgets + +`gui/lib/ui.c`. `ui_new(window)` takes over the window's handler (events +no widget uses, and `EV_CLOSE`, go on to the previous one) and draws the +widgets into the window's client surface. + +| Widget | Mouse | Keyboard | `action` | +|---|---|---|---| +| `ui_label` | - | - | - | +| `ui_button` | press and release on it | Enter, Space | clicked | +| `ui_check` | toggles | Space | toggled (`value`) | +| `ui_textfield` | places the caret | characters, Backspace, Del, Left/Right, Home/End | Enter | +| `ui_list` | selects; the scroll bar pages | Up/Down, Home/End, Enter | selected (`value`) | +| `ui_menubar` | opens a menu; an item chooses it | F10 opens the first menu; Up/Down, Enter, Esc | chosen (`menu`, `value`) | + +Tab and Shift+Tab move the focus in creation order; the focused widget +is drawn in teal. Menus are popup windows (`wm_popup_new`): no title bar, +on top, closed by a mouse press outside them. + +## Desktop shell + +`gui/desk/desk.c`, built into `gui/build/MDDESK.EXE` (also on the +release image). `wm_desktop()` gives the shell a 30-pixel band at the top +that windows stay below, drawn after the desktop background, and the +events where no window is. + +- Panel: the launcher button, a button per open window (the top one + highlighted; a click raises the window), and a clock (HH:MM, checked + while idle). +- Launcher (click, or F10): About modernDOS (display, boot type and + sessions through the MDVMM API, free DPMI memory), Run... and Exit to + DOS. Menus are `ui_popup()` popups. +- Run: the desktop calls `gfx_suspend()` (text mode, buffers kept), runs + the command with `system()` (COMMAND.COM), waits for a key, then + `gfx_resume()` sets the mode again and everything is redrawn. +- 32-bit DPMI programs run this way too: the program becomes a DPMI + client started by the desktop's (the host nests them). + +Two monitor fixes came with it: a DPMI client running a DOS program is no +longer torn down when that program exits (INT 21h AH=4Ch is only the +client's exit when DOS's current PSP is the client's), and the monitor's +own services (INT 2Fh AH=DEh, INT 15h AH=87h) now also answer interrupts +a DPMI client reflects to real mode, not only V86 INT instructions. + +## Testing + +`tests/gui/gfxtest.c` (GFXTEST) runs in the MDVMM test (DOS boot) and +the UEFI test. It draws a known pattern, logs `GFXTEST: drawn WxH`, and +returns to text mode after 3 seconds. `tests/gui/gfxshot.py` takes a +QEMU screendump when the pattern is up, `tests/gui/gfxcheck.py` checks +pixels: the corner boxes, the background, clipping, the gradient. +`SHOTS=dir` keeps the screenshots (gfx, mouse, wm .ppm). + +`tests/gui/mousetest.c` (MOUSETEST) shows the cursor and logs clicks; +`tests/gui/mousedrive.py` moves the mouse by (+120, +60) through the QEMU +monitor, clicks, takes a screenshot and presses q; `mousecheck.py` +checks the click position (exact with the virtual BIOS driver, direction +only with CTMOUSE), the orange square and the cursor in the screenshot. + +`tests/gui/wmtest.c` (WMTEST) opens three overlapping windows. +`wmdrive.py` drags one by its title bar and clicks another to raise it; +it steers the pointer closed loop by the positions WMTEST logs, because +QEMU only sends relative motion and CTMOUSE accelerates it. `wmcheck.py` +checks the final layout and z-order from the log and pixels in the +screenshot (the raised window covers the overlap, the moved window's old +place shows the desktop). + +`tests/gui/uitest.c` (UITEST) is a dialog with every widget. +`uidrive.py` types into the text field, toggles the checkbox with Tab and +Space, picks a list item, clicks OK, and quits through File/Quit with the +keyboard; `uicheck.py` checks the values the OK button logged and the +checkbox, list and text field in the screenshot. `guidrive.py` holds the +shared closed loop mouse steering. + +`MDDESK /TEST` logs positions and events; `deskdrive.py` opens About +from the launcher, runs `A:\V86CHK` through Run (it logs a second time) +and returns to the desktop with a key, then exits through the launcher; +`deskcheck.py` checks the clock, the boot type the About box got from the +MDVMM API, the window list, the program run and the redrawn screen. + +The DJGPP test programs are linked +with `-s`: unstripped, they no longer fit on the 1.44 MB test floppy. diff --git a/docs/hardware/imac8,1-bootlog-1.txt b/docs/hardware/imac8,1-bootlog-1.txt new file mode 100644 index 00000000..59fcd8e5 --- /dev/null +++ b/docs/hardware/imac8,1-bootlog-1.txt @@ -0,0 +1,8 @@ +MDVMM - modernDOS virtual machine monitor (UEFI) +Firmware: Apple, EFI 1.10 +Hardware report written to \MODERNDOS\HWINFO.TXT +Memory: disk image at 0x00000000BD374000, monitor pool 32 MB at 0x00000000BAE21000, DOS extended memory 64 MB at 0x00000000B6E21000 +Hard disks are read-only (no \MODERNDOS\DISKRW). +The monitor's log will stay on the screen for a while (\MODERNDOS\BOOTWAIT). +MDVMM: UGA graphics, 1680x1050 depth 32: framebuffer not found, the screen stays dark +Starting the monitor (leaving the firmware's boot services)... diff --git a/docs/hardware/imac8,1-bootlog-2.txt b/docs/hardware/imac8,1-bootlog-2.txt new file mode 100644 index 00000000..6db04fae --- /dev/null +++ b/docs/hardware/imac8,1-bootlog-2.txt @@ -0,0 +1,11 @@ +MDVMM - modernDOS virtual machine monitor (UEFI) +Firmware: Apple, EFI 1.10 +Hardware report written to \MODERNDOS\HWINFO.TXT +Memory: disk image at 0x00000000BD374000, monitor pool 32 MB at 0x00000000BAE21000, DOS extended memory 64 MB at 0x00000000B6E21000 +Hard disks are read-only (no \MODERNDOS\DISKRW). +The monitor's log will stay on the screen for a while (\MODERNDOS\BOOTWAIT). +Graphics (UGA): 1680x1050, depth 32 +Framebuffer probe: 1 video memory area(s) 0x00000000C0000000+0x0000000010000000 + graphics console, area 0: fill status 0x0000000000000000/0x0000000000000000, pixel (0,1) reads 0x0000000000A1B2C3, scan found it +Framebuffer found: 1680x1050, framebuffer at 0x00000000C0010000, 1728 pixels per line +Starting the monitor (leaving the firmware's boot services)... diff --git a/docs/hardware/imac8,1-bootlog-3.txt b/docs/hardware/imac8,1-bootlog-3.txt new file mode 100644 index 00000000..9b34853d --- /dev/null +++ b/docs/hardware/imac8,1-bootlog-3.txt @@ -0,0 +1,11 @@ +MDVMM - modernDOS virtual machine monitor (UEFI) +Firmware: Apple, EFI 1.10 +Hardware report written to \MODERNDOS\HWINFO.TXT +Memory: disk image at 0x00000000BCB51000, monitor pool 32 MB at 0x00000000BAB51000, DOS extended memory 64 MB at 0x00000000B6B51000 +Hard disks are read-only (no \MODERNDOS\DISKRW). +The monitor's log will stay on the screen for a while (\MODERNDOS\BOOTWAIT). +Graphics (UGA): 1680x1050, depth 32 +Framebuffer probe: 1 video memory area(s) 0x00000000C0000000+0x0000000010000000 + graphics console, area 0: fill status 0x0000000000000000/0x0000000000000000, pixel (0,1) reads 0x0000000000A1B2C3, scan found it +Framebuffer found: 1680x1050, framebuffer at 0x00000000C0010000, 1728 pixels per line +Starting the monitor (leaving the firmware's boot services)... diff --git a/docs/hardware/imac8,1-hwinfo.txt b/docs/hardware/imac8,1-hwinfo.txt new file mode 100644 index 00000000..dd12034c --- /dev/null +++ b/docs/hardware/imac8,1-hwinfo.txt @@ -0,0 +1,247 @@ +modernDOS hardware report (BOOTX64.EFI) +Firmware: Apple revision 0001000a, EFI 1.1 +PCI devices (bus:dev.fn vendor:device class rev subsystem) + 00:00.0 8086:2a00 class 060000 rev 03 sub 106b:00a0 + BARs 00000000 00000000 00000000 00000000 00000000 00000000 irq 0 + 00:01.0 8086:2a01 class 060400 rev 03 + 00:1a.0 8086:2834 class 0c0300 rev 04 sub 0000:0000 + BARs 00000000 00000000 00000000 00000000 000070c1 00000000 irq 0 + 00:1a.1 8086:2835 class 0c0300 rev 04 sub 106b:00a0 + BARs 00000000 00000000 00000000 00000000 000070a1 00000000 irq 0 + 00:1a.7 8086:283a class 0c0320 rev 04 sub 106b:00a0 + BARs d0604c00 00000000 00000000 00000000 00000000 00000000 irq 0 + 00:1b.0 8086:284b class 040300 rev 04 sub 106b:00a0 + BARs d0600004 00000000 00000000 00000000 00000000 00000000 irq 0 + 00:1c.0 8086:283f class 060400 rev 04 + 00:1c.3 8086:2845 class 060400 rev 04 + 00:1c.4 8086:2847 class 060400 rev 04 + 00:1c.5 8086:2849 class 060400 rev 04 + 00:1d.0 8086:2830 class 0c0300 rev 04 sub 106b:00a0 + BARs 00000000 00000000 00000000 00000000 00007081 00000000 irq 0 + 00:1d.1 8086:2831 class 0c0300 rev 04 sub 106b:00a0 + BARs 00000000 00000000 00000000 00000000 00007061 00000000 irq 0 + 00:1d.2 8086:2832 class 0c0300 rev 04 sub 106b:00a0 + BARs 00000000 00000000 00000000 00000000 00007041 00000000 irq 0 + 00:1d.7 8086:2836 class 0c0320 rev 04 sub 106b:00a0 + BARs d0604800 00000000 00000000 00000000 00000000 00000000 irq 0 + 00:1e.0 8086:2448 class 060401 rev f4 + 00:1f.0 8086:2815 class 060100 rev 04 sub 106b:00a0 + BARs 00000000 00000000 00000000 00000000 00000000 00000000 irq 0 + 00:1f.1 8086:2850 class 01018f rev 04 sub 106b:00a0 + BARs 00007109 0000711d 00007101 00007119 000070e1 00000000 irq 0 + 00:1f.2 8086:2829 class 010601 rev 04 sub 106b:00a0 + BARs 000070f9 00007115 000070f1 00007111 00007021 d0604000 irq 0 + 00:1f.3 8086:283e class 0c0500 rev 04 sub 106b:00a0 + BARs d0605000 00000000 00000000 00000000 0000efa1 00000000 irq 0 + 01:00.0 1002:94c8 class 030000 rev 00 sub 106b:0084 + BARs c000000c 00000000 d0520004 00000000 00006001 00000000 irq 0 + 03:00.0 11c1:5901 class 0c0010 rev 06 sub 11c1:5900 + BARs d0300004 00000000 00000000 00000000 00000000 00000000 irq 0 + 04:00.0 14e4:4328 class 028000 rev 05 sub 106b:008c + BARs d0200004 00000000 00000000 00000000 00000000 00000000 irq 0 + 05:00.0 11ab:436a class 020000 rev 13 sub 11ab:00ba + BARs d0100004 00000000 00005001 00000000 00000000 00000000 irq 0 +GOP: none +UGA: present, 1680x1050 depth 32 refresh 60 +CPU: Intel(R) Core(TM)2 Duo CPU E8135 @ 2.40GHz (cpuid 1: eax 00010676 edx bfebfbff ecx 0008e3bd) +BIOS: Apple Inc., IM81.88Z.00C1.B00.0802091538, 02/09/08 +System: Apple Inc. / iMac8,1 / 1.0 +Board: Apple Inc. / Mac-F226BEC8 +EFI configuration tables + 05ad34ba-6f02-4214-952e-4da0398e2bb9 + 7739f24c-93d7-11d4-9a3a-0090273fc14d + 4c19049f-4137-4dd3-9c10-8b97a83ffdfa + 49152e77-1ada-4764-b7a2-7afefed95e8b + 5751da6e-1376-4e02-ba92-d294fdd30901 + f76761dc-ff89-44e4-9c0c-cd0ada4ef983 + eb9d2d30-2d88-11d3-9a16-0090273fc14d + 8868e871-e4f1-11d3-bc22-0080c73c8881 + eb9d2d31-2d88-11d3-9a16-0090273fc14d +Memory map (type start pages attributes) + 7 000000000000 143 000000000000000f + 10 00000008f000 1 000000000000000f + 7 000000090000 16 000000000000000f + 7 000000100000 773409 000000000000000f + 4 0000bce21000 1153 000000000000000f + 7 0000bd2a2000 570 000000000000000f + 4 0000bd4dc000 4580 000000000000000f + 7 0000be6c0000 14 000000000000000f + 4 0000be6ce000 178 000000000000000f + 7 0000be780000 15 000000000000000f + 4 0000be78f000 66 000000000000000f + 3 0000be7d1000 31 000000000000000f + 4 0000be7f0000 63 000000000000000f + 5 0000be82f000 6 800000000000000f + 3 0000be835000 3 000000000000000f + 4 0000be838000 2 000000000000000f + 3 0000be83a000 8 000000000000000f + 4 0000be842000 5 000000000000000f + 5 0000be847000 2 800000000000000f + 4 0000be849000 1 000000000000000f + 6 0000be84a000 1 800000000000000f + 4 0000be84b000 17 000000000000000f + 3 0000be85c000 15 000000000000000f + 4 0000be86b000 1 000000000000000f + 3 0000be86c000 6 000000000000000f + 4 0000be872000 4 000000000000000f + 3 0000be876000 16 000000000000000f + 4 0000be886000 7 000000000000000f + 3 0000be88d000 5 000000000000000f + 4 0000be892000 1 000000000000000f + 3 0000be893000 1 000000000000000f + 4 0000be894000 1 000000000000000f + 3 0000be895000 1 000000000000000f + 4 0000be896000 1 000000000000000f + 3 0000be897000 4 000000000000000f + 4 0000be89b000 1 000000000000000f + 3 0000be89c000 5 000000000000000f + 4 0000be8a1000 4 000000000000000f + 3 0000be8a5000 3 000000000000000f + 4 0000be8a8000 1 000000000000000f + 3 0000be8a9000 1 000000000000000f + 4 0000be8aa000 1 000000000000000f + 6 0000be8ab000 1 800000000000000f + 3 0000be8ac000 1 000000000000000f + 4 0000be8ad000 1 000000000000000f + 3 0000be8ae000 2 000000000000000f + 4 0000be8b0000 1 000000000000000f + 3 0000be8b1000 6 000000000000000f + 4 0000be8b7000 1 000000000000000f + 3 0000be8b8000 2 000000000000000f + 4 0000be8ba000 1 000000000000000f + 3 0000be8bb000 6 000000000000000f + 4 0000be8c1000 4 000000000000000f + 3 0000be8c5000 5 000000000000000f + 4 0000be8ca000 2 000000000000000f + 3 0000be8cc000 4 000000000000000f + 4 0000be8d0000 1 000000000000000f + 7 0000be8d1000 165 000000000000000f + 1 0000be976000 42 000000000000000f + 7 0000be9a0000 21 000000000000000f + 4 0000be9b5000 5 000000000000000f + 2 0000be9ba000 16 000000000000000f + 4 0000be9ca000 13 000000000000000f + 7 0000be9d7000 1 000000000000000f + 4 0000be9d8000 677 000000000000000f + 3 0000bec7d000 5 000000000000000f + 4 0000bec82000 8 000000000000000f + 3 0000bec8a000 18 000000000000000f + 4 0000bec9c000 3 000000000000000f + 3 0000bec9f000 17 000000000000000f + 4 0000becb0000 3 000000000000000f + 3 0000becb3000 19 000000000000000f + 4 0000becc6000 1 000000000000000f + 3 0000becc7000 14 000000000000000f + 4 0000becd5000 2 000000000000000f + 3 0000becd7000 2 000000000000000f + 4 0000becd9000 2 000000000000000f + 3 0000becdb000 16 000000000000000f + 4 0000beceb000 2 000000000000000f + 3 0000beced000 19 000000000000000f + 4 0000bed00000 2 000000000000000f + 3 0000bed02000 1 000000000000000f + 4 0000bed03000 2 000000000000000f + 3 0000bed05000 1 000000000000000f + 4 0000bed06000 1 000000000000000f + 3 0000bed07000 3 000000000000000f + 4 0000bed0a000 1 000000000000000f + 3 0000bed0b000 1 000000000000000f + 4 0000bed0c000 1 000000000000000f + 3 0000bed0d000 5 000000000000000f + 4 0000bed12000 3 000000000000000f + 5 0000bed15000 2 800000000000000f + 4 0000bed17000 2 000000000000000f + 6 0000bed19000 1 800000000000000f + 4 0000bed1a000 2 000000000000000f + 5 0000bed1c000 8 800000000000000f + 4 0000bed24000 1 000000000000000f + 3 0000bed25000 1 000000000000000f + 4 0000bed26000 1 000000000000000f + 5 0000bed27000 1 800000000000000f + 4 0000bed28000 3 000000000000000f + 3 0000bed2b000 1 000000000000000f + 4 0000bed2c000 1 000000000000000f + 5 0000bed2d000 4 800000000000000f + 4 0000bed31000 10 000000000000000f + 3 0000bed3b000 2 000000000000000f + 4 0000bed3d000 1 000000000000000f + 3 0000bed3e000 1 000000000000000f + 5 0000bed3f000 2 800000000000000f + 4 0000bed41000 3 000000000000000f + 10 0000bed44000 513 000000000000000f + 4 0000bef45000 16 000000000000000f + 3 0000bef55000 12 000000000000000f + 4 0000bef61000 22 000000000000000f + 3 0000bef77000 4 000000000000000f + 4 0000bef7b000 128 000000000000000f + 10 0000beffb000 2 000000000000000f + 4 0000beffd000 4 000000000000000f + 6 0000bf001000 2 800000000000000f + 4 0000bf003000 38 000000000000000f + 3 0000bf029000 17 000000000000000f + 4 0000bf03a000 6 000000000000000f + 3 0000bf040000 2 000000000000000f + 4 0000bf042000 14 000000000000000f + 3 0000bf050000 2 000000000000000f + 4 0000bf052000 1 000000000000000f + 3 0000bf053000 1 000000000000000f + 6 0000bf054000 18 800000000000000f + 5 0000bf066000 4 800000000000000f + 3 0000bf06a000 2 000000000000000f + 4 0000bf06c000 6 000000000000000f + 3 0000bf072000 3 000000000000000f + 4 0000bf075000 1 000000000000000f + 3 0000bf076000 1 000000000000000f + 6 0000bf077000 1 800000000000000f + 3 0000bf078000 1 000000000000000f + 4 0000bf079000 3 000000000000000f + 6 0000bf07c000 17 800000000000000f + 5 0000bf08d000 3 800000000000000f + 3 0000bf090000 13 000000000000000f + 4 0000bf09d000 1 000000000000000f + 3 0000bf09e000 8 000000000000000f + 5 0000bf0a6000 2 800000000000000f + 6 0000bf0a8000 1 800000000000000f + 4 0000bf0a9000 1 000000000000000f + 3 0000bf0aa000 1 000000000000000f + 5 0000bf0ab000 1 800000000000000f + 4 0000bf0ac000 1 000000000000000f + 3 0000bf0ad000 1 000000000000000f + 4 0000bf0ae000 2 000000000000000f + 5 0000bf0b0000 3 800000000000000f + 6 0000bf0b3000 1 800000000000000f + 3 0000bf0b4000 1 000000000000000f + 4 0000bf0b5000 2 000000000000000f + 6 0000bf0b7000 1 800000000000000f + 3 0000bf0b8000 1 000000000000000f + 4 0000bf0b9000 1057 000000000000000f + 3 0000bf4da000 9 000000000000000f + 4 0000bf4e3000 1 000000000000000f + 3 0000bf4e4000 1 000000000000000f + 5 0000bf4e5000 2 800000000000000f + 4 0000bf4e7000 34 000000000000000f + 3 0000bf509000 2 000000000000000f + 5 0000bf50b000 1 800000000000000f + 3 0000bf50c000 1 000000000000000f + 4 0000bf50d000 3 000000000000000f + 3 0000bf510000 1 000000000000000f + 4 0000bf511000 1429 000000000000000f + 6 0000bfaa6000 1 800000000000000f + 4 0000bfaa7000 1015 000000000000000f + 6 0000bfe9e000 1 800000000000000f + 7 0000bfe9f000 38 000000000000000f + 10 0000bfec5000 2 000000000000000f + 9 0000bfec7000 3 000000000000000f + 10 0000bfeca000 21 000000000000000f + 9 0000bfedf000 16 000000000000000f + 7 0000bfeef000 10 000000000000000f + 0 0000bfef9000 6 000000000000000f + 6 0000bfeff000 1 800000000000000f + 7 000100000000 262144 000000000000000f + 0 0000000a0000 32 8000000000000000 + 0 0000bff00000 256 8000000000000000 + 11 0000f00f8000 1 8000000000000000 + 11 0000fed1c000 4 8000000000000000 + 11 0000fffa0000 48 8000000000000000 +Usable memory: 4092 MB +End of report diff --git a/docs/lfnapi.txt b/docs/lfnapi.txt index 2a323041..9d5012b5 100644 --- a/docs/lfnapi.txt +++ b/docs/lfnapi.txt @@ -1,21 +1,52 @@ - FreeDOS LFN helper API. + modernDOS native long filename (LFN) API -struct lfn_inode -{ - UNICODE name[261]; +The kernel implements the Windows 95 long filename functions +(INT 21h AH=71h) for local FAT12, FAT16 and FAT32 drives. No TSR such +as DOSLFN is needed. If one is loaded it hooks INT 21h first and keeps +working as before. - struct dirent l_dir; /* this file's dir entry image */ +Supported functions + 710Dh reset drive + 7139h make directory 713Ah remove directory + 713Bh change directory 7147h get current directory + 7141h delete (SI=1: wildcards, long and short names) + 7143h get/set attributes, physical size, write/access/creation times + 714Eh find first 714Fh find next 71A1h find close + 7156h rename / move (also changes only the case of a name) + 7160h truename (CL=0 canonical, CL=1 short, CL=2 long) + 716Ch extended open/create + 71A0h volume information (BX=4006h, "FAT" or "FAT32") + 71A7h FILETIME <-> DOS date/time + 71A8h generate short name (basis name, no numeric tail) + 7142h and 71A6h are passed to network redirectors as before. + All other subfunctions, and all calls for network/redirected drives, + return AX=7100h with CF set (the Win95 "not supported" convention). - ULONG l_diroff; /* offset of the dir entry */ -}; -typedef struct lfn_inode FAR * lfn_inode_ptr; +Behaviour + - Short aliases follow Win95: NAME~1.EXT, and the base shrinks for + longer numeric tails (LOTSO~10.TXT). Names that fit 8.3 but contain + lower case keep their case through an LFN entry. + - Lookups are case insensitive and match long and short names. + - Names are exchanged in the OEM code page; code page 437 is used for + the UCS-2 conversion on disk. + - DOS has no time zone; FILETIME values treat local time as UTC. + - 8 concurrent 714Eh search handles; handles left open are released + when the owning process terminates. -COUNT lfn_allocate_inode(VOID); -COUNT lfn_free_inode(COUNT handle); +Builds + Enabled in the GCC (ia16-gcc) build, the modernDOS reference build. + The Open Watcom build does not include it: Watcom links init code into + the same 64K TGROUP as resident code, and the LFN code (~7.4K) does not + fit. That build behaves exactly like upstream FreeDOS. -COUNT lfn_setup_inode(COUNT handle, ULONG dirstart, ULONG diroff); +Limitations + - JOINed directories inside a long path are not followed. + - Long paths are limited to 260 characters; the equivalent short path + must fit in 127 characters (directories: 66, as for classic DOS). -COUNT lfn_create_entries(COUNT handle, lfn_inode_ptr lip); - -COUNT lfn_dir_read(COUNT handle, lfn_inode_ptr lip); -COUNT lfn_dir_write(COUNT handle); +Implementation: kernel/lfnapi.c (path translation, name generation, +directory scanning) plus small hooks in kernel/fatfs.c that reserve +consecutive directory entries and write the LFN entries. +Tests: tests/lfn (run with scripts/mdtest.sh): an ia16 test of every +subfunction, plus a DJGPP program checking the same through libc +(fopen, readdir, rename, stat, getcwd, _truename, ...). diff --git a/docs/mdvmm.md b/docs/mdvmm.md new file mode 100644 index 00000000..3cff589e --- /dev/null +++ b/docs/mdvmm.md @@ -0,0 +1,347 @@ +# MDVMM - modernDOS virtual machine monitor + +MDVMM is the 32-bit supervisor in the modernDOS architecture. It runs DOS in +a virtual 8086 machine and will host 32-bit DPMI programs (the future GUI) +and several DOS sessions. + +## Status + +| Part | State | +|---|---| +| M2.1 V86 monitor | working: DOS, FreeCOM, XMS, disk, timer, keyboard controller under the monitor | +| M2.2 DPMI host | working: DPMI 0.9 for 16/32 bit clients; DJGPP programs run without CWSDPMI | +| M2.3 multiple DOS sessions | working: up to 4 preemptively scheduled DOS sessions, Ctrl+Alt+F1..F4 | +| M3.1 UEFI boot | working: BOOTX64.EFI starts the core, which provides a virtual PC BIOS (GOP text console, PS/2 keyboard, timer, RTC, disk image from the ESP) and boots DOS | +| M3.2 UEFI: XMS, sessions | working: extended memory for XMS drivers (DOS=HIGH), DPMI, DOS sessions on UEFI boots | +| M3.3 AHCI | working: SATA disks on AHCI controllers are BIOS hard disks 80h+ (EDD), writes reach the disk | +| M3.4 NVMe | working: NVMe namespaces (512-byte blocks) are BIOS hard disks too; registers above 4 GB via PSE-36 | +| M3.5 USB keyboard | working: keyboards on xHCI root ports (HID boot protocol) arrive as PS/2 scancodes, with typematic repeat | + +## Using it + +``` +DEVICE=HIMEMX.EXE (CONFIG.SYS: any XMS driver) +MDVMM (AUTOEXEC.BAT or prompt) +``` + +``` +MDVMM NEW [command] start another DOS session running COMSPEC + (/C command); Ctrl+Alt+F1..F4 switch the screen +``` + +On a UEFI PC (no CSM), copy `mdvmm/build/BOOTX64.EFI` to +`\EFI\BOOT\BOOTX64.EFI` on the EFI system partition and a bootable DOS +floppy image to `\MDOS\BOOT.IMG`. The monitor is then already +running when DOS starts; `MDVMM` without arguments (AUTOEXEC.BAT) only +sets up DOS sessions. See "UEFI boot" below. + +MDVMM takes a 32 MB pool from XMS (less if less is free), moves itself there +and keeps under 1 KB of conventional memory. DPMI programs allocate from the +pool. It cannot be unloaded; reboot +to leave it. It refuses to start when the CPU is already in protected or V86 +mode (EMM386, JemmEx, another MDVMM). + +## Design + +- `mdvmm/loader/loader.asm` - MDVMM.COM: CPU/XMS checks, pool allocation, + copies the core into the pool, switches to protected mode, and continues + in V86 mode at `resumed` before going resident. +- `mdvmm/core/` - freestanding 32-bit C, linked at 0xF0000000. It does not + depend on DOS; the UEFI loader starts the same core. + - `entry.asm` - position independent start, page tables, interrupt stubs + - `cpu.c` - GDT, IDT, TSS with I/O permission bitmap, PIC remapped to 20h + - `mm.c` - pool allocator, temporary physical mappings + - `v86.c` - the monitor + - `dpmi.c` - DPMI host + - `vm.c` - DOS sessions + - `dma.c` - ISA DMA virtualization + - `bios.c`, `rom.asm`, `fbcon.c`, `font.c` - virtual PC BIOS (UEFI boot) + - `pci.c`, `ahci.c`, `nvme.c` - PCI configuration space, device register + mappings, AHCI and NVMe disk drivers + - `xhci.c`, `usbkbd.c` - xHCI host controller, USB keyboards + - `nobios.c` - stubs: the core in MDVMM.COM (64 KB .COM limit) is linked + without the virtual BIOS and the drivers; BOOTX64.EFI has the full core +- `mdvmm/uefi/` - BOOTX64.EFI: x64 UEFI application with the core embedded. +- The loader and the core share `struct bootinfo` (`mdvmm/include`). + +V86 mode runs with IOPL 0. CLI, STI, PUSHF, POPF, INT, IRET and HLT trap into +the monitor and are emulated against a virtual interrupt flag. Hardware +interrupts always reach the monitor and are reflected into the DOS interrupt +vector table when the virtual IF allows it. + +Intercepted services: + +| Interface | Handling | +|---|---| +| INT 15h AH=87h | extended memory block move, done by the monitor (XMS drivers use it in V86 mode) | +| INT 15h AH=89h | switch to protected mode: refused (CF=1) | +| ports 60h, 64h, 92h | A20 stays enabled: A20 commands are swallowed, other traffic passes through | +| INT 2Fh AX=DE00h | installation check: AL=FFh, BX=4D44h ("MD"), CX=API version | +| INT 2Fh AX=DE01h | write the ASCIZ string at DS:DX to the monitor log | +| INT 2Fh AX=DE02h | fork the running session (parent: AX=new session, child: AX=0, BX=number) | +| INT 2Fh AX=DE03h | end the running session (not session 0) | +| INT 2Fh AX=DE04h | loader registers the per-session DOS data (internal) | +| INT 2Fh AX=DE05h | set focus: BL=session | +| INT 2Fh AX=DE06h | AX=running session, BX=focused session, CX=number of sessions, DX=1 if sessions are set up | +| INT 2Fh AX=DE07h | UEFI boots: install the virtual BIOS mouse driver as INT 33h; AX=1 if installed | +| ports 00-0F, C0-DF, 81-8F | ISA DMA controllers, virtualized (see below) | + +The monitor logs to I/O port E9h (QEMU `-debugcon`, Bochs). + +## DPMI host + +`core/dpmi.c` implements DPMI 0.9 (16 or 32 bit clients). Every DOS +session can have a client, and a client can start a program that becomes +a client itself (four deep): the first waits in its EXEC call. The host's +state (descriptor table, client record, transitions, host stack) is that +of the running session and is swapped on a session switch; each session's +clients have their own slice of the linear address space. +Clients run at ring 3 with IOPL 3, so CLI/STI act on the real interrupt +flag, as with CWSDPMI. + +Mode transitions use breakpoints. On the V86 side these are HLT +instructions in the loader's resident stub (`BP_*` in `bootinfo.h`): the +DPMI entry, returns from real-mode calls, raw mode switches and 16 real-mode +callbacks. On the protected-mode side, a ring-3 host code page full of HLT +(selector 2Bh) serves as return addresses for exception, IRQ and callback +handlers and as the default interrupt and exception vectors. Nested +transitions are kept on a stack of saved frames. + +| Group | Functions | +|---|---| +| descriptors | 0000-0003h, 0006-000Ch (LDT of 1024 entries) | +| DOS memory | 0100-0102h | +| interrupts | 0200-0205h; IRQs go to PM handlers in PM and in real mode | +| real mode | 0300-0306h, 16 callbacks, raw switch | +| info | 0400h (0.90, 32 bit), 0500h | +| memory | 0501-0503h (paged from the pool), 0600-0604h, 0702/0703h, 0800/0801h | +| virtual IF | 0900-0902h | + +The host real-mode stack is the 2 KB of private data the client allocates +for the host (SI=80h from INT 2Fh AX=1687h). For returns to 16-bit client +stacks the monitor uses the "espfix" technique, so ESP[31:16] does not leak +the monitor's stack address. + +A DOS program a client starts (e.g. with `system()`) runs normally: its +INT 21h AH=4Ch ends the client only if DOS's current PSP is the client's. +Interrupts a client reflects to real mode also reach the monitor's own +services (INT 2Fh AH=DEh, INT 15h AH=87h). + +Not yet: DPMI 1.0 functions, several clients at once (a DPMI program +starting another one), virtual memory. + +### DOS extenders and other DOS programs + +`tests/compat` runs programs of the kinds DOS software comes in: a 16-bit +real mode program, the same program under DOS/4GW, PMODE/W, DOS/32A and +CauseWay, and the Open Watcom compiler and linker hosted on DOS (DOS/4GW +programs started by a real mode driver). What they needed from the host: + +- `MOV r32, CR0` in V86 mode is answered (protected mode on), other + control and debug register moves are ignored; an instruction a program + cannot use here (LIDT, a switch to real mode) ends the program, not the + machine. +- The I/O privilege level in the flags reads as 3 and cannot be changed, + as under EMM386 and Windows: that is how programs tell V86 mode from + real mode (DOS/32A). +- A client's own protected mode handlers come first, also for INT 31h + (CauseWay adds its services there) and INT 21h AH=4Ch (DOS/4GW cleans + up in its handler before the program ends); they chain to the host. +- Selector 0040h is the BIOS data area (DOS/4GW reads the timer there). +- Real mode vectors a program leaves pointing into its own memory when it + ends are put back to what they were before the program set them. + +`tests/compat/game.sh` plays the start of a game off the shelf +(Kiloblaster, 1992: real mode, its own keyboard and timer handlers, mode +X) on both editions and compares the pictures. + +## DOS sessions + +All sessions share one DOS kernel, as in Windows 386 enhanced mode. +`MDVMM NEW` forks the running session in the monitor and the child EXECs +COMSPEC; session 0 is the original DOS. + +- Memory below the end of MDVMM's resident block (rounded up to 4K) is + global: kernel, drivers, TSRs loaded before MDVMM. From there to 640K + each session has private pages. +- Instance data is swapped on every switch: IVT, BIOS data area and + 500h area, the CDS array and the kernel's instance table from the + INT 2Fh AX=1605h startup broadcast (the swappable data area with the + DOS stacks, and the private stacks of the built-in drivers and INT 2Fh). + Global kernel structures (SFTs, buffers, DPBs) are not instanced. +- The kernel is built with WIN31SUPPORT: INT 21h functions other than + character I/O (01h-0Ch) run inside an INT 2Ah critical section, and the + monitor never switches sessions inside one. +- Scheduling: round robin, 2 timer ticks per slice; a session that idles + (INT 28h, INT 2Fh AX=1680h, HLT) yields at once. Missed timer ticks are + added to the BIOS tick count when a session runs again. +- Hardware interrupts go to the running session, except the keyboard: + the monitor takes every scancode from the controller (hotkeys are its + own) and gives it to the session on the display as a keyboard interrupt + of its own - the scancode at port 60h, the controller's status saying + so, one keystroke at a time (not before the handler of the one before + has returned). A 32-bit program's own keyboard handler reads the + controller itself, unseen by the monitor (DPMI clients have I/O + privilege; every DJGPP program has such a handler, for Ctrl+C): for it + the scancode is put into the controller (keyboard interface off, what + waits there into the queue, command D2h), or the handler would take the + next waiting one in its place and that keystroke would be lost. Needs a + keyboard controller: on machines with USB keyboards only, such handlers + read nothing of use (DOS and BIOS keyboard input are not affected). +- Text mode video: the focused session owns B8000h, the others write to + shadow pages. +- DOS boots (the machine's own BIOS), "flat" sessions: memory below 640K + is copied on a switch, not remapped, so a linear address is the + physical one (BIOS disk code in system management mode and DMA + hardware read memory by physical address). A session inside a BIOS + service (INT 10h-1Ah) is not switched out - a BIOS is written for one + thread (SeaBIOS: one stack of its own for all services) - and a wait + for a key (INT 16h AH=00h/10h) is done by the monitor in the BIOS's + place. A session that is not on the display does not reach the video + hardware: writes to the VGA ports are dropped, a text mode set is done + in its own screen memory, a graphics mode set waits for the display. +- One network card for all sessions: see `docs/network.md`. +- INT 15h AH=87h block moves translate addresses below 110000h through + the running session's page tables (XMS moves into private memory). + +### ISA DMA + +The 8237 controllers use physical addresses, so the monitor owns them. +It keeps a shadow of each channel and programs the real controller +itself: unchanged for identity mapped memory, translated for physically +contiguous memory, otherwise through a 128 KB bounce buffer below 16 MB. +Device->memory data is copied out of the bounce buffer at every hardware +interrupt before any handler runs, when the channel is masked and when +the status register is read. Reads of the current address are translated +back. DPMI clients (IOPL 3) program the controller directly. + +## UEFI boot + +A UEFI machine has no PC BIOS, and DOS needs one. `BOOTX64.EFI` reads +`\MDOS\BOOT.IMG` from the boot volume and takes the GOP framebuffer, +a 32 MB pool below 4 GB and one page below 640K. It then exits boot +services, leaves long mode (32-bit protected mode, paging off) and starts +the core like the DOS loader does, with `boot_type = BOOT_UEFI` in +`struct bootinfo` (version 3). + +It also allocates up to 64 MB of contiguous memory below 4 GB as DOS +extended memory (`xms_phys`/`xms_size`, bootinfo version 4). + +Before anything else the loader writes a hardware report, +`\MDOS\HWINFO.TXT`, to the boot volume if it is writable (a USB +stick, not a CD): firmware vendor and version, SMBIOS model, CPU, GOP +modes and UGA, every PCI device with its BARs and IRQ line, the EFI +configuration tables and the memory map (`uefi/hwinfo.c`). It is how +drivers for a real machine are written without access to it. + +The core then sets up a PC (`bios.c`): + +- `rom.asm` at F000:0000 (RAM from the pool). BIOS services are HLT + breakpoints followed by RETF 2: the monitor does the work on the V86 + registers. IRQ0/IRQ1 handlers are real 16-bit code with a breakpoint + inside, so DOS and TSRs hook and chain all vectors as usual. The ROM + also holds the DPMI stubs, so the DPMI host works without MDVMM.COM. +- IVT, BIOS data area (conventional memory size from the UEFI memory + map), PIT at 18.2 Hz, PIC masks. +- INT 10h: text mode 3 on RAM at B8000h. `fbcon.c` draws changed cells + and the cursor on the framebuffer every timer tick, with the 8x16 font + scaled up to 2x. Teletype output is mirrored to COM1 when a UART exists. + VBE 3.0 with one mode (141h): the GOP framebuffer, 32 bpp linear; the + console stops drawing while it is set (see `docs/gui.md`). +- INT 13h: the disk image as floppy drive 00h (geometry from its BPB); + writes go to memory only. Hard disks from native drivers are drives + 80h and up (BIOS data area 40:75h): CHS functions with a 255/63 + geometry, and the EDD extensions 41h, 42h, 43h, 48h. Transfers go + through 64 KB of pool pages; drivers implement `struct disk`. Disk + resets (AH=00h/0Dh, e.g. from INT 21h AH=0Dh) flush the drive's write + cache. +- AHCI (`ahci.c`): every AHCI controller on PCI (class 01:06:01), every + port with a SATA disk. Port takeover, IDENTIFY, READ/WRITE DMA (EXT), + one command at a time, polled with interrupts off (the machine stops + during a transfer, as with a PIO BIOS). +- NVMe (`nvme.c`): every NVMe controller (class 01:08:02): reset, admin + queue, one I/O queue pair of 16 entries, polled. Each active namespace + with 512-byte blocks becomes a hard disk (4K-block namespaces are + skipped). Disk order: AHCI ports first, then NVMe namespaces. +- Device registers are mapped uncached at EC000000h. Registers above + 4 GB (64-bit BARs, the usual case for NVMe) get 4 MB pages with PSE-36, + which puts physical address bits 32-39 in the page directory entry; the + core keeps 32-bit paging. +- INT 16h / IRQ1: PS/2 keyboard (scancode set 1; machines without a + keyboard controller, e.g. Macs, read FFh and are left alone), BIOS keyboard buffer, + INT 15h AH=4Fh hook, Ctrl+Alt+Del reboots. +- USB keyboards (`xhci.c`, `usbkbd.c`), like a BIOS's legacy USB + support: each xHCI controller (class 0C:03:30) is taken from the + firmware (legacy support handoff) and reset; devices on root ports are + addressed and the first HID boot keyboard interface gets eight queued + interrupt transfers. The event ring is polled on every timer tick and + INT 16h call. Report changes become scancode set 1 make/break codes, + which reach the focused session as a virtual IRQ1 with the byte at + port 60h (`vm_key`), so INT 09h hooks see them as PS/2 keys and the + session hotkeys work. The last key held repeats after 500 ms, about + 9 per second. (by the clock, not by timer ticks: every session has + its ticks, and missed ones come in a burst). Not yet: hubs, hotplug, keyboard LEDs. +- USB mice (HID boot protocol) feed an INT 33h mouse driver + (`mouse.c`); `MDVMM` installs it after DOS has started (DOS resets + INT 33h). See `docs/gui.md`. +- Extended memory: DOS sees the loader's region at 1 MB, through INT 15h + E820h, E801h and 88h, so any XMS driver works (HIMEMX, `DOS=HIGH`). + The HMA (linear 100000h-10FFFFh) is mapped to its first 64 KB. INT 15h + AH=87h block moves and DPMI 0800h mappings translate addresses in this + window (`ext_phys`); moves outside it fail. +- INT 1Ah (ticks, CMOS RTC), INT 11h, 12h, 14h, 15h (C0h, 24h, 4Fh), + 17h, 18h, 19h. + +Finally the boot sector of the disk image is started at 0000:7C00, as a +BIOS does, and loads the kernel. + +## Limitations + +- Programs that switch to protected mode themselves without DPMI (raw or + VCPI) stop the machine with a monitor panic. VCPI is not planned. +- Reprogramming the PIC vector base from DOS is not virtualized. +- A20 is always enabled (programs relying on 1 MB wraparound need LOADFIX). +- UEFI boot: the boot floppy is a RAM copy of the image (writes are + lost; hard disks are real); USB keyboards only on root ports (no + hubs, no hotplug), no USB mice; of the VGA modes text, mode 13h (320x200, 256 + colours), its unchained relatives ("mode X": four planes, page + flipping, 320x240) and the 16 colour modes 0Dh, 0Eh, 10h and 12h (up to + 640x480; palette registers of the attribute controller, BIOS pixels and + text in the graphics modes) - `core/vga.c`: the monitor is the display + card, the picture is drawn enlarged on the framebuffer; a DPMI client's + access to the card's ports is caught with I/O breakpoints; in the planar + modes A0000h is unmapped and `core/vgaemu.c` runs the instructions that + touch it. Not: split screen, pixel panning, blinking, the CGA modes + 04h-06h, the monochrome modes, the VGA's fonts in memory (text in + graphics modes uses the monitor's 8x16 font, cut to 14 and 8 lines); + the framebuffer must be below 4 GB + and 32 bpp RGB/BGR; no ISA DMA (no bounce buffer below 16 MB). +- Sessions: graphics modes are not virtualized (a session that is not on + the display waits when it sets one; a DPMI client's mode set through + DPMI is not caught); DPMI clients are not protected from each other + (their memory is all mapped); on UEFI boots a DPMI client doing its own + DMA in a session other than 0 gets wrong addresses. + +## Testing + +`tests/mdvmm/run.sh` boots HIMEMX + FreeCOM in QEMU, loads MDVMM from +AUTOEXEC.BAT and runs V86CHK, XMSTEST, the long filename suite and two +DJGPP programs inside the virtual machine, then starts a second session +(`MDVMM NEW BG.BAT`) and runs SESSTEST in both: preemption while session 0 +never yields, Ctrl+Alt+F2/F1 (sent through the QEMU monitor), the floppy +DMA bounce path and file contents written by both sessions. DJTEST +covers libc file I/O with long names; DPMITEST covers memory, exceptions +as signals, a protected-mode IRQ0 handler, a real-mode callback, DOS +memory and descriptors. There is no CWSDPMI on the test disk. Extra QEMU +options can be passed in `QEMU_EXTRA`, for example `-d int,cpu_reset -D qemu.log`. + +`tests/uefi/run.sh` boots OVMF from a FAT ESP holding BOOTX64.EFI and the +DOS image (HIMEMX, `DOS=HIGH`), runs the MDVMM test programs (V86CHK, +XMSTEST, LFNTEST, DJTEST, DPMITEST, a second session with SESSTEST) and +DISKTEST on a 64 MB AHCI disk as C: and a 96 MB NVMe disk as D: (MBR, +FAT16; OVMF puts the NVMe registers above 4 GB). After QEMU exits both +disks are checked from Linux: fsck, a 1 MB pattern file, FROMDOS.TXT. It +also types a command at the FreeCOM prompt through QEMU `sendkey` and +checks the echo in the COM1 mirror of the screen; a key held for 1.5 s +must repeat. All keys go to a USB keyboard on an xHCI controller. +`SCREEN=file.ppm` saves the framebuffer. diff --git a/docs/modern-hooks.md b/docs/modern-hooks.md new file mode 100644 index 00000000..af9e135c --- /dev/null +++ b/docs/modern-hooks.md @@ -0,0 +1,25 @@ +# Kernel hooks for the MDVMM supervisor + +MDVMM (milestone M2) is a planned 32-bit supervisor that runs the modernDOS kernel and legacy programs in V86 virtual machines. It will cooperate with the kernel the way Windows 3.x/9x enhanced mode cooperated with MS-DOS. That interface already exists in the FreeDOS kernel, and modernDOS treats it as a stable contract. + +## Interfaces the kernel provides + +| Call | Where | Status | Purpose | +|---|---|---|---| +| INT 2Fh AX=1605h | `kernel/inthndlr.c` (AH=16h) | implemented | Startup broadcast. The kernel returns ES:BX pointing to a startup structure with its instance data table (`kernel/kernel.asm`, `instance_table`, ending at `_markEndInstanceData`). These are the DOS data areas the supervisor must keep per VM. Sets `winInstanced`. | +| INT 2Fh AX=1606h | same | implemented | Exit broadcast. Clears `winInstanced`. | +| INT 2Fh AX=1607h, BX=0015h | same | implemented | DOSMGR device API: query support, return the kernel patch table, enable/disable compatibility behaviour. | +| INT 2Fh AX=1680h | `kernel/int2f.asm` | implemented | Idle / release time slice. The kernel calls it from its idle loop and may HLT, depending on `IDLEHALT`. A supervisor hooks it to schedule other VMs. | +| INT 2Ah AH=80h/81h | `kernel/entry.asm` | **built only with `WIN31SUPPORT`** | Enter or leave a DOS critical section around INT 21h, signalled only while `winInstanced` is set. | +| INT 2Ah AH=82h | `kernel/entry.asm` | implemented | End of all critical sections (server hook), called on INT 21h exit. | +| InDOS flag / SDA | `kernel/entry.asm`, INT 21h AX=5D06h | implemented | Lets a supervisor tell whether DOS can be re-entered safely. | + +## Decisions for M2 + +- **Turn on `WIN31SUPPORT` in the GCC and Watcom builds**, so the kernel signals critical sections once a supervisor has announced itself through 1605h. The code path is inert until then (`winInstanced == 0`). It stays off in milestone 1 because nothing can test it yet. +- MDVMM should announce itself with a Windows-compatible 1605h broadcast. DOS TSRs and drivers that already understand Windows (SHARE, network clients, mouse drivers) then work unchanged. +- The kernel keeps all hardware access behind BIOS interrupts (INT 10h/13h/16h/1Ah). This is the boundary where MDVMM substitutes native drivers on UEFI machines. + +## Long filename API + +INT 21h AH=71h is implemented natively in `kernel/lfnapi.c`. It answers local FAT drives only. Network and redirected drives (CD-ROM, network clients) get AX=7100h with CF set, so the redirector or a TSR can handle them. A supervisor needs no special handling for it. diff --git a/docs/network.md b/docs/network.md new file mode 100644 index 00000000..6dfc0b4a --- /dev/null +++ b/docs/network.md @@ -0,0 +1,139 @@ +# modernDOS networking, SSH, installation (milestone M6) + +## The layers + +| Layer | What | Where | +|---|---|---| +| Network cards | UEFI boots: **iPXE's drivers** built into the monitor (Marvell Yukon/Yukon-2, Intel 8254x/8257x/I210 and 8255x, Realtek 8139/8169/8111, Broadcom tg3 and b44, nForce, Atheros L1E, JMicron, VIA, SiS 190, AMD PCnet, NatSemi, 3c90x, virtio, vmxnet3). DOS boots: a small native Intel e1000 driver (MDVMM.COM has no room for more) | `mdvmm/ipxe/`, `mdvmm/core/ipxenic.c`, `e1000.c`, `nic.c` | +| Monitor calls | INT 2Fh AX=DE10h info, DE11h send, DE12h receive, DE13h driver state to the log | `mdvmm/core/nic.c` | +| Packet driver | `PKTDRV.COM`: a standard packet driver (class 1) on those calls | `mdvmm/pktdrv/` | +| TCP/IP | Watt-32 (DJGPP library): DHCP, DNS, BSD sockets; `WATTCP.CFG` | build image, `build/watt32.sh` | +| SSH | `SSHD.EXE` (shell, exec, sftp/scp), `SSH.EXE` (client with a terminal emulator) | `net/ssh/` | + +### iPXE's drivers in the monitor + +iPXE's drivers are written for a polled, single-threaded environment, and +its 32-bit memory model ("physical = virtual + a fixed offset") is true +for the monitor's pool. `mdvmm/ipxe/build.sh` compiles the drivers named +in `drivers.list` and the parts of iPXE's core in `core.list` with a small +platform configuration (`overlay/`), links them with `glue.c` into one +object and makes every name but `ipxe_*` local. The source tree is a +pinned snapshot in the build image (`build/ipxe.sh`). To add a driver: add +its file to `drivers.list`; the link step lists what else it needs. +`make -C mdvmm IPXE_DEBUG=sky2` sends that driver's debug messages to the +monitor's log (`MDLOG`). + +## Using it + +`NET` (NET.BAT) starts job slots for remote shells, a local prompt in +another session (Ctrl+Alt+F4), `PKTDRV` and `SSHD`. Logins need +`AUTHKEYS.TXT` (OpenSSH public keys) or a password (`SSHD /PASSWD`). +From another machine: `ssh dos@host`, `sftp`, `scp`; drives are `/A`, `/C`. +`MDLOG` shows the monitor's log, `MDLOG /N` with the network card's state. + +A personal image has one's own keys built in: + + mkdir -p _output/personal + head -c 32 /dev/urandom > _output/personal/HOSTKEY.ED # the host key + cp ~/.ssh/id_ed25519.pub _output/personal/AUTHKEYS.TXT + scripts/mkiso.sh 0.0.2-dev-personal _output/personal + +Never publish a personal image: it holds the host's private key. + +## Installing on a machine's disk + +A stick made from a personal image has `\MDOS\INSTALL`: at start the +loader offers to install (press Y). It copies `\EFI\BOOT\BOOTX64.EFI` and +`\MDOS` to a writable FAT volume of the machine, normally the EFI +system partition of its disk, with the firmware's own file system driver. +Nothing else on the disk is changed; another fallback loader is kept as +`BOOTX64.OLD`. On Apple firmware the loader also makes it the default +start entry (otherwise: hold Option, "EFI Boot"). + +Installed, the EFI system partition is DOS drive `C:`: the virtual BIOS +gives DOS a made-up MBR for GPT disks that lists their FAT partitions. +`C:\MDOS\SSH` keeps the SSH host key, `AUTHKEYS.TXT` and `WATTCP.CFG` +(copied there at the first start); the network and SSH server start by +themselves. `A:` stays a RAM disk loaded from `C:\MDOS\BOOT.IMG`. + +## Updating a machine nobody sits at + + scripts/mdpush.sh # upload a build, restart into it as a trial + scripts/mdpush.sh status + scripts/mdpush.sh keep # the trial becomes the installed build + +A build is two files, `BOOTX64.EFI` and `BOOT.IMG`. They go to +`C:\MDOS\TRY`; `TRYBOOT` creates `\MDOS\TRYONCE` and restarts. +The installed loader removes that file and starts the loader in `TRY`, +once. A trial that is not confirmed (`KEEP`, or `MDSYS KEEP`) within ten +minutes restarts the machine: back into the installed build. So does a +monitor panic during a trial (after a minute). `KEEP` copies the trial's +files over the installed ones. + +What this does not cover: a trial that hangs with interrupts off inside +the monitor, and power loss while `KEEP` copies (the stick is the rescue). + +## The BIOS edition on a disk + +`modernDOS--bios.img` is a hard disk image (MBR, one 64 MB FAT16 +partition): written to a USB stick it starts on a PC BIOS, with the system +in `C:\MDOS` on the stick itself (settings, keys and packages stay). +`INSTALL` there puts it on the machine's own disk - started from the stick +that is disk 2 for FDISK, its first partition drive D: + + INSTALL GO on D:, a FAT partition that is there (files stay, + the boot sector is replaced) + INSTALL NEW an empty disk: one partition over the whole disk + (erases it); restart from the stick, then + INSTALL FORMAT formats D:, then installs + +It uses the kernel's SYS and FreeDOS FDISK, FORMAT and XCOPY, copies +`C:\MDOS` with the SSH keys, and sets the partition active. Test: +`tests/bios`. + +## One card, several sessions + +The packet driver is loaded before the DOS sessions are forked, so every +session has it, and every program brings its own TCP/IP stack (Watt-32) +and gets the card's one address from DHCP. The monitor sorts the frames +(`mdvmm/core/nic.c`): TCP and UDP of a connection go to the session that +has sent on it, TCP to a port a session has accepted on goes there, +everything else (ARP, DHCP, ICMP, a first SYN) to every session whose +program polls. The answers stacks give to segments that were not theirs +(TCP resets, ICMP unreachable) are dropped on the way out. So the SSH +server, a browser and PKG work side by side. Limit: two sessions that +pick the same local port for the same server at the same time collide. + +## Packages + +`PKG` (`net/pkg/`, UEFI boot disk) installs packages from a repository on +a web server: + + PKG UPDATE fetch the repository's package list + PKG LIST packages, [*] = installed + PKG INSTALL name download, check, unpack + PKG REMOVE name + +`PKG.CFG` (next to PKG.EXE, or in `%PKGDIR%`; `C:\MDOS` when installed) +names the repository, its public key and where packages go: + + repo = http://192.168.1.10:8080/ + key = <64 hex digits> + root = C:\ + +A repository may be `http://` or `https://`; trust comes from signatures +either way: `INDEX.TXT` (name, +version, file, size, SHA-256, description per package) is signed with the +repository's ed25519 key (`INDEX.SIG`); PKG uses a list only if the +signature fits the key in PKG.CFG, and a package only if its SHA-256 is +the one in the list. Packages are uncompressed tar archives; names that +would leave the install root are skipped. A repository is made with + + scripts/mkrepo.sh # prints the public key + python3 -m http.server 8080 -d + +from a directory per package (`/PKGINFO` with `version=` and +`description=`, the files under `/root/`). + +Tests: `tests/net`, `tests/ssh`, `tests/usb`, `tests/install`, `tests/pkg` +(all in `scripts/mdtest.sh`). diff --git a/gui/Makefile b/gui/Makefile new file mode 100644 index 00000000..9ea9b9fe --- /dev/null +++ b/gui/Makefile @@ -0,0 +1,41 @@ +# mdgui - modernDOS graphics library (32-bit DPMI programs, DJGPP) +# Builds build/mdgui.o: the library as one relocatable object (link it +# into a program like a .o; DJGPP's ar is broken in the build image), and +# build/MDDESK.EXE, the desktop. + +DJGPP ?= /opt/djgpp/bin/i586-pc-msdosdjgpp- +CC = $(DJGPP)gcc +CFLAGS = -O2 -Wall -Wextra -Werror -Ilib + +B = build +OBJS = $(B)/gfx.o $(B)/draw.o $(B)/text.o $(B)/input.o $(B)/wm.o $(B)/ui.o $(B)/theme.o $(B)/font.o + +all: $(B)/mdgui.o $(B)/MDDESK.EXE + +$(B): + mkdir -p $(B) + +$(B)/%.o: lib/%.c lib/mdgui.h | $(B) + $(CC) $(CFLAGS) -c -o $@ $< + +$(B)/font.o: ../mdvmm/core/font.c | $(B) + $(CC) $(CFLAGS) -c -o $@ $< + +$(B)/mdgui.o: $(OBJS) + $(CC) -r -nostdlib -o $@ $(OBJS) + +DESK = desk/desk.c desk/files.c desk/editor.c desk/settings.c desk/term.c desk/browser.c +# the browser's network side: the HTTP client on Watt-32, code page 437 +WATT = /opt/watt32 +BEAR ?= $(firstword $(wildcard /opt/bearssl ../_output/ext/bearssl)) +NET = ../net/pkg/http.c ../net/pkg/tls.c ../net/ssh/console.c ../net/ssh/buf.c ../net/ssh/rng.c \ + ../net/ssh/crypto/monocypher.c + +$(B)/MDDESK.EXE: $(DESK) $(NET) desk/desk.h $(B)/mdgui.o lib/mdgui.h ../net/pkg/http.h + $(CC) $(CFLAGS) -I$(WATT)/inc -I$(BEAR)/inc -I$(BEAR) -s -o $@ $(DESK) $(NET) $(B)/mdgui.o \ + -L$(WATT)/lib -lwatt $(BEAR)/lib/libbearssl.a + +clean: + rm -rf $(B) + +.PHONY: all clean diff --git a/gui/desk/browser.c b/gui/desk/browser.c new file mode 100644 index 00000000..c9d326ef --- /dev/null +++ b/gui/desk/browser.c @@ -0,0 +1,874 @@ +/* + * MDDESK Browser - a small web browser (M6). + * + * http and https (TLS 1.2, BearSSL), text layout: a page becomes lines of character + * cells with a style (text, bold, heading, link, preformatted). Handles + * headings, paragraphs, line breaks, lists, links, preformatted text, + * rules, tables (cells in a row), image and form placeholders, character + * entities and UTF-8 (shown in code page 437). Scripts and style sheets + * are skipped. + * + * Address field + Go, Back; in the page: click a link, Up/Down, PgUp/PgDn, + * Home/End scroll, Backspace goes back. The network is Watt-32 through + * the packet driver (load PKTDRV before the desktop). + */ +#include +#include +#include +#include +#include +#include "desk.h" +#include "../../net/pkg/http.h" +#include "../../net/ssh/console.h" + +enum { ST_TEXT, ST_BOLD, ST_HEAD, ST_LINK, ST_PRE, ST_DIM }; +#define MAX_COLS 150 +#define MAX_LINES 20000 +#define MAX_LINKS 2000 +#define MAX_PAGE (2 * 1024 * 1024) +#define HISTORY 16 + +struct cell { + unsigned char ch, style; + unsigned short link; /* 1-based, 0: none */ +}; + +struct line { + struct cell *c; + int n; +}; + +struct browser { + struct window *win; + struct ui *ui; + struct widget *addr, *view, *status; + struct line *lines; + int nlines, cap; + char **links; + int nlinks; + char title[80], url[512]; + int top; /* first line shown */ + int cols, rows; + char history[HISTORY][512]; + int nhist; + /* layout state while a page is parsed */ + struct cell cur[MAX_COLS]; + int ncur, style, link, pre, indent, pending_space, blank; +}; + +/* strstr without regard to case (not in every C library) */ +static const char *find_nocase(const char *hay, const char *needle) +{ + size_t n = strlen(needle); + + for (; *hay; hay++) + if (!strncasecmp(hay, needle, n)) + return hay; + return 0; +} + +static struct browser *the; /* one browser window */ +static int net_up; + +/* ---------------------------------------------------------------- */ +/* the page: lines of cells */ + +static void page_clear(struct browser *b) +{ + int i; + + for (i = 0; i < b->nlines; i++) + free(b->lines[i].c); + for (i = 0; i < b->nlinks; i++) + free(b->links[i]); + b->nlines = b->nlinks = 0; + b->ncur = b->style = b->link = b->pre = b->indent = b->pending_space = 0; + b->blank = 1; + b->top = 0; + b->title[0] = 0; +} + +static void flush_line(struct browser *b) +{ + struct line *l; + + if (b->nlines == MAX_LINES) + { + b->ncur = 0; + return; + } + if (b->nlines == b->cap) + { + int cap = b->cap ? b->cap * 2 : 256; + struct line *n = realloc(b->lines, (size_t)cap * sizeof(*n)); + if (!n) + return; + b->lines = n; + b->cap = cap; + } + l = &b->lines[b->nlines++]; + l->n = b->ncur; + l->c = b->ncur ? malloc((size_t)b->ncur * sizeof(struct cell)) : 0; + if (l->c) + memcpy(l->c, b->cur, (size_t)b->ncur * sizeof(struct cell)); + else + l->n = 0; + b->blank = b->ncur == 0; + b->ncur = 0; + b->pending_space = 0; +} + +static void put_cell(struct browser *b, unsigned char ch) +{ + if (b->ncur == 0) + while (b->ncur < b->indent && b->ncur < b->cols - 8) + { + b->cur[b->ncur].ch = ' '; + b->cur[b->ncur].style = ST_TEXT; + b->cur[b->ncur++].link = 0; + } + if (b->ncur >= b->cols || b->ncur >= MAX_COLS) + { + if (b->pre) + return; /* preformatted: cut */ + /* wrap: move the last word to the next line */ + { + struct cell word[MAX_COLS]; + int n = 0, i = b->ncur; + while (i > b->indent && b->cur[i - 1].ch != ' ') + i--; + if (i > b->indent) + { + n = b->ncur - i; + memcpy(word, b->cur + i, (size_t)n * sizeof(struct cell)); + b->ncur = i; + while (b->ncur > 0 && b->cur[b->ncur - 1].ch == ' ') + b->ncur--; + } + flush_line(b); + while (b->ncur < b->indent && b->ncur < b->cols - 8) + { + b->cur[b->ncur].ch = ' '; + b->cur[b->ncur].style = ST_TEXT; + b->cur[b->ncur++].link = 0; + } + memcpy(b->cur + b->ncur, word, (size_t)n * sizeof(struct cell)); + b->ncur += n; + } + } + b->cur[b->ncur].ch = ch; + b->cur[b->ncur].style = (unsigned char)(b->link ? ST_LINK : b->pre ? ST_PRE : b->style); + b->cur[b->ncur++].link = (unsigned short)b->link; +} + +/* a character of the text (code page 437) */ +static void put_text(struct browser *b, unsigned char ch) +{ + if (b->pre) + { + if (ch == '\n') + flush_line(b); + else if (ch == '\t') + do + put_cell(b, ' '); + while (b->ncur % 8); + else if (ch != '\r') + put_cell(b, ch); + return; + } + if (ch == ' ' || ch == '\n' || ch == '\t' || ch == '\r') + { + b->pending_space = b->ncur > b->indent; + return; + } + if (b->pending_space) + { + b->pending_space = 0; + put_cell(b, ' '); + } + put_cell(b, ch); +} + +static void put_string(struct browser *b, const char *s) +{ + for (; *s; s++) + put_text(b, (unsigned char)*s); +} + +static void line_break(struct browser *b) +{ + if (b->ncur > b->indent || b->pre) + flush_line(b); + b->pending_space = 0; +} + +static void paragraph(struct browser *b) +{ + line_break(b); + if (!b->blank) + { + b->ncur = 0; + flush_line(b); + } +} + +/* ---------------------------------------------------------------- */ +/* addresses */ + +/* href, seen from the page at base, as an absolute address */ +static void resolve(const char *base, const char *href, char *out, size_t n) +{ + char root[512]; + const char *p; + + while (*href == ' ') + href++; + if (strstr(href, "://") || !strncasecmp(href, "about:", 6) || !strncasecmp(href, "mailto:", 7)) + { + snprintf(out, n, "%s", href); + return; + } + snprintf(root, sizeof(root), "%s", base); + p = strstr(root, "://"); + p = p ? strchr(p + 3, '/') : 0; + if (!strncmp(href, "//", 2)) + snprintf(out, n, "%s:%s", strncasecmp(base, "https:", 6) ? "http" : "https", href); + else if (*href == '/') + { + if (p) + root[p - root] = 0; + snprintf(out, n, "%s%s", root, href); + } + else if (*href == '#') + snprintf(out, n, "%s", base); + else + { + char *q = strchr(root, '?'), *slash; + if (q) + *q = 0; + slash = strrchr(root, '/'); + if (p && slash >= root + (p - root)) + slash[1] = 0; + else + strcat(root, "/"); + snprintf(out, n, "%s%s", root, href); + } + if ((p = strchr(out, '#'))) + out[p - out] = 0; +} + +/* ---------------------------------------------------------------- */ +/* HTML */ + +static const struct { const char *name; const char *text; } entities[] = { + { "amp", "&" }, { "lt", "<" }, { "gt", ">" }, { "quot", "\"" }, { "apos", "'" }, { "nbsp", " " }, + { "copy", "(c)" }, { "reg", "(R)" }, { "trade", "(TM)" }, { "mdash", "--" }, { "ndash", "-" }, + { "hellip", "..." }, { "laquo", "\xae" }, { "raquo", "\xaf" }, { "bull", "\x07" }, { "middot", "\xfa" }, + { "lsquo", "'" }, { "rsquo", "'" }, { "ldquo", "\"" }, { "rdquo", "\"" }, { "deg", "\xf8" }, + { "euro", "EUR" }, { "pound", "\x9c" }, { "times", "x" }, { "rarr", "->" }, { "larr", "<-" }, + { "uuml", "\x81" }, { "eacute", "\x82" }, { "auml", "\x84" }, { "agrave", "\x85" }, { "ccedil", "\x87" }, + { "egrave", "\x8a" }, { "Auml", "\x8e" }, { "Eacute", "\x90" }, { "ouml", "\x94" }, { "Ouml", "\x99" }, + { "Uuml", "\x9a" }, { "szlig", "\xe1" }, { "ntilde", "\xa4" }, { "Ntilde", "\xa5" }, { "aacute", "\xa0" }, + { "iacute", "\xa1" }, { "oacute", "\xa2" }, { "uacute", "\xa3" }, +}; + +static void put_unicode(struct browser *b, unsigned long u) +{ + unsigned char c; + + if (u == 0xa0) + c = ' '; + else if (u == 0x2018 || u == 0x2019) + c = '\''; + else if (u == 0x201c || u == 0x201d) + c = '"'; + else if (u == 0x2013 || u == 0x2014) + c = '-'; + else if (u == 0x2026) + { + put_string(b, "..."); + return; + } + else + c = cp437_from_unicode(u); + if (u == '\n' || u == '\t' || u == '\r') + c = (unsigned char)u; + if (!c) + c = '?'; + if (u == 0xa0 && !b->pre) + put_cell(b, ' '); /* a space that stays */ + else + put_text(b, c); +} + +static int attr(const char *tag, const char *name, char *out, size_t n) +{ + const char *p = tag; + size_t l = strlen(name), k = 0; + + out[0] = 0; + while ((p = find_nocase(p, name))) + { + const char *v = p + l; + if (p > tag && !isspace((unsigned char)p[-1])) + { + p += l; + continue; + } + while (*v == ' ') + v++; + if (*v != '=') + { + p += l; + continue; + } + v++; + while (*v == ' ') + v++; + if (*v == '"' || *v == '\'') + { + char q = *v++; + while (*v && *v != q && k + 1 < n) + out[k++] = *v++; + } + else + while (*v && !isspace((unsigned char)*v) && *v != '>' && k + 1 < n) + out[k++] = *v++; + out[k] = 0; + return 1; + } + return 0; +} + +static int tag_is(const char *tag, const char *name) +{ + size_t l = strlen(name); + + return !strncasecmp(tag, name, l) && (!tag[l] || isspace((unsigned char)tag[l]) || tag[l] == '/'); +} + +static void parse_html(struct browser *b, const char *h, size_t len) +{ + size_t i = 0; + int list_depth = 0, ordered[8] = { 0 }, counter[8] = { 0 }, cell_no = 0, in_title = 0; + size_t tl = 0; + + while (i < len) + { + unsigned char c = (unsigned char)h[i]; + if (c == '<') + { + char tag[600]; + const char *name; + size_t j = i + 1, k = 0; + int closing; + + if (!strncmp(h + i, ""); + i = e ? (size_t)(e - h) + 3 : len; + continue; + } + while (j < len && h[j] != '>' && k + 1 < sizeof(tag)) + tag[k++] = h[j++]; + tag[k] = 0; + while (j < len && h[j] != '>') + j++; + i = j + 1; + name = tag; + closing = *name == '/'; + if (closing) + name++; + if (tag_is(name, "script") || tag_is(name, "style") || tag_is(name, "svg") || tag_is(name, "noscript")) + { + if (!closing) /* skip to its end tag */ + { + char end[16]; + const char *e; + snprintf(end, sizeof(end), "\t\r\n")] = 0; + e = find_nocase(h + i, end); + i = e ? (size_t)(e - h) : len; + } + continue; + } + if (tag_is(name, "title")) + { + in_title = !closing; + continue; + } + if (tag_is(name, "br")) + flush_line(b); + else if (tag_is(name, "p") || tag_is(name, "div") || tag_is(name, "table") || tag_is(name, "form") || + tag_is(name, "blockquote") || tag_is(name, "section") || tag_is(name, "article") || + tag_is(name, "header") || tag_is(name, "footer") || tag_is(name, "nav") || + tag_is(name, "main") || tag_is(name, "center") || tag_is(name, "dl")) + tag_is(name, "p") || tag_is(name, "table") || tag_is(name, "blockquote") ? paragraph(b) : line_break(b); + else if (name[0] && (name[0] == 'h' || name[0] == 'H') && name[1] >= '1' && name[1] <= '6' && + (!name[2] || isspace((unsigned char)name[2]))) + { + paragraph(b); + b->style = closing ? ST_TEXT : ST_HEAD; + } + else if (tag_is(name, "hr")) + { + int n; + line_break(b); + for (n = 0; n < b->cols - b->indent; n++) + put_cell(b, 0xc4); + flush_line(b); + } + else if (tag_is(name, "ul") || tag_is(name, "ol")) + { + line_break(b); + if (!closing && list_depth < 7) + { + list_depth++; + ordered[list_depth] = tag_is(name, "ol"); + counter[list_depth] = 0; + } + else if (closing && list_depth > 0) + list_depth--; + b->indent = list_depth * 3; + if (!list_depth) + paragraph(b); + } + else if (tag_is(name, "li") && !closing) + { + char num[24]; + line_break(b); + b->indent = list_depth > 1 ? (list_depth - 1) * 3 : 0; + if (list_depth && ordered[list_depth]) + snprintf(num, sizeof(num), "%d. ", ++counter[list_depth]); + else + strcpy(num, "\x07 "); + put_string(b, num); + put_cell(b, ' '); + b->ncur--; + b->indent = (list_depth ? list_depth : 1) * 3; + } + else if (tag_is(name, "dt") || tag_is(name, "dd")) + { + line_break(b); + b->indent = tag_is(name, "dd") && !closing ? 4 : 0; + } + else if (tag_is(name, "pre") || tag_is(name, "textarea")) + { + paragraph(b); + b->pre = !closing; + } + else if (tag_is(name, "tr")) + { + line_break(b); + cell_no = 0; + } + else if ((tag_is(name, "td") || tag_is(name, "th")) && !closing) + { + if (cell_no++) + put_string(b, " \xb3 "); + b->style = tag_is(name, "th") ? ST_BOLD : ST_TEXT; + } + else if (tag_is(name, "b") || tag_is(name, "strong") || tag_is(name, "em") || tag_is(name, "i")) + b->style = closing ? ST_TEXT : ST_BOLD; + else if (tag_is(name, "a")) + { + char href[400], abs[512]; + if (closing) + b->link = 0; + else if (attr(tag, "href", href, sizeof(href)) && b->nlinks < MAX_LINKS) + { + if (b->pending_space) /* the space before a link is not part of it */ + { + b->pending_space = 0; + put_cell(b, ' '); + } + char **n = realloc(b->links, (size_t)(b->nlinks + 1) * sizeof(char *)); + resolve(b->url, href, abs, sizeof(abs)); + if (n) + { + b->links = n; + if ((b->links[b->nlinks] = strdup(abs))) + b->link = ++b->nlinks; + } + } + } + else if (tag_is(name, "img")) + { + char alt[80]; + put_text(b, '['); + put_string(b, attr(tag, "alt", alt, sizeof(alt)) && alt[0] ? alt : "image"); + put_text(b, ']'); + } + else if (tag_is(name, "input")) + { + char type[16], val[60]; + attr(tag, "type", type, sizeof(type)); + if (strcasecmp(type, "hidden")) + { + put_text(b, '['); + put_string(b, attr(tag, "value", val, sizeof(val)) && val[0] ? val : "______"); + put_text(b, ']'); + } + } + continue; + } + /* text */ + if (in_title) + { + if (tl + 1 < sizeof(b->title) && c >= ' ') + b->title[tl++] = (char)(c < 128 ? c : '?'), b->title[tl] = 0; + i++; + continue; + } + if (c == '&') + { + char name[12]; + size_t k = 0, j = i + 1; + unsigned e; + while (j < len && k + 1 < sizeof(name) && (isalnum((unsigned char)h[j]) || h[j] == '#')) + name[k++] = h[j++]; + name[k] = 0; + if (j < len && h[j] == ';' && k) + { + if (name[0] == '#') + { + put_unicode(b, strtoul(name + (tolower((unsigned char)name[1]) == 'x' ? 2 : 1), 0, + tolower((unsigned char)name[1]) == 'x' ? 16 : 10)); + i = j + 1; + continue; + } + for (e = 0; e < sizeof(entities) / sizeof(entities[0]); e++) + if (!strcmp(name, entities[e].name)) + { + if (!strcmp(name, "nbsp")) + put_unicode(b, 0xa0); + else + put_string(b, entities[e].text); + break; + } + if (e < sizeof(entities) / sizeof(entities[0])) + { + i = j + 1; + continue; + } + } + put_text(b, '&'); + i++; + continue; + } + if (c >= 0xc0) /* UTF-8 */ + { + int n = c >= 0xf0 ? 3 : c >= 0xe0 ? 2 : 1, k; + unsigned long u = c & (0x3f >> n); + if (i + (size_t)n < len) + { + for (k = 1; k <= n; k++) + u = u << 6 | ((unsigned char)h[i + (size_t)k] & 0x3f); + put_unicode(b, u); + i += (size_t)n + 1; + continue; + } + } + put_text(b, c < 0x80 ? c : cp437_from_unicode(c) ? cp437_from_unicode(c) : '?'); + i++; + } + line_break(b); +} + +static void parse_text(struct browser *b, const char *t, size_t len) +{ + size_t i; + + b->pre = 1; + for (i = 0; i < len; i++) + put_text(b, (unsigned char)t[i]); + line_break(b); + b->pre = 0; +} + +/* ---------------------------------------------------------------- */ +/* the window */ + +static void paint(struct widget *w, struct surface *s) +{ + struct browser *b = w->user; + static const color_t ink[] = { RGB(0x20, 0x24, 0x2c), RGB(0x00, 0x00, 0x00), RGB(0x10, 0x30, 0x70), + RGB(0x10, 0x50, 0xc0), RGB(0x30, 0x30, 0x30), RGB(0x70, 0x70, 0x78) }; + int r, c; + + draw_fill(s, w->x, w->y, w->w, w->h, RGB(0xff, 0xff, 0xff)); + draw_frame(s, w->x, w->y, w->w, w->h, RGB(0x90, 0x98, 0xa8)); + for (r = 0; r < b->rows && b->top + r < b->nlines; r++) + { + struct line *l = &b->lines[b->top + r]; + int y = w->y + 4 + r * FONT_H; + for (c = 0; c < l->n && c < b->cols; c++) + { + char t[2] = { (char)l->c[c].ch, 0 }; + int x = w->x + 6 + c * FONT_W; + if (l->c[c].ch == ' ' && l->c[c].style != ST_LINK) + continue; + draw_text(s, x, y, t, ink[l->c[c].style], l->c[c].style == ST_PRE ? RGB(0xf0, 0xf0, 0xf4) : TEXT_TRANSPARENT); + if (l->c[c].style == ST_LINK) + draw_hline(s, x, y + FONT_H - 2, FONT_W, ink[ST_LINK]); + else if (l->c[c].style == ST_HEAD || l->c[c].style == ST_BOLD) + draw_text(s, x + 1, y, t, ink[l->c[c].style], TEXT_TRANSPARENT); /* bold */ + } + } +} + +static void show_status(struct browser *b, const char *text) +{ + ui_set_text(b->status, text); + wm_update(); +} + +static void test_log(struct browser *b) +{ + int r, c, links = 0; + + tlog("MDDESK: browser loaded %s title=%s lines=%d links=%d\n", b->url, b->title, b->nlines, b->nlinks); + for (r = 0; r < b->rows && r < b->nlines; r++) + for (c = 0; c < b->lines[r].n; c++) + if (b->lines[r].c[c].link && (c == 0 || b->lines[r].c[c - 1].link != b->lines[r].c[c].link) && + links++ < 8) + { + int sx, sy; + ui_widget_center(b->view, &sx, &sy); + tlog("MDDESK: browser link %d at %d,%d\n", b->lines[r].c[c].link, + sx - b->view->w / 2 + 6 + c * FONT_W + 4, sy - b->view->h / 2 + 4 + r * FONT_H + 8); + } +} + +struct mem { + char *d; + size_t len, cap; +}; + +static int to_mem(void *ctx, const void *data, size_t n) +{ + struct mem *m = ctx; + + if (m->len + n > MAX_PAGE) + n = MAX_PAGE - m->len; /* the rest is cut */ + if (m->len + n + 1 > m->cap) + { + size_t cap = (m->len + n + 1) * 2; + char *d = realloc(m->d, cap); + if (!d) + return 1; + m->d = d; + m->cap = cap; + } + memcpy(m->d + m->len, data, n); + m->len += n; + m->d[m->len] = 0; + return 0; +} + +static const char start_page[] = + "modernDOS Browser

modernDOS Browser

" + "

Type an address above and press Enter. This browser shows pages as text: headings, " + "lists, links, tables and preformatted text, from http and https sites. " + "It runs no scripts, so sites that are built by scripts in the page stay empty.

" + "

In a page: click a link; Up, Down, PgUp, PgDn, Home, " + "End scroll; Backspace goes back.

" + "

Places that read well as text

"; + +static void go(struct browser *b, const char *url, int remember) +{ + struct mem m = { 0, 0, 0 }; + char err[200], type[64], full[512], msg[900]; + int ok = 1; + + if (!strstr(url, "://") && strncasecmp(url, "about:", 6)) + snprintf(full, sizeof(full), "http://%s", url); + else + snprintf(full, sizeof(full), "%s", url); + if (remember && b->url[0] && b->nhist < HISTORY) + strcpy(b->history[b->nhist++], b->url); + else if (remember && b->url[0]) + { + memmove(b->history[0], b->history[1], sizeof(b->history[0]) * (HISTORY - 1)); + strcpy(b->history[HISTORY - 1], b->url); + } + page_clear(b); + snprintf(b->url, sizeof(b->url), "%s", full); + ui_set_text(b->addr, full); + type[0] = 0; + if (!strncasecmp(full, "about:", 6)) + parse_html(b, start_page, sizeof(start_page) - 1); + else + { + snprintf(msg, sizeof(msg), "Loading %.200s ...", full); + show_status(b, msg); + if (!net_up && !(net_up = http_init())) + { + snprintf(err, sizeof(err), "No network: load the packet driver (PKTDRV) before the desktop."); + ok = 0; + } + else if (http_get(full, to_mem, &m, type, err, sizeof(err))) + ok = 0; + wm_redraw_all(); /* the network code may have written text */ + if (!ok) + { + snprintf(msg, sizeof(msg), "Not loaded

The page could not be loaded

%s

" + "

%.300s

", err, full); + parse_html(b, msg, strlen(msg)); + } + else if (!m.d) + parse_html(b, "

(an empty page)

", 22); + else if (!strncasecmp(type, "text/plain", 10)) + parse_text(b, m.d, m.len); + else if (!type[0] || !strncasecmp(type, "text/", 5) || find_nocase(type, "html") || find_nocase(type, "xml")) + parse_html(b, m.d, m.len); + else + { + snprintf(msg, sizeof(msg), "

Cannot show this

The address holds a file of the kind " + "%.60s (%lu bytes), not a page.

", type, (unsigned long)m.len); + parse_html(b, msg, strlen(msg)); + } + free(m.d); + } + snprintf(msg, sizeof(msg), "%.60s%s%d lines, %d links", b->title, b->title[0] ? " - " : "", b->nlines, + b->nlinks); + ui_set_text(b->status, msg); + ui_redraw(b->ui); + test_log(b); +} + +static void scroll_to(struct browser *b, int top) +{ + if (top > b->nlines - b->rows) + top = b->nlines - b->rows; + if (top < 0) + top = 0; + b->top = top; +} + +static void back(struct browser *b) +{ + char url[512]; + + if (!b->nhist) + return; + strcpy(url, b->history[--b->nhist]); + go(b, url, 0); +} + +static int input(struct widget *w, const struct event *e) +{ + struct browser *b = w->user; + + if (e->type == EV_MOUSE_DOWN) + { + int r = (e->y - w->y - 4) / FONT_H + b->top, c = (e->x - w->x - 6) / FONT_W; + if (r >= 0 && r < b->nlines && c >= 0 && c < b->lines[r].n && b->lines[r].c[c].link) + { + char url[512]; + snprintf(url, sizeof(url), "%s", b->links[b->lines[r].c[c].link - 1]); + go(b, url, 1); + } + return 1; + } + if (e->type != EV_KEY) + return 0; + switch (e->scan) + { + case 0x48: scroll_to(b, b->top - 1); return 1; + case 0x50: scroll_to(b, b->top + 1); return 1; + case 0x49: scroll_to(b, b->top - (b->rows - 1)); return 1; + case 0x51: scroll_to(b, b->top + (b->rows - 1)); return 1; + case 0x47: scroll_to(b, 0); return 1; + case 0x4f: scroll_to(b, b->nlines); return 1; + case 0x0e: back(b); return 1; + } + if (e->ascii == ' ') + { + scroll_to(b, b->top + (b->rows - 1)); + return 1; + } + return 0; +} + +static void a_go(struct widget *w) +{ + struct browser *b = w->user; + char url[130]; + + snprintf(url, sizeof(url), "%s", b->addr->text); + go(b, url, 1); + ui_focus(b->view); +} + +static void a_back(struct widget *w) +{ + back(w->user); +} + +static int events(struct window *w, const struct event *e) +{ + struct browser *b = the; + + if (e->type != EV_CLOSE || !b || b->win != w) + return 0; + page_clear(b); + free(b->lines); + free(b->links); + wm_window_close(w); + free(b); + the = 0; + panel_damage(); + tlog("MDDESK: browser closed\n"); + return 1; +} + +void browser_open(const char *url) +{ + struct browser *b; + struct widget *go_button, *back_button; + int W = 900, H = 600; + + if (the) + { + wm_raise(the->win); + if (url) + go(the, url, 1); + return; + } + if (!(b = calloc(1, sizeof(*b))) || !(b->win = wm_window_new(50, 44, W, H, "Browser"))) + { + free(b); + return; + } + the = b; + b->win->handler = events; + b->ui = ui_new(b->win); + W = b->win->client->w; + H = b->win->client->h; + back_button = ui_button(b->ui, 8, 8, 60, 26, "Back", a_back); + back_button->user = b; + b->addr = ui_textfield(b->ui, 76, 9, W - 76 - 68, a_go); + b->addr->user = b; + go_button = ui_button(b->ui, W - 60, 8, 52, 26, "Go", a_go); + go_button->user = b; + b->view = ui_canvas(b->ui, 8, 42, W - 16, H - 42 - 28, paint, input); + b->view->user = b; + b->status = ui_label(b->ui, 10, H - 22, ""); + b->cols = (b->view->w - 12) / FONT_W; + if (b->cols > MAX_COLS) + b->cols = MAX_COLS; + b->rows = (b->view->h - 8) / FONT_H; + desk_widget("browser_addr", b->addr); + desk_widget("browser_view", b->view); + tlog("MDDESK: window Browser at %d,%d\n", b->win->x, b->win->y); + go(b, url ? url : "about:start", 0); + ui_focus(b->addr); + panel_damage(); +} diff --git a/gui/desk/desk.c b/gui/desk/desk.c new file mode 100644 index 00000000..9b84aafb --- /dev/null +++ b/gui/desk/desk.c @@ -0,0 +1,437 @@ +/* + * MDDESK - the modernDOS desktop (DJGPP, mdgui). + * + * A panel at the top: the launcher (modernDOS menu), a button for every + * open window (raises it) and a clock. The launcher has About, Run (a DOS + * program: the desktop goes to text mode, runs it through COMMAND.COM, + * waits for a key and comes back) and Exit to DOS. + * + * MDDESK [/TEST] [/EXIT] + * /TEST logs positions and events to port E9h for the test harness + * (tests/gui/deskdrive.py); /EXIT starts and leaves at once + * + * Not yet: starting DJGPP (32-bit DPMI) programs from the desktop - the + * DPMI host runs one client at a time. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "desk.h" + +#define VERSION "0.2" +#define TASK_W 150 + +#define C_PANEL RGB(24, 30, 40) +#define C_PANEL_LINE RGB(48, 58, 74) +#define C_PANEL_TEXT RGB(220, 226, 234) +#define C_TASK RGB(44, 52, 66) + +int test_mode, clock24 = 1; +static int quit, menu_open_now, exit_at_once; +static char clock_text[12]; +static char last_tasks[256]; +static struct window *about_win, *run_win; +static struct widget *run_field; + +void tlog(const char *fmt, ...) +{ + static char buf[8192]; + char *p; + va_list ap; + + if (!test_mode) + return; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + for (p = buf; *p; p++) + { + if (*p == '\n') + outportb(0xe9, '\r'); + outportb(0xe9, *p); + } +} + +/* ---------------------------------------------------------------- */ +/* panel */ + +static int launcher_w(void) +{ + return text_width("modernDOS") + 28; +} + +void panel_damage(void) +{ + wm_damage(0, 0, gfx_screen()->w, PANEL_H); +} + +static void draw_panel(struct surface *s) +{ + struct window *top = wm_top(); + int i, x = launcher_w() + 16, n = 0; + char tasks[256] = ""; + + draw_fill(s, 0, 0, s->w, PANEL_H, C_PANEL); + draw_hline(s, 0, PANEL_H - 1, s->w, C_PANEL_LINE); + /* launcher */ + draw_fill(s, 6, 4, launcher_w(), PANEL_H - 8, menu_open_now ? theme.accent : C_TASK); + draw_fill(s, 14, PANEL_H / 2 - 4, 8, 8, theme.accent_hi); + draw_text(s, 30, (PANEL_H - FONT_H) / 2, "modernDOS", C_PANEL_TEXT, TEXT_TRANSPARENT); + /* open windows */ + for (i = 0; i < wm_count(); i++) + { + struct window *w = wm_window(i); + char t[20]; + if (w->popup || x + TASK_W > s->w - 80) + continue; + strncpy(t, w->title, 17); + t[17] = 0; + draw_fill(s, x, 4, TASK_W, PANEL_H - 8, w == top ? theme.accent : C_TASK); + draw_text(s, x + 8, (PANEL_H - FONT_H) / 2, t, C_PANEL_TEXT, TEXT_TRANSPARENT); + n += sprintf(tasks + n, " %s=%d,%d", w->title, x + TASK_W / 2, PANEL_H / 2); + x += TASK_W + 6; + } + /* clock */ + draw_text(s, s->w - text_width(clock_text) - 14, (PANEL_H - FONT_H) / 2, clock_text, + C_PANEL_TEXT, TEXT_TRANSPARENT); + if (strcmp(tasks, last_tasks)) + { + strcpy(last_tasks, tasks); + tlog("MDDESK: taskbar%s\n", tasks); + } +} + +void desk_widget(const char *name, const struct widget *w) +{ + int x, y; + + if (!test_mode) + return; + ui_widget_center(w, &x, &y); + tlog("MDDESK: widget %s %d,%d\n", name, x, y); +} + +static void tick_clock(void) +{ + time_t t = time(0); + struct tm *tm = localtime(&t); + char now[12]; + + if (clock24) + sprintf(now, "%02d:%02d", tm->tm_hour, tm->tm_min); + else + sprintf(now, "%d:%02d %s", tm->tm_hour % 12 ? tm->tm_hour % 12 : 12, tm->tm_min, + tm->tm_hour < 12 ? "AM" : "PM"); + if (strcmp(now, clock_text)) + { + strcpy(clock_text, now); + panel_damage(); + tlog("MDDESK: clock %s\n", clock_text); + } +} + +/* redraw the clock now (its format changed) */ +void desk_clock_refresh(void) +{ + clock_text[0] = 0; + if (gfx_screen()) + tick_clock(); +} + +/* ---------------------------------------------------------------- */ +/* windows */ + +static int close_handler(struct window *w, const struct event *e) +{ + if (e->type == EV_CLOSE) + { + if (w == about_win) + about_win = 0; + if (w == run_win) + run_win = 0; + wm_window_close(w); + panel_damage(); + return 1; + } + return 0; +} + +static void about_ok(struct widget *w) +{ + (void)w; + if (about_win) + { + wm_window_close(about_win); + about_win = 0; + panel_damage(); + } +} + +static void open_about(void) +{ + const struct gfx_mode *m = gfx_mode(); + __dpmi_free_mem_info mi; + __dpmi_regs r; + struct ui *ui; + struct widget *ok; + char line[96]; + int x, y, mdvmm, sessions = 0; + + if (about_win) + { + wm_raise(about_win); + return; + } + about_win = wm_window_new(260, 140, 420, 250, "About modernDOS"); + if (!about_win) + return; + about_win->handler = close_handler; + ui = ui_new(about_win); + ui_label(ui, 20, 20, "modernDOS desktop " VERSION); + ui_label(ui, 20, 40, "DOS, reimagined as if it never faded."); + sprintf(line, "Display: %dx%d, VBE mode %Xh", m->w, m->h, m->vbe_mode); + ui_label(ui, 20, 76, strdup(line)); + memset(&r, 0, sizeof(r)); + r.x.ax = 0xde00; + __dpmi_int(0x2f, &r); + mdvmm = r.h.al == 0xff && r.x.bx == 0x4d44; + if (mdvmm) + { + memset(&r, 0, sizeof(r)); + r.x.ax = 0xde06; + __dpmi_int(0x2f, &r); + sessions = r.x.dx ? r.x.cx : 0; + } + sprintf(line, "Boot: %s", !mdvmm ? "DOS, no MDVMM" : + m->vbe_mode == 0x141 ? "UEFI, MDVMM virtual BIOS" : "BIOS, MDVMM"); + ui_label(ui, 20, 96, strdup(line)); + tlog("MDDESK: about %s, sessions %d\n", line, sessions); + __dpmi_get_free_memory_information(&mi); + sprintf(line, "Free memory: %lu KB, DOS sessions: %d", mi.largest_available_free_block_in_bytes / 1024, + sessions); + ui_label(ui, 20, 116, strdup(line)); + ok = ui_button(ui, 300, 170, 90, 28, "OK", about_ok); + ui_focus(ok); + ui_redraw(ui); + ui_widget_center(ok, &x, &y); + tlog("MDDESK: window About at %d,%d\n", about_win->x, about_win->y); + tlog("MDDESK: widget aboutok %d,%d\n", x, y); + panel_damage(); +} + +void desk_run(const char *cmd) +{ + int rc; + + tlog("MDDESK: running %s\n", cmd); + input_close(); + gfx_suspend(); + printf("modernDOS desktop: running %s\n\n", cmd); + fflush(stdout); + rc = system(cmd); + printf("\n[exit code %d] Press a key to return to the desktop.", rc); + fflush(stdout); + tlog("MDDESK: ran %s exit %d\n", cmd, rc); + while (kbhit()) + getch(); + getch(); + gfx_resume(); + input_open(); + gfx_cursor_show(1); + wm_damage(0, 0, gfx_screen()->w, gfx_screen()->h); + tlog("MDDESK: resumed\n"); +} + +static void run_go(struct widget *w) +{ + char cmd[128]; + + (void)w; + if (!run_win) + return; + strcpy(cmd, run_field->text); + wm_window_close(run_win); + run_win = 0; + panel_damage(); + wm_update(); + if (cmd[0]) + desk_run(cmd); +} + +static void run_cancel(struct widget *w) +{ + (void)w; + if (run_win) + { + wm_window_close(run_win); + run_win = 0; + panel_damage(); + } +} + +static void open_run(void) +{ + struct ui *ui; + struct widget *go; + int x, y; + + if (run_win) + { + wm_raise(run_win); + return; + } + run_win = wm_window_new(300, 200, 400, 150, "Run a DOS program"); + if (!run_win) + return; + run_win->handler = close_handler; + ui = ui_new(run_win); + ui_label(ui, 16, 20, "Command:"); + run_field = ui_textfield(ui, 96, 16, 280, run_go); + go = ui_button(ui, 176, 70, 96, 28, "Run", run_go); + ui_button(ui, 280, 70, 96, 28, "Cancel", run_cancel); + ui_focus(run_field); + ui_redraw(ui); + ui_widget_center(run_field, &x, &y); + tlog("MDDESK: widget runfield %d,%d\n", x, y); + ui_widget_center(go, &x, &y); + tlog("MDDESK: widget runbutton %d,%d\n", x, y); + panel_damage(); +} + +/* ---------------------------------------------------------------- */ +/* launcher */ + +static const char *const launcher_items[] = { "About modernDOS", "Files", "Editor", "Settings", + "Terminal", "Browser", "Run...", "Exit to DOS" }; +static const char *const launcher_names[] = { "about", "files", "editor", "settings", "terminal", + "browser", "run", "exit" }; +#define NLAUNCH 8 + +static void launcher_choose(int item, void *user) +{ + (void)user; + menu_open_now = 0; + panel_damage(); + switch (item) + { + case 0: open_about(); break; + case 1: files_open(0); break; + case 2: editor_open(0); break; + case 3: settings_open(); break; + case 4: term_open(); break; + case 5: browser_open(0); break; + case 6: open_run(); break; + case 7: quit = 1; break; + } +} + +static void open_launcher(void) +{ + int i; + + menu_open_now = 1; + panel_damage(); + ui_popup(6, PANEL_H - 2, launcher_items, NLAUNCH, launcher_choose, 0); + for (i = 0; i < NLAUNCH; i++) + tlog("MDDESK: item %s %d,%d\n", launcher_names[i], 6 + 40, PANEL_H - 2 + 1 + 2 + i * 20 + 10); +} + +static int desk_event(const struct event *e) +{ + int i, x = launcher_w() + 16; + + if (e->type == EV_KEY && e->scan == 0x44) /* F10 */ + { + open_launcher(); + return 1; + } + if (e->type != EV_MOUSE_DOWN || e->y >= PANEL_H) + return 0; + if (e->x >= 6 && e->x < 6 + launcher_w()) + { + open_launcher(); + return 1; + } + for (i = 0; i < wm_count(); i++) + { + struct window *w = wm_window(i); + if (w->popup) + continue; + if (e->x >= x && e->x < x + TASK_W) + { + wm_raise(w); + panel_damage(); + return 1; + } + x += TASK_W + 6; + } + return 0; +} + +/* ---------------------------------------------------------------- */ + +int main(int argc, char **argv) +{ + struct surface *s; + struct window *top = 0; + struct event e; + __dpmi_regs r; + int i; + + for (i = 1; i < argc; i++) + { + if (!strcasecmp(argv[i], "/TEST")) + test_mode = 1; + if (!strcasecmp(argv[i], "/EXIT")) + exit_at_once = 1; /* start, show, leave (tests) */ + } + settings_load(argv[0]); + if (gfx_open(1024, 768)) + { + printf("MDDESK: %s\n", gfx_error()); + return 1; + } + s = gfx_screen(); + input_open(); + wm_init(); + tick_clock(); + wm_desktop(PANEL_H, draw_panel, desk_event); + wm_update(); + gfx_cursor_move(s->w / 2, s->h / 2); + gfx_cursor_show(1); + tlog("MDDESK: widget launcher %d,%d\n", 6 + launcher_w() / 2, PANEL_H / 2); + tlog("MDDESK: ready at %d,%d\n", s->w / 2, s->h / 2); + quit = exit_at_once; + + while (!quit) + { + if (wm_top() != top) /* the panel shows the top window */ + { + top = wm_top(); + panel_damage(); + } + term_idle(); /* terminal windows follow their sessions */ + wm_update(); + if (!input_poll(&e)) + { + tick_clock(); + memset(&r, 0, sizeof(r)); + r.x.ax = 0x1680; /* idle */ + __dpmi_int(0x2f, &r); + continue; + } + if (e.type == EV_MOUSE_MOVE) + tlog("MDDESK: at %d,%d\n", e.x, e.y); + wm_dispatch(&e); + } + input_close(); + gfx_close(); + tlog("MDDESK: exit\n"); + printf("modernDOS desktop closed.\n"); + return 0; +} diff --git a/gui/desk/desk.h b/gui/desk/desk.h new file mode 100644 index 00000000..c43c565e --- /dev/null +++ b/gui/desk/desk.h @@ -0,0 +1,27 @@ +/* MDDESK - shared between the desktop and its applications */ +#ifndef DESK_H +#define DESK_H + +#include "mdgui.h" + +#define PANEL_H 30 + +void tlog(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +extern int test_mode; +void panel_damage(void); +void desk_run(const char *cmd); /* run a DOS program, come back */ +void desk_widget(const char *name, const struct widget *w); /* test log */ + +/* applications */ +void files_open(const char *path); /* file manager */ +void editor_open(const char *path); /* text editor; 0: a new text */ +void settings_open(void); +void term_open(void); /* a DOS session in a window */ +void term_idle(void); /* its screens: call when idle */ +void browser_open(const char *url); /* web browser; 0: the start page */ +void settings_load(const char *argv0); /* MDDESK.CFG, applies it */ + +extern int clock24; /* 24 or 12 hour clock */ +void desk_clock_refresh(void); + +#endif diff --git a/gui/desk/editor.c b/gui/desk/editor.c new file mode 100644 index 00000000..b05abfa9 --- /dev/null +++ b/gui/desk/editor.c @@ -0,0 +1,277 @@ +/* + * MDDESK Editor - a text editor. + * + * A window per file: a menu bar (File: New, Open..., Save, Save as..., + * Close), the text (the toolkit's UI_EDIT widget) and a status line with + * the caret position and the modified mark. Ctrl+S saves. Files are read + * with LF or CRLF line ends and written with CRLF. Closing with unsaved + * changes asks first. + */ +#include +#include +#include +#include +#include "desk.h" + +#define MAX_FILE (1024L * 1024L) +#define MAX_EDITORS 8 + +struct editor { + struct window *win; + struct ui *ui; + struct widget *bar, *text, *status; + char path[260]; /* "" for a new file */ + char status_text[160]; +}; + +static struct editor *editors[MAX_EDITORS]; + +static const char *const file_items[] = { "New", "Open...", "Save", "Save as...", "Close" }; +static const struct ui_menu menus[] = { { "File", file_items, 5 } }; + +static struct editor *find(const struct window *w) +{ + int i; + for (i = 0; i < MAX_EDITORS; i++) + if (editors[i] && editors[i]->win == w) + return editors[i]; + return 0; +} + +static void update_title(struct editor *ed) +{ + const char *name = ed->path[0] ? strrchr(ed->path, '\\') : 0; + + snprintf(ed->win->title, sizeof(ed->win->title), "%s%.48s - Editor", + edit_modified(ed->text) ? "*" : "", + ed->path[0] ? (name ? name + 1 : ed->path) : "Untitled"); + wm_invalidate(ed->win); + panel_damage(); +} + +static void update_status(struct editor *ed) +{ + int line, col; + + edit_caret(ed->text, &line, &col); + snprintf(ed->status_text, sizeof(ed->status_text), "Line %d of %d, column %d%s", line, + edit_lines(ed->text), col, edit_modified(ed->text) ? " modified" : ""); + ui_set_text(ed->status, ed->status_text); +} + +static void changed(struct widget *w) +{ + struct editor *ed = w->user; + static int was_modified; + + update_status(ed); + if (edit_modified(w) != was_modified) + { + was_modified = edit_modified(w); + update_title(ed); + } +} + +static int load(struct editor *ed, const char *path) +{ + FILE *f = fopen(path, "rb"); + long size; + char *buf; + + if (!f) + return -1; + fseek(f, 0, SEEK_END); + size = ftell(f); + fseek(f, 0, SEEK_SET); + if (size < 0 || size > MAX_FILE || !(buf = malloc(size + 1))) + { + fclose(f); + return -1; + } + size = (long)fread(buf, 1, size, f); + fclose(f); + edit_set_text(ed->text, buf, size); + free(buf); + strncpy(ed->path, path, sizeof(ed->path) - 1); + update_title(ed); + update_status(ed); + tlog("MDDESK: editor opened %s, %d lines\n", path, edit_lines(ed->text)); + return 0; +} + +static int save(struct editor *ed) +{ + long len; + char *text = edit_get_text(ed->text, &len); + FILE *f; + int ok; + + if (!text) + return -1; + f = fopen(ed->path, "wb"); + ok = f && fwrite(text, 1, len, f) == (size_t)len; + if (f && fclose(f)) + ok = 0; + if (!ok) + { + free(text); + ui_set_text(ed->status, "Cannot save the file."); + return -1; + } + edit_set_modified(ed->text, 0); + update_title(ed); + update_status(ed); + tlog("MDDESK: editor saved %s, %ld bytes: %s\n", ed->path, len, text); + free(text); + return 0; +} + +/* ---------------------------------------------------------------- */ + +static void close_editor(struct editor *ed) +{ + int i; + + for (i = 0; i < MAX_EDITORS; i++) + if (editors[i] == ed) + editors[i] = 0; + wm_window_close(ed->win); + free(ed); + panel_damage(); + tlog("MDDESK: editor closed\n"); +} + +static void discard_done(int yes, void *user) +{ + if (yes) + close_editor(user); +} + +static void ask_close(struct editor *ed) +{ + struct widget *yes; + + if (!edit_modified(ed->text)) + { + close_editor(ed); + return; + } + yes = ui_confirm("Editor", "The text has changed. Close without saving?", discard_done, ed); + if (yes) + desk_widget("confirmyes", yes); +} + +static void open_done(const char *path, void *user) +{ + struct editor *ed = user; + + if (path && path[0] && load(ed, path)) + ui_set_text(ed->status, "Cannot open the file."); +} + +static void save_as_done(const char *path, void *user) +{ + struct editor *ed = user; + + if (!path || !path[0]) + return; + strncpy(ed->path, path, sizeof(ed->path) - 1); + save(ed); +} + +static void menu(struct widget *w) +{ + struct editor *ed = w->user; + struct widget *field; + + switch (w->value) + { + case 0: /* New */ + editor_open(0); + break; + case 1: /* Open... */ + field = ui_ask_text("Open", "File to open:", ed->path, open_done, ed); + if (field) + desk_widget("dialogfield", field); + break; + case 2: /* Save */ + if (ed->path[0]) + { + save(ed); + break; + } + __attribute__((fallthrough)); /* no name yet: Save as */ + case 3: /* Save as... */ + field = ui_ask_text("Save as", "Save the text as:", ed->path, save_as_done, ed); + if (field) + desk_widget("dialogfield", field); + break; + case 4: + ask_close(ed); + break; + } +} + +static int editor_events(struct window *win, const struct event *e) +{ + struct editor *ed = find(win); + + if (!ed) + return 0; + if (e->type == EV_CLOSE) + { + ask_close(ed); + return 1; + } + if (e->type == EV_KEY && e->ascii == 0x13) /* Ctrl+S */ + { + ed->bar->value = 2; + menu(ed->bar); + return 1; + } + return 0; +} + +void editor_open(const char *path) +{ + static int count; + struct editor *ed = calloc(1, sizeof(*ed)); + int i, cw, ch; + + if (!ed) + return; + for (i = 0; i < MAX_EDITORS && editors[i]; i++) + ; + if (i == MAX_EDITORS) + { + free(ed); + return; + } + ed->win = wm_window_new(120 + 24 * (count % 5), 70 + 24 * (count % 5), 660, 480, "Editor"); + count++; + if (!ed->win) + { + free(ed); + return; + } + editors[i] = ed; + ed->win->handler = editor_events; + ed->ui = ui_new(ed->win); + cw = ed->win->client->w; + ch = ed->win->client->h; + ed->bar = ui_menubar(ed->ui, menus, 1, menu); + ed->bar->user = ed; + ed->text = ui_edit(ed->ui, 6, 28, cw - 12, ch - 28 - 30, changed); + ed->text->user = ed; + ed->status = ui_label(ed->ui, 8, ch - 22, ""); + ui_focus(ed->text); + if (!path || load(ed, path)) + { + if (path) + strncpy(ed->path, path, sizeof(ed->path) - 1); + update_title(ed); + update_status(ed); + } + ui_redraw(ed->ui); + tlog("MDDESK: window Editor at %d,%d\n", ed->win->x, ed->win->y); +} diff --git a/gui/desk/files.c b/gui/desk/files.c new file mode 100644 index 00000000..21dce8dc --- /dev/null +++ b/gui/desk/files.c @@ -0,0 +1,430 @@ +/* + * MDDESK Files - the file manager. + * + * A window per folder view: the path (type one and press Enter: a folder + * or a drive such as C:), buttons (Up, Refresh, New folder, Rename, + * Delete, Open) and the folder's contents, folders first, with long file + * names, sizes and dates. Enter or a double click opens: a folder is + * entered, a program (.EXE .COM .BAT) is run through the desktop, other + * files open in the editor. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "desk.h" + +#define MAX_ENTRIES 512 +#define NAME_COLS 38 + +struct entry { + char name[256]; + int dir; + long size; + time_t mtime; +}; + +struct files { + struct window *win; + struct ui *ui; + struct widget *path_field, *list, *status; + char path[260]; /* always ends in a backslash */ + struct entry *entries; + int n; + char **items; + char status_text[256]; +}; + +/* ---------------------------------------------------------------- */ + +static void join(char *out, const char *dir, const char *name) +{ + strcpy(out, dir); + strcat(out, name); +} + +static int compare(const void *a, const void *b) +{ + const struct entry *x = a, *y = b; + if (x->dir != y->dir) + return y->dir - x->dir; /* folders first */ + if (!strcmp(x->name, "..")) + return -1; + if (!strcmp(y->name, "..")) + return 1; + return strcasecmp(x->name, y->name); +} + +static void status(struct files *f, const char *text) +{ + snprintf(f->status_text, sizeof(f->status_text), "%s", text); + ui_set_text(f->status, f->status_text); +} + +static void format_item(char *out, const struct entry *e) +{ + char name[NAME_COLS + 1], size[16], date[64]; + struct tm *tm = localtime(&e->mtime); + + strncpy(name, e->name, NAME_COLS); + name[NAME_COLS] = 0; + if ((int)strlen(e->name) > NAME_COLS) + name[NAME_COLS - 1] = '~'; + if (e->dir) + strcpy(size, ""); + else + sprintf(size, "%ld", e->size); + if (strcmp(e->name, "..") && tm) + sprintf(date, "%04d-%02d-%02d %02d:%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, + tm->tm_hour, tm->tm_min); + else + date[0] = 0; + snprintf(out, 160, "%-*s %9s %.16s", NAME_COLS, name, size, date); +} + +/* read the folder f->path into the list */ +static void refresh(struct files *f) +{ + DIR *d; + struct dirent *de; + char full[520], line[160]; + int i, n = 0; + + for (i = 0; i < f->n; i++) + free(f->items[i]); + f->n = 0; + d = opendir(f->path); + if (!d) + { + sprintf(line, "Cannot open %s", f->path); + status(f, line); + } + while (d && (de = readdir(d)) && n < MAX_ENTRIES) + { + struct entry *e = &f->entries[n]; + struct stat st; + + if (!strcmp(de->d_name, ".")) + continue; + if (!strcmp(de->d_name, "..") && strlen(f->path) <= 3) + continue; /* no .. in a root folder */ + strncpy(e->name, de->d_name, sizeof(e->name) - 1); + e->name[sizeof(e->name) - 1] = 0; + join(full, f->path, e->name); + if (stat(full, &st) == 0) + { + e->dir = S_ISDIR(st.st_mode); + e->size = st.st_size; + e->mtime = st.st_mtime; + } + else + { + e->dir = !strcmp(e->name, ".."); + e->size = 0; + e->mtime = 0; + } + n++; + } + if (d) + closedir(d); + if (n > 1) + qsort(f->entries, n, sizeof(*f->entries), compare); + for (i = 0; i < n; i++) + { + format_item(line, &f->entries[i]); + f->items[i] = strdup(line); + } + f->n = n; + f->list->items = (const char *const *)f->items; + f->list->nitems = n; + f->list->value = n ? 0 : -1; + f->list->scroll = 0; + ui_set_text(f->path_field, f->path); + sprintf(line, "%d item%s", n, n == 1 ? "" : "s"); + status(f, line); + sprintf(f->win->title, "Files - %s", f->path); + wm_invalidate(f->win); + panel_damage(); + + if (test_mode) /* the listing, and where its items are */ + { + char *buf = malloc(n * 260 + 64), *p = buf; + int rows = (f->list->h - 4) / 20; + p += sprintf(p, "MDDESK: files %s %d:", f->path, n); + for (i = 0; i < n; i++) + p += sprintf(p, "%s%s", i ? "|" : " ", f->entries[i].name); + tlog("%s\n", buf); + free(buf); + for (i = 0; i < n && i < rows; i++) + { + int x, y; + ui_widget_center(f->list, &x, &y); + tlog("MDDESK: fileitem %s %d,%d\n", f->entries[i].name, x - 100, + y - f->list->h / 2 + 2 + i * 20 + 10); + } + } +} + +static void go(struct files *f, const char *path) +{ + char p[260]; + size_t len; + + strncpy(p, path, sizeof(p) - 2); + p[sizeof(p) - 2] = 0; + len = strlen(p); + if (len == 2 && p[1] == ':') /* "C:" means the root */ + strcat(p, "\\"); + len = strlen(p); + if (len && p[len - 1] != '\\' && p[len - 1] != '/') + strcat(p, "\\"); + strcpy(f->path, p); + refresh(f); +} + +static void up(struct files *f) +{ + char *p; + + if (strlen(f->path) <= 3) + return; + f->path[strlen(f->path) - 1] = 0; /* drop the last backslash */ + p = strrchr(f->path, '\\'); + if (p) + p[1] = 0; + refresh(f); +} + +static struct entry *selected(struct files *f) +{ + return f->list->value >= 0 && f->list->value < f->n ? &f->entries[f->list->value] : 0; +} + +static int is_program(const char *name) +{ + const char *dot = strrchr(name, '.'); + return dot && (!strcasecmp(dot, ".exe") || !strcasecmp(dot, ".com") || !strcasecmp(dot, ".bat")); +} + +static void open_entry(struct files *f) +{ + struct entry *e = selected(f); + char full[520]; + + if (!e) + return; + if (!strcmp(e->name, "..")) + { + up(f); + return; + } + join(full, f->path, e->name); + if (e->dir) + go(f, full); + else if (is_program(e->name)) + { + char cmd[530]; + sprintf(cmd, strchr(full, ' ') ? "\"%s\"" : "%s", full); + desk_run(cmd); + } + else + editor_open(full); +} + +/* ---------------------------------------------------------------- */ +/* buttons */ + +static void b_up(struct widget *w) { up(w->user); } +static void b_refresh(struct widget *w) { refresh(w->user); } +static void b_open(struct widget *w) { open_entry(w->user); } +static void l_activate(struct widget *w) { open_entry(w->user); } +static void p_enter(struct widget *w) { go(w->user, w->text); } + +static void new_folder_done(const char *name, void *user) +{ + struct files *f = user; + char full[520]; + + if (!name || !name[0]) + return; + join(full, f->path, name); + if (mkdir(full, 0777)) + { + status(f, "Cannot create the folder."); + return; + } + refresh(f); + tlog("MDDESK: created %s\n", full); +} + +static void b_new_folder(struct widget *w) +{ + struct widget *field = ui_ask_text("New folder", "Name of the new folder:", "", new_folder_done, + w->user); + if (field) + desk_widget("dialogfield", field); +} + +static char rename_from[256]; + +static void rename_done(const char *name, void *user) +{ + struct files *f = user; + char from[520], to[520]; + + if (!name || !name[0] || !strcmp(name, rename_from)) + return; + join(from, f->path, rename_from); + join(to, f->path, name); + if (rename(from, to)) + { + status(f, "Cannot rename."); + return; + } + refresh(f); + tlog("MDDESK: renamed %s to %s\n", rename_from, name); +} + +static void b_rename(struct widget *w) +{ + struct files *f = w->user; + struct entry *e = selected(f); + struct widget *field; + + if (!e || !strcmp(e->name, "..")) + return; + strcpy(rename_from, e->name); + field = ui_ask_text("Rename", "New name:", e->name, rename_done, f); + if (field) + desk_widget("dialogfield", field); +} + +static void delete_done(int yes, void *user) +{ + struct files *f = user; + struct entry *e = selected(f); + char full[520]; + + if (!yes || !e) + return; + join(full, f->path, e->name); + if (e->dir ? rmdir(full) : remove(full)) + { + status(f, e->dir ? "Cannot delete (is the folder empty?)." : "Cannot delete."); + return; + } + tlog("MDDESK: deleted %s\n", full); + refresh(f); +} + +static void b_delete(struct widget *w) +{ + struct files *f = w->user; + struct entry *e = selected(f); + char text[300]; + struct widget *yes; + + if (!e || !strcmp(e->name, "..")) + return; + sprintf(text, "Delete %s \"%.200s\"?", e->dir ? "the folder" : "the file", e->name); + yes = ui_confirm("Delete", text, delete_done, f); + if (yes) + desk_widget("confirmyes", yes); +} + +#define MAX_VIEWS 16 +static struct files *views[MAX_VIEWS]; /* open file manager windows */ + +static int files_events(struct window *w, const struct event *e) +{ + struct files *f = 0; + int i; + + if (e->type != EV_CLOSE) + return 0; + for (i = 0; i < MAX_VIEWS; i++) + if (views[i] && views[i]->win == w) + { + f = views[i]; + views[i] = 0; + } + if (!f) + return 0; + for (i = 0; i < f->n; i++) + free(f->items[i]); + free(f->items); + free(f->entries); + wm_window_close(w); + free(f); + panel_damage(); + return 1; +} + +void files_open(const char *path) +{ + static int count; + struct files *f = calloc(1, sizeof(*f)); + struct widget *b; + char cwd[260]; + int x = 12, bw = 92, i; + static const struct { const char *text; ui_action a; const char *name; } buttons[] = { + { "Up", b_up, "files_up" }, { "Refresh", b_refresh, "files_refresh" }, + { "New folder", b_new_folder, "files_newfolder" }, { "Rename", b_rename, "files_rename" }, + { "Delete", b_delete, "files_delete" }, { "Open", b_open, "files_open" }, + }; + + if (!f) + return; + f->entries = calloc(MAX_ENTRIES, sizeof(*f->entries)); + f->items = calloc(MAX_ENTRIES, sizeof(char *)); + f->win = wm_window_new(60 + 24 * (count % 6), 50 + 24 * (count % 6), 640, 440, "Files"); + count++; + if (!f->entries || !f->items || !f->win) + return; + for (i = 0; i < MAX_VIEWS && views[i]; i++) + ; + if (i == MAX_VIEWS) + { + wm_window_close(f->win); + free(f->entries); + free(f->items); + free(f); + return; + } + views[i] = f; + f->win->handler = files_events; + f->ui = ui_new(f->win); + ui_label(f->ui, 12, 14, "Path:"); + f->path_field = ui_textfield(f->ui, 60, 10, 560, p_enter); + f->path_field->user = f; + for (i = 0; i < 6; i++) + { + b = ui_button(f->ui, x, 44, bw, 26, buttons[i].text, buttons[i].a); + b->user = f; + desk_widget(buttons[i].name, b); + x += bw + 8; + } + f->list = ui_list(f->ui, 12, 80, 612, 284, 0, 0, 0); + f->list->user = f; + f->list->activate = l_activate; + f->status = ui_label(f->ui, 12, 374, ""); + desk_widget("files_path", f->path_field); + if (!path) + { + getcwd(cwd, sizeof(cwd)); + cwd[3] = 0; /* the root of the current drive */ + path = cwd; + } + for (i = 0; path[i] && i < 259; i++) + cwd[i] = path[i] == '/' ? '\\' : path[i]; + cwd[i] = 0; + cwd[0] = (char)toupper((unsigned char)cwd[0]); + ui_focus(f->list); + go(f, cwd); + tlog("MDDESK: window Files at %d,%d\n", f->win->x, f->win->y); +} diff --git a/gui/desk/settings.c b/gui/desk/settings.c new file mode 100644 index 00000000..0682ba1f --- /dev/null +++ b/gui/desk/settings.c @@ -0,0 +1,215 @@ +/* + * MDDESK Settings - the desktop's look and behaviour. + * + * Background (a gradient preset), accent colour (active title bars, + * focus, selection), 12 or 24 hour clock, mouse speed. Changes apply at + * once; Save writes MDDESK.CFG next to MDDESK.EXE (key=value lines), + * which the desktop reads when it starts. + */ +#include +#include +#include +#include "desk.h" + +struct preset_bg { const char *name; color_t top, bottom; }; +struct preset_accent { const char *name; color_t accent, hi, soft; }; + +static const struct preset_bg backgrounds[] = { + { "Slate", RGB(36, 52, 71), RGB(18, 28, 40) }, + { "Ocean", RGB(24, 72, 112), RGB(8, 28, 52) }, + { "Forest", RGB(34, 70, 48), RGB(14, 30, 22) }, + { "Plum", RGB(70, 40, 72), RGB(28, 16, 30) }, + { "Charcoal", RGB(40, 42, 46), RGB(40, 42, 46) }, +}; +static const struct preset_accent accents[] = { + { "Teal", RGB(32, 128, 136), RGB(64, 168, 176), RGB(238, 246, 247) }, + { "Blue", RGB(40, 96, 176), RGB(80, 136, 216), RGB(236, 242, 250) }, + { "Orange", RGB(196, 104, 32), RGB(230, 146, 72), RGB(250, 242, 234) }, + { "Purple", RGB(120, 72, 160), RGB(160, 112, 200), RGB(244, 238, 250) }, + { "Green", RGB(48, 132, 72), RGB(88, 172, 112), RGB(236, 246, 238) }, +}; +static const char *const speeds[] = { "Slow", "Normal", "Fast" }; +static const int speed_mickeys[] = { 16, 8, 4 }; + +#define NBG (int)(sizeof(backgrounds) / sizeof(backgrounds[0])) +#define NACCENT (int)(sizeof(accents) / sizeof(accents[0])) +#define NSPEED 3 + +static struct { + int bg, accent, clock24, speed; +} cfg = { 0, 0, 1, 1 }; + +static char cfg_path[260] = "MDDESK.CFG"; +static const char *bg_names[NBG], *accent_names[NACCENT]; +static struct window *win; +static struct widget *check24; + +static void describe(char *out, size_t n) +{ + snprintf(out, n, "background=%s accent=%s clock=%d mouse=%s", backgrounds[cfg.bg].name, + accents[cfg.accent].name, cfg.clock24 ? 24 : 12, speeds[cfg.speed]); +} + +static void apply(void) +{ + theme.desk_top = backgrounds[cfg.bg].top; + theme.desk_bottom = backgrounds[cfg.bg].bottom; + theme.accent = accents[cfg.accent].accent; + theme.accent_hi = accents[cfg.accent].hi; + theme.accent_soft = accents[cfg.accent].soft; + clock24 = cfg.clock24; + input_set_speed(speed_mickeys[cfg.speed]); + wm_redraw_all(); + desk_clock_refresh(); +} + +static int find(const char *v, const char *const *names, int n, int def) +{ + int i; + for (i = 0; i < n; i++) + if (!strcasecmp(v, names[i])) + return i; + return def; +} + +/* MDDESK.CFG next to the program (argv[0]) */ +void settings_load(const char *argv0) +{ + char line[128], *eq, text[160]; + const char *slash; + FILE *f; + int i; + + for (i = 0; i < NBG; i++) + bg_names[i] = backgrounds[i].name; + for (i = 0; i < NACCENT; i++) + accent_names[i] = accents[i].name; + slash = argv0 ? strrchr(argv0, '\\') : 0; + if (!slash && argv0) + slash = strrchr(argv0, '/'); + if (slash && slash - argv0 < (int)sizeof(cfg_path) - 12) + { + memcpy(cfg_path, argv0, slash - argv0 + 1); + strcpy(cfg_path + (slash - argv0 + 1), "MDDESK.CFG"); + } + f = fopen(cfg_path, "r"); + while (f && fgets(line, sizeof(line), f)) + { + line[strcspn(line, "\r\n")] = 0; + if (!(eq = strchr(line, '='))) + continue; + *eq++ = 0; + if (!strcasecmp(line, "background")) + cfg.bg = find(eq, bg_names, NBG, cfg.bg); + else if (!strcasecmp(line, "accent")) + cfg.accent = find(eq, accent_names, NACCENT, cfg.accent); + else if (!strcasecmp(line, "clock")) + cfg.clock24 = atoi(eq) != 12; + else if (!strcasecmp(line, "mouse")) + cfg.speed = find(eq, speeds, NSPEED, cfg.speed); + } + if (f) + fclose(f); + apply(); + describe(text, sizeof(text)); + tlog("MDDESK: settings %s %s\n", f ? "loaded" : "default", text); +} + +static void save(struct widget *w) +{ + FILE *f = fopen(cfg_path, "w"); + char text[160]; + + (void)w; + describe(text, sizeof(text)); + if (!f) + return; + fprintf(f, "background=%s\naccent=%s\nclock=%d\nmouse=%s\n", backgrounds[cfg.bg].name, + accents[cfg.accent].name, cfg.clock24 ? 24 : 12, speeds[cfg.speed]); + fclose(f); + tlog("MDDESK: settings saved %s\n", text); +} + +static void close_settings(void) +{ + if (win) + { + wm_window_close(win); + win = 0; + panel_damage(); + } +} + +static void b_close(struct widget *w) +{ + (void)w; + close_settings(); +} + +static void pick_bg(struct widget *w) { cfg.bg = w->value; apply(); } +static void pick_accent(struct widget *w) { cfg.accent = w->value; apply(); } +static void pick_speed(struct widget *w) { cfg.speed = w->value; apply(); } +static void toggle_clock(struct widget *w) { cfg.clock24 = w->value; apply(); } + +static int events(struct window *w, const struct event *e) +{ + (void)w; + if (e->type == EV_CLOSE) + { + close_settings(); + return 1; + } + return 0; +} + +/* test log: where list item i is on the screen */ +static void log_items(const char *prefix, struct widget *l, const char *const *names, int n) +{ + int i, x, y; + + if (!test_mode) + return; + ui_widget_center(l, &x, &y); + for (i = 0; i < n; i++) + tlog("MDDESK: widget %s_%s %d,%d\n", prefix, names[i], x, y - l->h / 2 + 2 + i * 20 + 10); +} + +void settings_open(void) +{ + struct ui *ui; + struct widget *bg, *ac, *sp, *b; + + if (win) + { + wm_raise(win); + return; + } + win = wm_window_new(320, 120, 440, 380, "Settings"); + if (!win) + return; + win->handler = events; + ui = ui_new(win); + ui_label(ui, 16, 14, "Background"); + bg = ui_list(ui, 16, 36, 180, 108, bg_names, NBG, pick_bg); + bg->value = cfg.bg; + ui_label(ui, 220, 14, "Accent colour"); + ac = ui_list(ui, 220, 36, 196, 108, accent_names, NACCENT, pick_accent); + ac->value = cfg.accent; + ui_label(ui, 16, 162, "Mouse speed"); + sp = ui_list(ui, 16, 184, 180, 68, speeds, NSPEED, pick_speed); + sp->value = cfg.speed; + check24 = ui_check(ui, 220, 184, "24-hour clock", toggle_clock); + check24->value = cfg.clock24; + ui_label(ui, 220, 214, "Saved in MDDESK.CFG"); + b = ui_button(ui, 228, 300, 92, 28, "Save", save); + desk_widget("settings_save", b); + b = ui_button(ui, 328, 300, 92, 28, "Close", b_close); + desk_widget("settings_close", b); + desk_widget("settings_clock24", check24); + log_items("bg", bg, bg_names, NBG); + log_items("accent", ac, accent_names, NACCENT); + ui_focus(bg); + ui_redraw(ui); + panel_damage(); + tlog("MDDESK: window Settings at %d,%d\n", win->x, win->y); +} diff --git a/gui/desk/term.c b/gui/desk/term.c new file mode 100644 index 00000000..66ddda23 --- /dev/null +++ b/gui/desk/term.c @@ -0,0 +1,296 @@ +/* + * MDDESK Terminal - a DOS session in a window (M5.4). + * + * The desktop is a DPMI program; MDVMM keeps the other DOS sessions + * running beside it. A terminal window takes one of the job slots + * (sessions started by SSHSLOT.COM before the desktop), runs COMMAND.COM + * in it, shows that session's 80x25 text screen in the window and types + * the window's keys into the session's keyboard buffer (monitor calls + * INT 2Fh AX=DE08h..DE0Dh). EXIT in the shell closes the window; closing + * the window sends Ctrl+C and EXIT. + * + * A session that is not on the display has its own text screen memory + * (the monitor maps it at B8000h), which is what the window shows. Works + * for programs that write text through DOS, the BIOS or into that memory; + * a program that sets a graphics mode needs the real display (Ctrl+Alt+Fn + * switches to its session). + * Programs in the terminal may be DPMI programs too (each session has its + * own DPMI client). + */ +#include +#include +#include +#include +#include +#include +#include "desk.h" + +#define COLS 80 +#define ROWS 25 +#define MAX_TERMS 3 + +struct term { + struct window *win; + int slot; + unsigned char shown[COLS * ROWS * 2]; + int have; /* shown[] is valid */ + int row, col, cursor_on; + int ready; /* the shell's prompt was seen (tests) */ +}; + +static struct term terms[MAX_TERMS]; +static int leaving[8]; /* slots of closed windows, to end */ +static clock_t last_poll; + +static const color_t cga[16] = { + RGB(0x00, 0x00, 0x00), RGB(0x00, 0x00, 0xaa), RGB(0x00, 0xaa, 0x00), RGB(0x00, 0xaa, 0xaa), + RGB(0xaa, 0x00, 0x00), RGB(0xaa, 0x00, 0xaa), RGB(0xaa, 0x55, 0x00), RGB(0xaa, 0xaa, 0xaa), + RGB(0x55, 0x55, 0x55), RGB(0x55, 0x55, 0xff), RGB(0x55, 0xff, 0x55), RGB(0x55, 0xff, 0xff), + RGB(0xff, 0x55, 0x55), RGB(0xff, 0x55, 0xff), RGB(0xff, 0xff, 0x55), RGB(0xff, 0xff, 0xff), +}; + +/* ---------------------------------------------------------------- */ +/* the monitor's session calls */ + +static int api(__dpmi_regs *r, int al) +{ + r->h.ah = 0xde; + r->h.al = (unsigned char)al; + __dpmi_int(0x2f, r); + return !(r->x.flags & 1); +} + +static int job_start(void) +{ + __dpmi_regs r; + char empty = 0; + + memset(&r, 0, sizeof(r)); + dosmemput(&empty, 1, __tb); + r.x.ds = __tb >> 4; + r.x.si = __tb & 15; + return api(&r, 0x0c) ? r.x.ax : -1; +} + +static int job_state(int slot) +{ + __dpmi_regs r; + + memset(&r, 0, sizeof(r)); + r.h.bl = (unsigned char)slot; + return api(&r, 0x0d) ? (short)r.x.ax : -1; +} + +static int screen(int slot, unsigned char *cells, int *row, int *col, int *hidden) +{ + __dpmi_regs r; + + memset(&r, 0, sizeof(r)); + r.h.bl = (unsigned char)slot; + r.x.es = __tb >> 4; + r.x.di = __tb & 15; + r.x.cx = COLS * ROWS * 2; + if (!api(&r, 0x08)) + return 0; + memset(cells, 0, COLS * ROWS * 2); + dosmemget(__tb, r.x.si, cells); + *row = r.h.ah; + *col = r.h.al; + *hidden = (r.x.bx & 0x2000) != 0; + return 1; +} + +static int type_keys(int slot, const unsigned short *keys, int n) +{ + __dpmi_regs r; + + memset(&r, 0, sizeof(r)); + dosmemput(keys, (size_t)n * 2, __tb); + r.h.bl = (unsigned char)slot; + r.x.ds = __tb >> 4; + r.x.si = __tb & 15; + r.x.cx = (unsigned short)n; + return api(&r, 0x09) ? r.x.cx : 0; +} + +/* ---------------------------------------------------------------- */ + +static void draw_cell(struct term *t, int i, int cursor) +{ + struct surface *s = t->win->client; + unsigned char ch = t->shown[i * 2], a = t->shown[i * 2 + 1]; + char text[2] = { (char)(ch ? ch : ' '), 0 }; + int x = (i % COLS) * FONT_W, y = (i / COLS) * FONT_H; + + draw_text(s, x, y, text, cga[a & 15], cga[(a >> 4) & 7]); + if (cursor) + draw_fill(s, x, y + FONT_H - 3, FONT_W, 2, cga[a & 15]); +} + +static void close_term(struct term *t, int end_job) +{ + int i; + + if (end_job) + for (i = 0; i < 8; i++) + if (!leaving[i]) + { + leaving[i] = t->slot; /* Ctrl+C and EXIT until it ends */ + break; + } + wm_window_close(t->win); + t->win = 0; + tlog("MDDESK: term closed\n"); + panel_damage(); +} + +static int events(struct window *w, const struct event *e) +{ + struct term *t = w->user; + int i; + + if (e->type == EV_KEY) + { + unsigned short key = (unsigned short)(e->scan << 8 | (e->ascii & 0xff)); + type_keys(t->slot, &key, 1); + return 1; + } + if (e->type == EV_REDRAW) + { + for (i = 0; i < COLS * ROWS; i++) + draw_cell(t, i, 0); + wm_invalidate(w); + return 1; + } + if (e->type == EV_CLOSE) + { + close_term(t, 1); + return 1; + } + return e->type == EV_MOUSE_DOWN; +} + +/* called by the desktop when it is idle: screens, ended sessions */ +void term_idle(void) +{ + static clock_t last_leave; + clock_t now = clock(); + int i, n; + + if (now - last_poll < CLOCKS_PER_SEC / 20) + return; + last_poll = now; + for (n = 0; n < MAX_TERMS; n++) + { + struct term *t = &terms[n]; + unsigned char cells[COLS * ROWS * 2]; + int row, col, hidden, changed = 0, cur, old; + + if (!t->win) + continue; + i = job_state(t->slot); + if (i == 3 || i < 0) /* the shell ended */ + { + close_term(t, 0); + continue; + } + if (!screen(t->slot, cells, &row, &col, &hidden)) + continue; + cur = hidden || row >= ROWS || col >= COLS ? -1 : row * COLS + col; + old = t->cursor_on ? t->row * COLS + t->col : -1; + for (i = 0; i < COLS * ROWS; i++) + if (!t->have || cells[i * 2] != t->shown[i * 2] || cells[i * 2 + 1] != t->shown[i * 2 + 1] || + (cur != old && (i == cur || i == old))) + { + t->shown[i * 2] = cells[i * 2]; + t->shown[i * 2 + 1] = cells[i * 2 + 1]; + draw_cell(t, i, i == cur); + changed = 1; + } + t->have = 1; + t->row = row; + t->col = col; + t->cursor_on = cur >= 0; + if (changed) + { + wm_invalidate(t->win); + if (test_mode) /* the cursor's line and the one above */ + for (i = row > 0 ? row - 1 : 0; i <= row && i < ROWS; i++) + { + char line[COLS + 1]; + int c; + for (c = 0; c < COLS; c++) + line[c] = (char)(t->shown[(i * COLS + c) * 2] >= ' ' ? t->shown[(i * COLS + c) * 2] : ' '); + while (c > 0 && line[c - 1] == ' ') + c--; + line[c] = 0; + if (c) + tlog("MDDESK: term line %s\n", line); + if (!t->ready && strchr(line, '>')) + { + t->ready = 1; + tlog("MDDESK: term ready\n"); + } + } + } + } + /* sessions whose window was closed: ask the shell to leave */ + if (now - last_leave >= CLOCKS_PER_SEC) + { + static const unsigned short bye[] = { 0x2e03, 0x1c0d, 0x1265, 0x2d78, 0x1769, 0x1474, 0x1c0d }; + last_leave = now; + for (i = 0; i < 8; i++) + if (leaving[i]) + { + int st = job_state(leaving[i]); + if (st == 3 || st == 0 || st < 0) + leaving[i] = 0; + else + type_keys(leaving[i], bye, 7); + } + } +} + +static void message(const char *text) +{ + struct window *w = wm_window_new(200, 200, 560, 110, "Terminal"); + struct ui *ui; + + if (!w) + return; + ui = ui_new(w); + ui_label(ui, 16, 16, text); + tlog("MDDESK: term unavailable\n"); + wm_raise(w); + panel_damage(); +} + +void term_open(void) +{ + struct term *t = 0; + struct window *w; + int i, slot; + + for (i = 0; i < MAX_TERMS; i++) + if (!terms[i].win && !t) + t = &terms[i]; + if (!t || (slot = job_start()) < 0) + { + message("No free DOS session (start SSHSLOT before the desktop)."); + return; + } + w = wm_window_new(40 + 24 * (int)(t - terms), 50 + 24 * (int)(t - terms), + COLS * FONT_W + 2 * WM_BORDER, ROWS * FONT_H + WM_TITLE_H + 2 * WM_BORDER, "DOS"); + if (!w) + return; + memset(t, 0, sizeof(*t)); + t->win = w; + t->slot = slot; + w->user = t; + w->handler = events; + draw_fill(w->client, 0, 0, w->client->w, w->client->h, cga[0]); + wm_raise(w); + wm_invalidate(w); + panel_damage(); + tlog("MDDESK: term opened in session %d, window %dx%d\n", slot, w->client->w, w->client->h); +} diff --git a/gui/lib/draw.c b/gui/lib/draw.c new file mode 100644 index 00000000..0634e29c --- /dev/null +++ b/gui/lib/draw.c @@ -0,0 +1,164 @@ +/* mdgui - surfaces and drawing primitives, clipped to surface->clip */ +#include +#include +#include "mdgui.h" + +struct surface *surface_new(int w, int h) +{ + struct surface *s = malloc(sizeof(*s)); + + if (!s) + return 0; + s->px = calloc((size_t)w * h, sizeof(color_t)); + if (!s->px) + { + free(s); + return 0; + } + s->w = w; + s->h = h; + s->stride = w; + surface_noclip(s); + return s; +} + +void surface_free(struct surface *s) +{ + if (!s) + return; + free(s->px); + free(s); +} + +void surface_noclip(struct surface *s) +{ + s->clip.x = s->clip.y = 0; + s->clip.w = s->w; + s->clip.h = s->h; +} + +/* clip to x,y,w,h (within the surface) */ +void surface_clip(struct surface *s, int x, int y, int w, int h) +{ + if (x < 0) { w += x; x = 0; } + if (y < 0) { h += y; y = 0; } + if (x + w > s->w) w = s->w - x; + if (y + h > s->h) h = s->h - y; + s->clip.x = x; + s->clip.y = y; + s->clip.w = w > 0 ? w : 0; + s->clip.h = h > 0 ? h : 0; +} + +/* intersect x,y,w,h with the clip rectangle; 0 if nothing is left */ +static int clip(const struct surface *s, int *x, int *y, int *w, int *h) +{ + int x1 = *x + *w, y1 = *y + *h; + int cx1 = s->clip.x + s->clip.w, cy1 = s->clip.y + s->clip.h; + + if (*x < s->clip.x) *x = s->clip.x; + if (*y < s->clip.y) *y = s->clip.y; + if (x1 > cx1) x1 = cx1; + if (y1 > cy1) y1 = cy1; + *w = x1 - *x; + *h = y1 - *y; + return *w > 0 && *h > 0; +} + +void draw_pixel(struct surface *s, int x, int y, color_t c) +{ + if (x >= s->clip.x && y >= s->clip.y && x < s->clip.x + s->clip.w && y < s->clip.y + s->clip.h) + s->px[y * s->stride + x] = c; +} + +void draw_fill(struct surface *s, int x, int y, int w, int h, color_t c) +{ + int i, j; + + if (!clip(s, &x, &y, &w, &h)) + return; + for (j = y; j < y + h; j++) + { + color_t *p = s->px + j * s->stride + x; + for (i = 0; i < w; i++) + p[i] = c; + } +} + +void draw_hline(struct surface *s, int x, int y, int w, color_t c) +{ + draw_fill(s, x, y, w, 1, c); +} + +void draw_vline(struct surface *s, int x, int y, int h, color_t c) +{ + draw_fill(s, x, y, 1, h, c); +} + +void draw_frame(struct surface *s, int x, int y, int w, int h, color_t c) +{ + if (w <= 0 || h <= 0) + return; + draw_hline(s, x, y, w, c); + draw_hline(s, x, y + h - 1, w, c); + draw_vline(s, x, y + 1, h - 2, c); + draw_vline(s, x + w - 1, y + 1, h - 2, c); +} + +void draw_line(struct surface *s, int x0, int y0, int x1, int y1, color_t c) +{ + int dx = abs(x1 - x0), dy = -abs(y1 - y0); + int sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1, err = dx + dy; + + for (;;) + { + int e2 = 2 * err; + + draw_pixel(s, x0, y0, c); + if (x0 == x1 && y0 == y1) + break; + if (e2 >= dy) + { + err += dy; + x0 += sx; + } + if (e2 <= dx) + { + err += dx; + y0 += sy; + } + } +} + +static color_t mix(color_t a, color_t b, int t, int n) +{ + int r = (int)(a >> 16 & 0xff) + ((int)(b >> 16 & 0xff) - (int)(a >> 16 & 0xff)) * t / n; + int g = (int)(a >> 8 & 0xff) + ((int)(b >> 8 & 0xff) - (int)(a >> 8 & 0xff)) * t / n; + int bl = (int)(a & 0xff) + ((int)(b & 0xff) - (int)(a & 0xff)) * t / n; + return RGB(r, g, bl); +} + +/* vertical gradient from top to bottom */ +void draw_gradient(struct surface *s, int x, int y, int w, int h, color_t top, color_t bottom) +{ + int j; + + for (j = 0; j < h; j++) + draw_hline(s, x, y + j, w, mix(top, bottom, j, h > 1 ? h - 1 : 1)); +} + +void draw_blit(struct surface *dst, int dx, int dy, const struct surface *src, + int sx, int sy, int w, int h) +{ + int x = dx, y = dy, j; + + if (!clip(dst, &x, &y, &w, &h)) + return; + sx += x - dx; + sy += y - dy; + if (sx < 0 || sy < 0 || sx + w > src->w || sy + h > src->h) + return; + for (j = 0; j < h; j++) + memmove(dst->px + (y + j) * dst->stride + x, src->px + (sy + j) * src->stride + sx, + w * sizeof(color_t)); +} diff --git a/gui/lib/gfx.c b/gui/lib/gfx.c new file mode 100644 index 00000000..1e770ac2 --- /dev/null +++ b/gui/lib/gfx.c @@ -0,0 +1,315 @@ +/* mdgui - display: VBE linear framebuffer modes, back buffer, present + * + * Uses the VBE BIOS through DPMI (real BIOS on DOS boots, the MDVMM + * virtual BIOS on UEFI boots). Only 32 bpp direct color modes with a + * linear framebuffer are used; the framebuffer is mapped with DPMI 0800h + * and reached through its own selector. + */ +#include +#include +#include +#include +#include +#include +#include "mdgui.h" + +struct vbe_mode_info { + uint16_t attr; + uint8_t win_a, win_b; + uint16_t gran, win_size, seg_a, seg_b; + uint32_t win_func; + uint16_t pitch, w, h; + uint8_t cw, ch, planes, bpp, banks, model, bank_size, pages, res1; + uint8_t r_size, r_pos, g_size, g_pos, b_size, b_pos, x_size, x_pos, dc_info; + uint32_t phys, res2; + uint16_t res3, lin_pitch; + uint8_t bnk_pages, lin_pages; + uint8_t lr_size, lr_pos, lg_size, lg_pos, lb_size, lb_pos, lx_size, lx_pos; + uint32_t max_clock; + uint8_t pad[190]; +} __attribute__((packed)); + +static struct gfx_mode mode; +static struct surface *screen; +static int sel = -1; /* framebuffer selector */ +static uint32_t pitch; /* bytes */ +static int r_pos, g_pos, b_pos; +static uint32_t *row; /* conversion buffer, one line */ +static char error[96]; + +/* mouse cursor: arrow sprite, '#' outline, 'o' fill */ +#define CUR_W 11 +#define CUR_H 17 +static const char *const cursor_shape[CUR_H] = { + "# ", "## ", "#o# ", "#oo# ", "#ooo# ", + "#oooo# ", "#ooooo# ", "#oooooo# ", "#ooooooo# ", "#oooooooo# ", + "#ooooooooo#", "#oooooo####", "#ooo#oo# ", "#oo# #oo# ", "#o# #oo# ", + "## #oo# ", " ### ", +}; +static int cur_on, cur_x, cur_y; +static __dpmi_meminfo map; + +const char *gfx_error(void) +{ + return error; +} + +const struct gfx_mode *gfx_mode(void) +{ + return &mode; +} + +struct surface *gfx_screen(void) +{ + return screen; +} + +static int vbe(__dpmi_regs *r) +{ + __dpmi_int(0x10, r); + return r->x.ax == 0x004f; +} + +static int mode_info(int m, struct vbe_mode_info *mi) +{ + __dpmi_regs r; + + memset(&r, 0, sizeof(r)); + r.x.ax = 0x4f01; + r.x.cx = (uint16_t)m; + r.x.es = __tb >> 4; + r.x.di = __tb & 15; + if (!vbe(&r)) + return 0; + dosmemget(__tb, sizeof(*mi), mi); + return 1; +} + +static int usable(const struct vbe_mode_info *mi) +{ + return (mi->attr & 0x91) == 0x91 && mi->bpp == 32 && mi->model == 6 && mi->phys && + mi->r_size == 8 && mi->g_size == 8 && mi->b_size == 8; +} + +/* the mode to use: want_w x want_h if there is one, else the largest + that fits in it, else the smallest */ +static int pick(int want_w, int want_h, struct vbe_mode_info *best) +{ + __dpmi_regs r; + uint8_t info[512]; + uint16_t modes[256]; + uint32_t list; + int best_mode = -1, i; + + memset(best, 0, sizeof(*best)); + memset(&r, 0, sizeof(r)); + memset(info, 0, sizeof(info)); + memcpy(info, "VBE2", 4); + dosmemput(info, sizeof(info), __tb); + r.x.ax = 0x4f00; + r.x.es = __tb >> 4; + r.x.di = __tb & 15; + if (!vbe(&r)) + { + strcpy(error, "no VBE BIOS"); + return -1; + } + dosmemget(__tb, sizeof(info), info); + if (memcmp(info, "VESA", 4) || *(uint16_t *)(info + 4) < 0x0200) + { + strcpy(error, "VBE 2.0 or later needed"); + return -1; + } + /* copy the mode list first: it may be in the buffer (__tb) that the + mode information calls overwrite */ + list = *(uint32_t *)(info + 14); + list = (list >> 16) * 16 + (list & 0xffff); + dosmemget(list, sizeof(modes), modes); + modes[255] = 0xffff; + for (i = 0; i < 256; i++) + { + uint16_t m = modes[i]; + struct vbe_mode_info mi; + int fits, best_fits; + + if (m == 0xffff) + break; + if (!mode_info(m, &mi) || !usable(&mi)) + continue; + if (mi.w == want_w && mi.h == want_h) + { + *best = mi; + return m; + } + fits = mi.w <= want_w && mi.h <= want_h; + best_fits = best_mode >= 0 && best->w <= want_w && best->h <= want_h; + if (best_mode < 0 || + (fits && (!best_fits || mi.w * mi.h > best->w * best->h)) || + (!fits && !best_fits && mi.w * mi.h < best->w * best->h)) + { + *best = mi; + best_mode = m; + } + } + if (best_mode < 0) + strcpy(error, "no 32 bpp linear framebuffer mode"); + return best_mode; +} + +int gfx_open(int want_w, int want_h) +{ + struct vbe_mode_info mi; + __dpmi_regs r; + int m = pick(want_w, want_h, &mi); + + if (m < 0) + return -1; + pitch = mi.lin_pitch ? mi.lin_pitch : mi.pitch; + r_pos = mi.lr_size ? mi.lr_pos : mi.r_pos; + g_pos = mi.lg_size ? mi.lg_pos : mi.g_pos; + b_pos = mi.lb_size ? mi.lb_pos : mi.b_pos; + + /* map the framebuffer, give it a selector */ + map.address = mi.phys; + map.size = (pitch * mi.h + 4095) & ~4095u; + if (__dpmi_physical_address_mapping(&map)) + { + strcpy(error, "cannot map the framebuffer"); + return -1; + } + sel = __dpmi_allocate_ldt_descriptors(1); + if (sel < 0 || __dpmi_set_segment_base_address(sel, map.address) || + __dpmi_set_segment_limit(sel, map.size - 1)) + { + strcpy(error, "cannot make a framebuffer selector"); + return -1; + } + screen = surface_new(mi.w, mi.h); + row = malloc(mi.w * 4); + if (!screen || !row) + { + strcpy(error, "out of memory"); + return -1; + } + + memset(&r, 0, sizeof(r)); + r.x.ax = 0x4f02; + r.x.bx = (uint16_t)(m | 0x4000); /* linear framebuffer */ + if (!vbe(&r)) + { + sprintf(error, "cannot set mode %x", m); + return -1; + } + mode.w = mi.w; + mode.h = mi.h; + mode.vbe_mode = m; + mode.phys = mi.phys; + return 0; +} + +void gfx_close(void) +{ + __dpmi_regs r; + + memset(&r, 0, sizeof(r)); + r.x.ax = 0x0003; + __dpmi_int(0x10, &r); + if (sel >= 0) + __dpmi_free_ldt_descriptor(sel); + if (map.address) + __dpmi_free_physical_address_mapping(&map); + sel = -1; + map.address = 0; + surface_free(screen); + screen = 0; + cur_on = 0; + free(row); + row = 0; +} + +/* text mode for a while, keeping the back buffer and the mapping */ +void gfx_suspend(void) +{ + __dpmi_regs r; + + memset(&r, 0, sizeof(r)); + r.x.ax = 0x0003; + __dpmi_int(0x10, &r); +} + +int gfx_resume(void) +{ + __dpmi_regs r; + + memset(&r, 0, sizeof(r)); + r.x.ax = 0x4f02; + r.x.bx = (uint16_t)(mode.vbe_mode | 0x4000); + if (!vbe(&r)) + return -1; + gfx_present_all(); + return 0; +} + +void gfx_present(int x, int y, int w, int h) +{ + int j, i; + + if (!screen || sel < 0) + return; + if (x < 0) { w += x; x = 0; } + if (y < 0) { h += y; y = 0; } + if (x + w > screen->w) w = screen->w - x; + if (y + h > screen->h) h = screen->h - y; + if (w <= 0 || h <= 0) + return; + for (j = y; j < y + h; j++) + { + const color_t *src = screen->px + j * screen->stride + x; + int cy = j - cur_y; + int on_cursor = cur_on && cy >= 0 && cy < CUR_H && cur_x < x + w && cur_x + CUR_W > x; + + if (r_pos == 16 && g_pos == 8 && b_pos == 0 && !on_cursor) + { + movedata(_my_ds(), (unsigned)src, sel, j * pitch + x * 4, w * 4); + continue; + } + memcpy(row, src, w * 4); + if (on_cursor) /* the cursor goes over the screen */ + for (i = 0; i < CUR_W; i++) + { + int px = cur_x + i - x; + char c = cursor_shape[cy][i]; + if (px >= 0 && px < w && c != ' ') + row[px] = c == '#' ? RGB(16, 16, 16) : RGB(255, 255, 255); + } + if (!(r_pos == 16 && g_pos == 8 && b_pos == 0)) + for (i = 0; i < w; i++) + row[i] = (row[i] >> 16 & 0xff) << r_pos | (row[i] >> 8 & 0xff) << g_pos | + (row[i] & 0xff) << b_pos; + movedata(_my_ds(), (unsigned)row, sel, j * pitch + x * 4, w * 4); + } +} + +void gfx_cursor_show(int on) +{ + cur_on = on; + gfx_present(cur_x, cur_y, CUR_W, CUR_H); +} + +void gfx_cursor_move(int x, int y) +{ + int ox = cur_x, oy = cur_y; + + if (x == cur_x && y == cur_y) + return; + cur_x = x; + cur_y = y; + gfx_present(ox, oy, CUR_W, CUR_H); /* uncover the old place */ + gfx_present(x, y, CUR_W, CUR_H); +} + +void gfx_present_all(void) +{ + if (screen) + gfx_present(0, 0, screen->w, screen->h); +} diff --git a/gui/lib/input.c b/gui/lib/input.c new file mode 100644 index 00000000..df6e0ca4 --- /dev/null +++ b/gui/lib/input.c @@ -0,0 +1,226 @@ +/* mdgui - input events: keyboard through INT 16h, mouse through INT 33h + * + * The mouse driver (CTMOUSE on DOS boots, the MDVMM virtual BIOS on UEFI + * boots) is set to the screen size with 1:1 motion. Button presses and + * releases come from the driver's counters (functions 05h/06h), so a + * quick click between two polls is not lost. + */ +#include +#include +#include +#include +#include "mdgui.h" + +#define QSIZE 32 + +static int mouse, mx, my, mbuttons; +static int speed = 8; /* mickeys per 8 pixels */ +static struct event queue[QSIZE]; +static int qhead, qtail; + +static void push(const struct event *e) +{ + int next = (qtail + 1) % QSIZE; + if (next != qhead) + { + queue[qtail] = *e; + qtail = next; + } +} + +static void int33(__dpmi_regs *r) +{ + __dpmi_int(0x33, r); +} + +int input_open(void) +{ + const struct gfx_mode *m = gfx_mode(); + __dpmi_regs r; + unsigned long vec; + + qhead = qtail = 0; + mouse = 0; + /* a driver is installed if INT 33h points somewhere */ + dosmemget(0x33 * 4, 4, &vec); + if (!vec) + return 0; + memset(&r, 0, sizeof(r)); + int33(&r); /* reset */ + if (r.x.ax != 0xffff) + return 0; + mouse = 1; + r.x.ax = 0x0007; /* horizontal range */ + r.x.cx = 0; + r.x.dx = (unsigned short)(m->w - 1); + int33(&r); + r.x.ax = 0x0008; /* vertical range */ + r.x.cx = 0; + r.x.dx = (unsigned short)(m->h - 1); + int33(&r); + r.x.ax = 0x000f; /* mickeys per 8 pixels, both ways */ + r.x.cx = (unsigned short)speed; + r.x.dx = (unsigned short)speed; + int33(&r); + r.x.ax = 0x0013; /* no double speed */ + r.x.dx = 0x7fff; + int33(&r); + mx = m->w / 2; + my = m->h / 2; + r.x.ax = 0x0004; + r.x.cx = (unsigned short)mx; + r.x.dx = (unsigned short)my; + int33(&r); + mbuttons = 0; + return 1; +} + +void input_set_speed(int mickeys) +{ + __dpmi_regs r; + + speed = mickeys > 0 ? mickeys : 8; + if (!mouse) + return; + memset(&r, 0, sizeof(r)); + r.x.ax = 0x000f; + r.x.cx = (unsigned short)speed; + r.x.dx = (unsigned short)speed; + int33(&r); +} + +void input_close(void) +{ + __dpmi_regs r; + + if (mouse) + { + memset(&r, 0, sizeof(r)); + int33(&r); /* reset: text mode defaults */ + } + mouse = 0; +} + +static void poll_mouse(void) +{ + __dpmi_regs r; + struct event e; + int b, x, y, buttons; + + memset(&r, 0, sizeof(r)); + r.x.ax = 0x0003; + int33(&r); + x = (short)r.x.cx; + y = (short)r.x.dx; + buttons = r.x.bx & 7; + memset(&e, 0, sizeof(e)); + if (x != mx || y != my) + { + e.type = EV_MOUSE_MOVE; + e.x = mx = x; + e.y = my = y; + e.buttons = mbuttons; + push(&e); + } + for (b = 0; b < 3; b++) + { + static const int bits[3] = { MB_LEFT, MB_RIGHT, MB_MIDDLE }; + int presses, releases; + + r.x.ax = 0x0005; + r.x.bx = (unsigned short)b; + int33(&r); + presses = r.x.bx; + if (presses) + { + e.type = EV_MOUSE_DOWN; + e.x = (short)r.x.cx; + e.y = (short)r.x.dx; + e.button = bits[b]; + mbuttons |= bits[b]; + e.buttons = mbuttons; + push(&e); + } + r.x.ax = 0x0006; + r.x.bx = (unsigned short)b; + int33(&r); + releases = r.x.bx; + if (!releases && presses) + { + /* pressed and no release counted: is it still down? Asked now, not + taken from the state read before - the press may have come in + between, and a release made up from the old state ended a drag + as it began */ + __dpmi_regs q; + memset(&q, 0, sizeof(q)); + q.x.ax = 0x0003; + int33(&q); + buttons = q.x.bx & 7; + } + if (releases || (presses && !(buttons & bits[b]))) + { + e.type = EV_MOUSE_UP; + e.x = (short)r.x.cx; + e.y = (short)r.x.dx; + e.button = bits[b]; + mbuttons &= ~bits[b]; + e.buttons = mbuttons; + push(&e); + } + } +} + +static void poll_keyboard(void) +{ + __dpmi_regs r; + struct event e; + + memset(&r, 0, sizeof(r)); + r.h.ah = 0x11; /* key waiting? (extended) */ + __dpmi_int(0x16, &r); + if (r.x.flags & 0x40) /* ZF: none */ + return; + r.h.ah = 0x10; + __dpmi_int(0x16, &r); + memset(&e, 0, sizeof(e)); + e.type = EV_KEY; + e.scan = r.h.ah; + e.ascii = r.h.al == 0xe0 ? 0 : r.h.al; + e.x = mx; + e.y = my; + e.buttons = mbuttons; + r.h.ah = 0x12; + __dpmi_int(0x16, &r); + e.shift = r.x.ax; + push(&e); +} + +int input_poll(struct event *e) +{ + if (qhead == qtail) + { + poll_keyboard(); + if (mouse) + poll_mouse(); + } + if (qhead == qtail) + { + e->type = EV_NONE; + return 0; + } + *e = queue[qhead]; + qhead = (qhead + 1) % QSIZE; + return 1; +} + +void input_wait(struct event *e) +{ + __dpmi_regs r; + + while (!input_poll(e)) + { + memset(&r, 0, sizeof(r)); + r.x.ax = 0x1680; /* idle: release the time slice */ + __dpmi_int(0x2f, &r); + } +} diff --git a/gui/lib/mdgui.h b/gui/lib/mdgui.h new file mode 100644 index 00000000..49367bed --- /dev/null +++ b/gui/lib/mdgui.h @@ -0,0 +1,224 @@ +/* mdgui - modernDOS graphics library (32-bit DPMI, DJGPP) + * + * Graphics layer of the modernDOS desktop: a VBE linear framebuffer mode + * with 32 bits per pixel, an off-screen back buffer the program draws in, + * and gfx_present() to copy changed areas to the screen. Colors are + * 0x00RRGGBB everywhere; the conversion to the mode's pixel layout + * happens when presenting. + */ +#ifndef MDGUI_H +#define MDGUI_H + +#include + +typedef uint32_t color_t; + +#define RGB(r, g, b) ((color_t)(((r) & 0xff) << 16 | ((g) & 0xff) << 8 | ((b) & 0xff))) + +struct rect { + int x, y, w, h; +}; + +/* a drawing target: pixels, size, and a clip rectangle all drawing is + limited to (initially the whole surface) */ +struct surface { + int w, h, stride; /* stride in pixels */ + color_t *px; + struct rect clip; +}; + +/* the display */ +struct gfx_mode { + int w, h; + int vbe_mode; + uint32_t phys; /* framebuffer address */ +}; + +/* theme.c - colors the window manager and the widgets use */ +struct theme { + color_t desk_top, desk_bottom; /* desktop gradient */ + color_t accent; /* active title bar, focus, selection */ + color_t accent_hi; /* lighter: the title bar's top line */ + color_t accent_soft; /* very light: the editor's line */ +}; +extern struct theme theme; + +/* gfx.c - display */ +int gfx_open(int want_w, int want_h); /* 0 = ok, else an error message */ +const char *gfx_error(void); +void gfx_close(void); /* back to 80x25 text mode */ +const struct gfx_mode *gfx_mode(void); +struct surface *gfx_screen(void); /* the back buffer */ +void gfx_present(int x, int y, int w, int h); +void gfx_present_all(void); +void gfx_suspend(void); /* text mode for a while (run a DOS program) */ +int gfx_resume(void); /* the graphics mode again, screen redrawn */ +/* mouse cursor, drawn over the presented screen (not in the back buffer) */ +void gfx_cursor_show(int on); +void gfx_cursor_move(int x, int y); + +/* draw.c - drawing on surfaces (clipped) */ +struct surface *surface_new(int w, int h); +void surface_free(struct surface *s); +void surface_clip(struct surface *s, int x, int y, int w, int h); +void surface_noclip(struct surface *s); +void draw_pixel(struct surface *s, int x, int y, color_t c); +void draw_fill(struct surface *s, int x, int y, int w, int h, color_t c); +void draw_hline(struct surface *s, int x, int y, int w, color_t c); +void draw_vline(struct surface *s, int x, int y, int h, color_t c); +void draw_frame(struct surface *s, int x, int y, int w, int h, color_t c); +void draw_line(struct surface *s, int x0, int y0, int x1, int y1, color_t c); +void draw_gradient(struct surface *s, int x, int y, int w, int h, color_t top, color_t bottom); +void draw_blit(struct surface *dst, int dx, int dy, const struct surface *src, + int sx, int sy, int w, int h); + +/* text.c - 8x16 bitmap font (code page 437) */ +#define FONT_W 8 +#define FONT_H 16 +#define TEXT_TRANSPARENT 0xff000000u /* as bg: leave the background */ +int draw_text(struct surface *s, int x, int y, const char *text, color_t fg, color_t bg); +int text_width(const char *text); + +/* input.c - keyboard (INT 16h) and mouse (INT 33h) events */ +enum { EV_NONE, EV_MOUSE_MOVE, EV_MOUSE_DOWN, EV_MOUSE_UP, EV_KEY }; +#define MB_LEFT 1 +#define MB_RIGHT 2 +#define MB_MIDDLE 4 + +struct event { + int type; + int x, y; /* mouse position (all events) */ + int buttons; /* buttons held (MB_*) */ + int button; /* EV_MOUSE_DOWN/UP: which one */ + int scan, ascii; /* EV_KEY: BIOS scan code, character */ + int shift; /* EV_KEY: BIOS shift flags */ +}; + +int input_open(void); /* 1 if there is a mouse */ +void input_set_speed(int mickeys); /* per 8 pixels: 8 normal, more slower */ +int input_poll(struct event *e); /* 1 if *e is an event */ +void input_wait(struct event *e); /* until there is one; idles */ +void input_close(void); + +/* wm.c - windows: frames, z-order, focus, moving, damage repaint */ +#define WM_TITLE_H 24 +#define WM_BORDER 1 + +struct window; +/* event handler: mouse coordinates are client coordinates; return 1 if + handled. EV_CLOSE when the close button is clicked (default: close) */ +enum { EV_CLOSE = 100, EV_REDRAW }; /* EV_REDRAW: draw the contents again */ +typedef int (*wm_handler)(struct window *w, const struct event *e); + +struct window { + int x, y, w, h; /* outer rectangle, screen coords */ + char title[64]; + struct surface *client; /* contents, drawn by the program */ + wm_handler handler; + void *user; + int visible; + int popup; /* no title bar; closes when the + mouse is pressed outside it */ +}; + +int wm_init(void); /* after gfx_open; draws the desktop */ +struct window *wm_window_new(int x, int y, int w, int h, const char *title); +struct window *wm_popup_new(int x, int y, int w, int h); +void wm_window_close(struct window *w); +void wm_window_move(struct window *w, int x, int y); +void wm_raise(struct window *w); /* to the top, with the focus */ +struct window *wm_focus(void); +struct window *wm_top(void); +int wm_count(void); +struct window *wm_window(int i); /* bottom (0) to top */ +void wm_invalidate(struct window *w); /* client contents changed */ +void wm_damage(int x, int y, int w, int h); +void wm_update(void); /* repaint and present damage */ +void wm_redraw_all(void); /* EV_REDRAW to every window (new theme) */ +int wm_dispatch(const struct event *e); /* route one event; 0 if unused */ +void wm_run(int (*idle)(void)); /* until wm_quit; idle may be 0 */ +/* the desktop's content: a band of `top` pixels windows stay below (a + panel), drawn by draw() after the background; event() gets the mouse + where there is no window, and keys when there is none */ +void wm_desktop(int top, void (*draw)(struct surface *s), int (*event)(const struct event *e)); +int wm_desktop_top(void); +void wm_quit(void); + +/* ui.c - widgets in a window */ +enum { UI_LABEL, UI_BUTTON, UI_CHECK, UI_TEXT, UI_LIST, UI_MENUBAR, UI_EDIT, UI_CANVAS }; + +struct ui; +struct widget; +typedef void (*ui_action)(struct widget *w); + +struct ui_menu { + const char *title; + const char *const *items; + int nitems; +}; + +struct widget { + int type; + int x, y, w, h; /* client coordinates */ + char text[128]; /* caption; UI_TEXT: the contents */ + int value; /* check: on; list: selection (-1); + text: caret; menubar: item chosen */ + int menu; /* menubar: menu chosen */ + int scroll; /* list: first row; text: first char */ + const char *const *items; /* list items */ + int nitems; + const struct ui_menu *menus; /* menubar */ + int nmenus; + int disabled; + ui_action action; /* click, toggle, select, Enter, menu */ + ui_action activate; /* list: Enter, double click (else action) */ + void *data; /* UI_EDIT: the text */ + long last_click; + void *user; + struct ui *ui; + /* UI_CANVAS: drawn and handled by the program */ + void (*paint)(struct widget *w, struct surface *s); + int (*input)(struct widget *w, const struct event *e); +}; + +struct ui *ui_new(struct window *win); /* takes the window's handler; the + old one gets unused events */ +struct widget *ui_label(struct ui *ui, int x, int y, const char *text); +struct widget *ui_button(struct ui *ui, int x, int y, int w, int h, const char *text, ui_action a); +struct widget *ui_check(struct ui *ui, int x, int y, const char *text, ui_action a); +struct widget *ui_textfield(struct ui *ui, int x, int y, int w, ui_action a); +struct widget *ui_list(struct ui *ui, int x, int y, int w, int h, const char *const *items, int n, + ui_action a); +struct widget *ui_menubar(struct ui *ui, const struct ui_menu *menus, int n, ui_action a); +void ui_set_text(struct widget *w, const char *text); +/* an area the program draws itself: paint() draws it (on every redraw of + the window), input() gets mouse presses in it and, when it has the + focus, keys (client coordinates; return 1 if used) */ +struct widget *ui_canvas(struct ui *ui, int x, int y, int w, int h, + void (*paint)(struct widget *w, struct surface *s), + int (*input)(struct widget *w, const struct event *e)); +/* multi-line text editor; action: the text or the caret changed */ +struct widget *ui_edit(struct ui *ui, int x, int y, int w, int h, ui_action a); +int edit_set_text(struct widget *w, const char *text, long len); /* -1: no memory */ +char *edit_get_text(struct widget *w, long *len); /* malloc'd, CRLF lines */ +int edit_modified(struct widget *w); +void edit_set_modified(struct widget *w, int m); +void edit_caret(struct widget *w, int *line, int *col); /* from 1 */ +int edit_lines(struct widget *w); +void ui_focus(struct widget *w); +struct widget *ui_focused(struct ui *ui); +void ui_redraw(struct ui *ui); +int ui_widget_center(const struct widget *w, int *sx, int *sy); /* screen */ +/* a popup menu at x,y (screen); choose gets the item or -1 (closed) */ +int ui_popup(int x, int y, const char *const *items, int n, void (*choose)(int item, void *user), + void *user); +int ui_popup_open(void); +/* dialogs (windows in the middle of the screen); Enter is OK, Esc and the + close button cancel. ui_ask_text returns the text field, done() gets + the text or 0; ui_confirm returns the Yes button, done() gets 1/0 */ +struct widget *ui_ask_text(const char *title, const char *prompt, const char *initial, + void (*done)(const char *text, void *user), void *user); +struct widget *ui_confirm(const char *title, const char *text, + void (*done)(int yes, void *user), void *user); + +#endif diff --git a/gui/lib/text.c b/gui/lib/text.c new file mode 100644 index 00000000..15e5f355 --- /dev/null +++ b/gui/lib/text.c @@ -0,0 +1,34 @@ +/* mdgui - text in the 8x16 code page 437 font (shared with the MDVMM + console: mdvmm/core/font.c) */ +#include +#include "mdgui.h" + +extern const uint8_t font8x16[4096]; + +/* draw text at x,y (top left); returns the width drawn */ +int draw_text(struct surface *s, int x, int y, const char *text, color_t fg, color_t bg) +{ + int x0 = x, row, col; + + for (; *text; text++, x += FONT_W) + { + const uint8_t *glyph = font8x16 + (uint8_t)*text * FONT_H; + + if (x >= s->clip.x + s->clip.w || x + FONT_W <= s->clip.x) + continue; + for (row = 0; row < FONT_H; row++) + for (col = 0; col < FONT_W; col++) + { + if (glyph[row] & (0x80 >> col)) + draw_pixel(s, x + col, y + row, fg); + else if (bg != TEXT_TRANSPARENT) + draw_pixel(s, x + col, y + row, bg); + } + } + return x - x0; +} + +int text_width(const char *text) +{ + return (int)strlen(text) * FONT_W; +} diff --git a/gui/lib/theme.c b/gui/lib/theme.c new file mode 100644 index 00000000..fded505a --- /dev/null +++ b/gui/lib/theme.c @@ -0,0 +1,7 @@ +/* mdgui - the theme: the default look (slate desktop, teal accent) */ +#include "mdgui.h" + +struct theme theme = { + RGB(36, 52, 71), RGB(18, 28, 40), + RGB(32, 128, 136), RGB(64, 168, 176), RGB(238, 246, 247), +}; diff --git a/gui/lib/ui.c b/gui/lib/ui.c new file mode 100644 index 00000000..a76ffae8 --- /dev/null +++ b/gui/lib/ui.c @@ -0,0 +1,1233 @@ +/* mdgui - widget toolkit + * + * Widgets live in a window's client area and are drawn into its client + * surface. ui_new() installs a handler on the window; events no widget + * uses (and EV_CLOSE) go on to the window's previous handler. + * + * Keyboard: Tab / Shift+Tab move the focus between focusable widgets; + * buttons take Enter/Space, checkboxes Space, lists Up/Down/Home/End and + * Enter, text fields editing keys and Enter (action). Menus open with the + * mouse on the menu bar, or F10; in a menu Up/Down/Enter/Esc work. + */ +#include +#include +#include +#include "mdgui.h" + +#define MAX_WIDGETS 64 +#define ROW_H 20 +#define MENUBAR_H 22 +#define SCROLL_W 12 + +/* theme */ +#define C_FACE RGB(242, 244, 247) +#define C_INK RGB(30, 34, 40) +#define C_INK_DIM RGB(140, 146, 156) +#define C_LINE RGB(150, 158, 170) +#define C_BUTTON RGB(224, 228, 234) +#define C_PRESSED RGB(196, 204, 214) +#define C_FIELD RGB(255, 255, 255) +#define C_ACCENT theme.accent +#define C_ACCENT_TX RGB(255, 255, 255) +#define C_BAR RGB(228, 232, 238) + +struct ui { + struct window *win; + wm_handler next; + struct widget *w[MAX_WIDGETS]; + int n; + struct widget *focus, *pressed; + /* open menu */ + struct window *popup; + struct widget *menubar; + int open; +}; + +static int focusable(const struct widget *w) +{ + return !w->disabled && w->type != UI_LABEL && w->type != UI_MENUBAR; +} + +static struct widget *add(struct ui *ui, int type, int x, int y, int w, int h, const char *text) +{ + struct widget *wd; + + if (ui->n == MAX_WIDGETS || !(wd = calloc(1, sizeof(*wd)))) + return 0; + wd->type = type; + wd->x = x; + wd->y = y; + wd->w = w; + wd->h = h; + if (text) + strncpy(wd->text, text, sizeof(wd->text) - 1); + wd->ui = ui; + ui->w[ui->n++] = wd; + if (!ui->focus && focusable(wd)) + ui->focus = wd; + return wd; +} + +struct widget *ui_label(struct ui *ui, int x, int y, const char *text) +{ + return add(ui, UI_LABEL, x, y, text_width(text), FONT_H, text); +} + +struct widget *ui_button(struct ui *ui, int x, int y, int w, int h, const char *text, ui_action a) +{ + struct widget *wd = add(ui, UI_BUTTON, x, y, w, h, text); + if (wd) + wd->action = a; + return wd; +} + +struct widget *ui_check(struct ui *ui, int x, int y, const char *text, ui_action a) +{ + struct widget *wd = add(ui, UI_CHECK, x, y, 22 + text_width(text), 18, text); + if (wd) + wd->action = a; + return wd; +} + +struct widget *ui_textfield(struct ui *ui, int x, int y, int w, ui_action a) +{ + struct widget *wd = add(ui, UI_TEXT, x, y, w, FONT_H + 8, ""); + if (wd) + wd->action = a; + return wd; +} + +struct widget *ui_list(struct ui *ui, int x, int y, int w, int h, const char *const *items, int n, + ui_action a) +{ + struct widget *wd = add(ui, UI_LIST, x, y, w, h, 0); + if (wd) + { + wd->items = items; + wd->nitems = n; + wd->value = -1; + wd->action = a; + } + return wd; +} + +struct widget *ui_menubar(struct ui *ui, const struct ui_menu *menus, int n, ui_action a) +{ + struct widget *wd = add(ui, UI_MENUBAR, 0, 0, ui->win->client->w, MENUBAR_H, 0); + if (wd) + { + wd->menus = menus; + wd->nmenus = n; + wd->action = a; + ui->menubar = wd; + } + return wd; +} + +struct widget *ui_canvas(struct ui *ui, int x, int y, int w, int h, + void (*paint)(struct widget *w, struct surface *s), + int (*input)(struct widget *w, const struct event *e)) +{ + struct widget *wd = add(ui, UI_CANVAS, x, y, w, h, 0); + + if (wd) + { + wd->paint = paint; + wd->input = input; + } + return wd; +} + +void ui_set_text(struct widget *w, const char *text) +{ + strncpy(w->text, text, sizeof(w->text) - 1); + w->text[sizeof(w->text) - 1] = 0; + if (w->type == UI_TEXT) + { + w->value = (int)strlen(w->text); + w->scroll = 0; + } + ui_redraw(w->ui); +} + +struct widget *ui_focused(struct ui *ui) +{ + return ui->focus; +} + +void ui_focus(struct widget *w) +{ + if (w && focusable(w)) + { + w->ui->focus = w; + ui_redraw(w->ui); + } +} + +int ui_widget_center(const struct widget *w, int *sx, int *sy) +{ + const struct window *win = w->ui->win; + int top = win->popup ? WM_BORDER : WM_TITLE_H; + + *sx = win->x + WM_BORDER + w->x + w->w / 2; + *sy = win->y + top + w->y + w->h / 2; + return 0; +} + + +/* ---------------------------------------------------------------- */ +/* multi-line text (UI_EDIT) */ + +#define TAB_SPACES 4 + +struct ebuf { + char **line; + int *len; + int n, cap; + int cl, cc; /* caret */ + int top, left; /* first visible line, column */ + int modified; +}; + +static int eb_grow(struct ebuf *b, int n) +{ + if (n <= b->cap) + return 0; + { + int cap = b->cap ? b->cap * 2 : 64; + char **l; + int *ln; + while (cap < n) + cap *= 2; + l = realloc(b->line, cap * sizeof(char *)); + if (!l) + return -1; + b->line = l; + ln = realloc(b->len, cap * sizeof(int)); + if (!ln) + return -1; + b->len = ln; + b->cap = cap; + } + return 0; +} + +static void eb_clear(struct ebuf *b) +{ + int i; + for (i = 0; i < b->n; i++) + free(b->line[i]); + b->n = 0; +} + +/* insert a line (copy of s, len) at i */ +static int eb_insert_line(struct ebuf *b, int i, const char *s, int len) +{ + char *l; + + if (eb_grow(b, b->n + 1) || !(l = malloc(len + 1))) + return -1; + memcpy(l, s, len); + l[len] = 0; + memmove(b->line + i + 1, b->line + i, (b->n - i) * sizeof(char *)); + memmove(b->len + i + 1, b->len + i, (b->n - i) * sizeof(int)); + b->line[i] = l; + b->len[i] = len; + b->n++; + return 0; +} + +static void eb_delete_line(struct ebuf *b, int i) +{ + free(b->line[i]); + memmove(b->line + i, b->line + i + 1, (b->n - i - 1) * sizeof(char *)); + memmove(b->len + i, b->len + i + 1, (b->n - i - 1) * sizeof(int)); + b->n--; +} + +/* replace line i's text */ +static int eb_set_line(struct ebuf *b, int i, const char *s, int len) +{ + char *l = malloc(len + 1); + if (!l) + return -1; + memcpy(l, s, len); + l[len] = 0; + free(b->line[i]); + b->line[i] = l; + b->len[i] = len; + return 0; +} + +struct widget *ui_edit(struct ui *ui, int x, int y, int w, int h, ui_action a) +{ + struct widget *wd = add(ui, UI_EDIT, x, y, w, h, 0); + struct ebuf *b; + + if (!wd) + return 0; + b = calloc(1, sizeof(*b)); + if (!b || eb_insert_line(b, 0, "", 0)) + return 0; + wd->data = b; + wd->action = a; + return wd; +} + +int edit_set_text(struct widget *w, const char *text, long len) +{ + struct ebuf *b = w->data; + long i, start = 0; + + eb_clear(b); + for (i = 0; i <= len; i++) + if (i == len || text[i] == '\n') + { + long end = i; + if (end > start && text[end - 1] == '\r') + end--; + if (i == len && start == len && b->n) + break; /* text ends with a newline */ + if (eb_insert_line(b, b->n, text + start, (int)(end - start))) + return -1; + start = i + 1; + } + if (!b->n && eb_insert_line(b, 0, "", 0)) + return -1; + b->cl = b->cc = b->top = b->left = 0; + b->modified = 0; + ui_redraw(w->ui); + return 0; +} + +char *edit_get_text(struct widget *w, long *len) +{ + struct ebuf *b = w->data; + long total = 0; + char *t, *p; + int i; + + for (i = 0; i < b->n; i++) + total += b->len[i] + 2; + t = malloc(total + 1); + if (!t) + return 0; + for (p = t, i = 0; i < b->n; i++) + { + memcpy(p, b->line[i], b->len[i]); + p += b->len[i]; + *p++ = '\r'; + *p++ = '\n'; + } + *p = 0; + if (len) + *len = total; + return t; +} + +int edit_modified(struct widget *w) +{ + return ((struct ebuf *)w->data)->modified; +} + +void edit_set_modified(struct widget *w, int m) +{ + ((struct ebuf *)w->data)->modified = m; +} + +void edit_caret(struct widget *w, int *line, int *col) +{ + struct ebuf *b = w->data; + *line = b->cl + 1; + *col = b->cc + 1; +} + +int edit_lines(struct widget *w) +{ + return ((struct ebuf *)w->data)->n; +} + +static int edit_rows(const struct widget *w) +{ + return (w->h - 6) / FONT_H; +} + +static int edit_cols(const struct widget *w) +{ + return (w->w - 10 - SCROLL_W) / FONT_W; +} + +/* keep the caret in the text and on the screen */ +static void edit_fix(struct widget *w) +{ + struct ebuf *b = w->data; + int rows = edit_rows(w), cols = edit_cols(w); + + if (b->cl < 0) b->cl = 0; + if (b->cl >= b->n) b->cl = b->n - 1; + if (b->cc < 0) b->cc = 0; + if (b->cc > b->len[b->cl]) b->cc = b->len[b->cl]; + if (b->cl < b->top) b->top = b->cl; + if (b->cl >= b->top + rows) b->top = b->cl - rows + 1; + if (b->cc < b->left) b->left = b->cc; + if (b->cc >= b->left + cols) b->left = b->cc - cols + 1; +} + +static void edit_insert(struct ebuf *b, const char *s, int n) +{ + char *l = malloc(b->len[b->cl] + n + 1); + + if (!l) + return; + memcpy(l, b->line[b->cl], b->cc); + memcpy(l + b->cc, s, n); + memcpy(l + b->cc + n, b->line[b->cl] + b->cc, b->len[b->cl] - b->cc + 1); + free(b->line[b->cl]); + b->line[b->cl] = l; + b->len[b->cl] += n; + b->cc += n; + b->modified = 1; +} + +static int edit_key(struct widget *w, const struct event *e) +{ + struct ebuf *b = w->data; + int ctrl = (e->shift & 4) != 0, rows = edit_rows(w); + char *l = b->line[b->cl]; + + switch (e->scan) + { + case 0x48: b->cl--; break; /* up */ + case 0x50: b->cl++; break; /* down */ + case 0x4b: /* left */ + if (b->cc > 0) b->cc--; + else if (b->cl > 0) { b->cl--; b->cc = b->len[b->cl]; } + break; + case 0x4d: /* right */ + if (b->cc < b->len[b->cl]) b->cc++; + else if (b->cl < b->n - 1) { b->cl++; b->cc = 0; } + break; + case 0x47: case 0x77: if (ctrl || e->scan == 0x77) b->cl = 0; b->cc = 0; break; /* home */ + case 0x4f: case 0x75: /* end */ + if (ctrl || e->scan == 0x75) b->cl = b->n - 1; + b->cc = b->len[b->cl]; + break; + case 0x49: b->cl -= rows; b->top -= rows; if (b->top < 0) b->top = 0; break; /* pgup */ + case 0x51: b->cl += rows; b->top += rows; break; /* pgdn */ + case 0x53: /* delete */ + if (b->cc < b->len[b->cl]) + { + memmove(l + b->cc, l + b->cc + 1, b->len[b->cl] - b->cc); + b->len[b->cl]--; + b->modified = 1; + } + else if (b->cl < b->n - 1) /* join the next line */ + { + int n = b->len[b->cl] + b->len[b->cl + 1]; + char *j = malloc(n + 1); + if (j) + { + memcpy(j, l, b->len[b->cl]); + memcpy(j + b->len[b->cl], b->line[b->cl + 1], b->len[b->cl + 1] + 1); + eb_set_line(b, b->cl, j, n); + free(j); + eb_delete_line(b, b->cl + 1); + b->modified = 1; + } + } + break; + default: + if (e->ascii == 8) /* backspace */ + { + if (b->cc > 0) + { + memmove(l + b->cc - 1, l + b->cc, b->len[b->cl] - b->cc + 1); + b->len[b->cl]--; + b->cc--; + b->modified = 1; + } + else if (b->cl > 0) + { + int pl = b->len[b->cl - 1], n = pl + b->len[b->cl]; + char *j = malloc(n + 1); + if (j) + { + memcpy(j, b->line[b->cl - 1], pl); + memcpy(j + pl, l, b->len[b->cl] + 1); + eb_set_line(b, b->cl - 1, j, n); + free(j); + eb_delete_line(b, b->cl); + b->cl--; + b->cc = pl; + b->modified = 1; + } + } + } + else if (e->ascii == 13) /* split the line */ + { + if (!eb_insert_line(b, b->cl + 1, l + b->cc, b->len[b->cl] - b->cc)) + { + l = b->line[b->cl]; + l[b->cc] = 0; + b->len[b->cl] = b->cc; + b->cl++; + b->cc = 0; + b->modified = 1; + } + } + else if (e->ascii == 9) + edit_insert(b, " ", TAB_SPACES - b->cc % TAB_SPACES); + else if (e->ascii >= 32 && e->ascii != 127) + { + char c = (char)e->ascii; + edit_insert(b, &c, 1); + } + else + return 0; + } + edit_fix(w); + if (w->action) + w->action(w); + return 1; +} + +static void edit_click(struct widget *w, const struct event *e) +{ + struct ebuf *b = w->data; + int rows = edit_rows(w); + + if (e->x >= w->x + w->w - SCROLL_W - 1) /* scroll bar: page */ + { + b->top += e->y < w->y + w->h / 2 ? -rows : rows; + if (b->top > b->n - rows) b->top = b->n - rows; + if (b->top < 0) b->top = 0; + b->cl = b->top; + } + else + { + b->cl = b->top + (e->y - w->y - 3) / FONT_H; + if (b->cl >= b->n) b->cl = b->n - 1; + b->cc = b->left + (e->x - w->x - 5 + FONT_W / 2) / FONT_W; + } + edit_fix(w); + if (w->action) + w->action(w); +} + +static void edit_draw(struct surface *s, struct widget *w, int focused) +{ + struct ebuf *b = w->data; + int rows = edit_rows(w), cols = edit_cols(w), i; + char part[256]; + + draw_fill(s, w->x, w->y, w->w, w->h, C_FIELD); + draw_frame(s, w->x, w->y, w->w, w->h, focused ? C_ACCENT : C_LINE); + surface_clip(s, w->x + 1, w->y + 1, w->w - SCROLL_W - 3, w->h - 2); + for (i = 0; i < rows && b->top + i < b->n; i++) + { + int ln = b->top + i, y = w->y + 3 + i * FONT_H, n = b->len[ln] - b->left; + if (n > cols + 1) + n = cols + 1; + if (n > (int)sizeof(part) - 1) + n = sizeof(part) - 1; + if (n < 0) + n = 0; + memcpy(part, b->line[ln] + (b->left < b->len[ln] ? b->left : b->len[ln]), n); + part[n] = 0; + if (ln == b->cl && focused) + draw_fill(s, w->x + 2, y, w->w - SCROLL_W - 5, FONT_H, theme.accent_soft); + draw_text(s, w->x + 5, y, part, C_INK, TEXT_TRANSPARENT); + if (ln == b->cl && focused) + draw_vline(s, w->x + 5 + (b->cc - b->left) * FONT_W, y, FONT_H, C_INK); + } + surface_noclip(s); + { /* scroll bar */ + int track = w->h - 2, th = b->n > rows ? track * rows / b->n : track, ty0; + if (th < 12) th = 12; + ty0 = w->y + 1 + (b->n > rows ? (track - th) * b->top / (b->n - rows) : 0); + draw_fill(s, w->x + w->w - SCROLL_W - 1, w->y + 1, SCROLL_W, track, RGB(232, 235, 240)); + draw_fill(s, w->x + w->w - SCROLL_W + 1, ty0 + 1, SCROLL_W - 4, th - 2, RGB(176, 184, 196)); + } +} + +/* ---------------------------------------------------------------- */ +/* drawing */ + +static int list_rows(const struct widget *w) +{ + return (w->h - 4) / ROW_H; +} + +static int menu_title_x(const struct widget *w, int i) +{ + int x = 8, j; + for (j = 0; j < i; j++) + x += text_width(w->menus[j].title) + 20; + return x; +} + +static void draw_widget(struct surface *s, struct widget *w, int focused) +{ + int i, tx, ty; + color_t frame = focused ? C_ACCENT : C_LINE; + + switch (w->type) + { + case UI_CANVAS: + if (w->paint) + { + surface_clip(s, w->x, w->y, w->w, w->h); + w->paint(w, s); + surface_noclip(s); + if (focused) + draw_frame(s, w->x, w->y, w->w, w->h, frame); + } + break; + case UI_LABEL: + draw_text(s, w->x, w->y, w->text, w->disabled ? C_INK_DIM : C_INK, TEXT_TRANSPARENT); + break; + case UI_BUTTON: + draw_fill(s, w->x, w->y, w->w, w->h, w->ui->pressed == w ? C_PRESSED : C_BUTTON); + draw_frame(s, w->x, w->y, w->w, w->h, frame); + if (focused) + draw_frame(s, w->x + 1, w->y + 1, w->w - 2, w->h - 2, frame); + tx = w->x + (w->w - text_width(w->text)) / 2; + ty = w->y + (w->h - FONT_H) / 2; + draw_text(s, tx, ty, w->text, w->disabled ? C_INK_DIM : C_INK, TEXT_TRANSPARENT); + break; + case UI_CHECK: + draw_fill(s, w->x, w->y + 2, 14, 14, w->value ? C_ACCENT : C_FIELD); + draw_frame(s, w->x, w->y + 2, 14, 14, w->value ? C_ACCENT : frame); + if (w->value) + { + draw_line(s, w->x + 3, w->y + 9, w->x + 6, w->y + 12, C_ACCENT_TX); + draw_line(s, w->x + 6, w->y + 12, w->x + 11, w->y + 5, C_ACCENT_TX); + draw_line(s, w->x + 3, w->y + 8, w->x + 6, w->y + 11, C_ACCENT_TX); + draw_line(s, w->x + 6, w->y + 11, w->x + 11, w->y + 4, C_ACCENT_TX); + } + draw_text(s, w->x + 22, w->y + 1, w->text, C_INK, TEXT_TRANSPARENT); + if (focused) + draw_hline(s, w->x + 22, w->y + 17, text_width(w->text), C_ACCENT); + break; + case UI_TEXT: + { + int visible = (w->w - 10) / FONT_W, len = (int)strlen(w->text); + char part[128]; + if (w->value < w->scroll) + w->scroll = w->value; + if (w->value > w->scroll + visible) + w->scroll = w->value - visible; + draw_fill(s, w->x, w->y, w->w, w->h, C_FIELD); + draw_frame(s, w->x, w->y, w->w, w->h, frame); + strncpy(part, w->text + (w->scroll < len ? w->scroll : len), sizeof(part) - 1); + part[visible < 127 ? visible : 127] = 0; + draw_text(s, w->x + 5, w->y + 4, part, C_INK, TEXT_TRANSPARENT); + if (focused) + draw_vline(s, w->x + 5 + (w->value - w->scroll) * FONT_W, w->y + 3, FONT_H + 2, C_INK); + break; + } + case UI_LIST: + { + int rows = list_rows(w), iw = w->nitems > rows ? w->w - SCROLL_W : w->w; + draw_fill(s, w->x, w->y, w->w, w->h, C_FIELD); + draw_frame(s, w->x, w->y, w->w, w->h, frame); + surface_clip(s, w->x + 1, w->y + 1, iw - 2, w->h - 2); + for (i = 0; i < rows && w->scroll + i < w->nitems; i++) + { + int item = w->scroll + i, y = w->y + 2 + i * ROW_H; + int sel = item == w->value; + if (sel) + draw_fill(s, w->x + 2, y, iw - 4, ROW_H, focused ? C_ACCENT : C_PRESSED); + draw_text(s, w->x + 6, y + (ROW_H - FONT_H) / 2, w->items[item], + sel && focused ? C_ACCENT_TX : C_INK, TEXT_TRANSPARENT); + } + surface_noclip(s); + if (w->nitems > rows) /* scroll bar */ + { + int track = w->h - 2, th = track * rows / w->nitems; + int ty0 = w->y + 1 + (track - th) * w->scroll / (w->nitems - rows); + draw_fill(s, w->x + w->w - SCROLL_W - 1, w->y + 1, SCROLL_W, track, RGB(232, 235, 240)); + draw_fill(s, w->x + w->w - SCROLL_W + 1, ty0 + 1, SCROLL_W - 4, th - 2, RGB(176, 184, 196)); + } + break; + } + case UI_EDIT: + edit_draw(s, w, focused); + break; + case UI_MENUBAR: + draw_fill(s, 0, 0, s->w, MENUBAR_H, C_BAR); + draw_hline(s, 0, MENUBAR_H - 1, s->w, RGB(206, 212, 220)); + for (i = 0; i < w->nmenus; i++) + { + int x = menu_title_x(w, i), open = w->ui->popup && w->ui->open == i; + if (open) + draw_fill(s, x - 6, 0, text_width(w->menus[i].title) + 12, MENUBAR_H - 1, C_ACCENT); + draw_text(s, x, (MENUBAR_H - FONT_H) / 2, w->menus[i].title, + open ? C_ACCENT_TX : C_INK, TEXT_TRANSPARENT); + } + break; + } +} + +void ui_redraw(struct ui *ui) +{ + struct surface *s = ui->win->client; + int i; + + draw_fill(s, 0, 0, s->w, s->h, C_FACE); + for (i = 0; i < ui->n; i++) + draw_widget(s, ui->w[i], ui->w[i] == ui->focus && !ui->popup); + wm_invalidate(ui->win); +} + +/* ---------------------------------------------------------------- */ +/* popup menus */ + +/* one popup menu at a time */ +static struct { + struct window *win; + const char *const *items; + int n, hot; + void (*choose)(int item, void *user); + void *user; +} pm; + +static void pm_draw(void) +{ + struct surface *s = pm.win->client; + int i; + + draw_fill(s, 0, 0, s->w, s->h, C_FIELD); + for (i = 0; i < pm.n; i++) + { + if (i == pm.hot) + draw_fill(s, 2, 2 + i * ROW_H, s->w - 4, ROW_H, C_ACCENT); + draw_text(s, 12, 2 + i * ROW_H + (ROW_H - FONT_H) / 2, pm.items[i], + i == pm.hot ? C_ACCENT_TX : C_INK, TEXT_TRANSPARENT); + } + wm_invalidate(pm.win); +} + +/* close the popup; tell the owner the item (-1: none) */ +static void pm_end(int item) +{ + void (*choose)(int, void *) = pm.choose; + void *user = pm.user; + struct window *w = pm.win; + + if (!w) + return; + pm.win = 0; + wm_window_close(w); + if (choose) + choose(item, user); +} + +static int pm_handler(struct window *win, const struct event *e) +{ + int row; + + switch (e->type) + { + case EV_REDRAW: + pm_draw(); + return 1; + case EV_CLOSE: + pm_end(-1); + return 1; + case EV_MOUSE_MOVE: + case EV_MOUSE_DOWN: + row = e->y >= 2 ? (e->y - 2) / ROW_H : -1; + if (row >= 0 && row < pm.n && e->x >= 0 && e->x < win->client->w && row != pm.hot) + { + pm.hot = row; + pm_draw(); + } + return 1; + case EV_MOUSE_UP: + row = e->y >= 2 ? (e->y - 2) / ROW_H : -1; + if (row >= 0 && row < pm.n && e->x >= 0 && e->x < win->client->w) + pm_end(row); + return 1; + case EV_KEY: + if (e->scan == 0x48 && pm.hot > 0) /* up */ + pm.hot--; + else if (e->scan == 0x50 && pm.hot < pm.n - 1) /* down */ + pm.hot++; + else if (e->ascii == 13) + { + pm_end(pm.hot); + return 1; + } + else if (e->ascii == 27) + { + pm_end(-1); + return 1; + } + pm_draw(); + return 1; + } + return 0; +} + +int ui_popup(int x, int y, const char *const *items, int n, void (*choose)(int item, void *user), + void *user) +{ + int w = 0, j; + + pm_end(-1); + for (j = 0; j < n; j++) + if (text_width(items[j]) > w) + w = text_width(items[j]); + pm.items = items; + pm.n = n; + pm.hot = 0; + pm.choose = choose; + pm.user = user; + pm.win = wm_popup_new(x, y, w + 40, n * ROW_H + 6); + if (!pm.win) + return -1; + pm.win->handler = pm_handler; + pm_draw(); + return 0; +} + +int ui_popup_open(void) +{ + return pm.win != 0; +} + +/* the menu bar's menus */ +static void bar_choose(int item, void *user) +{ + struct ui *ui = user; + struct widget *bar = ui->menubar; + int menu = ui->open; + + ui->popup = 0; + ui_redraw(ui); + if (item >= 0 && bar->action) + { + bar->menu = menu; + bar->value = item; + bar->action(bar); + } +} + +static void menu_open(struct ui *ui, int i) +{ + const struct ui_menu *m = &ui->menubar->menus[i]; + + ui->open = i; + ui->popup = 0; + if (ui_popup(ui->win->x + WM_BORDER + menu_title_x(ui->menubar, i) - 6, + ui->win->y + WM_TITLE_H + MENUBAR_H - 1, m->items, m->nitems, bar_choose, ui)) + return; + ui->popup = pm.win; + ui_redraw(ui); +} + +/* ---------------------------------------------------------------- */ +/* events */ + +static struct widget *widget_at(struct ui *ui, int x, int y) +{ + int i; + for (i = ui->n - 1; i >= 0; i--) + { + struct widget *w = ui->w[i]; + if (!w->disabled && x >= w->x && x < w->x + w->w && y >= w->y && y < w->y + w->h) + return w; + } + return 0; +} + +static void act(struct widget *w) +{ + if (w->action) + w->action(w); +} + +/* list: Enter or a double click */ +static void activate(struct widget *w) +{ + if (w->activate) + w->activate(w); + else + act(w); +} + +static void list_select(struct widget *w, int item) +{ + int rows = list_rows(w); + + if (item < 0) + item = 0; + if (item >= w->nitems) + item = w->nitems - 1; + w->value = item; + if (item < w->scroll) + w->scroll = item; + if (item >= w->scroll + rows) + w->scroll = item - rows + 1; +} + +static void focus_next(struct ui *ui, int back) +{ + int i, start = 0, k; + + for (i = 0; i < ui->n; i++) + if (ui->w[i] == ui->focus) + start = i; + for (k = 1; k <= ui->n; k++) + { + struct widget *w = ui->w[((back ? start - k : start + k) % ui->n + ui->n) % ui->n]; + if (focusable(w)) + { + ui->focus = w; + return; + } + } +} + +static int text_key(struct widget *w, const struct event *e) +{ + int len = (int)strlen(w->text); + + switch (e->scan) + { + case 0x4b: if (w->value > 0) w->value--; return 1; /* left */ + case 0x4d: if (w->value < len) w->value++; return 1; /* right */ + case 0x47: w->value = 0; return 1; /* home */ + case 0x4f: w->value = len; return 1; /* end */ + case 0x53: /* delete */ + if (w->value < len) + memmove(w->text + w->value, w->text + w->value + 1, len - w->value); + return 1; + } + if (e->ascii == 8) + { + if (w->value > 0) + { + memmove(w->text + w->value - 1, w->text + w->value, len - w->value + 1); + w->value--; + } + return 1; + } + if (e->ascii == 13) + { + act(w); + return 1; + } + if (e->ascii >= 32 && e->ascii < 256 && e->ascii != 127 && len < (int)sizeof(w->text) - 1) + { + memmove(w->text + w->value + 1, w->text + w->value, len - w->value + 1); + w->text[w->value++] = (char)e->ascii; + return 1; + } + return 0; +} + +static int key(struct ui *ui, const struct event *e) +{ + struct widget *w = ui->focus; + + if (w && w->type == UI_EDIT && e->ascii == 9) /* Tab: the editor's */ + return edit_key(w, e); + if (e->ascii == 9 || (e->scan == 0x0f && !e->ascii)) /* Tab, Shift+Tab */ + { + focus_next(ui, e->ascii != 9 || (e->shift & 3)); + return 1; + } + if (e->scan == 0x44 && ui->menubar) /* F10: first menu */ + { + menu_open(ui, 0); + return 1; + } + if (!w) + return 0; + switch (w->type) + { + case UI_BUTTON: + if (e->ascii == 13 || e->ascii == ' ') + { + act(w); + return 1; + } + break; + case UI_CHECK: + if (e->ascii == ' ') + { + w->value = !w->value; + act(w); + return 1; + } + break; + case UI_LIST: + if (e->scan == 0x48) { list_select(w, w->value - 1); act(w); return 1; } + if (e->scan == 0x50) { list_select(w, w->value + 1); act(w); return 1; } + if (e->scan == 0x47) { list_select(w, 0); act(w); return 1; } + if (e->scan == 0x4f) { list_select(w, w->nitems - 1); act(w); return 1; } + if (e->ascii == 13) { activate(w); return 1; } + break; + case UI_TEXT: + return text_key(w, e); + case UI_EDIT: + return edit_key(w, e); + case UI_CANVAS: + return w->input ? w->input(w, e) : 0; + } + return 0; +} + +static int mouse_down(struct ui *ui, const struct event *e) +{ + struct widget *w = widget_at(ui, e->x, e->y); + int i; + + if (!w) + return 0; + if (w->type == UI_MENUBAR) + { + for (i = w->nmenus - 1; i >= 0; i--) + if (e->x >= menu_title_x(w, i) - 6) + { + if (e->x < menu_title_x(w, i) + text_width(w->menus[i].title) + 6) + menu_open(ui, i); + break; + } + return 1; + } + if (focusable(w)) + ui->focus = w; + switch (w->type) + { + case UI_CANVAS: + if (w->input) + w->input(w, e); + break; + case UI_BUTTON: + ui->pressed = w; + break; + case UI_CHECK: + w->value = !w->value; + act(w); + break; + case UI_EDIT: + edit_click(w, e); + break; + case UI_TEXT: + { + int pos = w->scroll + (e->x - w->x - 5 + FONT_W / 2) / FONT_W, len = (int)strlen(w->text); + w->value = pos < 0 ? 0 : pos > len ? len : pos; + break; + } + case UI_LIST: + { + int rows = list_rows(w); + if (w->nitems > rows && e->x >= w->x + w->w - SCROLL_W - 1) + { /* scroll bar: page up/down */ + w->scroll += e->y < w->y + w->h / 2 ? -rows : rows; + if (w->scroll > w->nitems - rows) + w->scroll = w->nitems - rows; + if (w->scroll < 0) + w->scroll = 0; + break; + } + i = w->scroll + (e->y - w->y - 2) / ROW_H; + if (e->y >= w->y + 2 && i < w->nitems) + { + int again = i == w->value && clock() - w->last_click < CLOCKS_PER_SEC / 2; + list_select(w, i); + if (again) + activate(w); /* double click */ + else + act(w); + w->last_click = again ? 0 : clock(); + } + break; + } + } + return 1; +} + +static int alive(const struct window *win) +{ + int i; + for (i = 0; i < wm_count(); i++) + if (wm_window(i) == win) + return 1; + return 0; +} + +static int handler(struct window *win, const struct event *e) +{ + struct ui *ui = win->user; + int used = 0; + + switch (e->type) + { + case EV_REDRAW: + ui_redraw(ui); + return 1; + case EV_MOUSE_DOWN: + if (e->button == MB_LEFT) + used = mouse_down(ui, e); + break; + case EV_MOUSE_UP: + if (ui->pressed) + { + struct widget *w = ui->pressed; + ui->pressed = 0; + if (widget_at(ui, e->x, e->y) == w) + act(w); + used = 1; + } + break; + case EV_KEY: + used = key(ui, e); + break; + } + if (used) + { + if (alive(win)) /* the action may have closed it */ + ui_redraw(ui); + return 1; + } + return ui->next ? ui->next(win, e) : 0; +} + +struct ui *ui_new(struct window *win) +{ + struct ui *ui = calloc(1, sizeof(*ui)); + + if (!ui) + return 0; + ui->win = win; + ui->next = win->handler; + win->handler = handler; + win->user = ui; + ui_redraw(ui); + return ui; +} + +/* ---------------------------------------------------------------- */ +/* dialogs */ + +struct dialog { + struct window *win; + struct widget *field; + void (*text_done)(const char *text, void *user); + void (*confirm_done)(int yes, void *user); + void *user; +}; + +static void dialog_end(struct dialog *d, int ok) +{ + char text[128]; + void (*td)(const char *, void *) = d->text_done; + void (*cd)(int, void *) = d->confirm_done; + void *user = d->user; + + if (d->field) + strcpy(text, d->field->text); + wm_window_close(d->win); + free(d); + if (td) + td(ok ? text : 0, user); + if (cd) + cd(ok, user); +} + +static void dialog_ok(struct widget *w) +{ + dialog_end(w->user, 1); +} + +static void dialog_cancel(struct widget *w) +{ + dialog_end(w->user, 0); +} + +static int dialog_events(struct window *win, const struct event *e) +{ + struct ui *ui = win->user; + + if (e->type == EV_CLOSE || (e->type == EV_KEY && e->ascii == 27)) + { + dialog_end(ui->w[ui->n - 1]->user, 0); /* any widget knows the dialog */ + return 1; + } + return 0; +} + +static struct dialog *dialog_new(const char *title, const char *text, int h) +{ + struct surface *s = gfx_screen(); + struct dialog *d = calloc(1, sizeof(*d)); + int w = text_width(text) + 48; + struct ui *ui; + + if (!d) + return 0; + if (w < 360) + w = 360; + d->win = wm_window_new((s->w - w) / 2, (s->h - h) / 2, w, h, title); + if (!d->win) + { + free(d); + return 0; + } + d->win->handler = dialog_events; + ui = ui_new(d->win); + ui_label(ui, 20, 18, text)->user = d; + return d; +} + +static struct widget *dialog_buttons(struct dialog *d, const char *ok, const char *cancel) +{ + struct ui *ui = d->win->user; + int cw = d->win->client->w, ch = d->win->client->h; + struct widget *b; + + b = ui_button(ui, cw - 208, ch - 44, 92, 28, ok, dialog_ok); + b->user = d; + ui_button(ui, cw - 108, ch - 44, 92, 28, cancel, dialog_cancel)->user = d; + return b; +} + +struct widget *ui_ask_text(const char *title, const char *prompt, const char *initial, + void (*done)(const char *text, void *user), void *user) +{ + struct dialog *d = dialog_new(title, prompt, 150); + struct ui *ui; + + if (!d) + return 0; + ui = d->win->user; + d->text_done = done; + d->user = user; + d->field = ui_textfield(ui, 20, 42, d->win->client->w - 40, dialog_ok); + d->field->user = d; + ui_set_text(d->field, initial ? initial : ""); + dialog_buttons(d, "OK", "Cancel"); + ui_focus(d->field); + ui_redraw(ui); + return d->field; +} + +struct widget *ui_confirm(const char *title, const char *text, + void (*done)(int yes, void *user), void *user) +{ + struct dialog *d = dialog_new(title, text, 120); + struct widget *yes; + + if (!d) + return 0; + d->confirm_done = done; + d->user = user; + yes = dialog_buttons(d, "Yes", "No"); + ui_focus(yes); + ui_redraw(d->win->user); + return yes; +} diff --git a/gui/lib/wm.c b/gui/lib/wm.c new file mode 100644 index 00000000..dc8da24f --- /dev/null +++ b/gui/lib/wm.c @@ -0,0 +1,453 @@ +/* mdgui - window manager + * + * All windows live in one program (the desktop). Each window has a frame, + * a title bar with a close button, and a retained client surface the + * program draws into. The screen is composed from the desktop and the + * windows, bottom to top, only where it was damaged, and then presented. + * + * Mouse: a press raises the window under the pointer and focuses it; on + * the title bar it starts a move, on the close button it closes the + * window; elsewhere it goes to the window (client coordinates), which + * keeps the mouse until the button is released. Keys go to the focused + * window. + */ +#include +#include +#include "mdgui.h" + +#define MAX_WINDOWS 32 +#define CLOSE_W 18 + +/* theme */ +#define C_TITLE RGB(58, 66, 82) +#define C_TITLE_ACTIVE theme.accent +#define C_TITLE_TEXT RGB(236, 240, 244) +#define C_BORDER RGB(20, 24, 30) +#define C_CLOSE RGB(196, 72, 64) + +static struct window *wins[MAX_WINDOWS]; /* bottom to top */ +static int nwin; +static struct rect dmg; +static int dmg_set, quit; +static struct window *drag, *capture; +static int drag_dx, drag_dy; +/* the desktop's own content (a panel): drawn over the background, gets + the mouse where no window is; windows stay below desk_top */ +static int desk_top; +static void (*desk_draw)(struct surface *s); +static int (*desk_event)(const struct event *e); + +void wm_desktop(int top, void (*draw)(struct surface *s), int (*event)(const struct event *e)) +{ + struct surface *s = gfx_screen(); + + desk_top = top; + desk_draw = draw; + desk_event = event; + if (s) + wm_damage(0, 0, s->w, s->h); +} + +int wm_desktop_top(void) +{ + return desk_top; +} + +static int clamp_y(const struct window *w, int y) +{ + return !w->popup && y < desk_top ? desk_top : y; +} + +int wm_count(void) +{ + return nwin; +} + +struct window *wm_window(int i) +{ + return i >= 0 && i < nwin ? wins[i] : 0; +} + +struct window *wm_top(void) +{ + int i; + for (i = nwin - 1; i >= 0; i--) + if (wins[i]->visible) + return wins[i]; + return 0; +} + +struct window *wm_focus(void) +{ + return wm_top(); +} + +void wm_damage(int x, int y, int w, int h) +{ + int x1, y1; + + if (w <= 0 || h <= 0) + return; + if (!dmg_set) + { + dmg.x = x; + dmg.y = y; + dmg.w = w; + dmg.h = h; + dmg_set = 1; + return; + } + x1 = dmg.x + dmg.w > x + w ? dmg.x + dmg.w : x + w; + y1 = dmg.y + dmg.h > y + h ? dmg.y + dmg.h : y + h; + if (x < dmg.x) dmg.x = x; + if (y < dmg.y) dmg.y = y; + dmg.w = x1 - dmg.x; + dmg.h = y1 - dmg.y; +} + +static void damage_window(struct window *w) +{ + wm_damage(w->x, w->y, w->w, w->h); +} + +void wm_invalidate(struct window *w) +{ + damage_window(w); +} + +static void client_rect(const struct window *w, struct rect *r) +{ + int top = w->popup ? WM_BORDER : WM_TITLE_H; + + r->x = w->x + WM_BORDER; + r->y = w->y + top; + r->w = w->w - 2 * WM_BORDER; + r->h = w->h - top - WM_BORDER; +} + +static struct window *window_new(int x, int y, int w, int h, const char *title, int popup) +{ + struct window *win; + struct rect c; + + if (nwin == MAX_WINDOWS || w < 16 || h < (popup ? 8 : WM_TITLE_H + 16)) + return 0; + win = calloc(1, sizeof(*win)); + if (!win) + return 0; + win->popup = popup; + if (!popup && y < desk_top) + y = desk_top; + win->x = x; + win->y = y; + win->w = w; + win->h = h; + strncpy(win->title, title, sizeof(win->title) - 1); + client_rect(win, &c); + win->client = surface_new(c.w, c.h); + if (!win->client) + { + free(win); + return 0; + } + draw_fill(win->client, 0, 0, c.w, c.h, RGB(242, 244, 247)); + win->visible = 1; + wins[nwin++] = win; + damage_window(win); + if (nwin > 1) + damage_window(wins[nwin - 2]); /* it loses the focus look */ + return win; +} + +struct window *wm_window_new(int x, int y, int w, int h, const char *title) +{ + return window_new(x, y, w, h, title, 0); +} + +/* a popup (menu): frame and client only, on top; a mouse press outside + it closes it (the handler gets EV_CLOSE first) */ +struct window *wm_popup_new(int x, int y, int w, int h) +{ + return window_new(x, y, w, h, "", 1); +} + +void wm_window_close(struct window *w) +{ + int i, j; + + for (i = 0; i < nwin && wins[i] != w; i++) + ; + if (i == nwin) + return; + damage_window(w); + for (j = i; j < nwin - 1; j++) + wins[j] = wins[j + 1]; + nwin--; + if (drag == w) + drag = 0; + if (capture == w) + capture = 0; + if (wm_top()) + damage_window(wm_top()); /* gets the focus look */ + surface_free(w->client); + free(w); +} + +void wm_window_move(struct window *w, int x, int y) +{ + damage_window(w); + w->x = x; + w->y = clamp_y(w, y); + damage_window(w); +} + +void wm_raise(struct window *w) +{ + int i, j; + + for (i = 0; i < nwin && wins[i] != w; i++) + ; + if (i == nwin || i == nwin - 1) + return; + damage_window(wins[nwin - 1]); + for (j = i; j < nwin - 1; j++) + wins[j] = wins[j + 1]; + wins[nwin - 1] = w; + damage_window(w); +} + +/* ---------------------------------------------------------------- */ + +static void draw_desktop(struct surface *s) +{ + draw_gradient(s, 0, 0, s->w, s->h, theme.desk_top, theme.desk_bottom); + draw_text(s, s->w - text_width("modernDOS") - 16, s->h - FONT_H - 12, "modernDOS", + RGB(90, 110, 130), TEXT_TRANSPARENT); + if (desk_draw) + desk_draw(s); +} + +static void close_box(const struct window *w, struct rect *r) +{ + r->w = CLOSE_W; + r->h = CLOSE_W - 2; + r->x = w->x + w->w - CLOSE_W - 4; + r->y = w->y + (WM_TITLE_H - r->h) / 2; +} + +static void draw_window(struct surface *s, const struct window *w, int active) +{ + struct rect c, cb; + color_t title = active ? C_TITLE_ACTIVE : C_TITLE; + int tw = w->w - CLOSE_W - 20, i; + char t[64]; + + draw_frame(s, w->x, w->y, w->w, w->h, w->popup ? RGB(120, 128, 140) : C_BORDER); + if (w->popup) + { + client_rect(w, &c); + draw_blit(s, c.x, c.y, w->client, 0, 0, c.w, c.h); + return; + } + draw_fill(s, w->x + 1, w->y + 1, w->w - 2, WM_TITLE_H - 1, title); + draw_hline(s, w->x + 1, w->y + 1, w->w - 2, active ? theme.accent_hi : RGB(78, 86, 102)); + /* title text, cut to fit */ + strcpy(t, w->title); + for (i = (int)strlen(t); i > 0 && text_width(t) > tw; i--) + t[i - 1] = 0; + draw_text(s, w->x + 10, w->y + (WM_TITLE_H - FONT_H) / 2, t, C_TITLE_TEXT, TEXT_TRANSPARENT); + close_box(w, &cb); + draw_fill(s, cb.x, cb.y, cb.w, cb.h, active ? C_CLOSE : RGB(88, 96, 112)); + draw_line(s, cb.x + 5, cb.y + 4, cb.x + cb.w - 6, cb.y + cb.h - 5, C_TITLE_TEXT); + draw_line(s, cb.x + cb.w - 6, cb.y + 4, cb.x + 5, cb.y + cb.h - 5, C_TITLE_TEXT); + client_rect(w, &c); + draw_blit(s, c.x, c.y, w->client, 0, 0, c.w, c.h); +} + +void wm_update(void) +{ + struct surface *s = gfx_screen(); + struct window *top = 0; + int i; + + for (i = nwin - 1; i >= 0 && !top; i--) + if (wins[i]->visible && !wins[i]->popup) + top = wins[i]; + + if (!dmg_set || !s) + return; + surface_clip(s, dmg.x, dmg.y, dmg.w, dmg.h); + draw_desktop(s); + for (i = 0; i < nwin; i++) + { + const struct window *w = wins[i]; + if (w->visible && w->x < dmg.x + dmg.w && w->x + w->w > dmg.x && + w->y < dmg.y + dmg.h && w->y + w->h > dmg.y) + draw_window(s, w, w == top); + } + surface_noclip(s); + gfx_present(dmg.x, dmg.y, dmg.w, dmg.h); + dmg_set = 0; +} + +int wm_init(void) +{ + struct surface *s = gfx_screen(); + + if (!s) + return -1; + nwin = 0; + drag = capture = 0; + quit = 0; + wm_damage(0, 0, s->w, s->h); + wm_update(); + return 0; +} + +/* ---------------------------------------------------------------- */ + +static struct window *window_at(int x, int y) +{ + int i; + for (i = nwin - 1; i >= 0; i--) + { + struct window *w = wins[i]; + if (w->visible && x >= w->x && x < w->x + w->w && y >= w->y && y < w->y + w->h) + return w; + } + return 0; +} + +static int deliver(struct window *w, const struct event *e) +{ + struct event c = *e; + struct rect r; + + if (!w || !w->handler) + return 0; + client_rect(w, &r); + c.x -= r.x; + c.y -= r.y; + return w->handler(w, &c); +} + +int wm_dispatch(const struct event *e) +{ + struct window *w; + struct rect cb; + + if (e->type == EV_MOUSE_MOVE || e->type == EV_MOUSE_DOWN || e->type == EV_MOUSE_UP) + gfx_cursor_move(e->x, e->y); + switch (e->type) + { + case EV_MOUSE_DOWN: + w = window_at(e->x, e->y); + if (wm_top() && wm_top()->popup && w != wm_top()) + { /* outside a popup: close it */ + struct window *p = wm_top(); + struct event c = *e; + c.type = EV_CLOSE; + if (!deliver(p, &c)) + wm_window_close(p); + return 1; + } + if (!w) + return desk_event ? desk_event(e) : 0; + if (w->popup) + { + capture = w; + return deliver(w, e); + } + wm_raise(w); + if (e->button != MB_LEFT || e->y >= w->y + WM_TITLE_H) + { + capture = w; + return deliver(w, e); + } + close_box(w, &cb); + if (e->x >= cb.x && e->x < cb.x + cb.w && e->y >= cb.y && e->y < cb.y + cb.h) + { + struct event c = *e; + c.type = EV_CLOSE; + if (!deliver(w, &c)) + wm_window_close(w); + return 1; + } + drag = w; /* title bar: move */ + drag_dx = e->x - w->x; + drag_dy = e->y - w->y; + return 1; + case EV_MOUSE_MOVE: + if (drag) + { + wm_window_move(drag, e->x - drag_dx, e->y - drag_dy); + return 1; + } + w = capture ? capture : window_at(e->x, e->y); + if (!w) + return desk_event ? desk_event(e) : 0; + return deliver(w, e); + case EV_MOUSE_UP: + if (drag) + { + drag = 0; + return 1; + } + w = capture ? capture : window_at(e->x, e->y); + if (!e->buttons) + capture = 0; + if (!w) + return desk_event ? desk_event(e) : 0; + return deliver(w, e); + case EV_KEY: + if (!wm_focus()) + return desk_event ? desk_event(e) : 0; + return deliver(wm_focus(), e); + } + return 0; +} + +void wm_redraw_all(void) +{ + struct event e; + struct surface *s = gfx_screen(); + int i; + + memset(&e, 0, sizeof(e)); + e.type = EV_REDRAW; + for (i = 0; i < nwin; i++) + if (wins[i]->handler) + wins[i]->handler(wins[i], &e); + if (s) + wm_damage(0, 0, s->w, s->h); +} + +void wm_quit(void) +{ + quit = 1; +} + +void wm_run(int (*idle)(void)) +{ + struct event e; + + quit = 0; + while (!quit) + { + wm_update(); + if (idle) + { + if (!input_poll(&e)) + { + if (!idle()) + input_wait(&e); + else + continue; + } + } + else + input_wait(&e); + wm_dispatch(&e); + } + wm_update(); +} diff --git a/hdr/fnode.h b/hdr/fnode.h index 1e2face8..982f0dfa 100644 --- a/hdr/fnode.h +++ b/hdr/fnode.h @@ -54,12 +54,4 @@ struct f_node { typedef struct f_node *f_node_ptr; -struct lfn_inode { - UNICODE l_name[261]; /* Long file name string */ - /* If the string is empty, */ - /* then file has the 8.3 name */ - struct dirent l_dir; /* Directory entry image */ - UWORD l_diroff; /* Current directory entry offset */ -}; - -typedef struct lfn_inode FAR * lfn_inode_ptr; + diff --git a/hdr/version.h b/hdr/version.h index 8dd36a3f..083a502e 100644 --- a/hdr/version.h +++ b/hdr/version.h @@ -45,7 +45,7 @@ #endif /* actual version string */ -#define KVS(v,s,o) "FreeDOS kernel " v "(build 20" #s " OEM:" #o ") [compiled " __DATE__ "]\n" +#define KVS(v,s,o) "modernDOS kernel " v "(FreeDOS build 20" #s " OEM:" #o ") [compiled " __DATE__ "]\n" #define xKVS(v,s,o) KVS(v,s,o) #define KERNEL_VERSION_STRING xKVS(KERNEL_VERSION, REVISION_SEQ, OEM_ID) diff --git a/hdr/win.h b/hdr/win.h index 93a07574..4e270e7e 100644 --- a/hdr/win.h +++ b/hdr/win.h @@ -19,9 +19,15 @@ struct WinStartupInfo }; extern struct WinStartupInfo winStartupInfo; #if defined __GNUC__ -extern UWORD winseg1, winseg2, winseg3; -extern UBYTE markEndInstanceData; -extern struct lol FAR ASM DATASTART; +extern UWORD winseg1; +/* instance data table: far pointer + size per entry, the pointers are + filled in at run time (startup broadcast) */ +struct WinInstance +{ + UWORD off, seg, size; +}; +extern struct WinInstance winInstTable[3]; +extern UBYTE inst_sda_start, inst_stk_start, inst_p0_start; #endif diff --git a/kernel/entry.asm b/kernel/entry.asm index ebceaad9..40dddb13 100644 --- a/kernel/entry.asm +++ b/kernel/entry.asm @@ -370,11 +370,6 @@ int21_onerrorstack: int21_2: -%IFDEF WIN31SUPPORT ; begin critical section - ; should be called as needed, but we just - ; mark the whole int21 api as critical - call begin_dos_crit_sect -%ENDIF ; WIN31SUPPORT inc byte [_InDOS] mov cx,_char_api_tos or ah,ah @@ -387,9 +382,14 @@ int21_2: jbe int21_normalentry int21_3: -%IFNDEF WIN31SUPPORT +%IFDEF WIN31SUPPORT ; begin critical section: everything but the + ; character I/O functions (01h-0Ch), which only + ; use per-VM (instance) data and may block for + ; keyboard input, so a supervisor can switch VMs + call begin_dos_crit_sect +%ELSE call end_dos_crit_sect -%ENDIF ; NOT WIN31SUPPORT +%ENDIF ; WIN31SUPPORT mov cx,_disk_api_tos int21_normalentry: diff --git a/kernel/fatfs.c b/kernel/fatfs.c index a4028da6..c4ecdb0a 100644 --- a/kernel/fatfs.c +++ b/kernel/fatfs.c @@ -195,6 +195,10 @@ int dos_open(char *path, unsigned flags, unsigned attrib, int fd) init_direntry(&fnp->f_dir, attrib, FREE, fnp->f_dmp->dm_name_pat); if (!dir_write(fnp)) return DE_ACCESS; +#ifdef WITHLFNAPI + if (status == S_CREATED && lfn_write_entries(fnp) != SUCCESS) + return DE_ACCESS; +#endif } merge_file_changes(fnp, status == S_OPENED); /* /// Added - Ron Cemer */ @@ -523,11 +527,23 @@ COUNT dos_rename(BYTE * path1, BYTE * path2, int attrib) /* one, it's an error. */ fnp2 = &fnode[1]; ret = find_fname(path2, attrib, fnp2); +#ifdef WITHLFNAPI + /* changing only the long name (or its case) of the same entry */ + if (ret == SUCCESS && lfn_create_name && + fnp1->f_dmp->dm_dircluster == fnp2->f_dmp->dm_dircluster && + fnp1->f_dmp->dm_entry == fnp2->f_dmp->dm_entry) + ret = DE_FILENOTFND; +#endif if (ret != DE_FILENOTFND) return ret == SUCCESS ? DE_ACCESS : ret; fcbname = fnp2->f_dmp->dm_name_pat; - if (fnp1->f_dmp->dm_dircluster == fnp2->f_dmp->dm_dircluster) + if (fnp1->f_dmp->dm_dircluster == fnp2->f_dmp->dm_dircluster +#ifdef WITHLFNAPI + /* a long name needs a fresh run of entries: move the entry */ + && lfn_create_name == NULL +#endif + ) { /* rename in the same directory: change the directory entry in-place */ fnp2 = fnp1; @@ -537,7 +553,8 @@ COUNT dos_rename(BYTE * path1, BYTE * path2, int attrib) else { /* do not allow to rename directories between different directories */ - if (fnp1->f_dir.dir_attrib & D_DIR) + if ((fnp1->f_dir.dir_attrib & D_DIR) && + fnp1->f_dmp->dm_dircluster != fnp2->f_dmp->dm_dircluster) return DE_ACCESS; /* create new entry in other directory */ @@ -562,7 +579,13 @@ COUNT dos_rename(BYTE * path1, BYTE * path2, int attrib) memcpy(fnp2->f_dir.dir_name, fcbname, FNAME_SIZE + FEXT_SIZE); /* SUCCESSful completion, return it */ - return dir_write(fnp2) ? SUCCESS : DE_ACCESS; + if (!dir_write(fnp2)) + return DE_ACCESS; +#ifdef WITHLFNAPI + return lfn_write_entries(fnp2); +#else + return SUCCESS; +#endif } /* */ @@ -625,6 +648,25 @@ STATIC BOOL find_free(f_node_ptr fnp) { COUNT rc; +#ifdef WITHLFNAPI + /* Find lfn_free_need consecutive free entries (room for long name */ + /* entries in front of the 8.3 entry). Returns with fnp on the last */ + /* one. lfn_free_run carries over a directory extension. */ + for (;;) + { + rc = dir_read(fnp); + if (rc < 0) + return FALSE; + if (rc == 0 || fnp->f_dir.dir_name[0] == DELETED) + { + if (++lfn_free_run >= lfn_free_need) + return TRUE; + } + else + lfn_free_run = 0; + fnp->f_dmp->dm_entry++; + } +#else while ((rc = dir_read(fnp)) == 1) { if (fnp->f_dir.dir_name[0] == DELETED) @@ -632,6 +674,7 @@ STATIC BOOL find_free(f_node_ptr fnp) fnp->f_dmp->dm_entry++; } return rc >= 0; +#endif } /* alloc_find_free: resets the directory */ @@ -639,8 +682,17 @@ STATIC BOOL find_free(f_node_ptr fnp) /* available, tries to extend the directory. */ STATIC int alloc_find_free(f_node_ptr fnp, char *path) { + int ret = SUCCESS; + fnp = split_path(path, fnp); +#ifdef WITHLFNAPI + /* one entry per 13 characters of long name plus the 8.3 entry */ + lfn_free_run = 0; + if (lfn_create_name) + lfn_free_need = 1 + (strlen(lfn_create_name) + 12) / 13; +#endif + /* Get a free f_node pointer so that we can use */ /* it in building the new file. */ /* Note that if we're in the root and we don't */ @@ -649,19 +701,19 @@ STATIC int alloc_find_free(f_node_ptr fnp, char *path) { if (fnp->f_dmp->dm_dircluster == 0) { - return DE_TOOMANY; + ret = DE_TOOMANY; } else { /* Otherwise just expand the directory */ - int ret; - - if ((ret = extend_dir(fnp)) != SUCCESS) - /* fnp already closed in extend_dir */ - return ret; + /* fnp already closed in extend_dir on error */ + ret = extend_dir(fnp); } } - return SUCCESS; +#ifdef WITHLFNAPI + lfn_free_need = 1; +#endif + return ret; } @@ -844,6 +896,10 @@ COUNT dos_mkdir(BYTE * dir) /* Write the new directory entry */ if (!dir_write(fnp)) return DE_ACCESS; +#ifdef WITHLFNAPI + if ((ret = lfn_write_entries(fnp)) != SUCCESS) + return ret; +#endif /* Craft the new directory. Note that if we're in a new */ /* directory just under the root, ".." pointer is 0. */ @@ -930,8 +986,21 @@ STATIC COUNT extend_dir(f_node_ptr fnp) if (ret != SUCCESS) return ret; +#ifdef WITHLFNAPI + while (!find_free(fnp)) + { + /* still not enough consecutive entries for the long name */ + cluster = extend(fnp); + if (cluster == LONG_LAST_CLUSTER) + return DE_HNDLDSKFULL; + ret = clear_dir(fnp, cluster); + if (ret != SUCCESS) + return ret; + } +#else if (!find_free(fnp)) return DE_HNDLDSKFULL; +#endif /* flush the drive buffers so that all info is written */ if (!flush_buffers(fnp->f_dpb->dpb_unit)) diff --git a/kernel/inthndlr.c b/kernel/inthndlr.c index ea45e240..13ca3297 100644 --- a/kernel/inthndlr.c +++ b/kernel/inthndlr.c @@ -1544,69 +1544,16 @@ VOID ASMCFUNC int21_service(iregs FAR * r) #ifdef WITHFAT32 /* LFN API */ case 0x71: - switch (lr.AL) - { #ifdef WITHLFNAPI - /* Win95 LFN - reset drive */ - case 0x0d: - /* Win95 LFN - make directory */ - case 0x39: - /* Win95 LFN - remove directory */ - case 0x3a: - /* Win95 LFN - change directory */ - case 0x3b: - /* Win95 LFN - delete file */ - case 0x41: - /* Win95 LFN - extended get/set file attributes */ - case 0x43: - /* Win95 LFN - get current directory */ - case 0x47: - /* Win95 LFN - find first file */ - case 0x4e: - /* Win95 LFN - find next file */ - case 0xa2: /* internal - same as 0x4f */ - case 0x4f: { - goto unsupp; - } - /* Win95 LFN - rename file */ - case 0x56: - /* Win95 LFN - canonicalize file name/path */ - case 0x60: { - switch (lr.CL) - { - /* truename - canonicalize path, accepts short/long/or combination as input and may return combined short/long name */ - case 0x00: { - } - /* get canonical short (8.3) name or path, truename that accepts long name and returns short name */ - case 0x01: { - } - /* get canonical long name or path, truename that accepts short name and returns long name */ - case 0x02: { - } - default: - goto unsupp; - } - } - /* Win95 LFN - create or open file */ - case 0xa9: /* for real-mode servers only, AX is _global_ file handle on return */ - case 0x6c: { - goto unsupp; - } - /* Win95 LFN - get volume information */ - case 0xa0: - /* Win95 LFN - find file close */ - case 0xa1: { -lfn_findclose: - goto unsupp; - } -#if 0 - /* Win95 LFN - internal use ??? */ - case 0xa3: - case 0xa4: - case 0xa5: - goto unsupp; -#endif + /* native long filename support, see lfnapi.c */ + CLEAR_CARRY_FLAG(); + CritErrCode = SUCCESS; + rc = int21_lfn(&lr); + if (rc != LFN_PASS) + goto short_check; #endif + switch (lr.AL) + { /* EDR-DOS LFN - Long LSEEK - SET CURRENT 64-bit FILE POSITION */ case 0x42: /* Win95 LFN - get file info by handle */ @@ -1649,36 +1596,9 @@ VOID ASMCFUNC int21_service(iregs FAR * r) fmemcpy(r, &saved_r, sizeof(saved_r)); goto unsupp; } -#ifdef WITHLFNAPI - /* Win95 LFN - Win95 64 UTC file time to/from DOS date and time (local timezone) */ - case 0xa7: { - /* Note: valid input range limited to Jan 1, 1980 to Dec 31, 2107 */ - switch (lr.BL) - { - /* from Win95 UTC to DOS date/time */ - case 0x00: { - } - /* from DOS date/time to Win95 UTC */ - case 0x01: { - } - default: - goto unsupp; - } - } - /* Win95 LFN - generate short filename */ - case 0xa8: - /* Win95 LFN - subst */ - case 0xaa: { - goto unsupp; - } -#endif default: goto unsupp; } -#ifdef WITHLFNAPI - /* Win95 beta LFN - find close */ - case 0x72: goto lfn_findclose; -#endif /* DOS 7.0+ FAT32 extended functions */ case 0x73: @@ -1688,44 +1608,6 @@ VOID ASMCFUNC int21_service(iregs FAR * r) goto short_check; #endif -#ifdef WITHLFNAPI - /* FreeDOS LFN helper API functions */ - case 0x74: - { - switch (lr.AL) - { - /* Allocate LFN inode */ - case 0x01: - rc = lfn_allocate_inode(); - break; - /* Free LFN inode */ - case 0x02: - rc = lfn_free_inode(lr.BX); - break; - /* Setup LFN inode */ - case 0x03: - rc = lfn_setup_inode(lr.BX, MK_ULONG(lr.CX, lr.DX), MK_ULONG(lr.SI,lr.DI)); - break; - /* Create LFN entries */ - case 0x04: - rc = lfn_create_entries(lr.BX, (lfn_inode_ptr)FP_DS_DX); - break; - /* Read next LFN */ - case 0x05: - rc = lfn_dir_read(lr.BX, (lfn_inode_ptr)FP_DS_DX); - break; - /* Write SFN pointed by LFN inode */ - case 0x06: - rc = lfn_dir_write(lr.BX); - break; - default: - goto error_invalid; - } - lr.AX = rc; - CLEAR_CARRY_FLAG(); - goto short_check; - } -#endif } goto exit_dispatch; #ifdef WITHFAT32 @@ -2040,8 +1922,12 @@ VOID ASMCFUNC int2F_12_handler(struct int2f12regs FAR *pr) winStartupInfo.winver = r.di; /* match what caller says it is */ #if defined __GNUC__ winseg1 = FP_SEG(&winStartupInfo); - winseg2 = FP_SEG(&DATASTART); - winseg3 = FP_OFF(&markEndInstanceData); + winInstTable[0].off = FP_OFF(&inst_sda_start); + winInstTable[0].seg = FP_SEG(&inst_sda_start); + winInstTable[1].off = FP_OFF(&inst_stk_start); + winInstTable[1].seg = FP_SEG(&inst_stk_start); + winInstTable[2].off = FP_OFF(&inst_p0_start); + winInstTable[2].seg = FP_SEG(&inst_p0_start); #endif winInstanced = 1; /* internal flag marking Windows is active */ DebugPrintf(("Win startup\n")); diff --git a/kernel/kernel.asm b/kernel/kernel.asm index 657dfbd8..dafc7081 100644 --- a/kernel/kernel.asm +++ b/kernel/kernel.asm @@ -628,20 +628,6 @@ _winStartupInfo: global _winseg1 _winseg1: dw 0 %endif -instance_table: ; should include stacks, Win may auto determine SDA region - ; we simply include whole DOS data segment - %ifnidni __OUTPUT_FORMAT__, elf - dw seg _DATASTART, 0 ; [SEG:OFF] address of region's base - dw _markEndInstanceData wrt seg _DATASTART ; size in bytes - %else -global _winseg2 -_winseg2: dw 0 - dw 0 ; [SEG:OFF] address of region's base -global _winseg3 -_winseg3: dw 0 ; size in bytes - %endif - dd 0 ; 0 marks end of table - dw 0 ; and 0 length for end of instance_table entry global _winPatchTable _winPatchTable: ; returns offsets to various internal variables dw 0x0006 ; DOS version, major# in low byte, eg. 6.00 @@ -675,6 +661,9 @@ _firstsftt: global MARK01FBH MARK01FBH equ $ + global inst_sda_start, _inst_sda_start +inst_sda_start: ; instance data: SDA and the +_inst_sda_start: ; preceding console/readline data global _local_buffer ; local_buffer is 256 bytes long ; so it overflows into kb_buf!! ; only when kb_buf is used, local_buffer is limited to 128 bytes. @@ -959,6 +948,37 @@ _VirtOpen db 0 ;782 - virtual open flag absrdwrflg db 0 ;7bbh - 0=int 25h/26h absolute read/write, 1=int 21h/ax=7305h times 12 dw 0 ;7bch to 7d2h, high word of 32bit values, see offsets 0x 2a2, 29c, 2bc, 29a, 276, 244, & registers ebx,edx,edi,ecx times 3 dw 0 ; ??? + global inst_sda_end, _inst_sda_end +inst_sda_end: +_inst_sda_end: + +%IFDEF WIN31SUPPORT + ; (not with the startup info: DS:00CCh is fixed) +instance_table: ; per virtual machine data, swapped by the supervisor on + ; every VM switch. Only what one VM may leave behind while + ; it is outside a DOS critical section (INT 2Ah 80h/82h): + ; the swappable data area with the DOS stacks, and the + ; private stacks of the built-in drivers and INT 2Fh. + ; Global structures (LoL, SFTs, buffers, DPBs) must not be + ; instanced: a VM switch would restore stale copies. + ; entries: DWORD far pointer (offset, segment), WORD size + %ifnidni __OUTPUT_FORMAT__, elf + dw inst_sda_start wrt seg _DATASTART, seg _DATASTART + dw inst_sda_end - inst_sda_start + dw inst_stk_start wrt seg _DATASTART, seg _DATASTART + dw inst_stk_end - inst_stk_start + dw inst_p0_start wrt seg _DATASTART, seg _DATASTART + dw _p_0_tos - inst_p0_start + %else +global _winInstTable ; offsets and segments filled in at run time +_winInstTable: + dw 0, 0, inst_sda_end - inst_sda_start + dw 0, 0, inst_stk_end - inst_stk_start + dw 0, 0, _p_0_tos - inst_p0_start + %endif + dd 0 ; 0 marks end of table + dw 0 ; and 0 length for end of instance_table entry +%ENDIF ; WIN31SUPPORT ; ; end of controlled variables @@ -991,6 +1011,9 @@ __init_end: init_end: segment _DATA + global inst_stk_start, _inst_stk_start +inst_stk_start: ; instance data: private stacks +_inst_stk_start: ; blockdev private stack global blk_stk_top times 256 dw 0 @@ -1005,6 +1028,8 @@ clk_stk_top: global int2f_stk_top times 128 dw 0 int2f_stk_top: + global inst_stk_end +inst_stk_end: ; Dynamic data: ; member of the DOS DATA GROUP @@ -1020,6 +1045,9 @@ _swap_indos: ; _swap_indos but only if int2a ah=80/81 (critical section start/end) ; are called upon entry and exit of the device drivers + global inst_p0_start, _inst_p0_start +inst_p0_start: +_inst_p0_start: times 96 dw 0x9090 ; Process 0 Stack global _p_0_tos _p_0_tos: diff --git a/kernel/lfnapi.c b/kernel/lfnapi.c index 928f16b2..a328ba0a 100644 --- a/kernel/lfnapi.c +++ b/kernel/lfnapi.c @@ -2,363 +2,1516 @@ /* */ /* lfnapi.c */ /* */ -/* Directory access functions for LFN helper API */ +/* Native Windows 95 compatible long filename API */ +/* (INT 21h AH=71h) for FAT12/16/32 volumes. */ /* */ +/* This file is part of modernDOS, derived from DOS-C/FreeDOS. */ +/* */ +/* This 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, */ +/* or (at your option) any later version. */ /****************************************************************/ +/* + * Design + * ------ + * Long names are a translation layer on top of the existing 8.3 file + * system code. lfn_resolve() walks a path that may contain long (or + * short) components and produces the equivalent fully qualified short + * path. Existing kernel functions (DosOpen, DosDelete, DosChangeDir, + * ...) then do the actual work, so their semantics stay identical to the + * classic INT 21h calls. + * + * Creating a long name (mkdir, create, rename target) generates a Win95 + * style short alias ("LONGNA~1.TXT") and arms a one-shot hook + * (lfn_create_name). fatfs.c then reserves enough contiguous directory + * slots and calls lfn_write_entries() right after writing the 8.3 entry. + * + * Long names are exchanged with programs in the OEM code page. On disk + * they are UCS-2; conversion currently uses code page 437. + * + * Not handled here (returned as unsupported, AX=7100h): network and + * redirected drives (MSCDEX, network clients implement their own LFN + * support), and JOINed directories inside a path. + */ + #include "portab.h" #include "globals.h" -#ifdef VERSION_STRINGS -static BYTE *lfnaidRcsId = - "$Id: lfnapi.c 1389 2009-05-20 18:13:37Z bartoldeman $"; -#endif - #ifdef WITHLFNAPI -#define RESERVED_FNODES 3 /* # of reserved fnodes for the kernel internal * - * usage. If something wrong happens with the * - * driver using helper API and it grabs all * - * possible fnodes, the kernel doesn't hang. */ - -/* All possible error codes, returned by directory access functions */ -/* Note. SUCCESS is returned if all OK. */ -#define LHE_INVLDHNDL -1 /* Invalid inode handle passed. */ -#define LHE_NOFREEHNDL -2 /* Couldn't allocate another inode handle. */ -#define LHE_IOERROR -3 /* Couldn't do I/O because of the lack of * - * memory or due to a physical damage. */ -#define LHE_INVLDDRV -4 /* Invalid drive chosen. */ -#define LHE_DAMAGEDFS -5 /* Damaged file system encountered. */ -#define LHE_NOSPACE -6 /* There are no free clusters on drive. */ -#define LHE_SEEK -7 /* Attempt to read beyound the end of the dir. */ - -#define lfn(fnp) ((struct lfn_entry FAR *)&(fnp->f_dir)) -#define CHARS_IN_LFN_ENTRY 13 -#define UNICODE_FILLER 0xffff - -COUNT ufstrlen(REG UNICODE FAR *); /* fstrlen for UNICODE strings */ -UBYTE lfn_checksum(UBYTE FAR *); -COUNT extend_dir(f_node_ptr); -BOOL lfn_to_unicode(UNICODE FAR **name, struct lfn_entry FAR *lep); -VOID unicode_to_lfn(UNICODE FAR **name, struct lfn_entry FAR *lep); - -/* Description. - * Allocates internal fnode and returns it's handle. - * Return value. - * LHE_NOFREEHNDL, LHE_INVLDDRV - * >= 0 - handle of the allocated fnode. - */ -COUNT lfn_allocate_inode(VOID) +#define LFN_MAX 255 /* max long name length (chars) */ +#define LFN_PATHMAX 260 /* max long path length */ +#define LFN_CHARS 13 /* UCS-2 chars per LFN dir entry */ +#define LFN_FINDHNDLS 8 /* concurrent 714Eh search handles */ +#define LFN_PATLEN 80 /* max stored wildcard pattern */ +#define FINDDATA_SIZE 0x13e /* Win95 WIN32_FIND_DATA as seen by DOS */ + +/* lfn_resolve() results (errors are negative) */ +#define LR_FOUND 0 /* whole path exists */ +#define LR_MISSING 1 /* last component missing (lfn_comp) */ +#define LR_WILD 2 /* last component is a wildcard */ +/* LFN_PASS (proto.h): not ours, report as unsupported */ + +/* lfn_resolve() flags */ +#define LRF_MISSING_OK 1 +#define LRF_WILD_OK 2 + +/* Hooks used by fatfs.c when creating directory entries */ +const char *lfn_create_name; /* long name for next created entry */ +UWORD lfn_free_need = 1; /* contiguous free entries needed */ +UWORD lfn_free_run; /* free entries found so far */ + +STATIC char lfn_comp[LFN_MAX + 1]; /* path component / name to create */ +STATIC char lfn_name[LFN_MAX + 1]; /* long (or display) name of entry */ +STATIC BOOL lfn_has_long; /* entry has a real long name */ +STATIC char lfn_path1[128]; /* resolved short paths */ +STATIC char lfn_path2[128]; +STATIC UBYTE lfn_drive; /* logical drive of last resolve */ +STATIC UWORD lfn_root_len; /* length of physical root in path */ +STATIC char FAR *lfn_lout; /* long path output, NULL = off */ +STATIC char FAR *lfn_lend; + +struct lfn_find { + UWORD psp; /* owner, 0 = free slot */ + UBYTE drive; + UBYTE allow; /* allowed attributes (CL) */ + UBYTE need; /* required attributes (CH) */ + UBYTE done; + CLUSTER dir; /* directory start cluster */ + UWORD entry; /* next directory entry to examine */ + char pat[LFN_PATLEN]; +}; +STATIC struct lfn_find lfn_finds[LFN_FINDHNDLS]; + +/* byte offsets of the 13 UCS-2 characters within an LFN entry */ +STATIC const UBYTE lfn_ofs[LFN_CHARS] = + { 1, 3, 5, 7, 9, 14, 16, 18, 20, 22, 24, 28, 30 }; + +/* code page 437, characters 80h-FFh */ +STATIC const UNICODE cp437_hi[128] = { + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, + 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, + 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, + 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, + 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, + 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, + 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, + 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, + 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, + 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 +}; + +/****************************************************************/ +/* Character and name helpers */ +/****************************************************************/ + +STATIC UNICODE oem_to_uni(UBYTE c) { - f_node_ptr fnp = get_f_node(&fnode[0]); - struct dpb FAR *dpbp; - COUNT handle; - if (fnp == 0) return LHE_NOFREEHNDL; + return c < 0x80 ? c : cp437_hi[c - 0x80]; +} - handle = xlt_fnp(fnp); - /* Check if there is at least # RESERVED_FNODES left for the kernel */ - if (f_nodes_cnt - handle < RESERVED_FNODES) +STATIC UBYTE uni_to_oem(UNICODE u) +{ + int i; + + if (u < 0x80) + return (UBYTE)u; + for (i = 0; i < 128; i++) + if (cp437_hi[i] == u) + return (UBYTE)(0x80 + i); + return '_'; +} + +STATIC UBYTE lfn_checksum(const char *sfn) +{ + UBYTE sum = 0; + int i; + + for (i = 0; i < FNAME_SIZE + FEXT_SIZE; i++) + sum = (UBYTE)(((sum & 1) << 7) + (sum >> 1) + (UBYTE)sfn[i]); + return sum; +} + +STATIC BOOL is_sep(char c) +{ + return c == '\\' || c == '/'; +} + +/* case insensitive comparison in the current code page */ +STATIC BOOL name_eq(const char *a, const char *b) +{ + for (;; a++, b++) + { + UBYTE ca = DosUpFChar(*a), cb = DosUpFChar(*b); + if (ca != cb) + return FALSE; + if (ca == '\0') + return TRUE; + } +} + +/* Win95 style wildcard match: '*' any run, '?' any char, + "*.*" also matches names without an extension */ +STATIC BOOL wild_match(const char *p, const char *s) +{ + const char *pstar = NULL, *sstar = NULL; + + while (*s) + { + if (*p == '*') + { + pstar = ++p; + sstar = s; + } + else if (*p == '?' || (*p && DosUpFChar(*p) == DosUpFChar(*s))) { - release_f_node(fnp); - return LHE_NOFREEHNDL; + p++; + s++; } + else if (pstar) + { + p = pstar; + s = ++sstar; + } + else + return FALSE; + } + while (*p == '*' || *p == '?') + p++; + if (*p == '.') + { + p++; + while (*p == '*' || *p == '?') + p++; + } + return *p == '\0'; +} + +STATIC BOOL has_wild(const char *s) +{ + for (; *s; s++) + if (*s == '*' || *s == '?') + return TRUE; + return FALSE; +} - /* Check that default drive is a block device */ - dpbp = get_dpb(default_drive); +/* 8.3 name as shown to programs, honouring the NT lower case flags + (dir_case bit 3: base name lower case, bit 4: extension lower case) */ +STATIC void sfn_display(char *dst, const struct dirent *de) +{ + BOOL ext = FALSE; + + ConvertName83ToNameSZ(dst, (BYTE *)de->dir_name); + if (!(de->dir_case & 0x18)) + return; + for (; *dst; dst++) + { + if (*dst == '.') + ext = TRUE; + else if ((de->dir_case & (ext ? 0x10 : 0x08)) && + *dst >= 'A' && *dst <= 'Z') + *dst += 'a' - 'A'; + } +} - if (dpbp == 0) +/****************************************************************/ +/* Directory access */ +/****************************************************************/ + +/* raw on-disk image of the entry last read with dir_read() */ +STATIC UBYTE FAR *dir_raw(f_node_ptr fnp, struct buffer FAR **bpp) +{ + struct buffer FAR *bp; + + bp = getblock(fnp->f_dirsector, fnp->f_dpb->dpb_unit); + if (bp == NULL) + return NULL; + if (bpp) + *bpp = bp; + return &bp->b_buffer[fnp->f_diridx * DIRENT_SIZE]; +} + +/* Read entries from the current position (dm_entry) until a short + entry is found and assemble the long name chain preceding it. + On return lfn_name holds the long name, or the display form of the + 8.3 name if there is no valid long name (lfn_has_long FALSE). + Returns 1: entry found (in fnp->f_dir, dm_entry is its index), + 0: end of directory, <0: error */ +STATIC COUNT lfn_dir_next(f_node_ptr fnp) +{ + COUNT rc; + UBYTE expect = 0; /* next expected ordinal, 0 = none */ + UBYTE chk = 0; + BOOL complete = FALSE; + + for (;; fnp->f_dmp->dm_entry++) + { + rc = dir_read(fnp); + if (rc == 0 || rc == DE_SEEK) + return 0; + if (rc < 0) + return rc; + + if (fnp->f_dir.dir_name[0] == DELETED) { - release_f_node(fnp); - return LHE_INVLDDRV; + expect = 0; + complete = FALSE; } + else if (fnp->f_dir.dir_attrib == D_LFN) + { + UBYTE FAR *raw = dir_raw(fnp, NULL); + UBYTE id, i; + unsigned pos; - fnp->f_dpb = dpbp; + if (raw == NULL) + return DE_BLKINVLD; + id = raw[0]; + complete = FALSE; + if (id & 0x40) + { + expect = id & 0x3f; + chk = raw[13]; + if (expect == 0 || expect > 20) + expect = 0; + else + { + pos = expect * LFN_CHARS; + lfn_name[pos > LFN_MAX ? LFN_MAX : pos] = '\0'; + } + } + else if (expect == 0 || id != expect || raw[13] != chk) + expect = 0; /* orphaned or damaged chain */ + if (expect) + { + pos = (expect - 1) * LFN_CHARS; + for (i = 0; i < LFN_CHARS && pos < LFN_MAX; i++, pos++) + { + UNICODE u = raw[lfn_ofs[i]] | ((UNICODE)raw[lfn_ofs[i] + 1] << 8); + if (u == 0) + { + lfn_name[pos] = '\0'; + break; + } + lfn_name[pos] = uni_to_oem(u); + } + if (--expect == 0) + complete = TRUE; + } + } + else + { + lfn_has_long = complete && lfn_name[0] != '\0' && + chk == lfn_checksum(fnp->f_dir.dir_name); + if (!lfn_has_long) + sfn_display(lfn_name, &fnp->f_dir); + return 1; + } + } +} - if (media_check(dpbp) < 0) +/* look up a long or short name in directory dir (short path); + returns 1 found (fnode[0] positioned on it), 0 not found, <0 error */ +STATIC COUNT lfn_lookup(const char *dir, const char *name) +{ + f_node_ptr fnp = dir_open(dir, FALSE, &fnode[0]); + char sfn[13]; + COUNT rc; + + if (fnp == NULL) + return DE_PATHNOTFND; + while ((rc = lfn_dir_next(fnp)) == 1) + { + if (!(fnp->f_dir.dir_attrib & D_VOLID)) { - release_f_node(fnp); - return LHE_INVLDDRV; + if (name_eq(lfn_name, name)) + return 1; + ConvertName83ToNameSZ(sfn, fnp->f_dir.dir_name); + if (name_eq(sfn, name)) + return 1; } + fnp->f_dmp->dm_entry++; + } + return rc; +} + +/* position fnode[0] on the entry named by short path `path'; + returns 1 found, 0 path is a root directory, <0 error */ +STATIC COUNT lfn_locate(char *path) +{ + char *sep = NULL, *p; + char sfn[13]; + COUNT rc; - return handle; + for (p = path; *p; p++) + if (*p == '\\') + sep = p; + if (sep == NULL || sep[1] == '\0' || (UWORD)strlen(path) <= lfn_root_len) + return 0; + strcpy(sfn, sep + 1); + if (sep == path + 2) + sep[1] = '\0'; + else + *sep = '\0'; + rc = lfn_lookup(path, sfn); + if (sep == path + 2) + sep[1] = sfn[0]; + else + *sep = '\\'; + return rc == 0 ? DE_FILENOTFND : rc; } -/* Description. - * Free allocated internal fnode. - * Return value. - * SUCCESS, LHE_INVLDHNDL - */ -COUNT lfn_free_inode(COUNT handle) +/* does the 8.3 name fcb exist in directory dir? 1 yes, 0 no, <0 error */ +STATIC COUNT sfn_exists(const char *dir, const char *fcb) { - f_node_ptr fnp = xlt_fd(handle); - if (fnp == 0 || fnp->f_count <= 0) return LHE_INVLDHNDL; + f_node_ptr fnp = dir_open(dir, FALSE, &fnode[0]); + COUNT rc; + + if (fnp == NULL) + return DE_PATHNOTFND; + while ((rc = dir_read(fnp)) == 1) + { + if (fnp->f_dir.dir_name[0] != DELETED && fnp->f_dir.dir_attrib != D_LFN + && memcmp(fnp->f_dir.dir_name, fcb, FNAME_SIZE + FEXT_SIZE) == 0) + return 1; + fnp->f_dmp->dm_entry++; + } + return rc == DE_SEEK ? 0 : rc; +} - dir_close(fnp); +/****************************************************************/ +/* Short name generation */ +/****************************************************************/ - return SUCCESS; +/* convert one character for a short name; 0 = drop it */ +STATIC UBYTE sfn_char(UBYTE c, BOOL *lossy) +{ + if (c == ' ' || c == '.') + { + *lossy = TRUE; + return 0; + } + if (c == '+' || c == ',' || c == ';' || c == '=' || c == '[' || c == ']') + { + *lossy = TRUE; + return '_'; + } + return DosUpFChar(c); } -/* Description. - * Initialize internal fnode, so that it'll point to the directory entry - * at "diroff" entry offset from the start of the directory with the "dirstart" - * starting cluster. - * Return value. - * SUCCESS, LHE_INVLDHNDL - */ -COUNT lfn_setup_inode(COUNT handle, ULONG dirstart, ULONG diroff) +/* Build the 11 character basis name for lname (Win95 algorithm + without numeric tail). Returns TRUE if the conversion lost + information and a numeric tail is required. */ +STATIC BOOL lfn_basis(const char *lname, char *fcb) +{ + const char *p, *start, *dot = NULL; + BOOL lossy = FALSE; + int n; + UBYTE c; + + memset(fcb, ' ', FNAME_SIZE + FEXT_SIZE); + for (start = lname; *start == '.'; start++) + lossy = TRUE; + for (p = start; *p; p++) + if (*p == '.') + dot = p; + + for (n = 0, p = start; *p && p != dot; p++) + if ((c = sfn_char(*p, &lossy)) != 0) + { + if (n < FNAME_SIZE) + fcb[n++] = c; + else + lossy = TRUE; + } + if (dot) + for (n = FNAME_SIZE, p = dot + 1; *p; p++) + if ((c = sfn_char(*p, &lossy)) != 0) + { + if (n < FNAME_SIZE + FEXT_SIZE) + fcb[n++] = c; + else + lossy = TRUE; + } + if (fcb[0] == ' ') + { + fcb[0] = '_'; + lossy = TRUE; + } + if ((UBYTE)fcb[0] == 0xe5) + fcb[0] = 0x05; + return lossy; +} + +/* generate a unique short name for lname in directory dir */ +STATIC COUNT lfn_gen_sfn(const char *dir, const char *lname, char *fcb) { - f_node_ptr fnp = xlt_fd(handle); - if (fnp == 0 || fnp->f_count <= 0) return LHE_INVLDHNDL; + char base[FNAME_SIZE], tail[8]; + int baselen, taillen, keep, i; + ULONG num; + COUNT rc; + + if (!lfn_basis(lname, fcb)) + { + rc = sfn_exists(dir, fcb); + if (rc <= 0) + return rc; + } + memcpy(base, fcb, FNAME_SIZE); + for (baselen = 0; baselen < FNAME_SIZE && base[baselen] != ' '; baselen++) + ; + + for (num = 1; num < 1000000L; num++) + { + ULONG v = num; + + /* tail = "~" */ + taillen = 0; + do + { + tail[7 - taillen++] = (char)('0' + (UBYTE)(v % 10)); + v /= 10; + } while (v); + tail[7 - taillen++] = '~'; - dir_init_fnode(fnp, (CLUSTER)dirstart); - fnp->f_diroff = diroff; + keep = baselen < FNAME_SIZE - taillen ? baselen : FNAME_SIZE - taillen; + memset(fcb, ' ', FNAME_SIZE); + memcpy(fcb, base, keep); + for (i = 0; i < taillen; i++) + fcb[keep + i] = tail[8 - taillen + i]; + + rc = sfn_exists(dir, fcb); + if (rc <= 0) + return rc; + } + return DE_ACCESS; +} + +/* Prepare creating lfn_comp in directory `path': append the generated + short name to path and arm the create hook if a long name is needed */ +STATIC COUNT lfn_prepare_create(char *path) +{ + char fcb[FNAME_SIZE + FEXT_SIZE], sfn[13]; + size_t len; + COUNT rc; + if (has_wild(lfn_comp)) + return DE_FILENOTFND; + rc = lfn_gen_sfn(path, lfn_comp, fcb); + if (rc < 0) + return rc; + ConvertName83ToNameSZ(sfn, fcb); + len = strlen(path); + if (len + 1 + strlen(sfn) >= sizeof(lfn_path1)) + return DE_PATHNOTFND; + if (path[len - 1] != '\\') + path[len++] = '\\'; + strcpy(path + len, sfn); + if (fstrcmp(sfn, lfn_comp) != 0) + lfn_create_name = lfn_comp; return SUCCESS; } -/* Description. - * Create LFN directory entries for the long name "lip->l_name", followed - * by the SFN entry with raw image "lip->l_dir". The "lip->l_diroff" points - * to the SFN entry on return. - * The internal fnode is released on fatal error, except LHE_INVLDHNDL of - * course. - * Return value. - * SUCCESS, LHE_INVLDHNDL, LHE_IOERROR, LHE_NOSPACE - */ -COUNT lfn_create_entries(COUNT handle, lfn_inode_ptr lip) -{ - f_node_ptr fnp = xlt_fd(handle); - COUNT entries_needed, free_entries, i, rc; - UNICODE FAR *lfn_name = lip->l_name; - UBYTE id = 1, sfn_checksum = lfn_checksum(lip->l_dir.dir_name); - unsigned sfn_offset; - if (fnp == 0 || fnp->f_count <= 0) return LHE_INVLDHNDL; - - entries_needed = (ufstrlen(lfn_name) + CHARS_IN_LFN_ENTRY - 1) - / CHARS_IN_LFN_ENTRY + 1; /* We want to create SFN entry too */ - - /* Scan the directory from the very begining for the free directory entries */ - lfn_setup_inode(handle, fnp->f_dirstart, 0); - - free_entries = 0; - while (TRUE) +/* Write the long name entries for the short entry fnp was just + written to. fatfs.c reserved the entries in front of it. + Called by fatfs.c; does nothing unless lfn_create_name is set. */ +COUNT lfn_write_entries(f_node_ptr fnp) +{ + struct f_node save; + const char *name = lfn_create_name; + unsigned sfn_entry, len, n, i, k, pos; + struct buffer FAR *bp; + UBYTE FAR *raw; + UBYTE chk; + COUNT rc = SUCCESS; + + lfn_create_name = NULL; + if (name == NULL || *name == '\0') + return SUCCESS; + + memcpy(&save, fnp, sizeof(save)); + sfn_entry = fnp->f_dmp->dm_entry; + chk = lfn_checksum(fnp->f_dir.dir_name); + len = strlen(name); + n = (len + LFN_CHARS - 1) / LFN_CHARS; + if (n > sfn_entry) + return DE_ACCESS; /* slots were not reserved */ + + /* forget the file context, walk the directory itself */ + dir_init_fnode(fnp, fnp->f_dmp->dm_dircluster); + for (i = 1; i <= n; i++) + { + fnp->f_dmp->dm_entry = sfn_entry - i; + if (dir_read(fnp) < 0 || (raw = dir_raw(fnp, &bp)) == NULL) { - rc = dir_read(fnp); - if (rc == 0 || fnp->f_dir.dir_name[0] == DELETED) - { - free_entries++; - if (free_entries == entries_needed) - break; - } - else if (rc == DE_BLKINVLD) - { - dir_close(fnp); - return LHE_IOERROR; - } - else if (rc == DE_SEEK) - { - if (extend_dir(fnp) != SUCCESS) return LHE_NOSPACE; - /* fnp points to the first free dir entry on return from extend_dir, - * so we go to previous entry to read this free entry on next cycle */ - fnp->f_diroff--; - } - else free_entries = 0; /* rc == 1 here => we've read some sfn entry */ + rc = DE_ACCESS; + break; } - sfn_offset = fnp->f_diroff; - - fnp->f_flags.f_dmod = TRUE; - /* Write SFN entry */ - fmemcpy(&fnp->f_dir, &lip->l_dir, sizeof(struct dirent)); - dir_write(fnp); - - fnp->f_diroff--; - /* Go in the reverse direction and create LFN entries */ - for (i = 0; i < entries_needed - 1; i++, id++) + raw[0] = (UBYTE)(i | (i == n ? 0x40 : 0)); + raw[11] = D_LFN; + raw[12] = 0; + raw[13] = chk; + raw[26] = raw[27] = 0; + pos = (i - 1) * LFN_CHARS; + for (k = 0; k < LFN_CHARS; k++, pos++) { - /* If this is the last LFN entry mark it's as those (6th bit is on) */ - if (i == (entries_needed - 2)) id |= 0x40; - lfn_name = &lip->l_name[i * CHARS_IN_LFN_ENTRY]; - unicode_to_lfn(&lfn_name, lfn(fnp)); - lfn(fnp)->lfn_checksum = sfn_checksum; - lfn(fnp)->lfn_id = id; - fnp->f_dir.dir_attrib = D_LFN; - if (!dir_write(fnp)) return LHE_IOERROR; - fnp->f_diroff--; + UNICODE u = pos < len ? oem_to_uni(name[pos]) : pos == len ? 0 : 0xffff; + raw[lfn_ofs[k]] = (UBYTE)u; + raw[lfn_ofs[k] + 1] = (UBYTE)(u >> 8); } - fnp->f_flags.f_dmod = FALSE; - - fnp->f_diroff = sfn_offset; + bp->b_flag |= BFR_DIRTY | BFR_VALID; + } - return SUCCESS; + memcpy(fnp, &save, sizeof(save)); + fnp->f_dmp->dm_entry = sfn_entry; + if (!flush_buffers(fnp->f_dpb->dpb_unit)) + rc = DE_ACCESS; + return rc; } -/* Description. - * Read next consequitve long file name. The LFN is stored into the - * "lip->l_name" in unicode and the corresponding SFN entry raw image into the - * "lip->l_dir". If directory entry being read is a 8.3 file name, then - * it's image is stored into the "lip->l_dir" and "lip->l_name" has zero - * length, i.e. "lip->l_name[0]" == 0. - * Return value. - * SUCCESS, LHE_INVLDHNDL, LHE_IOERROR, LHE_SEEK, LHE_DAMAGEDFS - */ -COUNT lfn_dir_read(COUNT handle, lfn_inode_ptr lip) +/****************************************************************/ +/* Path resolution */ +/****************************************************************/ + +/* append a component to the long path output */ +STATIC BOOL lout_add(const char *s) { + if (lfn_lout == NULL) + return TRUE; + if (lfn_lout[-1] != '\\') + { + if (lfn_lout >= lfn_lend) + return FALSE; + *lfn_lout++ = '\\'; + } + for (; *s; s++) + { + if (lfn_lout >= lfn_lend) + return FALSE; + *lfn_lout++ = *s; + } + *lfn_lout = '\0'; + return TRUE; +} + +/* remove the last component from the long path output */ +STATIC void lout_up(void) +{ + if (lfn_lout == NULL) + return; + while (lfn_lout[-1] != '\\') + lfn_lout--; + if (lfn_lout[-2] != ':') + lfn_lout--; + *lfn_lout = '\0'; +} + +/* Walk the components of src, appending their short names to dst + (a short path ending in a directory). See lfn_resolve(). */ +STATIC COUNT lfn_walk(const char FAR *src, char *dst, int flags) +{ + char *end = dst + strlen(dst); + char sfn[13]; COUNT rc; - UBYTE id = 1, real_id; - UNICODE FAR *lfn_name = lip->l_name; - UWORD sfn_diroff; - BOOL name_tail; - f_node_ptr fnp = xlt_fd(handle); - if (fnp == 0 || fnp->f_count <= 0) return LHE_INVLDHNDL; - - /* Scan a directory for the next valid SFN entry */ - while (TRUE) + + for (;;) + { + const char FAR *p; + int n = 0; + BOOL wild = FALSE, last; + + while (is_sep(*src)) + src++; + if (*src == '\0') + return LR_FOUND; + + /* extract the next component */ + while (*src && !is_sep(*src)) { - rc = dir_read(fnp); - if (rc == DE_SEEK) return LHE_SEEK; - else if (rc == DE_BLKINVLD) return LHE_IOERROR; - if (fnp->f_dir.dir_name[0] != DELETED && fnp->f_dir.dir_attrib != D_LFN) - { - fmemcpy(&lip->l_dir, &fnp->f_dir, sizeof(struct dirent)); - sfn_diroff = fnp->f_diroff; - break; - } - } - - /* Go in the reverse direction and find the LFN entries corresponding to - * the found SFN entry */ - while (TRUE) + UBYTE c = *src++; + if (n >= LFN_MAX || c < ' ' || c == '"' || c == '<' || c == '>' || + c == '|' || c == ':') + return DE_PATHNOTFND; + if (c == '*' || c == '?') + wild = TRUE; + lfn_comp[n++] = c; + } + lfn_comp[n] = '\0'; + for (p = src; is_sep(*p); p++) + ; + last = *p == '\0'; + + if (fstrcmp(lfn_comp, ".") == 0) + continue; + if (fstrcmp(lfn_comp, "..") == 0) { - if (fnp->f_diroff == 0) break; - fnp->f_diroff -= 2; - rc = dir_read(fnp); - if (rc == DE_BLKINVLD) return LHE_IOERROR; - if (fnp->f_dir.dir_name[0] == DELETED - || fnp->f_dir.dir_attrib != D_LFN) break; - real_id = lfn(fnp)->lfn_id; - if ((real_id & 0x3f) > 20) return LHE_DAMAGEDFS; - name_tail = lfn_to_unicode(&lfn_name, lfn(fnp)); - if (real_id & 0x40) - { - if ((id | 0x40) != real_id) return LHE_DAMAGEDFS; - break; - } - else - { - if (name_tail || real_id != id - || lfn(fnp)->lfn_checksum != lfn_checksum(lip->l_dir.dir_name)) - return LHE_DAMAGEDFS; - } - id++; + if ((UWORD)(end - dst) > lfn_root_len) + { + while (end[-1] != '\\') + end--; + if ((UWORD)(end - 1 - dst) >= lfn_root_len && end - 1 > dst + 2) + end--; + *end = '\0'; + lout_up(); + } + continue; + } + /* trailing dots and spaces are not significant */ + while (n && (lfn_comp[n - 1] == '.' || lfn_comp[n - 1] == ' ')) + lfn_comp[--n] = '\0'; + if (n == 0) + return last ? DE_FILENOTFND : DE_PATHNOTFND; + + if (wild) + { + if (last && (flags & LRF_WILD_OK)) + return lout_add(lfn_comp) ? LR_WILD : DE_PATHNOTFND; + return last ? DE_FILENOTFND : DE_PATHNOTFND; } - *lfn_name = 0; /* Terminate LFN string */ + rc = lfn_lookup(dst, lfn_comp); + if (rc < 0) + return rc; + if (rc == 0) + { + if (last && (flags & LRF_MISSING_OK)) + return lout_add(lfn_comp) ? LR_MISSING : DE_PATHNOTFND; + return last ? DE_FILENOTFND : DE_PATHNOTFND; + } + if (!last && !(fnode[0].f_dir.dir_attrib & D_DIR)) + return DE_PATHNOTFND; + + ConvertName83ToNameSZ(sfn, fnode[0].f_dir.dir_name); + if ((end - dst) + 1 + strlen(sfn) >= sizeof(lfn_path1)) + return DE_PATHNOTFND; + if (end[-1] != '\\') + *end++ = '\\'; + strcpy(end, sfn); + end += strlen(sfn); + if (!lout_add(lfn_name)) + return DE_PATHNOTFND; + if (last) + return LR_FOUND; + } +} + +/* Resolve the root (and for relative paths the current directory) + of drive into dst */ +STATIC COUNT lfn_start(UBYTE drive, char *dst, BOOL relative) +{ + struct cds FAR *cdsp = get_cds(drive); + char root[4]; + COUNT rc; + + if (cdsp == NULL) + return DE_INVLDDRV; + if (cdsp->cdsFlags & CDSNETWDRV) + return LFN_PASS; + lfn_drive = drive; - fnp->f_diroff = lip->l_diroff = sfn_diroff; + root[0] = 'A' + drive; + root[1] = ':'; + root[2] = '\\'; + root[3] = '\0'; + rc = truename(root, dst, CDS_MODE_CHECK_DEV_PATH); + if (rc < 0) + return rc; + if ((rc & IS_NETWORK) || dst[1] != ':' || dst[2] != '\\' || + get_dpb(dst[0] - 'A') == NULL) + return LFN_PASS; + lfn_root_len = strlen(dst); + if (lfn_lout) + { + root[3] = '\0'; + fstrcpy(lfn_lout, root); + lfn_lout += 3; + } + + if (relative) + { + if (lfn_lout) + { + /* walk the logical current directory to get its long form */ + root[2] = '\0'; + rc = truename(root, PriPathName, CDS_MODE_SKIP_PHYSICAL); + if (rc < 0) + return rc; + return lfn_walk(PriPathName + 3, dst, 0); + } + root[2] = '\0'; + rc = truename(root, dst, CDS_MODE_CHECK_DEV_PATH); + if (rc < 0) + return rc; + } return SUCCESS; } -/* Description. - * Writes directory entry pointed by internal fnode to disk. - * The fnode is released on error. - * Return value. - * SUCCESS, LHE_INVLDHNDL, LHE_IOERROR. - */ -COUNT lfn_dir_write(COUNT handle) +/* Resolve a long or short path to its fully qualified short form. + Returns LR_FOUND (dst = path), LR_MISSING / LR_WILD (dst = directory, + last component in lfn_comp), LFN_PASS or a negative error. + If lfn_lout is set, the long form is written there as well. */ +STATIC COUNT lfn_resolve(const char FAR *src, char *dst, int flags) +{ + UBYTE drive = default_drive; + COUNT rc; + + if (src[0] == '\0') + return DE_PATHNOTFND; + if (is_sep(src[0]) && is_sep(src[1])) + return LFN_PASS; /* UNC path */ + if (src[1] == ':') + { + drive = DosUpFChar(src[0]) - 'A'; + src += 2; + } + rc = lfn_start(drive, dst, !is_sep(src[0])); + if (rc != SUCCESS) + return rc; + return lfn_walk(src, dst, flags); +} + +/* is src a character device name (CON, NUL, ...)? */ +STATIC BOOL lfn_is_device(const char FAR *src) +{ + COUNT rc = truename(src, SecPathName, CDS_MODE_CHECK_DEV_PATH); + return rc >= 0 && (rc & IS_DEVICE) && !(rc & IS_NETWORK); +} + +/****************************************************************/ +/* Time conversion (Win95 FILETIME <-> DOS date/time) */ +/* DOS has no time zone, local time is treated as UTC. */ +/****************************************************************/ + +#define DAYS_1601_TO_1980 138426L + +STATIC void q_muladd(UWORD *q, UWORD m, UWORD a) +{ + ULONG carry = a; + int i; + + for (i = 0; i < 4; i++) + { + carry += (ULONG)q[i] * m; + q[i] = (UWORD)carry; + carry >>= 16; + } +} + +STATIC UWORD q_div(UWORD *q, UWORD d) +{ + ULONG rem = 0; + int i; + + for (i = 3; i >= 0; i--) + { + rem = (rem << 16) | q[i]; + q[i] = (UWORD)(rem / d); + rem %= d; + } + return (UWORD)rem; +} + +STATIC BOOL is_leap(UWORD y) { - f_node_ptr fnp = xlt_fd(handle); - if (fnp == 0 || fnp->f_count <= 0) return LHE_INVLDHNDL; + return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; +} + +STATIC const UWORD lfn_mdays[12] = + { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; - fnp->f_flags.f_dmod = TRUE; - if (!dir_write(fnp)) return LHE_IOERROR; - fnp->f_flags.f_dmod = FALSE; +/* DOS date/time + 10ms units -> FILETIME */ +STATIC void dos_to_filetime(UWORD date, UWORD time, UBYTE cs, UBYTE FAR *ft) +{ + UWORD q[4], y, m, d, i; + ULONG days; + if (date == 0) + { + fmemset(ft, 0, 8); + return; + } + y = 1980 + (date >> 9); + m = (date >> 5) & 15; + d = date & 31; + if (m < 1 || m > 12) + m = 1; + days = 0; + for (i = 1980; i < y; i++) + days += is_leap(i) ? 366 : 365; + days += lfn_mdays[m - 1] + (m > 2 && is_leap(y)) + (d ? d - 1 : 0); + days += DAYS_1601_TO_1980; + + q[0] = (UWORD)days; + q[1] = (UWORD)(days >> 16); + q[2] = q[3] = 0; + /* seconds = days * 86400 + time of day */ + q_muladd(q, 43200U, (time >> 11) * 1800 + ((time >> 5) & 63) * 30 + + (time & 31)); + q_muladd(q, 2, 0); + /* milliseconds, then 100ns units */ + q_muladd(q, 1000, cs * 10); + q_muladd(q, 10000, 0); + for (i = 0; i < 4; i++) + fputword(ft + 2 * i, q[i]); +} + +/* FILETIME -> DOS date/time + 10ms units; FALSE if out of range */ +STATIC BOOL filetime_to_dos(const UBYTE FAR *ft, UWORD *date, UWORD *time, + UBYTE *cs) +{ + UWORD q[4], ms, sec2, rem2, y, m; + ULONG days, secs; + int i; + + for (i = 0; i < 4; i++) + q[i] = fgetword(ft + 2 * i); + q_div(q, 10000); + ms = q_div(q, 1000); + sec2 = q_div(q, 43200U); /* half-day seconds */ + rem2 = q_div(q, 2); + if (q[2] || q[3]) + return FALSE; + days = ((ULONG)q[1] << 16) | q[0]; + if (days < DAYS_1601_TO_1980) + return FALSE; + days -= DAYS_1601_TO_1980; + secs = (ULONG)rem2 * 43200 + sec2; + + for (y = 1980;; y++) + { + UWORD ylen = is_leap(y) ? 366 : 365; + if (days < ylen) + break; + days -= ylen; + } + if (y > 2107) + return FALSE; + for (m = 12; m > 1; m--) + if (days >= lfn_mdays[m - 1] + (m > 2 && is_leap(y))) + break; + days -= lfn_mdays[m - 1] + (m > 2 && is_leap(y)); + + *date = ((y - 1980) << 9) | (m << 5) | (UWORD)(days + 1); + *time = (UWORD)((secs / 3600) << 11) | (UWORD)(((secs / 60) % 60) << 5) | + (UWORD)((secs % 60) / 2); + *cs = (UBYTE)(ms / 10 + (secs % 2) * 100); + return TRUE; +} + +STATIC void lfn_put_time(UBYTE FAR *d, UWORD date, UWORD time, UBYTE cs, + UWORD fmt) +{ + if (fmt == 1) + { + fputword(d, time); + fputword(d + 2, date); + fmemset(d + 4, 0, 4); + } + else + dos_to_filetime(date, time, cs, d); +} + +/****************************************************************/ +/* Find first/next/close */ +/****************************************************************/ + +STATIC BOOL lfn_attr_ok(UBYTE a, UBYTE allow, UBYTE need) +{ + return (a & ~allow & (D_HIDDEN | D_SYSTEM | D_DIR | D_VOLID)) == 0 && + (a & need) == need; +} + +/* fill a Win95 find data record from fnode[0] / lfn_name */ +STATIC void lfn_finddata(f_node_ptr fnp, UBYTE FAR *d, UWORD fmt) +{ + struct dirent *de = &fnp->f_dir; + + fmemset(d, 0, FINDDATA_SIZE); + d[0] = de->dir_attrib; + lfn_put_time(d + 0x04, de->dir_crdate, de->dir_crtime, de->dir_crtimems, + fmt); + lfn_put_time(d + 0x0c, de->dir_accdate, 0, 0, fmt); + lfn_put_time(d + 0x14, de->dir_date, de->dir_time, 0, fmt); + fputlong(d + 0x20, de->dir_size); + fstrcpy((char FAR *)(d + 0x2c), lfn_name); + if (lfn_has_long) + ConvertName83ToNameSZ((BYTE FAR *)(d + 0x130), de->dir_name); +} + +STATIC COUNT lfn_find_next(struct lfn_find *h, lregs *r) +{ + f_node_ptr fnp = &fnode[0]; + struct dpb FAR *dpbp; + char sfn[13]; + COUNT rc; + + if (h->done) + return DE_NFILES; + dpbp = get_dpb(h->drive); + if (dpbp == NULL) + return DE_NFILES; + fnp->f_dpb = dpbp; + dir_init_fnode(fnp, h->dir); + fnp->f_dmp->dm_entry = h->entry; + + while ((rc = lfn_dir_next(fnp)) == 1) + { + fnp->f_dmp->dm_entry++; + if (!lfn_attr_ok(fnp->f_dir.dir_attrib, h->allow, h->need)) + continue; + ConvertName83ToNameSZ(sfn, fnp->f_dir.dir_name); + if (!wild_match(h->pat, lfn_name) && !wild_match(h->pat, sfn)) + continue; + h->entry = fnp->f_dmp->dm_entry; + lfn_finddata(fnp, MK_FP(r->ES, r->DI), r->SI); + return SUCCESS; + } + h->done = TRUE; + return rc < 0 ? rc : DE_NFILES; +} + +STATIC struct lfn_find *lfn_find_handle(UWORD hnd) +{ + struct lfn_find *h; + + if (hnd == 0 || hnd > LFN_FINDHNDLS) + return NULL; + h = &lfn_finds[hnd - 1]; + return h->psp ? h : NULL; +} + +STATIC COUNT lfn_find_first(lregs *r) +{ + struct lfn_find *h; + COUNT rc; + UWORD i; + + for (i = 0; i < LFN_FINDHNDLS && lfn_finds[i].psp; i++) + ; + if (i == LFN_FINDHNDLS) + return DE_TOOMANY; + h = &lfn_finds[i]; + + rc = lfn_resolve(MK_FP(r->DS, r->DX), lfn_path1, LRF_WILD_OK); + if (rc < 0 || rc == LFN_PASS) + return rc; + + h->allow = r->CL; + h->need = r->CH; + h->done = FALSE; + h->drive = lfn_path1[0] - 'A'; + + if (rc == LR_WILD) + { + f_node_ptr fnp; + + if (strlen(lfn_comp) >= LFN_PATLEN) + return DE_PATHNOTFND; + fnp = dir_open(lfn_path1, FALSE, &fnode[0]); + if (fnp == NULL) + return DE_PATHNOTFND; + strcpy(h->pat, lfn_comp); + h->dir = fnp->f_dmp->dm_dircluster; + h->entry = 0; + h->psp = cu_psp; + rc = lfn_find_next(h, r); + if (rc < 0) + { + h->psp = 0; + return rc; + } + } + else + { + /* no wildcards: at most one match, no need to keep a pattern */ + rc = lfn_locate(lfn_path1); + if (rc <= 0) + return rc == 0 ? DE_FILENOTFND : rc; + if (!lfn_attr_ok(fnode[0].f_dir.dir_attrib, h->allow, h->need)) + return DE_FILENOTFND; + lfn_finddata(&fnode[0], MK_FP(r->ES, r->DI), r->SI); + h->done = TRUE; + h->psp = cu_psp; + } + r->AX = i + 1; + r->CX = 0; /* no unicode conversion problems */ return SUCCESS; } -/*********************************************************************/ -/* Miscellaneous functions. These functions are not part of the API. */ -/*********************************************************************/ +/* release all search handles of a terminating process */ +VOID lfn_close_finds(UWORD psp) +{ + int i; -/* Description. - * Copy the block of "count" unicode characters from source pointed by - * "sptr" to destination pointed by "dptr". The trailing characters of - * destination are filled with "UNICODE_FILLER". - * Return value. - * TRUE - The source string is too short, trailing characters are filled - * with "UNICODE_FILLER". - * FALSE - The unicode strings have the same size, no filling occured. - */ -BOOL transfer_unicode(UNICODE FAR **dptr, UNICODE FAR **sptr, COUNT count) + for (i = 0; i < LFN_FINDHNDLS; i++) + if (lfn_finds[i].psp == psp) + lfn_finds[i].psp = 0; +} + +/****************************************************************/ +/* Individual functions */ +/****************************************************************/ + +/* AX=7141h delete file(s) */ +STATIC COUNT lfn_delete(lregs *r) { - COUNT j; - BOOL found_zerro = FALSE; + f_node_ptr fnp; + CLUSTER dir; + UWORD entry = 0, deleted = 0; + UBYTE drive; + char sfn[13]; + size_t len; + COUNT rc; + + rc = lfn_resolve(MK_FP(r->DS, r->DX), lfn_path1, + r->SI == 1 ? LRF_WILD_OK : 0); + if (rc == LR_FOUND) + return DosDelete(lfn_path1, D_ALL); + if (rc != LR_WILD) + return rc; + + /* wildcard delete: match long and short names */ + fnp = dir_open(lfn_path1, FALSE, &fnode[0]); + if (fnp == NULL) + return DE_PATHNOTFND; + dir = fnp->f_dmp->dm_dircluster; + drive = lfn_path1[0] - 'A'; + len = strlen(lfn_path1); + if (lfn_path1[len - 1] != '\\') + lfn_path1[len++] = '\\'; + lfn_path1[len] = '\0'; - for (j = 0; j < count; j++, (*dptr)++, (*sptr)++) + for (;;) + { + fnp = &fnode[0]; + fnp->f_dpb = get_dpb(drive); + dir_init_fnode(fnp, dir); + fnp->f_dmp->dm_entry = entry; + while ((rc = lfn_dir_next(fnp)) == 1) { - if (found_zerro) **dptr = UNICODE_FILLER; - else **dptr = **sptr; - if (**sptr == 0) found_zerro = TRUE; + fnp->f_dmp->dm_entry++; + if (fnp->f_dir.dir_attrib & (D_DIR | D_VOLID) || + !lfn_attr_ok(fnp->f_dir.dir_attrib, r->CL, r->CH)) + continue; + ConvertName83ToNameSZ(sfn, fnp->f_dir.dir_name); + if (wild_match(lfn_comp, lfn_name) || wild_match(lfn_comp, sfn)) + break; } + if (rc < 0) + return rc; + if (rc == 0) + break; + entry = fnp->f_dmp->dm_entry; + if (len + strlen(sfn) >= sizeof(lfn_path2)) + return DE_PATHNOTFND; + strcpy(lfn_path2, lfn_path1); + strcpy(lfn_path2 + len, sfn); + rc = DosDelete(lfn_path2, D_ALL); + if (rc < 0) + return rc; + deleted++; + } + return deleted ? SUCCESS : DE_FILENOTFND; +} + +/* AX=7143h get/set attributes and time stamps */ +STATIC COUNT lfn_attrib(lregs *r) +{ + f_node_ptr fnp = &fnode[0]; + struct dirent *de = &fnp->f_dir; + COUNT rc; + + rc = lfn_resolve(MK_FP(r->DS, r->DX), lfn_path1, 0); + if (rc != LR_FOUND) + return rc; - return found_zerro; + switch (r->BL) + { + case 0x00: + rc = DosGetFattr(lfn_path1); + if (rc >= SUCCESS) + { + r->CX = rc; + rc = SUCCESS; + } + return rc; + case 0x01: + return DosSetFattr(lfn_path1, r->CX); + } + + rc = lfn_locate(lfn_path1); + if (rc <= 0) + return rc == 0 ? DE_ACCESS : rc; + switch (r->BL) + { + case 0x02: /* physical size */ + { + ULONG clsize = (ULONG)(fnp->f_dpb->dpb_clsmask + 1) * + fnp->f_dpb->dpb_secsize; + ULONG size = (de->dir_size + clsize - 1) / clsize * clsize; + r->AX = (UWORD)size; + r->DX = (UWORD)(size >> 16); + return SUCCESS; + } + case 0x03: + de->dir_date = r->DI; + de->dir_time = r->CX; + break; + case 0x04: + r->CX = de->dir_time; + r->DI = de->dir_date; + return SUCCESS; + case 0x05: + de->dir_accdate = r->DI; + break; + case 0x06: + r->DI = de->dir_accdate; + return SUCCESS; + case 0x07: + de->dir_crdate = r->DI; + de->dir_crtime = r->CX; + de->dir_crtimems = (UBYTE)r->SI; + break; + case 0x08: + r->CX = de->dir_crtime; + r->DI = de->dir_crdate; + r->SI = de->dir_crtimems; + return SUCCESS; + default: + return DE_INVLDFUNC; + } + return dir_write(fnp) ? SUCCESS : DE_ACCESS; } -/* Description. - * Retrieve the LFN string chunk from the directory entry "lep" and store it - * to the "name" unicode string. - * Return value. - * TRUE - The LFN string chunk contains zero character. - * FALSE - Doesn't terminate with zero. - */ -BOOL lfn_to_unicode(UNICODE FAR **name, struct lfn_entry FAR *lep) +/* AX=7147h get current directory (long form) */ +STATIC COUNT lfn_getcwd(lregs *r) { - UNICODE FAR *ptr; - - ptr = lep->lfn_name0_4; - if (transfer_unicode(name, &ptr, 5)) return TRUE; - ptr = lep->lfn_name5_10; - if (transfer_unicode(name, &ptr, 6)) return TRUE; - ptr = lep->lfn_name11_12; - if (transfer_unicode(name, &ptr, 2)) return TRUE; + UBYTE drive = r->DL ? r->DL - 1 : default_drive; + char FAR *buf = MK_FP(r->DS, r->SI); + char FAR *s; + COUNT rc; - return FALSE; + lfn_lout = buf; + lfn_lend = buf + LFN_PATHMAX; + rc = lfn_start(drive, lfn_path1, TRUE); + if (rc < 0 || rc == LFN_PASS) + return rc; + /* strip "X:\" */ + for (s = buf + 3;; s++) + { + s[-3] = *s; + if (*s == '\0') + break; + } + r->AX = 0x0100; + return SUCCESS; } -/* Description. - */ -VOID unicode_to_lfn(UNICODE FAR **name, struct lfn_entry FAR *lep) +/* AX=7156h rename / move */ +STATIC COUNT lfn_rename(lregs *r) { - UNICODE FAR *ptr; - - ptr = lep->lfn_name0_4; - transfer_unicode(&ptr, name, 5); - ptr = lep->lfn_name5_10; - transfer_unicode(&ptr, name, 6); - ptr = lep->lfn_name11_12; - transfer_unicode(&ptr, name, 2); + CLUSTER odir; + UWORD oentry; + COUNT rc; + + rc = lfn_resolve(MK_FP(r->DS, r->DX), lfn_path1, 0); + if (rc != LR_FOUND) + return rc; + rc = lfn_locate(lfn_path1); + if (rc <= 0) + return rc == 0 ? DE_ACCESS : rc; + odir = fnode[0].f_dmp->dm_dircluster; + oentry = fnode[0].f_dmp->dm_entry; + + rc = lfn_resolve(MK_FP(r->ES, r->DI), lfn_path2, LRF_MISSING_OK); + if (rc == LR_FOUND) + { + /* only allowed for the same file: change the long name/case */ + char sfn[13]; + + if (fstrcmp(lfn_path1, lfn_path2) != 0 || lfn_locate(lfn_path2) != 1 || + fnode[0].f_dmp->dm_dircluster != odir || + fnode[0].f_dmp->dm_entry != oentry) + return DE_ACCESS; + if (lfn_has_long && fstrcmp(lfn_name, lfn_comp) == 0) + return SUCCESS; /* nothing to do */ + ConvertName83ToNameSZ(sfn, fnode[0].f_dir.dir_name); + if (fstrcmp(sfn, lfn_comp) == 0) + { + if (!lfn_has_long) + return SUCCESS; + lfn_create_name = ""; /* drop the long name */ + } + else + lfn_create_name = lfn_comp; + } + else if (rc == LR_MISSING) + { + rc = lfn_prepare_create(lfn_path2); + if (rc < 0) + return rc; + } + else + return rc; + + rc = DosRename(lfn_path1, lfn_path2); + lfn_create_name = NULL; + return rc; +} + +/* AX=7160h truename: CL=0 canonical, CL=1 short, CL=2 long */ +STATIC COUNT lfn_truename(lregs *r) +{ + const char FAR *src = MK_FP(r->DS, r->SI); + char FAR *dst = MK_FP(r->ES, r->DI); + COUNT rc; + + if (r->CL > 2) + return DE_INVLDFUNC; + if (lfn_is_device(src)) + { + fstrcpy(dst, SecPathName); + return SUCCESS; + } + if (r->CL != 1) + { + lfn_lout = dst; + lfn_lend = dst + LFN_PATHMAX; + } + rc = lfn_resolve(src, lfn_path1, + r->CL == 0 ? LRF_MISSING_OK | LRF_WILD_OK : 0); + if (rc < 0 || rc == LFN_PASS) + return rc; + if (r->CL == 1) + fstrcpy(dst, lfn_path1); + return SUCCESS; } -/* Calculate checksum for the 8.3 name */ -UBYTE lfn_checksum(UBYTE FAR *sfn_name) +/* AX=716Ch extended open/create */ +STATIC COUNT lfn_open(lregs *r) { - UBYTE sum; - COUNT i; + const char FAR *src = MK_FP(r->DS, r->SI); + unsigned flags; + long lrc; + COUNT rc; - for (sum = 0, i = 11; --i >= 0; sum += *sfn_name++) - sum = (sum << 7) | (sum >> 1); + /* high nibble must be <= 1, low nibble must be <= 2 */ + if ((r->DL & 0xef) > 0x2) + return DE_INVLDFUNC; + flags = (r->BX & 0x70ff) | ((r->DL & 3) << 8) | ((r->DL & 0x10) << 6); - return sum; + if (lfn_is_device(src)) + lrc = DosOpen((char FAR *)src, flags, r->CL); + else + { + rc = lfn_resolve(src, lfn_path1, LRF_MISSING_OK); + if (rc == LR_MISSING) + { + if (!(r->DL & 0x10)) + return DE_FILENOTFND; + rc = lfn_prepare_create(lfn_path1); + if (rc < 0) + return rc; + } + else if (rc != LR_FOUND) + return rc; + lrc = DosOpen(lfn_path1, flags, r->CL); + lfn_create_name = NULL; + } + if (lrc < SUCCESS) + return (COUNT)lrc; + r->AX = (UWORD)lrc; + r->CX = (UWORD)(lrc >> 16); /* action taken */ + return SUCCESS; +} + +/* AX=71A0h get volume information */ +STATIC COUNT lfn_volinfo(lregs *r) +{ + const char FAR *root = MK_FP(r->DS, r->DX); + UBYTE drive = default_drive; + struct cds FAR *cdsp; + struct dpb FAR *dpbp; + const char *fs; + + if (root[0] && root[1] == ':') + drive = DosUpFChar(root[0]) - 'A'; + cdsp = get_cds(drive); + if (cdsp == NULL) + return DE_INVLDDRV; + if (cdsp->cdsFlags & CDSNETWDRV) + return LFN_PASS; + dpbp = cdsp->cdsDpb; + if (dpbp == NULL) + return LFN_PASS; + fs = ISFAT32(dpbp) ? "FAT32" : "FAT"; + if (r->CX > strlen(fs)) + fstrcpy(MK_FP(r->ES, r->DI), fs); + r->BX = 0x4006; /* case preserved, unicode on disk, LFN functions */ + r->CX = LFN_MAX; + r->DX = LFN_PATHMAX; + return SUCCESS; } -COUNT ufstrlen(REG UNICODE FAR *s) +/* AX=71A7h FILETIME <-> DOS date/time */ +STATIC COUNT lfn_timeconv(lregs *r) { - REG COUNT cnt = 0; + if (r->BL == 0) + { + UWORD date, time; + UBYTE cs; + + if (!filetime_to_dos(MK_FP(r->DS, r->SI), &date, &time, &cs)) + return DE_INVLDDATA; + r->CX = time; + r->DX = date; + r->BH = cs; + return SUCCESS; + } + if (r->BL == 1) + { + dos_to_filetime(r->DX, r->CX, r->BH, MK_FP(r->ES, r->DI)); + return SUCCESS; + } + return DE_INVLDFUNC; +} + +/* AX=71A8h generate short name (basis, no numeric tail) */ +STATIC COUNT lfn_genshort(lregs *r) +{ + const char FAR *src = MK_FP(r->DS, r->SI); + char fcb[FNAME_SIZE + FEXT_SIZE], sfn[13]; + int n; + + for (n = 0; src[n]; n++) + if (n >= LFN_MAX) + return DE_INVLDDATA; + fmemcpy(lfn_comp, src, n + 1); + lfn_basis(lfn_comp, fcb); + if (r->DH == 0) + fmemcpy(MK_FP(r->ES, r->DI), fcb, FNAME_SIZE + FEXT_SIZE); + else + { + ConvertName83ToNameSZ(sfn, fcb); + fstrcpy(MK_FP(r->ES, r->DI), sfn); + } + return SUCCESS; +} + +/****************************************************************/ +/* INT 21h AH=71h dispatcher */ +/* Returns SUCCESS, a negative DOS error, or LFN_PASS for */ +/* subfunctions/drives the kernel does not handle itself. */ +/****************************************************************/ + +COUNT int21_lfn(lregs *r) +{ + struct lfn_find *h; + COUNT rc; + + lfn_create_name = NULL; + lfn_lout = NULL; + + switch (r->AL) + { + case 0x0d: /* reset drive */ + flush(); + return SUCCESS; + + case 0x39: /* make directory */ + rc = lfn_resolve(MK_FP(r->DS, r->DX), lfn_path1, LRF_MISSING_OK); + if (rc == LR_FOUND) + return DE_ACCESS; + if (rc != LR_MISSING) + return rc; + rc = lfn_prepare_create(lfn_path1); + if (rc == SUCCESS) + rc = DosMkRmdir(lfn_path1, 0x39); + lfn_create_name = NULL; + return rc; + + case 0x3a: /* remove directory */ + rc = lfn_resolve(MK_FP(r->DS, r->DX), lfn_path1, 0); + if (rc != LR_FOUND) + return rc; + return DosMkRmdir(lfn_path1, 0x3a); + + case 0x3b: /* change directory */ + { + struct cds FAR *cdsp; + UWORD off; + + rc = lfn_resolve(MK_FP(r->DS, r->DX), lfn_path1, 0); + if (rc != LR_FOUND) + return rc; + /* use the logical drive so SUBSTed drives keep their own cwd */ + cdsp = get_cds(lfn_drive); + off = cdsp->cdsBackslashOffset; + if (off > 2 && strlen(lfn_path1) >= off) + { + lfn_path2[0] = 'A' + lfn_drive; + lfn_path2[1] = ':'; + strcpy(lfn_path2 + 2, lfn_path1[off] ? lfn_path1 + off : "\\"); + return DosChangeDir(lfn_path2); + } + return DosChangeDir(lfn_path1); + } + + case 0x41: + return lfn_delete(r); + + case 0x43: + return lfn_attrib(r); + + case 0x47: + return lfn_getcwd(r); + + case 0x4e: + return lfn_find_first(r); + + case 0x4f: + h = lfn_find_handle(r->BX); + if (h == NULL) + return DE_INVLDHNDL; + rc = lfn_find_next(h, r); + if (rc == SUCCESS) + r->CX = 0; + return rc; + + case 0xa1: + h = lfn_find_handle(r->BX); + if (h == NULL) + return DE_INVLDHNDL; + h->psp = 0; + return SUCCESS; + + case 0x56: + return lfn_rename(r); + + case 0x60: + return lfn_truename(r); + + case 0x6c: + return lfn_open(r); + + case 0xa0: + return lfn_volinfo(r); + + case 0xa7: + return lfn_timeconv(r); - while (*s++ != 0) - ++cnt; - return cnt; + case 0xa8: + return lfn_genshort(r); + } + return LFN_PASS; } #endif diff --git a/kernel/proto.h b/kernel/proto.h index a4c6abfa..3ce86890 100644 --- a/kernel/proto.h +++ b/kernel/proto.h @@ -247,16 +247,14 @@ void DosUmbLink(unsigned n); VOID mcb_print(mcb FAR * mcbp); /* lfnapi.c */ -COUNT lfn_allocate_inode(VOID); -COUNT lfn_free_inode(COUNT handle); - -COUNT lfn_setup_inode(COUNT handle, ULONG dirstart, ULONG diroff); - -COUNT lfn_create_entries(COUNT handle, lfn_inode_ptr lip); -COUNT lfn_remove_entries(COUNT handle); - -COUNT lfn_dir_read(COUNT handle, lfn_inode_ptr lip); -COUNT lfn_dir_write(COUNT handle); +#ifdef WITHLFNAPI +#define LFN_PASS 0x7100 /* int21_lfn(): not handled, report unsupported */ +extern const char *lfn_create_name; +extern UWORD lfn_free_need, lfn_free_run; +COUNT int21_lfn(lregs *r); +COUNT lfn_write_entries(f_node_ptr fnp); +VOID lfn_close_finds(UWORD psp); +#endif /* nls.c */ BYTE DosYesNo(UWORD ch); diff --git a/kernel/task.c b/kernel/task.c index 1f31b926..58b12c39 100644 --- a/kernel/task.c +++ b/kernel/task.c @@ -590,6 +590,11 @@ VOID return_user(void) abort_progress = -1; +#ifdef WITHLFNAPI + /* release LFN search handles the process left open */ + lfn_close_finds(cu_psp); +#endif + /* And free all process memory if not a TSR return */ network_redirector(REM_PROCESS_END); /* might be a good idea to do that after closing diff --git a/mdvmm/Makefile b/mdvmm/Makefile new file mode 100644 index 00000000..75d9c479 --- /dev/null +++ b/mdvmm/Makefile @@ -0,0 +1,109 @@ +# MDVMM - modernDOS virtual machine monitor +# Builds build/MDVMM.COM (16-bit DOS loader with the 32-bit core appended) +# and build/BOOTX64.EFI (UEFI loader with the same core embedded). + +CC = i686-linux-gnu-gcc +LD = i686-linux-gnu-ld +OBJCOPY = i686-linux-gnu-objcopy +NASM = nasm +CC64 = gcc +LD64 = ld + +CFLAGS = -m32 -std=gnu11 -O2 -Wall -Wextra -Werror \ + -ffreestanding -fno-builtin -fno-pic -fno-pie -fno-stack-protector \ + -fno-delete-null-pointer-checks -fno-strict-aliasing -fno-asynchronous-unwind-tables \ + -mgeneral-regs-only --param=min-pagesize=0 -Iinclude -Icore +NFLAGS = -Iinclude/ + +B = build +# core objects; the UEFI core adds the virtual BIOS and native drivers for +# disks, screen and input, the DOS core has stubs instead (the machine's +# BIOS does that); both have iPXE's network drivers +COBJS = $(B)/entry.o $(B)/main.o $(B)/lib.o $(B)/mm.o $(B)/cpu.o $(B)/v86.o $(B)/dpmi.o \ + $(B)/vm.o $(B)/dma.o $(B)/pci.o $(B)/nic.o $(B)/ipxenic.o $(B)/ipxe.o +UEFIOBJS = $(B)/bios.o $(B)/fbcon.o $(B)/font.o $(B)/romimg.o $(B)/ahci.o $(B)/nvme.o \ + $(B)/xhci.o $(B)/usbkbd.o $(B)/mouse.o $(B)/apic.o $(B)/uhci.o $(B)/vga.o $(B)/vgaemu.o +DOSOBJS = $(B)/nobios.o +HDRS = core/core.h include/bootinfo.h + +# iPXE's network drivers (ipxe/): the pinned source tree of the build image +IPXE ?= $(firstword $(wildcard /opt/ipxe ../_output/ext/ipxe/src)) +IPXE_DEBUG ?= + +CFLAGS64 = -m64 -std=gnu11 -O2 -Wall -Wextra -Werror -ffreestanding -fno-builtin \ + -fpie -fno-stack-protector -mno-red-zone -mgeneral-regs-only \ + -fno-asynchronous-unwind-tables -fshort-wchar -Iinclude -Iuefi + +all: $(B)/MDVMM.COM $(B)/BOOTX64.EFI $(B)/PKTDRV.COM $(B)/SSHSLOT.COM $(B)/MDLOG.COM $(B)/MDSYS.COM + +$(B): + mkdir -p $(B) + +$(B)/entry.o: core/entry.asm include/bootinfo.inc | $(B) + $(NASM) $(NFLAGS) -f elf32 -o $@ $< + +$(B)/rom.bin: core/rom.asm include/bootinfo.inc | $(B) + $(NASM) $(NFLAGS) -f bin -o $@ $< + +$(B)/romimg.o: core/romimg.asm $(B)/rom.bin + $(NASM) $(NFLAGS) -I$(B)/ -f elf32 -o $@ $< + +$(B)/%.o: core/%.c $(HDRS) | $(B) + $(CC) $(CFLAGS) -c -o $@ $< + +LDCORE = $(LD) -m elf_i386 -z noexecstack --no-warn-rwx-segments -T core/core.ld + +$(B)/core.elf: $(COBJS) $(UEFIOBJS) core/core.ld + $(LDCORE) -o $@ $(COBJS) $(UEFIOBJS) + +$(B)/core_dos.elf: $(COBJS) $(DOSOBJS) core/core.ld + $(LDCORE) -o $@ $(COBJS) $(DOSOBJS) + +$(B)/%.bin: $(B)/%.elf + $(OBJCOPY) -O binary $< $@ + +# MDVMM.COM is an MZ program laid out like a .COM (loader/mz.asm), with +# the core appended: the loader reads it from its own file, so the core +# is not held to 64 KB +$(B)/loader.bin: loader/loader.asm include/bootinfo.inc | $(B) + $(NASM) $(NFLAGS) -f bin -o $@ $< + +$(B)/MDVMM.COM: loader/mz.asm $(B)/loader.bin $(B)/core_dos.bin + $(NASM) -I$(B)/ -DLSIZE=$$(stat -c %s $(B)/loader.bin) -f bin -o $@ $< + +$(B)/uefi_main.o: uefi/main.c uefi/efi.h uefi/loader.h include/bootinfo.h | $(B) + $(CC64) $(CFLAGS64) -c -o $@ $< + +$(B)/uefi_start.o: uefi/start.asm $(B)/core.bin + $(NASM) -I$(B)/ -f elf64 -o $@ $< + +$(B)/uefi_hwinfo.o: uefi/hwinfo.c uefi/efi.h | $(B) + $(CC64) $(CFLAGS64) -c -o $@ $< + +$(B)/uefi_install.o: uefi/install.c uefi/loader.h uefi/efi.h | $(B) + $(CC64) $(CFLAGS64) -c -o $@ $< + +$(B)/BOOTX64.EFI: $(B)/uefi_main.o $(B)/uefi_hwinfo.o $(B)/uefi_install.o $(B)/uefi_start.o uefi/efi.ld + $(LD64) -m i386pep --subsystem 10 --image-base 0x10000000 -e efi_main --enable-reloc-section -nostdlib \ + -T uefi/efi.ld -o $@ $(B)/uefi_main.o $(B)/uefi_hwinfo.o $(B)/uefi_install.o $(B)/uefi_start.o + +$(B)/ipxe.o: ipxe/glue.c ipxe/glue_data.c ipxe/build.sh ipxe/drivers.list ipxe/core.list ipxe/ipxe.lds \ + ipxe/overlay/config/defaults/mdvmm.h | $(B) + bash ipxe/build.sh $(IPXE) $@ $(IPXE_DEBUG) + +$(B)/PKTDRV.COM: pktdrv/pktdrv.asm | $(B) + $(NASM) -f bin -o $@ $< + +$(B)/SSHSLOT.COM: sshslot/sshslot.asm | $(B) + $(NASM) -f bin -o $@ $< + +$(B)/MDLOG.COM: mdlog/mdlog.asm | $(B) + $(NASM) -f bin -o $@ $< + +$(B)/MDSYS.COM: mdsys/mdsys.asm | $(B) + $(NASM) -f bin -o $@ $< + +clean: + rm -rf $(B) + +.PHONY: all clean diff --git a/mdvmm/compile_flags.txt b/mdvmm/compile_flags.txt new file mode 100644 index 00000000..5c7c9935 --- /dev/null +++ b/mdvmm/compile_flags.txt @@ -0,0 +1,5 @@ +-m32 +-ffreestanding +-std=gnu11 +-Iinclude +-Icore diff --git a/mdvmm/core/ahci.c b/mdvmm/core/ahci.c new file mode 100644 index 00000000..86e19d21 --- /dev/null +++ b/mdvmm/core/ahci.c @@ -0,0 +1,273 @@ +/* MDVMM core - AHCI (SATA) disk driver for the virtual BIOS + * + * Finds AHCI controllers on PCI, takes over every port with a SATA disk + * and registers it as a BIOS hard disk (INT 13h, bios.c). Commands are + * issued one at a time and polled with interrupts off: DOS does not + * overlap disk I/O anyway. Data goes through the caller's pool pages + * (one PRD entry per 4K page), so no physically contiguous buffers are + * needed. Not used on DOS boots, where the PC BIOS owns the disks. + */ +#include "core.h" + +#define MAX_DISKS 8 + +/* HBA registers */ +#define HBA_CAP 0x00 +#define HBA_GHC 0x04 +#define HBA_PI 0x0c +#define HBA_VS 0x10 +#define GHC_AE 0x80000000u + +/* port registers, at 100h + port * 80h */ +#define P_CLB 0x00 +#define P_CLBU 0x04 +#define P_FB 0x08 +#define P_FBU 0x0c +#define P_IS 0x10 +#define P_IE 0x14 +#define P_CMD 0x18 +#define P_TFD 0x20 +#define P_SIG 0x24 +#define P_SSTS 0x28 +#define P_SERR 0x30 +#define P_CI 0x38 + +#define CMD_ST 0x0001 +#define CMD_SUD 0x0002 +#define CMD_POD 0x0004 +#define CMD_FRE 0x0010 +#define CMD_FR 0x4000 +#define CMD_CR 0x8000 +#define IS_TFES 0x40000000u +#define TFD_ERR 0x01 +#define TFD_DRQ 0x08 +#define TFD_BSY 0x80 + +#define SIG_ATA 0x00000101u + +#define ATA_READ_DMA_EXT 0x25 +#define ATA_WRITE_DMA_EXT 0x35 +#define ATA_READ_DMA 0xc8 +#define ATA_WRITE_DMA 0xca +#define ATA_IDENTIFY 0xec +#define ATA_FLUSH_EXT 0xea + +struct port { + struct disk disk; + volatile uint8_t *regs; + uint32_t clb, fb, ctba; /* physical: command list, FIS, table */ + int lba48; +}; + +static struct port ports[MAX_DISKS]; +static int nports; + +static uint32_t rd(struct port *p, int r) +{ + return *(volatile uint32_t *)(p->regs + r); +} + +static void wr(struct port *p, int r, uint32_t v) +{ + *(volatile uint32_t *)(p->regs + r) = v; +} + +/* wait until (reg & mask) == val, up to ms milliseconds */ +static int wait_reg(struct port *p, int r, uint32_t mask, uint32_t val, uint32_t ms) +{ + uint32_t i; + + for (i = 0; i < ms * 1000; i++) + { + if ((rd(p, r) & mask) == val) + return 1; + udelay(1); + } + return 0; +} + +/* one command in slot 0; pages: data pages (4K each), bytes total */ +static int command(struct port *p, uint8_t cmd, uint64_t lba, uint32_t count, + const uint32_t *pages, uint32_t bytes, int write) +{ + uint32_t *hdr = pool_ptr(p->clb); + uint8_t *tbl = pool_ptr(p->ctba); + uint8_t *fis = tbl; + uint32_t *prd = (uint32_t *)(tbl + 0x80); + uint32_t i, nprd = (bytes + 4095) / 4096; + + memset(tbl, 0, 0x80 + nprd * 16); + fis[0] = 0x27; /* register FIS, host to device */ + fis[1] = 0x80; /* command */ + fis[2] = cmd; + fis[4] = (uint8_t)lba; + fis[5] = (uint8_t)(lba >> 8); + fis[6] = (uint8_t)(lba >> 16); + fis[7] = 0x40; /* LBA mode */ + fis[8] = (uint8_t)(lba >> 24); + fis[9] = (uint8_t)(lba >> 32); + fis[10] = (uint8_t)(lba >> 40); + fis[12] = (uint8_t)count; + fis[13] = (uint8_t)(count >> 8); + if (!p->lba48 && cmd != ATA_IDENTIFY) + fis[7] |= (uint8_t)((lba >> 24) & 0x0f); + for (i = 0; i < nprd; i++) + { + uint32_t n = bytes - i * 4096 < 4096 ? bytes - i * 4096 : 4096; + prd[i * 4] = pages[i]; + prd[i * 4 + 1] = 0; + prd[i * 4 + 3] = n - 1; + } + hdr[0] = 5 | (write ? 0x40 : 0) | nprd << 16; /* FIS 5 dwords */ + hdr[1] = 0; + hdr[2] = p->ctba; + hdr[3] = 0; + + if (!wait_reg(p, P_TFD, TFD_BSY | TFD_DRQ, 0, 1000)) + return 0x80; /* timeout */ + wr(p, P_IS, 0xffffffffu); + wr(p, P_CI, 1); + for (i = 0; i < 10000000; i++) /* about 10 s */ + { + if (!(rd(p, P_CI) & 1)) + break; + if (rd(p, P_IS) & IS_TFES) + break; + udelay(1); + } + if ((rd(p, P_IS) & IS_TFES) || (rd(p, P_TFD) & TFD_ERR)) + { + kprintf("ahci: %s: command %02x failed, TFD %02x\n", p->disk.model, cmd, rd(p, P_TFD) & 0xff); + wr(p, P_CMD, rd(p, P_CMD) & ~CMD_ST); /* recover the port */ + wait_reg(p, P_CMD, CMD_CR, 0, 500); + wr(p, P_SERR, 0xffffffffu); + wr(p, P_IS, 0xffffffffu); + wr(p, P_CMD, rd(p, P_CMD) | CMD_ST); + return write ? 0x03 : 0x10; /* write protect / bad CRC-ECC */ + } + if (rd(p, P_CI) & 1) + return 0x80; + return 0; +} + +static int ahci_rw(struct disk *d, uint64_t lba, uint32_t n, const uint32_t *pages, int write) +{ + struct port *p = d->drv; + uint8_t cmd; + + if (!n || n > DISK_MAX_SECTORS || lba + n > d->sectors) + return 0x04; + if (p->lba48) + cmd = write ? ATA_WRITE_DMA_EXT : ATA_READ_DMA_EXT; + else + cmd = write ? ATA_WRITE_DMA : ATA_READ_DMA; + return command(p, cmd, lba, n, pages, n * 512, write); +} + +static int ahci_flush(struct disk *d) +{ + struct port *p = d->drv; + return command(p, p->lba48 ? ATA_FLUSH_EXT : 0xe7, 0, 0, 0, 0, 0); +} + +static void copy_model(char *dst, const uint16_t *id) +{ + int i; + + for (i = 0; i < 20; i++) + { + dst[i * 2] = (char)(id[27 + i] >> 8); + dst[i * 2 + 1] = (char)id[27 + i]; + } + for (i = 40; i > 0 && (dst[i - 1] == ' ' || !dst[i - 1]); i--) + ; + dst[i] = 0; +} + +static void port_init(volatile uint8_t *hba, int n) +{ + struct port *p = &ports[nports]; + uint32_t id_page, ssts; + const uint16_t *id; + + memset(p, 0, sizeof(*p)); + p->regs = hba + 0x100 + n * 0x80; + ssts = rd(p, P_SSTS); + if ((ssts & 0x0f) != 3 || rd(p, P_SIG) != SIG_ATA) + return; /* no device, or ATAPI etc. */ + + /* stop the port, give it our command list and FIS area */ + wr(p, P_CMD, rd(p, P_CMD) & ~CMD_ST); + if (!wait_reg(p, P_CMD, CMD_CR, 0, 500)) + return; + wr(p, P_CMD, rd(p, P_CMD) & ~CMD_FRE); + if (!wait_reg(p, P_CMD, CMD_FR, 0, 500)) + return; + p->clb = page_alloc(); /* 1K list + 256 byte FIS */ + p->ctba = page_alloc(); + id_page = page_alloc(); + if (!p->clb || !p->ctba || !id_page) + return; + p->fb = p->clb + 0x400; + wr(p, P_CLB, p->clb); + wr(p, P_CLBU, 0); + wr(p, P_FB, p->fb); + wr(p, P_FBU, 0); + wr(p, P_IE, 0); + wr(p, P_SERR, 0xffffffffu); + wr(p, P_IS, 0xffffffffu); + wr(p, P_CMD, rd(p, P_CMD) | CMD_FRE | CMD_SUD | CMD_POD); + if (!wait_reg(p, P_TFD, TFD_BSY | TFD_DRQ, 0, 2000)) + return; + wr(p, P_CMD, rd(p, P_CMD) | CMD_ST); + + p->disk.drv = p; + p->disk.rw = ahci_rw; + p->disk.flush = ahci_flush; + memcpy(p->disk.model, "SATA disk", 10); + if (command(p, ATA_IDENTIFY, 0, 0, &id_page, 512, 0)) + return; + id = pool_ptr(id_page); + copy_model(p->disk.model, id); + p->lba48 = (id[83] & 0x0400) != 0; + if (p->lba48) + p->disk.sectors = (uint64_t)id[100] | (uint64_t)id[101] << 16 | + (uint64_t)id[102] << 32 | (uint64_t)id[103] << 48; + else + p->disk.sectors = (uint32_t)id[60] | (uint32_t)id[61] << 16; + page_free(id_page); + if (!p->disk.sectors) + return; + kprintf("ahci: port %d: %s, %u MB%s\n", n, p->disk.model, + (uint32_t)(p->disk.sectors >> 11), p->lba48 ? ", LBA48" : ""); + nports++; + disk_register(&p->disk); +} + +static void found(int bus, int dev, int fn) +{ + uint64_t abar = pci_bar(bus, dev, fn, 0x24); + volatile uint8_t *hba; + uint32_t pi; + int n; + + if (!abar) + return; + pci_enable(bus, dev, fn); + hba = mmio_map(abar, 0x1100); + if (!hba) + return; + *(volatile uint32_t *)(hba + HBA_GHC) |= GHC_AE; + *(volatile uint32_t *)(hba + HBA_GHC) &= ~2u; /* no interrupts */ + pi = *(volatile uint32_t *)(hba + HBA_PI); + kprintf("ahci: controller %02x:%02x.%x, version %x, ports %08x\n", bus, dev, fn, + *(volatile uint32_t *)(hba + HBA_VS), pi); + for (n = 0; n < 32 && nports < MAX_DISKS; n++) + if (pi & (1u << n)) + port_init(hba, n); +} + +void ahci_init(void) +{ + pci_scan(0x010601, found); /* mass storage, SATA, AHCI 1.0 */ +} diff --git a/mdvmm/core/apic.c b/mdvmm/core/apic.c new file mode 100644 index 00000000..6ec9e1ef --- /dev/null +++ b/mdvmm/core/apic.c @@ -0,0 +1,175 @@ +/* MDVMM core - interrupt routing after a UEFI boot + * + * DOS wants the PC/AT arrangement: the 8254 timer on IRQ0 of the 8259 + * PICs, their INTR line going to the CPU. UEFI firmware does not have to + * leave the machine that way: + * - the local APIC must pass the PIC's INTR through (LINT0 = ExtINT, + * "virtual wire" mode) and should not raise interrupts of its own + * - an I/O APIC with enabled entries would deliver the same IRQs a + * second time, on vectors nobody handles + * - an HPET in "legacy replacement" mode takes IRQ0 away from the 8254 + * apic_setup() puts all that right and logs what it found; timer_selftest() + * then checks that a timer tick really arrives, so a machine where it does + * not shows a message instead of a silent hang. + */ +#include "core.h" + +#define LAPIC_ID 0x020 +#define LAPIC_VER 0x030 +#define LAPIC_TPR 0x080 +#define LAPIC_SVR 0x0f0 +#define LAPIC_LVT_CMCI 0x2f0 +#define LAPIC_LVT_TIMER 0x320 +#define LAPIC_LVT_THERM 0x330 +#define LAPIC_LVT_PERF 0x340 +#define LAPIC_LINT0 0x350 +#define LAPIC_LINT1 0x360 +#define LAPIC_LVT_ERR 0x370 +#define LVT_MASKED 0x10000u + +static volatile uint32_t *lapic; + +static uint64_t rdmsr(uint32_t msr) +{ + uint32_t lo, hi; + __asm__ volatile("rdmsr" : "=a"(lo), "=d"(hi) : "c"(msr)); + return (uint64_t)hi << 32 | lo; +} + +static uint32_t lr(uint32_t reg) +{ + return lapic[reg / 4]; +} + +static void lw(uint32_t reg, uint32_t v) +{ + lapic[reg / 4] = v; +} + +void apic_setup(void) +{ + uint32_t a, b, c, d; + uint64_t base; + volatile uint32_t *io, *hpet; + + __asm__ volatile("cpuid" : "=a"(a), "=b"(b), "=c"(c), "=d"(d) : "a"(1), "c"(0)); + (void)a; (void)b; (void)c; + if (!(d & (1u << 9))) + kprintf("apic: no local APIC\n"); + else + { + base = rdmsr(0x1b); + if (!(base & 0x800)) + kprintf("apic: local APIC disabled (base %08x): the PIC drives the CPU directly\n", + (uint32_t)base); + else if (base & 0x400) + kprintf("apic: x2APIC mode, left alone\n"); + else if ((lapic = mmio_map(base & 0xfffff000ull, 0x1000))) + { + uint32_t maxlvt = (lr(LAPIC_VER) >> 16) & 0xff; + kprintf("apic: local APIC at %08x: SVR %x LINT0 %x LINT1 %x timer %x TPR %x\n", + (uint32_t)(base & 0xfffff000u), lr(LAPIC_SVR), lr(LAPIC_LINT0), lr(LAPIC_LINT1), + lr(LAPIC_LVT_TIMER), lr(LAPIC_TPR)); + lw(LAPIC_LVT_TIMER, LVT_MASKED); + lw(LAPIC_LVT_ERR, LVT_MASKED); + if (maxlvt >= 4) + lw(LAPIC_LVT_PERF, LVT_MASKED); + if (maxlvt >= 5) + lw(LAPIC_LVT_THERM, LVT_MASKED); + if (maxlvt >= 6) + lw(LAPIC_LVT_CMCI, LVT_MASKED); + lw(LAPIC_TPR, 0); + lw(LAPIC_LINT0, 0x700); /* ExtINT: the 8259's INTR */ + lw(LAPIC_LINT1, 0x400); /* NMI */ + lw(LAPIC_SVR, 0x1ff); /* enabled, spurious vector FFh */ + kprintf("apic: virtual wire mode set (LINT0 = ExtINT)\n"); + } + } + + /* I/O APIC (FEC00000h on PC chipsets): mask every entry */ + io = mmio_map(0xfec00000ull, 0x1000); + if (io) + { + uint32_t ver, n, i, live = 0; + io[0] = 1; + ver = io[4]; + n = ((ver >> 16) & 0xff) + 1; + if (ver != 0xffffffffu && ver != 0 && n <= 240) + { + for (i = 0; i < n; i++) + { + uint32_t lo; + io[0] = 0x10 + i * 2; + lo = io[4]; + if (!(lo & LVT_MASKED)) + { + live++; + io[0] = 0x10 + i * 2; + io[4] = lo | LVT_MASKED; + } + } + kprintf("apic: I/O APIC with %u entries, %u were enabled (now masked)\n", n, live); + } + else + kprintf("apic: no I/O APIC at FEC00000\n"); + } + + /* HPET (FED00000h): the 8254 must own IRQ0 */ + hpet = mmio_map(0xfed00000ull, 0x1000); + if (hpet) + { + uint32_t cap = hpet[0], cfg; + if (cap != 0xffffffffu && cap != 0 && (cap >> 16) != 0xffff) + { + cfg = hpet[0x10 / 4]; + if (cfg & 2) + { + hpet[0x10 / 4] = cfg & ~2u; + kprintf("hpet: legacy replacement mode was on (config %x): turned off\n", cfg); + } + else + kprintf("hpet: present, config %x (the 8254 has IRQ0)\n", cfg); + } + else + kprintf("hpet: none at FED00000\n"); + } +} + +/* does a timer tick reach the PIC, and then the CPU? */ +void timer_selftest(void) +{ + uint8_t mask = inb(0x21); + uint32_t spin; + int pic, cpu = 0; + + pic = pit_wait(2); + if (!pic) + { + kprintf("timer: FAILED - the 8254 raises no IRQ0 at the PIC (IRR %02x, mask %02x)\n", + (outb(0x20, 0x0a), inb(0x20)), mask); + return; + } + /* now with interrupts on: the handler notes IRQ0 as pending */ + vm1.pending &= ~1u; + outb(0x21, 0xfe); + __asm__ volatile("sti"); + for (spin = 0; spin < 3000000 && !(vm1.pending & 1); spin++) + inb(0x21); + __asm__ volatile("cli"); + cpu = (vm1.pending & 1) != 0; + if (cpu) + { + outb(0x20, 0x60); /* end of that interrupt */ + vm1.pending &= ~1u; + } + outb(0x21, mask); + if (cpu) + kprintf("timer: ok - the 8254 ticks and its interrupt reaches the CPU\n"); + else + { + kprintf("timer: FAILED - IRQ0 is raised at the PIC but no interrupt reaches the CPU\n"); + if (lapic) + kprintf("timer: local APIC SVR %x LINT0 %x TPR %x ISR0 %x IRR0 %x\n", lr(LAPIC_SVR), + lr(LAPIC_LINT0), lr(LAPIC_TPR), lr(0x100), lr(0x200)); + } +} diff --git a/mdvmm/core/bios.c b/mdvmm/core/bios.c new file mode 100644 index 00000000..25813b74 --- /dev/null +++ b/mdvmm/core/bios.c @@ -0,0 +1,1467 @@ +/* MDVMM core - virtual PC BIOS for UEFI boot + * + * A UEFI machine has no PC BIOS, but DOS does all its hardware access + * through one. The monitor provides it: rom.asm is mapped at F000:0000 + * and its interrupt vectors are HLT breakpoints that land here. + * - INT 10h: 80x25 text mode on a RAM screen, drawn on the GOP + * framebuffer by fbcon.c (and mirrored to COM1 when present); VBE 3.0 + * with one linear framebuffer mode, the GOP mode itself + * - INT 13h: the boot disk image the UEFI loader read from the ESP, + * as floppy drive 00h; hard disks 80h+ from native drivers (AHCI, NVMe), + * with the EDD extensions (41h-48h) + * - INT 16h / IRQ1: PS/2 keyboard, scancode set 1; USB keyboards on + * xHCI controllers (xhci.c, usbkbd.c) arrive as PS/2 scancodes + * - INT 1Ah / IRQ0: PIT ticks, RTC + * - INT 15h: extended memory (E820h/E801h/88h) for an XMS driver: the + * loader's region, seen by DOS at 1MB (HMA first); see ext_phys() + * - INT 11h, 12h, 14h, 17h, 18h, 19h: the usual small things + * After setting up the IVT and BIOS data area, the boot sector of the + * disk image is started at 0000:7C00, as a BIOS would. + */ +#include "core.h" + + +/* addresses in the ROM table, order of rom.asm */ +enum rom_id { + R_INT10, R_INT11, R_INT12, R_INT13, R_INT14, R_INT15, R_INT16, R_INT17, + R_INT18, R_INT19, R_INT1A, R_IRQ0_BP, R_IRQ1_BP, R_INT16_WAIT, + R_DPT, R_CONFIG, R_STUB_BP, R_STUB_ENTRY, R_STUB_PSP, R_STUB_RETF, + R_IRQ0, R_IRQ1, R_IRQ_MASTER, R_IRQ_SLAVE, R_IRET, + R_VBE_OEM, R_VBE_VENDOR, R_VBE_PRODUCT, R_VBE_REV, R_VBE_MODES, + R_INT33, + R_COUNT +}; + +extern const uint8_t rom_image[], rom_image_end[]; + +static uint16_t rom[R_COUNT]; +static int active; +static uint8_t *rd; /* disk image */ +static uint32_t rd_sectors, rd_spt, rd_heads, rd_cyls; +static uint8_t disk_status; +static int has_serial; + +/* BIOS data area */ +#define BDA8(o) (*(volatile uint8_t *)(0x400 + (o))) +#define BDA16(o) (*(volatile uint16_t *)(0x400 + (o))) +#define BDA32(o) (*(volatile uint32_t *)(0x400 + (o))) + +static void set_flag(struct frame *f, uint32_t flag, int on) +{ + if (on) + f->eflags |= flag; + else + f->eflags &= ~flag; +} + +static void set_vec(int v, uint16_t seg, uint16_t off) +{ + ((uint16_t *)0)[v * 2] = off; + ((uint16_t *)0)[v * 2 + 1] = seg; +} + +/* ---------------------------------------------------------------- */ +/* extended memory */ + +/* DOS extended memory address (as an XMS driver or DPMI client sees it) + -> physical address. On UEFI boots DOS sees the loader's region at + 1MB; 0 if the address is outside it. Identity on DOS boots. */ +uint32_t ext_phys(uint32_t a) +{ + if (boot.boot_type != BOOT_UEFI) + return a; + if (a < 0x100000 || a - 0x100000 >= boot.xms_size) + return 0; + return boot.xms_phys + (a - 0x100000); +} + +static void e820(struct frame *f) +{ + struct entry { uint64_t base, len; uint32_t type; } __attribute__((packed)) e[3]; + uint32_t conv = BDA16(0x13) * 1024u, n = 0, i = f->ebx; + + e[n].base = 0, e[n].len = conv, e[n++].type = 1; + e[n].base = conv, e[n].len = 0x100000 - conv, e[n++].type = 2; + if (boot.xms_size) + e[n].base = 0x100000, e[n].len = boot.xms_size, e[n++].type = 1; + if (f->edx != 0x534d4150 || i >= n || (f->ecx & 0xffff) < 20) + { + AH(f) = 0x86; + set_flag(f, EFL_CF, 1); + return; + } + memcpy(rm_ptr(f->es, DI(f)), &e[i], 20); + f->eax = 0x534d4150; + f->ecx = 20; + f->ebx = i + 1 < n ? i + 1 : 0; + set_flag(f, EFL_CF, 0); +} + +/* ---------------------------------------------------------------- */ +/* serial mirror of the console (COM1, if there is a UART) */ + +void serial_putc(uint8_t c) +{ + int i; + + if (!has_serial) + return; + for (i = 0; i < 100000 && !(inb(0x3fd) & 0x20); i++) + ; + outb(0x3f8, c); +} + +static void serial_init(void) +{ + outb(0x3ff, 0x5a); + if (inb(0x3ff) != 0x5a) + return; + outb(0x3f9, 0); /* no interrupts */ + outb(0x3fb, 0x80); + outb(0x3f8, 1); /* 115200 baud */ + outb(0x3f9, 0); + outb(0x3fb, 0x03); /* 8N1 */ + outb(0x3fc, 0x03); + has_serial = 1; +} + +/* ---------------------------------------------------------------- */ +/* INT 10h: text mode video */ + +#define COLS 80 +#define ROWS 25 + +static uint16_t *cell(int page, int row, int col) +{ + return (uint16_t *)(0xb8000 + (page & 7) * 0x1000 + (row * COLS + col) * 2); +} + +static void get_cursor(int page, int *row, int *col) +{ + uint16_t pos = BDA16(0x50 + (page & 7) * 2); + *row = pos >> 8; + *col = pos & 0xff; +} + +static void set_cursor(int page, int row, int col) +{ + BDA16(0x50 + (page & 7) * 2) = (uint16_t)(row << 8 | col); +} + +static void scroll(int page, int n, uint8_t attr, int top, int left, int bottom, int right, int up) +{ + int r, c, lines; + + if (right >= COLS) + right = COLS - 1; + if (bottom >= ROWS) + bottom = ROWS - 1; + if (top > bottom || left > right) + return; + lines = bottom - top + 1; + if (n == 0 || n > lines) + n = lines; + for (r = 0; r < lines; r++) + { + int dst = up ? top + r : bottom - r; + int src = up ? dst + n : dst - n; + for (c = left; c <= right; c++) + *cell(page, dst, c) = r < lines - n ? *cell(page, src, c) : (uint16_t)(attr << 8 | ' '); + } +} + +/* write a character at the cursor and advance; attr < 0 keeps the cell's */ +static void put_tty(int page, uint8_t ch, int attr) +{ + int row, col; + + serial_putc(ch); + get_cursor(page, &row, &col); + switch (ch) + { + case 7: + return; + case 8: + if (col) + col--; + break; + case 10: + row++; + break; + case 13: + col = 0; + break; + default: + { + uint16_t *c = cell(page, row, col); + *c = (uint16_t)((attr < 0 ? *c & 0xff00 : attr << 8) | ch); + if (++col >= COLS) + { + col = 0; + row++; + } + } + } + if (row >= ROWS) + { + scroll(page, 1, *cell(page, ROWS - 1, 0) >> 8, 0, 0, ROWS - 1, COLS - 1, 1); + row = ROWS - 1; + } + set_cursor(page, row, col); +} + +static void set_mode(uint8_t mode) +{ + int i; + + if ((mode & 0x7f) != 3 && (mode & 0x7f) != 2) + kprintf("bios: video mode %02x not supported, using 3\n", mode); + BDA8(0x49) = 3; + BDA16(0x4a) = COLS; + BDA16(0x4c) = 0x1000; + BDA16(0x4e) = 0; + BDA8(0x62) = 0; + BDA8(0x84) = ROWS - 1; + BDA16(0x85) = 16; + BDA16(0x60) = 0x0d0e; + for (i = 0; i < 8; i++) + BDA16(0x50 + i * 2) = 0; + if (!(mode & 0x80)) + for (i = 0; i < 0x4000; i++) + ((uint16_t *)0xb8000)[i] = 0x0720; +} + +/* ---------------------------------------------------------------- */ +/* INT 10h AH=4Fh: VBE 3.0 with one mode, the GOP framebuffer */ + +#define VBE_MODE 0x141 /* rom.asm */ + +static int gfx_mode; /* the framebuffer belongs to a program */ + +static void vbe_info(struct frame *f) +{ + uint8_t *b = rm_ptr(f->es, DI(f)); + int vbe2 = memcmp(b, "VBE2", 4) == 0; + + memset(b, 0, vbe2 ? 512 : 256); + memcpy(b, "VESA", 4); + *(uint16_t *)(b + 4) = 0x0300; + *(uint32_t *)(b + 6) = (uint32_t)ROM_SEG << 16 | rom[R_VBE_OEM]; + *(uint32_t *)(b + 10) = 0; /* capabilities: fixed DAC, VGA compatible */ + *(uint32_t *)(b + 14) = (uint32_t)ROM_SEG << 16 | rom[R_VBE_MODES]; + *(uint16_t *)(b + 18) = (uint16_t)(boot.fb_size >> 16); + if (vbe2) + { + *(uint16_t *)(b + 20) = 0x0100; + *(uint32_t *)(b + 22) = (uint32_t)ROM_SEG << 16 | rom[R_VBE_VENDOR]; + *(uint32_t *)(b + 26) = (uint32_t)ROM_SEG << 16 | rom[R_VBE_PRODUCT]; + *(uint32_t *)(b + 30) = (uint32_t)ROM_SEG << 16 | rom[R_VBE_REV]; + } +} + +static void vbe_mode_info(struct frame *f) +{ + uint8_t *b = rm_ptr(f->es, DI(f)); + uint32_t pitch = boot.fb_pitch * 4; + int rgb = boot.fb_format == FB_RGBX; + + memset(b, 0, 256); + *(uint16_t *)b = 0xfb; /* supported, color, graphics, LFB only */ + *(uint16_t *)(b + 0x10) = (uint16_t)pitch; + *(uint16_t *)(b + 0x12) = (uint16_t)boot.fb_width; + *(uint16_t *)(b + 0x14) = (uint16_t)boot.fb_height; + b[0x16] = 8; + b[0x17] = 16; + b[0x18] = 1; /* planes */ + b[0x19] = 32; /* bits per pixel */ + b[0x1a] = 1; /* banks */ + b[0x1b] = 6; /* direct color */ + b[0x1e] = 1; + b[0x1f] = 8; b[0x20] = rgb ? 0 : 16; /* red */ + b[0x21] = 8; b[0x22] = 8; /* green */ + b[0x23] = 8; b[0x24] = rgb ? 16 : 0; /* blue */ + b[0x25] = 8; b[0x26] = 24; /* reserved */ + *(uint32_t *)(b + 0x28) = boot.fb_phys; + *(uint16_t *)(b + 0x32) = (uint16_t)pitch; + b[0x36] = 8; b[0x37] = rgb ? 0 : 16; + b[0x38] = 8; b[0x39] = 8; + b[0x3a] = 8; b[0x3b] = rgb ? 16 : 0; + b[0x3c] = 8; b[0x3d] = 24; +} + +static void graphics(int on) +{ + /* a session in the background (a terminal window, a remote shell) only + changes its own screen memory, not the display */ + if (!vm_has_focus()) + return; + if (on == gfx_mode) + return; + gfx_mode = on; + fbcon_graphics(on); +} + +/* a program ends: if it left the display in mode 13h, text mode again (the + prompt would not show) */ +void bios_program_end(void) +{ + if (!vga_active() || !vm_has_focus()) + return; + vga_leave(); + set_mode(3); + graphics(0); +} + +static void vbe(struct frame *f) +{ + uint16_t mode; + uint8_t fn = AL(f); + + AX(f) = 0x014f; /* failed */ + if (!boot.fb_phys) + return; + switch (fn) + { + case 0x00: + vbe_info(f); + break; + case 0x01: + if ((CX(f) & 0x1ff) != VBE_MODE) + return; + vbe_mode_info(f); + break; + case 0x02: + mode = BX(f) & 0x1ff; + vga_leave(); + if (mode == VBE_MODE) + { + graphics(1); + if (!(BX(f) & 0x8000)) + fbcon_clear(); + } + else if (mode == 0x03 || mode == 0x02) + { + set_mode((uint8_t)(mode | (BX(f) & 0x8000 ? 0x80 : 0))); + graphics(0); + } + else + return; + break; + case 0x03: + BX(f) = gfx_mode ? VBE_MODE | 0x4000 : BDA8(0x49); + break; + case 0x06: /* scan line length: get only */ + if (BL(f) != 1) + return; + BX(f) = (uint16_t)(boot.fb_pitch * 4); + CX(f) = (uint16_t)boot.fb_pitch; + DX(f) = (uint16_t)boot.fb_height; + break; + case 0x07: /* display start: 0,0 only */ + if (BL(f) == 1) + CX(f) = DX(f) = 0; + else if (BL(f) == 0 || BL(f) == 0x80) + { + if (CX(f) || DX(f)) + return; + } + else + return; + break; + default: + return; + } + AX(f) = 0x004f; +} + +static void int10(struct frame *f) +{ + int page = BH(f) & 7, row, col, i; + + if (AH(f) != 0x00 && AH(f) != 0x0f && AH(f) != 0x4f && vga_int10(f)) + return; + switch (AH(f)) + { + case 0x00: + if (vm_has_focus() && vga_enter(AL(f) & 0x7f, AL(f) & 0x80)) + { + /* a graphics mode: the monitor is the display card (vga.c) */ + int mode = AL(f) & 0x7f, lines = mode == 0x12 ? 480 : mode == 0x10 ? 350 : 200; + int height = lines == 200 ? 8 : lines == 350 ? 14 : 16; + graphics(1); + BDA8(0x49) = (uint8_t)mode; + BDA16(0x4a) = mode == 0x0d || mode == 0x13 ? 40 : 80; + BDA16(0x4c) = mode == 0x13 || mode == 0x0d ? 0x2000 : mode == 0x0e ? 0x4000 : 0xa000; + BDA16(0x4e) = 0; + BDA8(0x62) = 0; + BDA8(0x84) = (uint8_t)(lines / height - 1); + BDA16(0x85) = (uint16_t)height; + for (i = 0; i < 8; i++) + BDA16(0x50 + i * 2) = 0; + AL(f) = 0x20; + break; + } + vga_leave(); + set_mode(AL(f)); + graphics(0); + AL(f) = 0x30; + break; + case 0x01: + BDA16(0x60) = CX(f); + break; + case 0x02: + set_cursor(page, DH(f), DL(f)); + break; + case 0x03: + get_cursor(page, &row, &col); + DX(f) = (uint16_t)(row << 8 | col); + CX(f) = BDA16(0x60); + break; + case 0x05: + BDA8(0x62) = AL(f) & 7; + BDA16(0x4e) = (AL(f) & 7) * 0x1000; + break; + case 0x06: + case 0x07: + scroll(BDA8(0x62), AL(f), BH(f), CH(f), CL(f), DH(f), DL(f), AH(f) == 6); + break; + case 0x08: + get_cursor(page, &row, &col); + AX(f) = *cell(page, row, col); + break; + case 0x09: + case 0x0a: + get_cursor(page, &row, &col); + for (i = 0; i < CX(f) && row * COLS + col + i < ROWS * COLS; i++) + { + uint16_t *p = cell(page, row, col + i); /* wraps to next rows */ + *p = AH(f) == 9 ? (uint16_t)(BL(f) << 8 | AL(f)) : (uint16_t)((*p & 0xff00) | AL(f)); + } + if (CX(f) == 1) + serial_putc(AL(f)); + break; + case 0x0e: + put_tty(BDA8(0x62), AL(f), -1); + break; + case 0x0f: + AL(f) = BDA8(0x49); + AH(f) = (uint8_t)BDA16(0x4a); + BH(f) = BDA8(0x62); + break; + case 0x11: + if (AL(f) == 0x30) + { + CX(f) = 16; + DL(f) = ROWS - 1; + f->es = 0; + *(uint16_t *)&f->ebp = 0; + } + break; + case 0x12: + if (BL(f) == 0x10) + { + BX(f) = 0x0003; /* color, 256K */ + CX(f) = 0x0009; + } + break; + case 0x13: /* write string */ + { + const uint8_t *str = rm_ptr(f->es, 0) + *(uint16_t *)&f->ebp; + get_cursor(page, &row, &col); + set_cursor(page, DH(f), DL(f)); + for (i = 0; i < CX(f); i++) + { + uint8_t ch = *str++; + int attr = BL(f); + if (AL(f) & 2) + attr = *str++; + put_tty(page, ch, attr); + } + if (!(AL(f) & 1)) + set_cursor(page, row, col); + break; + } + case 0x1a: + if (AL(f) == 0) + { + AL(f) = 0x1a; + BX(f) = 0x0008; /* VGA, color */ + } + break; + case 0x4f: + vbe(f); + break; + } +} + +/* ---------------------------------------------------------------- */ +/* keyboard */ + +/* scancode set 1 -> ASCII, 0x00-0x39 */ +static const char kb_norm[] = + "\0\0331234567890-=\b\tqwertyuiop[]\r\0asdfghjkl;'`\0\\zxcvbnm,./\0*\0 "; +static const char kb_shift[] = + "\0\033!@#$%^&*()_+\b\0QWERTYUIOP{}\r\0ASDFGHJKL:\"~\0|ZXCVBNM<>?\0*\0 "; + +#define KF_RSHIFT 0x01 +#define KF_LSHIFT 0x02 +#define KF_CTRL 0x04 +#define KF_ALT 0x08 +#define KF_SCROLL 0x10 +#define KF_NUM 0x20 +#define KF_CAPS 0x40 +#define KF_INS 0x80 + +static int kb_e0; + +static void kb_put(uint16_t key) +{ + uint16_t tail = BDA16(0x1c), next = tail + 2; + + if (next >= BDA16(0x82)) + next = BDA16(0x80); + if (next == BDA16(0x1a)) + return; /* full */ + *(uint16_t *)(0x400 + tail) = key; + BDA16(0x1c) = next; +} + +static void __attribute__((noreturn)) reboot(void) +{ + kprintf("bios: reboot\n"); + outb(0xcf9, 0x02); + outb(0xcf9, 0x06); + outb(0x64, 0xfe); + for (;;) + __asm__ volatile("cli; hlt"); +} + +static void kbd_scancode(uint8_t sc) +{ + uint8_t flags = BDA8(0x17), code = sc & 0x7f; + int up = sc & 0x80, e0 = kb_e0, shift, ctrl, alt; + uint8_t ascii = 0, scan = code; + + kb_e0 = 0; + if (sc == 0xe0 || sc == 0xe1) + { + kb_e0 = sc == 0xe0; + return; + } + switch (code) /* modifiers and locks */ + { + case 0x2a: + case 0x36: + if (e0) + return; /* fake shifts around gray keys */ + if (up) + flags &= ~(code == 0x2a ? KF_LSHIFT : KF_RSHIFT); + else + flags |= code == 0x2a ? KF_LSHIFT : KF_RSHIFT; + BDA8(0x17) = flags; + return; + case 0x1d: + BDA8(0x17) = up ? flags & ~KF_CTRL : flags | KF_CTRL; + return; + case 0x38: + BDA8(0x17) = up ? flags & ~KF_ALT : flags | KF_ALT; + return; + case 0x3a: + if (!up) + BDA8(0x17) = flags ^ KF_CAPS; + return; + case 0x45: + if (!up) + BDA8(0x17) = flags ^ KF_NUM; + return; + case 0x46: + if (!up && !e0) + BDA8(0x17) = flags ^ KF_SCROLL; + if (!up && e0 && (flags & KF_CTRL)) /* Ctrl+Break */ + { + BDA8(0x71) |= 0x80; + kb_put(0); + } + return; + } + if (up) + return; + + shift = flags & (KF_LSHIFT | KF_RSHIFT); + ctrl = flags & KF_CTRL; + alt = flags & KF_ALT; + + if (ctrl && alt && code == 0x53) + reboot(); + + if (e0) + { + if (code == 0x1c) /* keypad Enter */ + ascii = ctrl ? 10 : 13, scan = 0xe0; + else if (code == 0x35) /* keypad / */ + ascii = '/', scan = 0xe0; + else if (code >= 0x47 && code <= 0x53) + { + static const uint8_t ctrl_nav[13] = { 0x77, 0x8d, 0x84, 0, 0x73, 0, 0x74, 0, 0x75, 0x91, 0x76, 0x92, 0x93 }; + ascii = 0xe0; + if (ctrl && ctrl_nav[code - 0x47]) + scan = ctrl_nav[code - 0x47]; + else if (alt) + scan = code + 0x50, ascii = 0; + } + else + return; + kb_put((uint16_t)(scan << 8 | ascii)); + return; + } + + if (code == 0x52 && !(flags & KF_NUM) && !shift) + BDA8(0x17) ^= KF_INS; + + if (code >= 0x3b && code <= 0x44) /* F1-F10 */ + scan = alt ? code + 0x2d : ctrl ? code + 0x23 : shift ? code + 0x19 : code; + else if (code == 0x57 || code == 0x58) /* F11, F12 */ + scan = (uint8_t)((code == 0x57 ? 0x85 : 0x86) + (alt ? 6 : ctrl ? 4 : shift ? 2 : 0)); + else if (code >= 0x47 && code <= 0x53) /* keypad */ + { + static const char digits[] = "789-456+1230."; + if (code == 0x4a || code == 0x4e) + ascii = digits[code - 0x47]; + else if (((flags & KF_NUM) != 0) != (shift != 0)) + ascii = digits[code - 0x47]; + else if (ctrl) + { + static const uint8_t ctrl_nav[13] = { 0x77, 0x8d, 0x84, 0, 0x73, 0x8f, 0x74, 0, 0x75, 0x91, 0x76, 0x92, 0x93 }; + if (ctrl_nav[code - 0x47]) + scan = ctrl_nav[code - 0x47]; + } + } + else if (code < sizeof(kb_norm) - 1) + { + char n = kb_norm[code], s = kb_shift[code]; + int letter = n >= 'a' && n <= 'z'; + if (alt) + { + if (code >= 0x02 && code <= 0x0d) + scan = code + 0x76; /* Alt+1..= : 78h-83h */ + else if (!letter && code != 0x39 && code != 0x0e && code != 0x1c) + return; + } + else if (ctrl) + { + if (letter) + ascii = (uint8_t)(n - 'a' + 1); + else + switch (code) + { + case 0x01: ascii = 0x1b; break; + case 0x03: scan = 0x03; break; /* Ctrl+2: NUL */ + case 0x07: ascii = 0x1e; break; + case 0x0c: ascii = 0x1f; break; + case 0x0e: ascii = 0x7f; break; + case 0x0f: scan = 0x94; break; + case 0x1a: ascii = 0x1b; break; + case 0x1b: ascii = 0x1d; break; + case 0x1c: ascii = 0x0a; break; + case 0x2b: ascii = 0x1c; break; + case 0x39: ascii = ' '; break; + default: return; + } + } + else + { + int up_case = (shift != 0) != (letter && (flags & KF_CAPS)); + ascii = (uint8_t)(letter ? (up_case ? s : n) : shift ? s : n); + } + } + else + return; + kb_put((uint16_t)(scan << 8 | ascii)); +} + +static void int16(struct frame *f) +{ + uint16_t head = BDA16(0x1a), key; + int ext = AH(f) & 0x10; + + xhci_poll(); /* a key may be waiting */ + uhci_poll(); + switch (AH(f)) + { + case 0x00: + case 0x10: + if (head == BDA16(0x1c)) + { + f->eip = rom[R_INT16_WAIT]; /* idle until a key arrives */ + return; + } + key = *(uint16_t *)(0x400 + head); + head += 2; + if (head >= BDA16(0x82)) + head = BDA16(0x80); + BDA16(0x1a) = head; + if (!ext && (key & 0xff) == 0xe0 && key >> 8) + key &= 0xff00; + AX(f) = key; + break; + case 0x01: + case 0x11: + if (head == BDA16(0x1c)) + { + set_flag(f, EFL_ZF, 1); /* (no yield: DOS polls this on + every call for Ctrl+C) */ + break; + } + key = *(uint16_t *)(0x400 + head); + if (!ext && (key & 0xff) == 0xe0 && key >> 8) + key &= 0xff00; + AX(f) = key; + set_flag(f, EFL_ZF, 0); + break; + case 0x02: + AL(f) = BDA8(0x17); + break; + case 0x12: + AL(f) = BDA8(0x17); + AH(f) = BDA8(0x18); + break; + case 0x05: + { + uint16_t tail = BDA16(0x1c); + kb_put(CX(f)); + AL(f) = BDA16(0x1c) == tail; + break; + } + } + f->eip++; /* continue at RETF 2 */ +} + +/* ---------------------------------------------------------------- */ +/* INT 13h: hard disks 80h+ (native drivers: ahci.c, nvme.c) */ + +#define MAX_HD 8 +#define HD_HEADS 255 +#define HD_SPT 63 +#define STAGE_PAGES (DISK_MAX_SECTORS * 512 / 4096) + +static struct disk *hds[MAX_HD]; +static int nhd; +static uint8_t hd_status; +static uint32_t stage[STAGE_PAGES]; /* pool pages for transfers */ + +/* DOS knows MBR partition tables only. For a disk with a GUID partition + table (GPT: every UEFI machine's system disk) it gets a made-up MBR that + lists the disk's FAT partitions (up to four; the EFI system partition is + one), so they become DOS drives. The real sector 0 is not written. */ +static void gpt_probe(struct disk *d) +{ + uint8_t *s = pool_ptr(stage[0]), *mbr; + uint32_t entries, esize, i, found = 0; + uint64_t elba; + + d->mbr = 0; + if (d->rw(d, 0, 2, stage, 0) || memcmp(s + 512, "EFI PART", 8)) + return; + elba = *(uint64_t *)(s + 512 + 72); + entries = *(uint32_t *)(s + 512 + 80); + esize = *(uint32_t *)(s + 512 + 84); + if (esize < 128 || esize > 512 || 512 % esize || entries > 128) + return; + { + uint32_t page = page_alloc(); + if (!page) + return; + mbr = pool_ptr(page); + } + memset(mbr, 0, 512); + mbr[510] = 0x55; + mbr[511] = 0xaa; + for (i = 0; i < entries && found < 4; i++) + { + uint8_t e[512], type = 0; + uint64_t first, last, size; + uint32_t k; + const uint8_t *b; + + if (i % (512 / esize) == 0 && d->rw(d, elba + i / (512 / esize), 1, stage, 0)) + break; + memcpy(e, s + (i % (512 / esize)) * esize, esize); + for (k = 0; k < 16 && !e[k]; k++) + ; + if (k == 16) + continue; /* unused entry */ + first = *(uint64_t *)(e + 32); + last = *(uint64_t *)(e + 40); + size = last - first + 1; + if (last < first || last >= d->sectors || (first >> 32) || (size >> 32)) + continue; + /* a FAT file system? (its boot sector says) */ + if (d->rw(d, first, 1, stage + 1, 0)) + continue; + b = pool_ptr(stage[1]); + if (b[510] != 0x55 || b[511] != 0xaa) + continue; + if (!memcmp(b + 0x52, "FAT32", 5)) + type = 0x0c; + else if (!memcmp(b + 0x36, "FAT16", 5)) + type = size >= 65536 ? 0x0e : 0x04; + else if (!memcmp(b + 0x36, "FAT12", 5)) + type = 0x01; + else + continue; + b = mbr + 446 + found * 16; + ((uint8_t *)b)[1] = 0xfe; /* CHS: use the LBA fields */ + ((uint8_t *)b)[2] = 0xff; + ((uint8_t *)b)[3] = 0xff; + ((uint8_t *)b)[4] = type; + ((uint8_t *)b)[5] = 0xfe; + ((uint8_t *)b)[6] = 0xff; + ((uint8_t *)b)[7] = 0xff; + *(uint32_t *)(b + 8) = (uint32_t)first; + *(uint32_t *)(b + 12) = (uint32_t)size; + kprintf("bios: GPT partition %u: FAT%s, %u MB at sector %u\n", i + 1, + type == 0x0c ? "32" : type == 0x01 ? "12" : "16", (uint32_t)(size >> 11), (uint32_t)first); + found++; + } + d->mbr = mbr; + if (!found) + kprintf("bios: GPT without FAT partitions: no DOS drives on this disk\n"); +} + +void disk_register(struct disk *d) +{ + int i; + + if (nhd == MAX_HD) + return; + if (!stage[0]) + for (i = 0; i < STAGE_PAGES; i++) + if (!(stage[i] = page_alloc())) + panic("bios: out of memory"); + hds[nhd] = d; + kprintf("bios: hard disk %02xh: %s\n", 0x80 + nhd, d->model); + nhd++; + gpt_probe(d); +} + +static uint32_t hd_cyls(struct disk *d) +{ + uint32_t c; + + if (d->sectors >= 1024ull * HD_HEADS * HD_SPT) + return 1024; + c = (uint32_t)d->sectors / (HD_HEADS * HD_SPT); + return c ? c : 1; +} + +/* move n sectors between the disk and V86 memory at buf; *done = count */ +static int hd_transfer(struct disk *d, uint64_t lba, uint32_t n, uint8_t *buf, int write, uint32_t *done) +{ + int err = 0; + + *done = 0; + if (write && !(boot.flags & BOOTF_DISK_WRITE)) + return 0x03; /* write protected */ + if (write && d->mbr && lba == 0) + return 0x03; /* the made-up MBR of a GPT disk */ + while (n && !err) + { + uint32_t k = n > DISK_MAX_SECTORS ? DISK_MAX_SECTORS : n, i, bytes = k * 512; + + if (write) + for (i = 0; i < bytes; i += 4096) + memcpy(pool_ptr(stage[i / 4096]), buf + i, bytes - i < 4096 ? bytes - i : 4096); + err = d->rw(d, lba, k, stage, write); + if (err) + break; + if (!write) + for (i = 0; i < bytes; i += 4096) + memcpy(buf + i, pool_ptr(stage[i / 4096]), bytes - i < 4096 ? bytes - i : 4096); + if (!write && d->mbr && lba == 0) + memcpy(buf, d->mbr, 512); /* GPT disk: sector 0 for DOS */ + lba += k; + buf += bytes; + n -= k; + *done += k; + } + return err; +} + +static void int13_hd(struct frame *f) +{ + int idx = DL(f) - 0x80, err = 0; + struct disk *d = idx < nhd ? hds[idx] : 0; + uint32_t done; + + if (!d) + { + if (AH(f) == 0x15) + { + AH(f) = 0; /* no such drive */ + set_flag(f, EFL_CF, 0); + return; + } + if (AH(f) == 0x08) + DL(f) = (uint8_t)nhd; + AH(f) = 0x01; + set_flag(f, EFL_CF, 1); + return; + } + switch (AH(f)) + { + case 0x00: + case 0x0d: /* reset: commit the write cache */ + if (d->flush) + err = d->flush(d); + break; + case 0x04: case 0x0c: case 0x10: + case 0x11: case 0x14: case 0x44: case 0x47: + break; /* verify, seek, ready */ + case 0x01: + AH(f) = hd_status; + set_flag(f, EFL_CF, hd_status != 0); + return; + case 0x02: + case 0x03: + { + uint32_t cyl = CH(f) | (uint32_t)(CL(f) & 0xc0) << 2, sec = CL(f) & 0x3f; + if (!sec || sec > HD_SPT || !AL(f)) + { + err = 0x04; + AL(f) = 0; + break; + } + err = hd_transfer(d, ((uint64_t)cyl * HD_HEADS + DH(f)) * HD_SPT + sec - 1, AL(f), + rm_ptr(f->es, 0) + BX(f), AH(f) == 0x03, &done); + AL(f) = (uint8_t)done; + break; + } + case 0x08: + { + uint32_t c = hd_cyls(d) - 1; + AX(f) = 0; + BL(f) = 0; + CH(f) = c & 0xff; + CL(f) = (uint8_t)(HD_SPT | (c >> 2 & 0xc0)); + DH(f) = HD_HEADS - 1; + DL(f) = (uint8_t)nhd; + break; + } + case 0x15: + CX(f) = (uint16_t)((d->sectors > 0xffffffffu ? 0xffffffffu : d->sectors) >> 16); + DX(f) = (uint16_t)(d->sectors > 0xffffffffu ? 0xffffffffu : d->sectors); + AH(f) = 0x03; /* fixed disk */ + set_flag(f, EFL_CF, 0); + return; + case 0x41: + if (BX(f) != 0x55aa) + { + err = 0x01; + break; + } + BX(f) = 0xaa55; + CX(f) = 0x0001; /* extended disk access */ + AH(f) = 0x21; /* EDD 1.1 */ + set_flag(f, EFL_CF, 0); + return; + case 0x42: + case 0x43: + { + uint8_t *dap = rm_ptr(f->ds, SI(f)); + uint16_t *count = (uint16_t *)(dap + 2); + uint16_t off = *(uint16_t *)(dap + 4), seg = *(uint16_t *)(dap + 6); + if (dap[0] < 0x10 || (seg == 0xffff && off == 0xffff)) + { + err = 0x01; /* (no 64-bit flat buffers) */ + break; + } + err = hd_transfer(d, *(uint64_t *)(dap + 8), *count, rm_ptr(seg, 0) + off, + AH(f) == 0x43, &done); + *count = (uint16_t)done; + break; + } + case 0x48: + { + uint8_t *b = rm_ptr(f->ds, SI(f)); + uint16_t size = *(uint16_t *)b; + if (size < 0x1a) + { + err = 0x01; + break; + } + size = size >= 0x1e ? 0x1e : 0x1a; + memset(b, 0, size); + *(uint16_t *)b = size; + *(uint16_t *)(b + 2) = 0x0002; /* CHS information valid */ + *(uint32_t *)(b + 4) = hd_cyls(d); + *(uint32_t *)(b + 8) = HD_HEADS; + *(uint32_t *)(b + 12) = HD_SPT; + *(uint64_t *)(b + 16) = d->sectors; + *(uint16_t *)(b + 24) = 512; + if (size == 0x1e) + *(uint32_t *)(b + 26) = 0xffffffffu; + break; + } + default: + err = 0x01; + } + hd_status = (uint8_t)err; + AH(f) = (uint8_t)err; + set_flag(f, EFL_CF, err != 0); +} + +/* ---------------------------------------------------------------- */ +/* INT 13h: boot disk image as floppy drive 00h */ + +static void int13(struct frame *f) +{ + uint8_t drive = DL(f); + int err = 0; + + if (drive >= 0x80) + { + int13_hd(f); + return; + } + if (drive != 0 || !rd) + { + AH(f) = 0x01; /* no such floppy drive */ + set_flag(f, EFL_CF, 1); + return; + } + switch (AH(f)) + { + case 0x00: + break; + case 0x01: + AH(f) = disk_status; + set_flag(f, EFL_CF, disk_status != 0); + return; + case 0x02: + case 0x03: + case 0x04: + { + uint32_t cyl = CH(f) | (uint32_t)(CL(f) & 0xc0) << 2; + uint32_t sec = CL(f) & 0x3f, head = DH(f), n = AL(f), i; + uint32_t lba = (cyl * rd_heads + head) * rd_spt + sec - 1; + uint8_t *buf = rm_ptr(f->es, 0) + BX(f); + + if (!sec || sec > rd_spt || head >= rd_heads || !n || lba + n > rd_sectors) + { + err = 0x04; /* sector not found */ + AL(f) = 0; + break; + } + for (i = 0; i < n && AH(f) != 0x04; i++) + if (AH(f) == 0x02) + memcpy(buf + i * 512, rd + (lba + i) * 512, 512); + else + memcpy(rd + (lba + i) * 512, buf + i * 512, 512); + break; + } + case 0x05: + break; + case 0x08: + { + uint32_t c = rd_cyls - 1; + AX(f) = 0; + BL(f) = rd_sectors >= 5760 ? 6 : rd_sectors >= 2880 ? 4 : rd_sectors >= 2400 ? 2 : rd_sectors >= 1440 ? 3 : 1; + CH(f) = c & 0xff; + CL(f) = (uint8_t)(rd_spt | (c >> 2 & 0xc0)); + DH(f) = (uint8_t)(rd_heads - 1); + DL(f) = 1; + f->es = ROM_SEG; + DI(f) = rom[R_DPT]; + break; + } + case 0x15: + AH(f) = 0x01; /* floppy, no change line */ + set_flag(f, EFL_CF, 0); + return; + case 0x16: + break; /* not changed */ + case 0x17: + case 0x18: + f->es = ROM_SEG; + DI(f) = rom[R_DPT]; + break; + default: + err = 0x01; + } + disk_status = (uint8_t)err; + AH(f) = (uint8_t)err; + set_flag(f, EFL_CF, err != 0); +} + +static void disk_init(void) +{ + uint32_t i, pages = (boot.ramdisk_size + 4095) / 4096; + const uint8_t *bpb; + uint32_t total; + + if (!boot.ramdisk_phys || !boot.ramdisk_size || boot.ramdisk_size > RD_MAX) + { + kprintf("bios: no boot disk image\n"); + return; + } + for (i = 0; i < pages; i++) + if (!map_page(RD_VIRT + i * 4096, boot.ramdisk_phys + i * 4096, 3)) + panic("bios: cannot map the disk image"); + rd = (uint8_t *)RD_VIRT; + bpb = rd; + total = *(const uint16_t *)(bpb + 0x13); + if (!total) + total = *(const uint32_t *)(bpb + 0x20); + rd_spt = *(const uint16_t *)(bpb + 0x18); + rd_heads = *(const uint16_t *)(bpb + 0x1a); + if (*(const uint16_t *)(bpb + 0x0b) != 512 || !rd_spt || rd_spt > 63 || !rd_heads || rd_heads > 255) + { + rd_spt = 18; /* no BPB: assume 1.44 MB */ + rd_heads = 2; + total = 2880; + } + if (total > boot.ramdisk_size / 512) + total = boot.ramdisk_size / 512; + rd_sectors = total; + rd_cyls = (total + rd_spt * rd_heads - 1) / (rd_spt * rd_heads); + kprintf("bios: disk image %u KB, %u/%u/%u (CHS)\n", boot.ramdisk_size / 1024, + rd_cyls, rd_heads, rd_spt); +} + +/* ---------------------------------------------------------------- */ +/* time */ + +static uint8_t cmos(uint8_t reg) +{ + outb(0x70, reg); + return inb(0x71); +} + +static void int1a(struct frame *f) +{ + int i; + + set_flag(f, EFL_CF, 0); + switch (AH(f)) + { + case 0x00: + CX(f) = (uint16_t)(BDA32(0x6c) >> 16); + DX(f) = (uint16_t)BDA32(0x6c); + AL(f) = BDA8(0x70); + BDA8(0x70) = 0; + break; + case 0x01: + BDA32(0x6c) = (uint32_t)CX(f) << 16 | DX(f); + BDA8(0x70) = 0; + break; + case 0x02: + case 0x04: + for (i = 0; i < 100000 && (cmos(0x0a) & 0x80); i++) + ; + if (AH(f) == 2) + { + CH(f) = cmos(0x04); + CL(f) = cmos(0x02); + DH(f) = cmos(0x00); + DL(f) = 0; + } + else + { + CH(f) = cmos(0x32); + if (CH(f) < 0x19 || CH(f) > 0x21) + CH(f) = 0x20; + CL(f) = cmos(0x09); + DH(f) = cmos(0x08); + DL(f) = cmos(0x07); + } + break; + case 0x03: + case 0x05: + break; /* the monitor keeps the RTC */ + default: + set_flag(f, EFL_CF, 1); + } +} + +/* ---------------------------------------------------------------- */ + +static void int15(struct frame *f) +{ + set_flag(f, EFL_CF, 0); + switch (AH(f)) + { + case 0x4f: /* keyboard intercept: keep key */ + set_flag(f, EFL_CF, 1); + return; + case 0x24: /* A20: always on */ + if (AL(f) == 0x02) + AL(f) = 1; + else if (AL(f) == 0x03) + BX(f) = 0x0003; + AH(f) = 0; + return; + case 0x86: /* wait CX:DX microseconds */ + case 0x90: + case 0x91: + AH(f) = 0; + return; + case 0x88: /* KB above 1MB */ + AX(f) = boot.xms_size / 1024 > 0xffff ? 0xffff : (uint16_t)(boot.xms_size / 1024); + return; + case 0xe8: + if (AL(f) == 0x01) /* KB 1-16MB, 64K blocks above */ + { + uint32_t kb = boot.xms_size / 1024; + AX(f) = CX(f) = (uint16_t)(kb > 15 * 1024 ? 15 * 1024 : kb); + BX(f) = DX(f) = (uint16_t)(kb > 15 * 1024 ? (kb - 15 * 1024) / 64 : 0); + return; + } + if (AL(f) == 0x20) + { + e820(f); + return; + } + break; + case 0xc0: + f->es = ROM_SEG; + BX(f) = rom[R_CONFIG]; + AH(f) = 0; + return; + } + AH(f) = 0x86; /* not supported */ + set_flag(f, EFL_CF, 1); +} + +/* INT 2Fh AX=DE07h: install the mouse driver (INT 33h). DOS resets + INT 23h-3Fh while it starts, so this is done afterwards, like loading + a mouse driver (MDVMM.COM calls it). AX = 1 if installed. */ +int bios_mouse_install(void) +{ + if (!active) + return 0; + set_vec(0x33, ROM_SEG, rom[R_INT33]); + kprintf("bios: mouse driver installed (INT 33h)\n"); + return 1; +} + +/* HLT in the ROM: returns 1 if it was a BIOS breakpoint */ +int bios_bp(struct frame *f, uint16_t ip) +{ + int id; + uint16_t *stack; + + if (!active || f->cs != ROM_SEG) + return 0; + if (ip == rom[R_INT33]) + { + int33(f); + id = R_INT33; + f->eip++; /* continue at RETF 2 */ + goto done; + } + for (id = 0; id <= R_IRQ1_BP && rom[id] != ip; id++) + ; + if (id > R_IRQ1_BP) + return 0; + + if (id == R_IRQ0_BP) /* timer tick */ + { + if (++BDA32(0x6c) >= 0x1800b0) + { + BDA32(0x6c) = 0; + BDA8(0x70) = 1; + } + xhci_poll(); /* USB keyboards */ + uhci_poll(); + /* a trial boot that nobody confirms within ten minutes: back to the + installed system */ + if ((boot.flags & BOOTF_TRIAL) && !trial_confirmed) + { + /* by the clock: every DOS session has its timer ticks */ + static uint32_t trial_start; + static int trial_over; + uint32_t now = mdvmm_ms(); /* 0: the clock is not set up yet */ + if (now && !trial_start) + trial_start = now; + if (trial_start && !trial_over && now > trial_start && + now - trial_start >= (boot.flags & BOOTF_TRIAL_FAST ? 120000u : 600000u)) + { + trial_over = 1; + kprintf("trial boot: not confirmed in time, restarting (%u s after the start)\n", + (unsigned)(mdvmm_ms() / 1000)); + machine_reset(); + } + } + usbkbd_tick(); + fbcon_update(); + vga_tick(); + f->eip++; + return 1; + } + if (id == R_IRQ1_BP) + { + kbd_scancode(AL(f)); + f->eip++; + return 1; + } + + switch (id) + { + case R_INT10: int10(f); break; + case R_INT11: AX(f) = BDA16(0x10); break; + case R_INT12: AX(f) = BDA16(0x13); break; + case R_INT13: int13(f); break; + case R_INT14: AH(f) = 0x80; break; /* timeout: no ports */ + case R_INT15: int15(f); break; + case R_INT16: int16(f); goto done; /* sets IP itself */ + case R_INT17: AH(f) = 0x01; break; /* timeout */ + case R_INT18: panic("bios: no bootable disk (INT 18h)"); + case R_INT19: reboot(); + case R_INT1A: int1a(f); break; + } + f->eip++; /* continue at RETF 2 */ +done: + /* a BIOS service runs with interrupts as the caller had them */ + stack = rm_ptr(f->ss, (uint16_t)f->esp); + if (f->eip == (uint32_t)ip + 1) + vm1.vif = (stack[2] & EFL_IF) != 0; + if (vm1.vif) + v86_deliver(f); + return 1; +} + +/* ---------------------------------------------------------------- */ + +void bios_init(void) +{ + uint32_t size = (uint32_t)(rom_image_end - rom_image), p, i; + const uint16_t *hdr = (const uint16_t *)(rom_image + 4); + uint32_t conv = boot.conv_kb; + + if (size > 0xfff0 || *(const uint32_t *)rom_image != 0x5242444d || hdr[0] != R_COUNT) + panic("bios: bad ROM image"); + for (i = 0; i < R_COUNT; i++) + rom[i] = hdr[1 + i]; + + /* ROM at F0000h and the text screen at B8000h: RAM from the pool */ + for (p = 0; p < 16; p++) + { + uint32_t page = page_alloc(); + if (!page || !map_page(0xf0000 + p * 4096, page, 7)) + panic("bios: out of memory"); + } + memcpy((void *)0xf0000, rom_image, size); + { + static const uint8_t tail[16] = { + 0xea, 0, 0, 0x00, 0xf0, /* FFF0: JMP F000:INT 19h */ + '1', '1', '/', '2', '2', '/', '2', '6', /* FFF5: BIOS date */ + 0, 0xfc, 0 /* FFFE: model byte AT */ + }; + memcpy((void *)0xffff0, tail, 16); + *(uint16_t *)0xffff1 = rom[R_INT19]; + } + for (p = 0; p < VRAM_PAGES; p++) + { + vram_phys[p] = page_alloc(); + if (!vram_phys[p] || !map_page(0xb8000 + p * 4096, vram_phys[p], 7)) + panic("bios: out of memory"); + } + /* HMA: the first 64K of the extended memory region */ + for (p = 0; p < 16; p++) + { + uint32_t page = boot.xms_size >= 0x10000 ? boot.xms_phys + p * 4096 : page_alloc(); + if (!page || !map_page(0x100000 + p * 4096, page, 7)) + panic("bios: out of memory"); + } + boot.stub_seg = ROM_SEG; + boot.stub_bp = rom[R_STUB_BP]; + boot.stub_entry = rom[R_STUB_ENTRY]; + boot.stub_psp = rom[R_STUB_PSP]; + boot.stub_retf = rom[R_STUB_RETF]; + + /* interrupt vectors */ + memset((void *)0, 0, 0x600); + for (i = 0; i < 0x20; i++) + set_vec(i, ROM_SEG, rom[R_IRET]); + for (i = 0; i < 8; i++) + { + set_vec(0x08 + i, ROM_SEG, rom[R_IRQ_MASTER]); + set_vec(0x70 + i, ROM_SEG, rom[R_IRQ_SLAVE]); + } + set_vec(0x08, ROM_SEG, rom[R_IRQ0]); + set_vec(0x09, ROM_SEG, rom[R_IRQ1]); + for (i = R_INT10; i <= R_INT1A; i++) + set_vec(0x10 + i, ROM_SEG, rom[i]); + set_vec(0x1d, 0, 0); + set_vec(0x1e, ROM_SEG, rom[R_DPT]); + set_vec(0x1f, 0, 0); + set_vec(0x40, ROM_SEG, rom[R_INT13]); + set_vec(0x4a, ROM_SEG, rom[R_IRET]); + + /* BIOS data area */ + if (!conv || conv > 640) + conv = 640; + BDA16(0x10) = 0x0021 | 0x0002; /* 1 floppy, 80x25 color, FPU */ + BDA16(0x13) = (uint16_t)conv; + BDA16(0x1a) = BDA16(0x1c) = 0x1e; /* keyboard buffer */ + BDA16(0x80) = 0x1e; + BDA16(0x82) = 0x3e; + BDA8(0x17) = KF_NUM; + BDA8(0x96) = 0x10; /* 101 key keyboard */ + BDA16(0x63) = 0x3d4; + BDA8(0x65) = 0x29; + BDA8(0x87) = 0x60; + BDA8(0x88) = 0x09; + BDA8(0x89) = 0x11; + BDA16(0x72) = 0x1234; /* warm boot */ + set_mode(3); + + /* timer: PIT channel 0, 18.2 Hz; only timer, keyboard, cascade */ + outb(0x43, 0x36); + outb(0x40, 0); + outb(0x40, 0); + outb(0x21, 0xf8); + outb(0xa1, 0xff); + for (i = 0; i < 32 && inb(0x64) != 0xff && (inb(0x64) & 1); i++) + inb(0x60); /* drain the keyboard controller (Macs + have none: the status reads FFh) */ + apic_setup(); /* PIC interrupts to the CPU, 8254 on IRQ0 */ + timer_selftest(); + nic_init(); /* network cards (their clock needs the timer) */ + + serial_init(); + disk_init(); + ahci_init(); + nvme_init(); + xhci_init(); + uhci_init(); + BDA8(0x75) = (uint8_t)nhd; /* number of hard disks */ + if (nhd) + kprintf("bios: hard disks are %s\n", boot.flags & BOOTF_DISK_WRITE ? "writable" : + "read-only (no \\MDOS\\DISKRW on the boot volume)"); + active = 1; + + /* boot: the disk image's boot sector at 0000:7C00, DL = drive */ + if (!rd || rd[510] != 0x55 || rd[511] != 0xaa) + panic("bios: disk image is not bootable"); + memcpy((void *)0x7c00, rd, 512); + boot.cs = 0; + boot.ip = 0x7c00; + boot.ss = 0; + boot.sp = 0x7c00; + boot.ds = boot.es = boot.fs = boot.gs = 0; + boot.eflags = EFL_IF; + kprintf("bios: %u KB conventional memory, %u KB extended at %08x, booting the disk image\n", + conv, boot.xms_size / 1024, boot.xms_phys); + if (boot.flags & BOOTF_TRIAL) + kprintf("bios: TRIAL boot: restart in ten minutes unless confirmed (MDSYS KEEP)\n"); + + /* the log leaves the screen; \MDOS\BOOTWAIT keeps it for a while + (to read or photograph it on a machine that does not get further) */ + if (boot.flags & BOOTF_LOG_PAUSE) + { + kprintf("bios: the log stays on the screen for 15 seconds (\\MDOS\\BOOTWAIT)\n"); + pit_wait(273); + } + fbcon_text(); +} diff --git a/mdvmm/core/core.h b/mdvmm/core/core.h new file mode 100644 index 00000000..b11c8d67 --- /dev/null +++ b/mdvmm/core/core.h @@ -0,0 +1,304 @@ +/* MDVMM core - shared definitions */ +#ifndef MDVMM_CORE_H +#define MDVMM_CORE_H + +#include +#include +#include +#include "bootinfo.h" + +/* Linear address space of the monitor: + * 00000000-0010FFFF V86 machine (DOS), user + * 00400000-BEFFFFFF DPMI client memory (dpmi.c CLIENT_BASE/END) + * C0000000-DEFFFFFF DPMI 0800h physical mappings (PHYSMAP_BASE/END) + * E0000000-E0FFFFFF DPMI host code page and stacks (HOST_AREA) + * E1000000-E7FFFFFF UEFI framebuffer (FB_VIRT) + * E8000000-EBFFFFFF UEFI boot disk image (RD_VIRT) + * EC000000-EDFFFFFF device registers (MMIO_VIRT, pci.c) + * EE000000-EE3FFFFF DOS session instance data (vm.c INST_BASE) + * EE800000-EEFFFFFF DPMI clients that wait for one they started (dpmi.c NEST_AREA) + * EF000000-EF03FFFF the planes of the monitor's VGA (vga.c PLANES_VIRT) + * EFC00000-EFFFFFFF temporary physical windows (mm.c KMAP_BASE) + * F0000000- the core and its pool (KBASE) + * FFC00000-FFFFFFFF page tables (recursive mapping) + */ +#define KBASE 0xF0000000u +#define FB_VIRT 0xE1000000u +#define FB_MAX 0x07000000u +#define RD_VIRT 0xE8000000u +#define RD_MAX 0x04000000u +#define MMIO_VIRT 0xEC000000u +#define MMIO_MAX 0x02000000u +#define KCODE 0x08 +#define KDATA 0x10 +#define TSS_SEL 0x18 +#define LDT_SEL 0x20 +#define HCODE_SEL 0x2b /* ring 3 host code (PM breakpoints) */ +#define HDATA_SEL 0x33 /* ring 3 host data (host PM stacks) */ +#define ESPFIX_SEL 0x38 /* ring 0 alias stack for IRET to 16 bit SS */ +#define BDA_SEL 0x40 /* ring 3 data: the BIOS data area (0040h) */ + +#define EFL_CF 0x00000001u +#define EFL_ZF 0x00000040u +#define EFL_TF 0x00000100u +#define EFL_IF 0x00000200u +#define EFL_OF 0x00000800u +#define EFL_IOPL 0x00003000u +#define EFL_NT 0x00004000u +#define EFL_RF 0x00010000u +#define EFL_VM 0x00020000u +#define EFL_AC 0x00040000u +#define EFL_ID 0x00200000u +/* flags a V86 program may change directly */ +#define EFL_USER 0x00000DD5u /* CF PF AF ZF SF TF DF OF */ + +/* Trap frame, built by isr_common (entry.asm). esp/ss are only present for + * traps from ring 3 or V86, es/ds/fs/gs only for traps from V86 mode + * (never touch them for other frames: they lie above the stack). */ +struct frame { + uint32_t pgs, pfs, pes, pds; /* PM segment regs */ + uint32_t edi, esi, ebp, esp_k, ebx, edx, ecx, eax; /* pushad */ + uint32_t vector, err; + uint32_t eip, cs, eflags; + uint32_t esp, ss; + uint32_t es, ds, fs, gs; +}; + +/* 16 bit register views */ +#define AX(f) (*(uint16_t *)&(f)->eax) +#define BX(f) (*(uint16_t *)&(f)->ebx) +#define CX(f) (*(uint16_t *)&(f)->ecx) +#define DX(f) (*(uint16_t *)&(f)->edx) +#define SI(f) (*(uint16_t *)&(f)->esi) +#define DI(f) (*(uint16_t *)&(f)->edi) +#define AL(f) (*(uint8_t *)&(f)->eax) +#define AH(f) (*((uint8_t *)&(f)->eax + 1)) +#define BL(f) (*(uint8_t *)&(f)->ebx) +#define BH(f) (*((uint8_t *)&(f)->ebx + 1)) +#define CL(f) (*(uint8_t *)&(f)->ecx) +#define CH(f) (*((uint8_t *)&(f)->ecx + 1)) +#define DL(f) (*(uint8_t *)&(f)->edx) +#define DH(f) (*((uint8_t *)&(f)->edx + 1)) + +static inline void outb(uint16_t p, uint8_t v) { __asm__ volatile("outb %0,%1" :: "a"(v), "Nd"(p)); } +static inline void outw(uint16_t p, uint16_t v) { __asm__ volatile("outw %0,%1" :: "a"(v), "Nd"(p)); } +static inline void outl(uint16_t p, uint32_t v) { __asm__ volatile("outl %0,%1" :: "a"(v), "Nd"(p)); } +static inline uint8_t inb(uint16_t p) { uint8_t v; __asm__ volatile("inb %1,%0" : "=a"(v) : "Nd"(p)); return v; } +static inline uint16_t inw(uint16_t p) { uint16_t v; __asm__ volatile("inw %1,%0" : "=a"(v) : "Nd"(p)); return v; } +static inline uint32_t inl(uint16_t p) { uint32_t v; __asm__ volatile("inl %1,%0" : "=a"(v) : "Nd"(p)); return v; } +static inline void invlpg(uint32_t v) { __asm__ volatile("invlpg (%0)" :: "r"(v) : "memory"); } +static inline uint32_t read_cr2(void) { uint32_t v; __asm__ volatile("mov %%cr2,%0" : "=r"(v)); return v; } + +/* real mode / V86 address helpers (first 1MB+64K is identity mapped) */ +static inline void *rm_ptr(uint32_t seg, uint32_t off) { return (void *)((seg << 4) + (off & 0xffff)); } + +/* lib.c */ +void *memcpy(void *d, const void *s, size_t n); +void *memset(void *d, int c, size_t n); +int memcmp(const void *a, const void *b, size_t n); +size_t strlen(const char *s); +void kvprintf(const char *fmt, va_list ap); +void kprintf(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +void panic(const char *fmt, ...) __attribute__((noreturn, format(printf, 1, 2))); +void panic_frame(struct frame *f, const char *why) __attribute__((noreturn)); + +/* mm.c */ +extern struct bootinfo boot; +void mm_init(uint32_t free_phys); +uint32_t page_alloc(void); /* 0 if none */ +uint32_t page_alloc_isa(uint32_t size); +void page_free(uint32_t phys); +uint32_t pages_free(void); +uint32_t pages_total(void); +int map_page(uint32_t lin, uint32_t phys, uint32_t flags); +int map_large_mmio(uint32_t lin, uint64_t phys); +uint32_t unmap_page(uint32_t lin); +uint32_t lin_to_pte(uint32_t lin); +void *kmap(int slot, uint32_t phys); +void *pool_ptr(uint32_t phys); /* pool page, mapped at KBASE */ +void phys_copy(uint32_t dst, uint32_t src, uint32_t len); + +/* cpu.c */ +void cpu_init(void); +void io_trap(uint16_t port, int trap); +void gdt_set(int i, uint32_t base, uint32_t limit, uint8_t access, uint8_t gran); +void ldt_load(void *base, uint32_t entries); +const void *gdt_entry(uint16_t sel); + +/* v86.c */ +struct vm { + uint32_t vif; /* virtual interrupt flag */ + uint32_t vflags; /* virtual IOPL/NT bits */ + uint32_t pending; /* pending IRQ bitmap */ +}; +extern struct vm vm1; +void v86_start(void); +void v86_exception(struct frame *f); +void v86_irq(struct frame *f, int irq); +void v86_reflect(struct frame *f, uint8_t vec); +void v86_deliver(struct frame *f); +int v86_intercept(struct frame *f, uint8_t vec); +void v86_push16(struct frame *f, uint16_t v); +uint16_t v86_pop16(struct frame *f); +uint32_t v86_vflags(struct frame *f); + +/* dpmi.c */ +void dpmi_init(void); +void dpmi_detect(struct frame *v); +void dpmi_v86_bp(struct frame *v, int bp); +void dpmi_trap(struct frame *f); +void dpmi_irq(struct frame *f, int irq); +int dpmi_irq_v86(struct frame *v, int irq); +int dpmi_take_pending(struct frame *pm); +void dpmi_rm_exit(void); +int dpmi_active(void); +int dpmi_irq_hooked(int irq); +unsigned long mdvmm_ms(void); /* milliseconds since the start (ipxenic.c) */ +int dpmi_owner(void); +void dpmi_session_switch(int from, int to); +void dpmi_hwirq(struct frame *f, int irq); +#define MAX_SESSIONS 4 +int vm_current(void); +int vm_port60_waiting(void); +int vm_kbd_owned(void); +void vm_kbd_done(void); /* a session's keyboard handler returned */ +void vm_kbd_next(struct frame *f); /* give the session its next keystroke */ +void vm_debug(void); /* the sessions' state to the log */ +int vm_owed_tick(void); +void vm_tick_done(void); +uint32_t vm_ticks(void); /* timer ticks since the start */ +/* vga.c: VGA mode 13h on the UEFI framebuffer (stubs on DOS boots) */ +void bios_program_end(void); +int vga_active(void); +int vga_enter(int mode, int keep); +void vga_leave(void); +void vga_tick(void); +int vga_port_in(uint16_t port, int size, uint32_t *v); +int vga_port_out(uint16_t port, int size, uint32_t v); +int vga_debug(struct frame *f, const uint8_t *code, const uint8_t *esi_byte, int code32); +int vga_fault(struct frame *f, uint32_t addr, int v86, int code32); +uint8_t vga_mem_read(uint32_t off); +void vga_mem_write(uint32_t off, uint8_t v); +int vgaemu(struct frame *f, int v86, int code32); +uint32_t dpmi_sel_base(uint16_t sel); +int dpmi_vga_fault(struct frame *f, uint32_t addr); +int vga_int10(struct frame *f); +int dpmi_vga_debug(struct frame *f); +int vm_vga_blocked(void); +int vm_video_int(struct frame *f); +int vm_bios_call(uint8_t vec); +void vm_bios_done(void); +int vm_key_wait(const struct frame *f); +void v86_reflect_bp(struct frame *f, uint8_t vec, int bp); +void v86_vector_set(int psp, uint8_t vec); +void v86_vectors_end(int psp, int resident); +void v86_bp_return(struct frame *f, int hw); +int vm_has_focus(void); +uint8_t *vm_focus_bda(void); +extern int vm_hold; + +/* vm.c */ +#define VRAM_PAGES 8 +extern uint32_t vram_phys[VRAM_PAGES]; +void vm_tick(struct frame *f); +void vm_poll(struct frame *f); +void vm_yield(struct frame *f); +int vm_kbd(struct frame *f, int inject); +int vm_port60(uint8_t *v); +void vm_key(uint8_t sc); +int dos_current_psp(void); +int vm_key_pending(void); +int vm_api(struct frame *f); +void vm_crit(struct frame *f); + +/* bios.c, fbcon.c (UEFI boot: virtual PC BIOS) */ +#define ROM_SEG 0xF000 +void bios_init(void); +int bios_bp(struct frame *f, uint16_t ip); +int bios_mouse_install(void); +void apic_setup(void); +void timer_selftest(void); +int pit_wait(uint32_t ticks); +void fbcon_init(void); +void fbcon_text(void); +void fbcon_log(char c); +void fbcon_panic(void); +uint32_t fbcon_log_copy(char *dst, uint32_t room, uint32_t lines); +void fbcon_update(void); +void fbcon_graphics(int on); +void fbcon_clear(void); +void serial_putc(uint8_t c); +uint32_t ext_phys(uint32_t a); + +/* pci.c */ +uint32_t pci_read32(int bus, int dev, int fn, int reg); +void pci_write32(int bus, int dev, int fn, int reg, uint32_t v); +void pci_scan(uint32_t cls, void (*found)(int bus, int dev, int fn)); +void pci_enable(int bus, int dev, int fn); +void *mmio_map(uint64_t phys, uint32_t size); +uint64_t pci_bar(int bus, int dev, int fn, int reg); +void udelay(uint32_t us); + +/* hard disks for the virtual BIOS (INT 13h drives 80h+), from native + drivers. rw() moves up to DISK_MAX_SECTORS 512-byte sectors between + the disk and the pages in pages[] (4K each); 0 on success, else an + INT 13h error code. flush() (optional) commits the drive's write + cache; INT 13h disk resets call it. */ +#define DISK_MAX_SECTORS 128 +struct disk { + uint64_t sectors; + char model[41]; + void *drv; + int (*rw)(struct disk *d, uint64_t lba, uint32_t n, const uint32_t *pages, int write); + int (*flush)(struct disk *d); + uint8_t *mbr; /* GPT disk: the MBR DOS gets to see */ +}; +void disk_register(struct disk *d); +void ahci_init(void); +void nvme_init(void); + +/* xhci.c, usbkbd.c: USB keyboards */ +void xhci_init(void); +void xhci_poll(void); +void uhci_init(void); +void uhci_poll(void); +void usbkbd_report(const uint8_t *report); +void usbkbd_tick(void); + +/* mouse.c: INT 33h on UEFI boots */ +void mouse_input(int buttons, int dx, int dy); +int mouse_text_cell(void); +void int33(struct frame *f); + +/* nic.c: network cards (DOS and UEFI boots) */ +struct nic { + const char *name; + uint8_t mac[6]; + int (*send)(struct nic *n, const void *frame, int len); /* 0 ok */ + int (*recv)(struct nic *n, void *frame, int room); /* len, 0 none, -1 dropped */ + int (*link)(struct nic *n); + void (*debug)(struct nic *n); /* optional: its state to the log */ +}; +extern int trial_confirmed; +void machine_reset(void); +void nic_register(struct nic *n); +void nic_init(void); +void nic_api(struct frame *f); +void nic_debug(void); +void ipxenic_init(void); + +/* dma.c */ +void dma_init(void); +int dma_port(uint16_t port); +uint8_t dma_in(uint16_t port); +void dma_out(uint16_t port, uint8_t v); +void dma_irq(void); + +/* entry.asm */ +extern const uint32_t isr_table[256]; +extern uint8_t kstack_top[]; +void gdt_load(void *gdtr); +void enter_frame(const struct frame *f) __attribute__((noreturn)); +_Static_assert(sizeof(struct frame) == 92, "FRAME_SIZE in entry.asm"); + +#endif diff --git a/mdvmm/core/core.ld b/mdvmm/core/core.ld new file mode 100644 index 00000000..d1de4b3f --- /dev/null +++ b/mdvmm/core/core.ld @@ -0,0 +1,21 @@ +/* MDVMM core: linked at KBASE, loaded anywhere (4K aligned) by a loader */ +OUTPUT_FORMAT(elf32-i386) +OUTPUT_ARCH(i386) +ENTRY(_start) + +SECTIONS +{ + . = 0xF0000000; + .text : { *(.text.entry) *(.text*) } + .rodata : { *(.rodata*) } + .data : { *(.data*) } + . = ALIGN(16); + __image_end = .; + .bss (NOLOAD) : { + __bss_start = .; + *(.bss*) *(COMMON) + . = ALIGN(4096); + __bss_end = .; + } + /DISCARD/ : { *(.comment) *(.note*) *(.eh_frame*) } +} diff --git a/mdvmm/core/cpu.c b/mdvmm/core/cpu.c new file mode 100644 index 00000000..7961e5d1 --- /dev/null +++ b/mdvmm/core/cpu.c @@ -0,0 +1,110 @@ +/* MDVMM core - descriptor tables, TSS with I/O permission bitmap, PIC */ +#include "core.h" + +struct tss { + uint32_t link, esp0, ss0, esp1, ss1, esp2, ss2; + uint32_t cr3, eip, eflags, eax, ecx, edx, ebx, esp, ebp, esi, edi; + uint32_t es, cs, ss, ds, fs, gs, ldt; + uint16_t trap, iomap_base; + uint8_t iomap[8192]; + uint8_t iomap_end; /* must be 0xFF */ +} __attribute__((packed)); + +struct gdt_entry { uint16_t limit_lo, base_lo; uint8_t base_mid, access, gran, base_hi; } __attribute__((packed)); +struct idt_entry { uint16_t off_lo, sel; uint8_t zero, type; uint16_t off_hi; } __attribute__((packed)); +struct dtr { uint16_t limit; uint32_t base; } __attribute__((packed)); + +static struct tss tss __attribute__((aligned(16))); +struct gdt_entry gdt_table[9] __attribute__((aligned(16))); +#define gdt gdt_table +static struct idt_entry idt[256] __attribute__((aligned(16))); + +void gdt_set(int i, uint32_t base, uint32_t limit, uint8_t access, uint8_t gran) +{ + gdt[i].limit_lo = limit & 0xffff; + gdt[i].base_lo = base & 0xffff; + gdt[i].base_mid = (base >> 16) & 0xff; + gdt[i].access = access; + gdt[i].gran = (gran & 0xf0) | ((limit >> 16) & 0x0f); + gdt[i].base_hi = base >> 24; +} + +/* load an LDT of `entries` descriptors at linear address base */ +void ldt_load(void *base, uint32_t entries) +{ + gdt_set(LDT_SEL >> 3, (uint32_t)base, entries * 8 - 1, 0x82, 0x00); + __asm__ volatile("lldt %w0" :: "r"(LDT_SEL)); +} + +/* raw descriptor from the GDT, for selector base lookups */ +const void *gdt_entry(uint16_t sel) +{ + return &gdt[sel >> 3]; +} + +void io_trap(uint16_t port, int trap) +{ + if (trap) + tss.iomap[port >> 3] |= 1 << (port & 7); + else + tss.iomap[port >> 3] &= ~(1 << (port & 7)); +} + +/* move the PIC vectors away from the CPU exceptions: IRQ0-15 -> 20h-2Fh */ +static void pic_remap(void) +{ + uint8_t m1 = inb(0x21), m2 = inb(0xa1); + + outb(0x20, 0x11); + outb(0xa0, 0x11); + outb(0x21, 0x20); + outb(0xa1, 0x28); + outb(0x21, 0x04); + outb(0xa1, 0x02); + outb(0x21, 0x01); + outb(0xa1, 0x01); + outb(0x21, m1); + outb(0xa1, m2); +} + +void cpu_init(void) +{ + struct dtr d; + int i; + + gdt_set(0, 0, 0, 0, 0); + gdt_set(1, 0, 0xfffff, 0x9a, 0xc0); /* KCODE */ + gdt_set(2, 0, 0xfffff, 0x92, 0xc0); /* KDATA */ + gdt_set(3, (uint32_t)&tss, sizeof(tss) - 1, 0x89, 0x00); + gdt_set(7, 0, 0xfffff, 0x92, 0xc0); /* ESPFIX_SEL, base set on use */ + d.limit = sizeof(gdt) - 1; + d.base = (uint32_t)gdt; + gdt_load(&d); + + memset(&tss, 0, sizeof(tss)); + tss.ss0 = KDATA; + tss.esp0 = (uint32_t)kstack_top; + tss.iomap_base = offsetof(struct tss, iomap); + tss.iomap_end = 0xff; + __asm__ volatile("ltr %w0" :: "r"(TSS_SEL)); + + /* all gates DPL 0: INT n, INT3, INTO from V86 raise #GP and are emulated */ + for (i = 0; i < 256; i++) + { + idt[i].off_lo = isr_table[i] & 0xffff; + idt[i].off_hi = isr_table[i] >> 16; + idt[i].sel = KCODE; + idt[i].zero = 0; + idt[i].type = 0x8e; + } + d.limit = sizeof(idt) - 1; + d.base = (uint32_t)idt; + __asm__ volatile("lidt %0" :: "m"(d)); + + pic_remap(); + + /* A20 control (keyboard controller, port 92h) must stay with us */ + io_trap(0x60, 1); + io_trap(0x64, 1); + io_trap(0x92, 1); +} diff --git a/mdvmm/core/dma.c b/mdvmm/core/dma.c new file mode 100644 index 00000000..ee11cc45 --- /dev/null +++ b/mdvmm/core/dma.c @@ -0,0 +1,405 @@ +/* MDVMM core - ISA DMA virtualization (8237, both controllers) + * + * DMA controllers work with physical addresses, but V86 memory is paged: + * DOS sessions have private pages below 640K. The monitor keeps a shadow + * of every channel's address, count and page register and programs the + * real controller itself: + * - target identity mapped (session 0, global memory): the guest's + * values, unchanged + * - target physically contiguous, below 16MB, no 64K/128K crossing: + * the translated address + * - otherwise through a bounce buffer below 16MB. Memory->device data + * is copied in when the channel is unmasked; device->memory data is + * copied out at every hardware interrupt (before any handler runs), + * when the channel is masked and when the status register is read. + * The target pages are recorded when the transfer starts, so data + * lands in the right session even after a switch. + * Reads of the current address are translated back to the guest's view. + * Port I/O from DPMI clients (IOPL 3) is not virtualized. + */ +#include "core.h" + +#define NCH 8 +#define BOUNCE_SIZE 0x20000u /* 128K: largest 16 bit transfer */ +#define MAX_PAGES (BOUNCE_SIZE / 4096 + 1) + +#define MODE_TYPE(m) (((m) >> 2) & 3) /* 1: device->memory, 2: memory->device */ +#define MODE_AUTO 0x10 + +#define HAVE_ADDR 1 +#define HAVE_COUNT 2 +#define HAVE_ALL (HAVE_ADDR | HAVE_COUNT) + +struct chan { + uint16_t addr, count; /* guest values */ + uint8_t page, mode; + uint8_t masked, have, page_set; + uint16_t hw_addr; /* address programmed into the 8237 */ + /* bounce transfer */ + uint32_t len, copied, off0; + uint32_t phys[MAX_PAGES]; /* target page frames */ +}; + +static struct chan ch[NCH]; +static uint8_t ff[2]; /* guest view of the flip-flops */ +static uint8_t rd_hi[2]; /* high byte of a 16 bit read */ +static uint32_t bounce; /* physical, 0 if none */ +static int bounce_owner = -1; + +static const uint16_t page_port[NCH] = { 0x87, 0x83, 0x81, 0x82, 0x8f, 0x8b, 0x89, 0x8a }; + +/* controller register ports: r = 0 (status/command) .. 7 (write all mask) */ +static uint16_t reg_port(int ctl, int r) +{ + return ctl ? 0xd0 + r * 2 : 0x08 + r; +} + +static uint16_t addr_port(int c) +{ + return c < 4 ? c * 2 : 0xc0 + (c - 4) * 4; +} + +/* port -> kind: 1 address, 2 count, 3 page, 4 + r controller register; + *c = channel or controller; 0 if not a DMA port */ +static int decode(uint16_t port, int *c) +{ + int i; + + if (port < 0x08) + { + *c = port >> 1; + return 1 + (port & 1); + } + if (port < 0x10) + { + *c = 0; + return 4 + (port - 0x08); + } + if (port >= 0xc0 && port < 0xd0 && !(port & 1)) + { + *c = 4 + ((port - 0xc0) >> 2); + return 1 + ((port >> 1) & 1); + } + if (port >= 0xd0 && port < 0xe0 && !(port & 1)) + { + *c = 1; + return 4 + ((port - 0xd0) >> 1); + } + for (i = 0; i < NCH; i++) + if (port == page_port[i]) + { + *c = i; + return 3; + } + return 0; +} + +int dma_port(uint16_t port) +{ + int c; + return bounce && decode(port, &c); +} + +/* ---------------------------------------------------------------- */ +/* real controller */ + +static void hw_mask(int c, int mask) +{ + outb(reg_port(c >> 2, 2), (mask ? 4 : 0) | (c & 3)); +} + +static uint16_t hw_read16(uint16_t port, int ctl) +{ + uint16_t v; + + outb(reg_port(ctl, 4), 0); /* clear flip-flop */ + v = inb(port); + v |= inb(port) << 8; + return v; +} + +static void hw_write16(uint16_t port, int ctl, uint16_t v) +{ + outb(reg_port(ctl, 4), 0); + outb(port, v & 0xff); + outb(port, v >> 8); +} + +/* ---------------------------------------------------------------- */ +/* bounce buffer */ + +/* copy [a, b) of a bounce transfer; to_guest: bounce -> target pages */ +static void bounce_copy(struct chan *k, uint32_t a, uint32_t b, int to_guest) +{ + while (a < b) + { + uint32_t o = k->off0 + a; + uint32_t n = 4096 - (o & 0xfff); + uint32_t g = k->phys[o >> 12] + (o & 0xfff); + + if (n > b - a) + n = b - a; + if (to_guest) + phys_copy(g, bounce + a, n); + else + phys_copy(bounce + a, g, n); + a += n; + } +} + +/* device->memory: copy what the device has written so far */ +static void bounce_flush(int c) +{ + struct chan *k = &ch[c]; + uint32_t unit = c < 4 ? 1 : 2, done; + uint16_t rem; + + if (MODE_TYPE(k->mode) != 1) + { + /* memory->device, auto-init (sound playback): refresh the buffer */ + if (MODE_TYPE(k->mode) == 2 && (k->mode & MODE_AUTO)) + bounce_copy(k, 0, k->len, 0); + return; + } + rem = hw_read16(addr_port(c) + (c < 4 ? 1 : 2), c >> 2); + done = k->len - (uint32_t)(uint16_t)(rem + 1) * unit; + if (done >= k->copied) + bounce_copy(k, k->copied, done, 1); + else + { + bounce_copy(k, k->copied, k->len, 1); /* auto-init wrapped */ + bounce_copy(k, 0, done, 1); + } + k->copied = done; + if (done == k->len && !(k->mode & MODE_AUTO)) + bounce_owner = -1; /* complete */ +} + +void dma_irq(void) +{ + if (bounce_owner >= 0) + bounce_flush(bounce_owner); +} + +/* ---------------------------------------------------------------- */ + +/* program the real channel from the shadow */ +static void sync(int c) +{ + struct chan *k = &ch[c]; + int wide = c >= 4; + uint32_t lin, len, p, pte0, phys0, ident = 1, contig = 1; + uint32_t boundary = wide ? 0x20000 : 0x10000; + uint16_t hw_count = k->count; + uint8_t hw_page = k->page; + static int logged; + + if ((k->have & HAVE_ALL) != HAVE_ALL || !k->page_set) + { + hw_mask(c, k->masked); /* not programmed since we started */ + return; + } + lin = wide ? ((uint32_t)(k->page & 0xfe) << 16) | ((uint32_t)k->addr << 1) + : ((uint32_t)k->page << 16) | k->addr; + len = ((uint32_t)k->count + 1) * (wide ? 2 : 1); + k->hw_addr = k->addr; + + if (bounce_owner == c) + { + bounce_flush(c); + bounce_owner = -1; + } + + pte0 = lin_to_pte(lin); + phys0 = (pte0 & ~0xfffu) | (lin & 0xfff); + for (p = lin & ~0xfffu; p < lin + len; p += 4096) + { + uint32_t e = lin_to_pte(p); + if (!(e & 1)) + { + ident = 1; /* nothing sensible: leave it raw */ + contig = 1; + phys0 = lin; + break; + } + if ((e & ~0xfffu) != p) + ident = 0; + if ((e & ~0xfffu) != (pte0 & ~0xfffu) + (p - (lin & ~0xfffu))) + contig = 0; + } + + if (!ident) + { + uint32_t phys = phys0; + + if (!contig || phys + len > 0x1000000 || phys / boundary != (phys + len - 1) / boundary) + { + /* bounce */ + if (bounce_owner >= 0 && bounce_owner != c) + { + bounce_flush(bounce_owner); + kprintf("dma: channel %d takes the bounce buffer from %d\n", c, bounce_owner); + } + if (len > BOUNCE_SIZE) + len = BOUNCE_SIZE; + k->len = len; + k->copied = 0; + k->off0 = lin & 0xfff; + for (p = 0; p * 4096 < k->off0 + len; p++) + k->phys[p] = lin_to_pte((lin & ~0xfffu) + p * 4096) & ~0xfffu; + if (MODE_TYPE(k->mode) == 2) + bounce_copy(k, 0, len, 0); + bounce_owner = c; + phys = bounce; + if (!logged) + { + kprintf("dma: channel %d uses the bounce buffer (%u bytes at %05x)\n", c, len, lin); + logged = 1; + } + } + hw_page = (uint8_t)(phys >> 16); + k->hw_addr = wide ? (uint16_t)(phys >> 1) : (uint16_t)phys; + } + + hw_mask(c, 1); + hw_write16(addr_port(c), c >> 2, k->hw_addr); + hw_write16(addr_port(c) + (wide ? 2 : 1), c >> 2, hw_count); + outb(page_port[c], hw_page); + outb(reg_port(c >> 2, 3), k->mode); + if (!k->masked) + hw_mask(c, 0); +} + +static void set_mask(int c, int mask) +{ + if (mask && bounce_owner == c) + bounce_flush(c); + ch[c].masked = (uint8_t)mask; +} + +/* ---------------------------------------------------------------- */ +/* guest port access */ + +uint8_t dma_in(uint16_t port) +{ + int c, kind = decode(port, &c), ctl, i; + uint16_t v; + + switch (kind) + { + case 1: /* current address */ + case 2: /* current count */ + ctl = c >> 2; + if (ff[ctl]) + { + ff[ctl] = 0; + return rd_hi[ctl]; + } + v = hw_read16(port, ctl); + if (kind == 1) + v = (uint16_t)(v - ch[c].hw_addr + ch[c].addr); + ff[ctl] = 1; + rd_hi[ctl] = v >> 8; + return v & 0xff; + case 3: + return ch[c].page_set ? ch[c].page : inb(port); + case 4: /* status: TC bits, flush first */ + for (i = 0; i < 4; i++) + if (bounce_owner == c * 4 + i) + bounce_flush(bounce_owner); + break; + } + return inb(port); +} + +void dma_out(uint16_t port, uint8_t v) +{ + int c, kind = decode(port, &c), i; + struct chan *k; + + switch (kind) + { + case 1: + case 2: + { + int ctl = c >> 2; + uint16_t *r = kind == 1 ? &ch[c].addr : &ch[c].count; + if (ff[ctl]) + *r = (uint16_t)((*r & 0xff) | v << 8); + else + *r = (uint16_t)((*r & 0xff00) | v); + ff[ctl] ^= 1; + ch[c].have |= kind == 1 ? HAVE_ADDR : HAVE_COUNT; + if (!ch[c].masked) + sync(c); + return; + } + case 3: + ch[c].page = v; + ch[c].page_set = 1; + if (!ch[c].masked) + sync(c); + return; + case 4 + 2: /* single mask */ + i = c * 4 + (v & 3); + set_mask(i, v & 4); + if (v & 4) + break; + sync(i); + return; + case 4 + 3: /* mode */ + ch[c * 4 + (v & 3)].mode = v; + break; + case 4 + 4: /* clear flip-flop */ + ff[c] = 0; + return; + case 4 + 5: /* master clear */ + ff[c] = 0; + for (i = c * 4; i < c * 4 + 4; i++) + { + set_mask(i, 1); + if (bounce_owner == i) + bounce_owner = -1; + } + break; + case 4 + 6: /* clear all masks */ + for (i = c * 4; i < c * 4 + 4; i++) + { + set_mask(i, 0); + sync(i); + } + break; + case 4 + 7: /* write all masks */ + for (i = 0; i < 4; i++) + { + k = &ch[c * 4 + i]; + set_mask(c * 4 + i, (v >> i) & 1); + if (!k->masked) + sync(c * 4 + i); + } + break; + } + outb(port, v); +} + +void dma_init(void) +{ + int i; + uint16_t p; + + for (i = 0; i < NCH; i++) + ch[i].masked = i != 4; /* channel 4 cascades */ + bounce = page_alloc_isa(BOUNCE_SIZE); + if (!bounce) + { + kprintf("dma: no memory below 16MB for a bounce buffer\n"); + return; + } + for (p = 0; p < 0x100; p++) + { + int c; + if (decode(p, &c)) + io_trap(p, 1); + } + kprintf("dma: bounce buffer at %08x\n", bounce); +} diff --git a/mdvmm/core/dpmi.c b/mdvmm/core/dpmi.c new file mode 100644 index 00000000..d1cae6f4 --- /dev/null +++ b/mdvmm/core/dpmi.c @@ -0,0 +1,1778 @@ +/* MDVMM core - DPMI 0.9 host + * + * A client per DOS session (16 or 32 bit), and clients it starts in turn + * (a program run by a DPMI program: MAX_NEST deep), at ring 3 with IOPL 3, so + * CLI/STI/IRET act on the real interrupt flag. Transitions between the + * client and real mode are driven by breakpoints: + * V86 side: HLT bytes in the loader's resident stub (BP_* in bootinfo.h) + * PM side: a ring 3 host code page full of HLT (HBP_* below) + * Nested transitions are kept on a small stack of saved frames. + * A client belongs to the DOS session it started in (vm.c); the other + * sessions keep running around it and never see its handlers. The host's + * state below (descriptor table, client, transitions, host stack) is that + * of the running session; dpmi_session_switch() swaps it. Every session's + * client has its own slice of the linear address space, so all clients' + * memory stays mapped. + */ +#include "core.h" + +#define LDT_ENTRIES 1024 +#define HOST_AREA 0xE0000000u /* host code page + host PM stack */ +#define HOST_STACK 0x5000u /* top of host stack (HDATA offset) */ +#define HOST_LEVEL 0x1000u /* stack space per nesting level */ + +#define HBP_EXC_RET 0x000 /* exception handler returned (RETF) */ +#define HBP_IRET 0x001 /* IRQ/callback handler returned (IRET) */ +#define HBP_RAW 0x002 /* raw switch PM -> real mode */ +#define HBP_RETF 0x010 /* RETF: PM state save no-op */ +#define HBP_DEFINT 0x100 /* +vector: default PM int handlers */ +#define HBP_DEFEXC 0x200 /* +exception: default handlers */ + +#define CLIENT_BASE 0x00400000u /* client linear memory */ +#define CLIENT_END 0xBF000000u +#define PHYSMAP_BASE 0xC0000000u /* DPMI 0800h mappings */ +#define PHYSMAP_END 0xDF000000u +/* a session's slice of each */ +#define CLIENT_SLICE (((CLIENT_END - CLIENT_BASE) / MAX_SESSIONS) & ~0x3fffffu) +#define PHYSMAP_SLICE (((PHYSMAP_END - PHYSMAP_BASE) / MAX_SESSIONS) & ~0x3fffffu) +#define HSTACK_PAGES (HOST_STACK / 4096 - 1) + +#define MAX_BLOCKS 128 +#define MAX_CALLBACKS 16 +#define MAX_TRANS 16 + +#define ERR_UNSUPPORTED 0x8001 +#define ERR_DESC 0x8011 /* descriptor unavailable */ +#define ERR_LINEAR 0x8012 +#define ERR_PHYSICAL 0x8013 +#define ERR_CALLBACK 0x8015 +#define ERR_HANDLE 0x8023 +#define ERR_SELECTOR 0x8022 +#define ERR_VALUE 0x8021 + +struct desc { uint16_t limit_lo, base_lo; uint8_t base_mid, access, gran, base_hi; } __attribute__((packed)); +struct farptr { uint32_t off; uint16_t sel; }; +struct block { uint32_t lin, size; }; +struct callback { int used; struct farptr proc, regs; uint16_t stack_sel; }; + +struct rmregs { /* DPMI real mode call structure */ + uint32_t edi, esi, ebp, reserved, ebx, edx, ecx, eax; + uint16_t flags, es, ds, fs, gs, ip, cs, sp, ss; +} __attribute__((packed)); + +enum { + T_PM_INT, /* PM software INT reflected to real mode */ + T_PM_DEFINT, /* client chained to the default PM handler */ + T_PM_IRQ, /* hardware IRQ during PM reflected to RM */ + T_PM_CALL, /* DPMI 0300h-0302h */ + T_PM_DOSMEM, /* DPMI 0100h-0102h */ + T_TO_PM_HANDLER, /* PM IRQ handler running (from PM or V86) */ + T_CALLBACK, /* real mode callback running in PM */ +}; + +struct trans { + struct frame f; /* context to resume */ + int kind; + uint32_t a, b, c; + uint16_t rm_ss, rm_sp; + uint32_t hstack; + int bios; /* a BIOS service call (vm_bios_call) */ +}; + +static struct desc ldt[LDT_ENTRIES] __attribute__((aligned(8))); +static uint8_t ldt_used[LDT_ENTRIES]; + +static struct client { + int active, bits32, session; + uint16_t psp, env_seg, env_sel; + uint16_t rm_ss, rm_sp; /* host real mode stack */ + uint16_t rm_ds; /* segment for default reflection */ + struct farptr pmint[256]; /* sel 0: default */ + struct farptr exc[32]; + struct block blocks[MAX_BLOCKS]; + struct callback cb[MAX_CALLBACKS]; + uint32_t next_lin, next_phys; + uint32_t ivt[256]; /* the real mode vectors when it started */ + uint32_t lin_base, lin_end; /* this client's linear memory */ + uint32_t phys_base, phys_end; /* and its 0800h mappings */ +} cl; + +static struct trans ts[MAX_TRANS]; +static int tsp; +static uint16_t rm_ss_cur, rm_sp_cur; /* real mode stack for host calls */ +static uint32_t hstack_cur = HOST_STACK; + +/* the state of the sessions that are not running */ +static struct saved { + int valid; /* it has a client */ + struct desc ldt[LDT_ENTRIES]; + uint8_t ldt_used[LDT_ENTRIES]; + struct client cl; + struct trans ts[MAX_TRANS]; + int tsp; + uint16_t rm_ss_cur, rm_sp_cur; + uint32_t hstack_cur; +} saved[MAX_SESSIONS]; +static uint32_t hstack_pages[MAX_SESSIONS][HSTACK_PAGES]; + +/* Clients that started another program which became a client itself: they + wait (inside their INT 21h EXEC) until it ends. Kept per session, in + pages taken when needed. */ +#define MAX_NEST 4 +static struct saved *nest[MAX_SESSIONS][MAX_NEST]; +static int nest_depth[MAX_SESSIONS]; +#define NEST_PAGES ((sizeof(struct saved) + 4095) / 4096) +#define NEST_AREA 0xEE800000u /* their linear addresses (core.h) */ + +static void state_save(struct saved *a) +{ + memcpy(a->ldt, ldt, sizeof(ldt)); + memcpy(a->ldt_used, ldt_used, sizeof(ldt_used)); + memcpy(&a->cl, &cl, sizeof(cl)); + memcpy(a->ts, ts, sizeof(ts[0]) * (uint32_t)tsp); + a->tsp = tsp; + a->rm_ss_cur = rm_ss_cur; + a->rm_sp_cur = rm_sp_cur; + a->hstack_cur = hstack_cur; +} + +static void state_load(const struct saved *b) +{ + memcpy(ldt, b->ldt, sizeof(ldt)); + memcpy(ldt_used, b->ldt_used, sizeof(ldt_used)); + memcpy(&cl, &b->cl, sizeof(cl)); + memcpy(ts, b->ts, sizeof(ts[0]) * (uint32_t)b->tsp); + tsp = b->tsp; + rm_ss_cur = b->rm_ss_cur; + rm_sp_cur = b->rm_sp_cur; + hstack_cur = b->hstack_cur; +} + +/* the running client steps aside for a new one in its session; 0: no room */ +static int nest_push(void) +{ + int ses = cl.session, d = nest_depth[ses]; + uint32_t lin = NEST_AREA + ((uint32_t)ses * MAX_NEST + (uint32_t)d) * (NEST_PAGES + 1) * 4096, off, p; + + if (d == MAX_NEST) + return 0; + if (!nest[ses][d]) + { + if (pages_free() < NEST_PAGES + 8) + return 0; + for (off = 0; off < NEST_PAGES * 4096; off += 4096) + if (!(p = page_alloc()) || !map_page(lin + off, p, 3)) + return 0; + nest[ses][d] = (struct saved *)lin; + } + state_save(nest[ses][d]); + nest_depth[ses] = d + 1; + return 1; +} + +/* the running client has ended: the one that started it is the client again */ +static void nest_pop(void) +{ + int ses = vm_current(); + + if (!nest_depth[ses]) + return; + state_load(nest[ses][--nest_depth[ses]]); + kprintf("dpmi: back in the client with PSP %04x\n", cl.psp); +} + +/* ---------------------------------------------------------------- */ +/* descriptors */ + +#define LSEL(i) ((uint16_t)(((i) << 3) | 7)) + +static uint32_t desc_base(const struct desc *d) +{ + return d->base_lo | (uint32_t)d->base_mid << 16 | (uint32_t)d->base_hi << 24; +} + +static void desc_set_base(struct desc *d, uint32_t b) +{ + d->base_lo = b & 0xffff; + d->base_mid = (b >> 16) & 0xff; + d->base_hi = b >> 24; +} + +static void desc_set_limit(struct desc *d, uint32_t l) +{ + if (l > 0xfffff) + { + d->gran |= 0x80; + l >>= 12; + } + else + d->gran &= ~0x80; + d->limit_lo = l & 0xffff; + d->gran = (d->gran & 0xf0) | ((l >> 16) & 0x0f); +} + +static void desc_init(int i, uint32_t base, uint32_t limit, uint8_t access, uint8_t flags) +{ + ldt[i].gran = flags & 0x70; + desc_set_base(&ldt[i], base); + desc_set_limit(&ldt[i], limit); + ldt[i].access = access; +} + +static const struct desc *sel_desc(uint16_t sel) +{ + if (sel & 4) + return (sel >> 3) < LDT_ENTRIES ? &ldt[sel >> 3] : &ldt[0]; + return gdt_entry(sel); +} + +static uint32_t sel_base(uint16_t sel) +{ + return desc_base(sel_desc(sel)); +} + +static int sel_big(uint16_t sel) +{ + return (sel_desc(sel)->gran & 0x40) != 0; +} + +static int sel_client(uint16_t sel) +{ + int i = sel >> 3; + return (sel & 4) && i > 0 && i < LDT_ENTRIES && ldt_used[i]; +} + +static int ldt_alloc(int n) +{ + int i, j; + + for (i = 1; i + n <= LDT_ENTRIES; i++) + { + for (j = 0; j < n && !ldt_used[i + j]; j++) + ; + if (j < n) + { + i += j; + continue; + } + for (j = 0; j < n; j++) + { + ldt_used[i + j] = 1; + desc_init(i + j, 0, 0, 0xf2, cl.bits32 ? 0x40 : 0); + } + return i; + } + return -1; +} + +static void ldt_free(int i) +{ + ldt_used[i] = 0; + memset(&ldt[i], 0, sizeof(ldt[i])); +} + +static void *pm_ptr(uint16_t sel, uint32_t off) +{ + return (void *)(sel_base(sel) + off); +} + +/* offset registers: 32 bit for 32 bit clients */ +static uint32_t off32(uint32_t r) +{ + return cl.bits32 ? r : (r & 0xffff); +} + +/* ---------------------------------------------------------------- */ +/* frames and stacks */ + +static void pm_push(struct frame *f, uint32_t v, int size) +{ + uint32_t addr; + + if (sel_big(f->ss)) + { + f->esp -= size; + addr = sel_base(f->ss) + f->esp; + } + else + { + uint16_t sp = (uint16_t)(f->esp - size); + f->esp = (f->esp & 0xffff0000u) | sp; + addr = sel_base(f->ss) + sp; + } + if (size == 4) + *(uint32_t *)addr = v; + else + *(uint16_t *)addr = (uint16_t)v; +} + +static uint32_t pm_pop(struct frame *f, int size) +{ + uint32_t addr, v; + + if (sel_big(f->ss)) + { + addr = sel_base(f->ss) + f->esp; + f->esp += size; + } + else + { + uint16_t sp = (uint16_t)f->esp; + addr = sel_base(f->ss) + sp; + f->esp = (f->esp & 0xffff0000u) | (uint16_t)(sp + size); + } + v = size == 4 ? *(uint32_t *)addr : *(uint16_t *)addr; + return v; +} + +static int isize(void) +{ + return cl.bits32 ? 4 : 2; +} + +/* client flags: IOPL 3, never VM/NT */ +static uint32_t pm_flags(uint32_t fl) +{ + return (fl & ~(EFL_VM | EFL_NT | EFL_RF)) | EFL_IOPL | 0x2; +} + +static void set_cf(struct frame *f, int on) +{ + if (on) + f->eflags |= EFL_CF; + else + f->eflags &= ~EFL_CF; +} + +static void api_error(struct frame *f, uint16_t code) +{ + AX(f) = code; + set_cf(f, 1); +} + +/* replace segment registers that no longer refer to client selectors */ +static void sanitize_sregs(struct frame *f) +{ + if (f->pds && !sel_client(f->pds) && (f->pds & ~3) != (HDATA_SEL & ~3)) + f->pds = 0; + if (f->pes && !sel_client(f->pes) && (f->pes & ~3) != (HDATA_SEL & ~3)) + f->pes = 0; + if (f->pfs && !sel_client(f->pfs)) + f->pfs = 0; + if (f->pgs && !sel_client(f->pgs)) + f->pgs = 0; +} + +static int rm_bios; /* the call rm_int set up is a BIOS service */ + +static void trans_push(const struct frame *f, int kind, uint32_t a, uint32_t b, uint32_t c) +{ + struct trans *t; + + if (tsp >= MAX_TRANS) + panic("dpmi: transitions nested too deep"); + t = &ts[tsp++]; + memcpy(&t->f, f, sizeof(*f)); + t->kind = kind; + t->a = a; + t->b = b; + t->c = c; + t->rm_ss = rm_ss_cur; + t->rm_sp = rm_sp_cur; + t->hstack = hstack_cur; + t->bios = rm_bios; + rm_bios = 0; +} + +static struct trans *trans_pop(void) +{ + struct trans *t; + + if (tsp == 0) + panic("dpmi: unbalanced transition"); + t = &ts[--tsp]; + rm_ss_cur = t->rm_ss; + rm_sp_cur = t->rm_sp; + hstack_cur = t->hstack; + return t; +} + +/* V86 frame for a host initiated real mode call, registers from pm */ +static void rm_setup(struct frame *v, const struct frame *pm) +{ + memset(v, 0, sizeof(*v)); + v->eax = pm->eax; + v->ebx = pm->ebx; + v->ecx = pm->ecx; + v->edx = pm->edx; + v->esi = pm->esi; + v->edi = pm->edi; + v->ebp = pm->ebp; + v->ds = v->es = cl.rm_ds; + v->ss = rm_ss_cur; + v->esp = rm_sp_cur; + v->eflags = EFL_VM | EFL_IF | 0x2 | (pm->eflags & EFL_USER & ~EFL_TF); +} + +/* push a return to BP_RM_RETURN and enter the real mode code */ +static void rm_go(struct frame *v, const struct frame *pm, int kind, + uint32_t a, uint32_t b, uint32_t c) +{ + trans_push(pm, kind, a, b, c); + rm_sp_cur = (uint16_t)v->esp; + rm_ss_cur = (uint16_t)v->ss; + enter_frame(v); +} + +static void rm_int(struct frame *v, uint8_t vec, uint32_t flags) +{ + const uint16_t *ivt = (const uint16_t *)(uint32_t)(vec * 4); + + /* the monitor's own services (INT 2Fh AH=DEh, INT 15h AH=87h, ...) as + for an INT instruction: then V86 only passes the return breakpoint */ + int done; + + vm_hold = 1; /* `v` is not a live V86 frame */ + done = v86_intercept(v, vec); + vm_hold = 0; + if (done) + { + v->cs = boot.stub_seg; + v->eip = boot.stub_bp + BP_RM_RETURN; + vm1.vif = 0; + return; + } + + v86_push16(v, (uint16_t)(flags | EFL_IF)); + v86_push16(v, boot.stub_seg); + v86_push16(v, boot.stub_bp + BP_RM_RETURN); + v->eip = ivt[0]; + v->cs = ivt[1]; + vm1.vif = 0; + rm_bios = vm_bios_call(vec); /* kept with the transition (rm_go) */ +} + +/* set for the transition of a hardware interrupt: IRQ + 1 (kept in its b) */ +static uint32_t mark_irq; + +/* run PM code `h` on the host stack, it returns with IRET to HBP_IRET */ +static void pm_handler(const struct frame *cur, struct farptr h, int kind, + uint32_t a, uint32_t flags) +{ + struct frame n; + uint32_t esp = hstack_cur; + + if (!(cur->eflags & EFL_VM) && cur->ss == HDATA_SEL && cur->esp - 0x100 < esp) + esp = (cur->esp - 0x100) & ~3u; + trans_push(cur, kind, a, mark_irq, 0); + mark_irq = 0; + hstack_cur = esp - HOST_LEVEL; + + memcpy(&n, cur, sizeof(n)); + if (cur->eflags & EFL_VM) + n.pds = n.pes = n.pfs = n.pgs = 0; + n.ss = HDATA_SEL; + n.esp = esp; + pm_push(&n, pm_flags(flags), isize()); + pm_push(&n, HCODE_SEL, isize()); + pm_push(&n, HBP_IRET, isize()); + n.cs = h.sel; + n.eip = h.off; + n.eflags = pm_flags(flags) & ~(EFL_IF | EFL_TF); + sanitize_sregs(&n); + enter_frame(&n); +} + +/* ---------------------------------------------------------------- */ +/* client lifetime */ + +static void free_blocks(void) +{ + uint32_t lin, p, *ivt = (uint32_t *)0; + int i; + + /* real mode vectors the client pointed at its callbacks (DOS/4GW leaves + some): the callbacks go with the client, the vectors back to what + they were when it started */ + for (i = 0; i < 256; i++) + if ((ivt[i] >> 16) == boot.stub_seg && (uint16_t)ivt[i] >= boot.stub_bp + BP_CALLBACK && + (uint16_t)ivt[i] < boot.stub_bp + BP_CALLBACK + MAX_CALLBACKS) + { + kprintf("dpmi: real mode vector %02x was left on a callback: restored\n", i); + ivt[i] = cl.ivt[i]; + } + + for (i = 0; i < MAX_BLOCKS; i++) + { + struct block *b = &cl.blocks[i]; + for (lin = b->lin; b->size && lin < b->lin + b->size; lin += 4096) + if ((p = unmap_page(lin)) != 0) + page_free(p); + b->lin = b->size = 0; + } + for (lin = cl.phys_base; lin < cl.next_phys; lin += 4096) + unmap_page(lin); +} + +/* terminate the client: release everything, then INT 21h AH=4Ch in RM */ +static void __attribute__((noreturn)) client_exit(uint8_t code) +{ + struct frame v; + int i; + + kprintf("dpmi: client exit, code %u\n", code); + v86_vectors_end(cl.psp, 0); + if (cl.env_sel) + *(uint16_t *)rm_ptr(cl.psp, 0x2c) = cl.env_seg; + free_blocks(); + for (i = 1; i < LDT_ENTRIES; i++) + if (ldt_used[i]) + ldt_free(i); + memset(&v, 0, sizeof(v)); + v.ss = cl.rm_ss; + v.esp = cl.rm_sp; + v.ds = v.es = cl.rm_ds; + v.cs = boot.stub_seg; + v.eip = boot.stub_bp + BP_RM_RETURN; + v.eflags = EFL_VM | EFL_IF | 0x2; + v.eax = 0x4c00 | code; + cl.active = 0; + tsp = 0; + hstack_cur = HOST_STACK; + nest_pop(); /* DOS returns into its EXEC call */ + vm1.vif = 1; + v86_reflect(&v, 0x21); + enter_frame(&v); +} + +static void __attribute__((noreturn)) client_fault(struct frame *f, const char *why) +{ + kprintf("dpmi: %s: exception %u, error %04x at %04x:%08x (ss:esp %04x:%08x)\n", + why, f->vector, f->err, f->cs, f->eip, f->ss, f->esp); + kprintf("dpmi: cr2 %08x eax %08x ebx %08x ecx %08x edx %08x esi %08x edi %08x\n", + read_cr2(), f->eax, f->ebx, f->ecx, f->edx, f->esi, f->edi); + kprintf("dpmi: ds %04x (base %08x) es %04x cs base %08x\n", + f->pds, sel_base(f->pds), f->pes, sel_base(f->cs)); + client_exit(0xff); +} + +/* INT 2Fh AX=1687h in V86: report the host */ +void dpmi_detect(struct frame *v) +{ + AX(v) = 0; + BX(v) = 1; /* 32 bit programs supported */ + *(uint8_t *)&v->ecx = 5; /* Pentium */ + DX(v) = 0x005a; /* DPMI 0.90 */ + SI(v) = 0x80; /* 2K private data: host RM stack */ + v->es = boot.stub_seg; + DI(v) = boot.stub_entry; +} + +/* V86 breakpoint: initial switch to protected mode */ +static void client_enter(struct frame *v) +{ + uint16_t ret_ip = v86_pop16(v), ret_cs = v86_pop16(v); + struct frame p; + int i; + + uint32_t lin_base = CLIENT_BASE + (uint32_t)vm_current() * CLIENT_SLICE; + uint32_t phys_base = PHYSMAP_BASE + (uint32_t)vm_current() * PHYSMAP_SLICE; + uint32_t hstack = HOST_STACK; + + if (cl.active) + { + /* a program the client started: the client waits in its EXEC call; + the new one gets the memory above it and the rest of the host stack */ + lin_base = (cl.next_lin + 0x3fffffu) & ~0x3fffffu; + phys_base = cl.next_phys; + hstack = hstack_cur; + if (lin_base >= cl.lin_end || !nest_push()) + { + v->eip = ret_ip; + v->cs = ret_cs; + AX(v) = ERR_UNSUPPORTED; + v->eflags |= EFL_CF; + return; + } + } + memset(&cl, 0, sizeof(cl)); + memset(ldt, 0, sizeof(ldt)); + memset(ldt_used, 0, sizeof(ldt_used)); + tsp = 0; + hstack_cur = hstack; + cl.active = 1; + cl.session = vm_current(); + cl.bits32 = AX(v) & 1; + /* the program's PSP: DOS knows (the stub's copy is one for all sessions) */ + cl.psp = dos_current_psp() > 0 ? (uint16_t)dos_current_psp() + : *(uint16_t *)rm_ptr(boot.stub_seg, boot.stub_psp); + cl.rm_ss = (uint16_t)v->es; /* private data area */ + cl.rm_sp = 0x800; + cl.rm_ds = (uint16_t)v->ds; + memcpy(cl.ivt, (const void *)0, sizeof(cl.ivt)); + rm_ss_cur = cl.rm_ss; + rm_sp_cur = cl.rm_sp; + cl.lin_base = lin_base; + cl.lin_end = CLIENT_BASE + (uint32_t)(cl.session + 1) * CLIENT_SLICE; + cl.phys_base = phys_base; + cl.phys_end = PHYSMAP_BASE + (uint32_t)(cl.session + 1) * PHYSMAP_SLICE; + cl.next_lin = cl.lin_base; + cl.next_phys = cl.phys_base; + + i = ldt_alloc(5); + desc_init(i, (uint32_t)ret_cs << 4, 0xffff, 0xfa, 0x00); /* CS */ + desc_init(i + 1, v->ds << 4, 0xffff, 0xf2, 0x00); /* DS */ + desc_init(i + 2, v->ss << 4, 0xffff, 0xf2, 0x00); /* SS */ + desc_init(i + 3, (uint32_t)cl.psp << 4, 0xff, 0xf2, 0x00); /* PSP */ + cl.env_seg = *(uint16_t *)rm_ptr(cl.psp, 0x2c); + if (cl.env_seg) + { + uint16_t paras = *(uint16_t *)rm_ptr(cl.env_seg - 1, 3); + desc_init(i + 4, (uint32_t)cl.env_seg << 4, paras * 16u - 1, 0xf2, 0x00); + cl.env_sel = LSEL(i + 4); + *(uint16_t *)rm_ptr(cl.psp, 0x2c) = cl.env_sel; + } + else + ldt_free(i + 4); + + memcpy(&p, v, sizeof(p)); + p.cs = LSEL(i); + p.eip = ret_ip; + p.ss = LSEL(i + 2); + p.esp = v->esp & 0xffff; + p.pds = LSEL(i + 1); + p.pes = LSEL(i + 3); + p.pfs = p.pgs = 0; + p.eflags = pm_flags(v86_vflags(v)) & ~EFL_CF; + kprintf("dpmi: %u bit client, PSP %04x, session %d%s\n", cl.bits32 ? 32 : 16, cl.psp, + cl.session, nest_depth[cl.session] ? ", started by a client" : ""); + enter_frame(&p); +} + +/* ---------------------------------------------------------------- */ +/* memory */ + +static struct block *block_find(uint32_t handle) +{ + int i; + + for (i = 0; i < MAX_BLOCKS; i++) + if (cl.blocks[i].size && cl.blocks[i].lin == handle) + return &cl.blocks[i]; + return NULL; +} + +/* map `size' bytes of fresh pages at lin; 0 on failure (nothing mapped) */ +static int map_fresh(uint32_t lin, uint32_t size) +{ + uint32_t off, p; + + if (size / 4096 + 8 > pages_free()) + return 0; + for (off = 0; off < size; off += 4096) + { + p = page_alloc(); + if (!p || !map_page(lin + off, p, 7)) + { + if (p) + page_free(p); + while (off) + { + off -= 4096; + page_free(unmap_page(lin + off)); + } + return 0; + } + } + return 1; +} + +static void api_alloc(struct frame *f, uint32_t size) +{ + struct block *b; + int i; + + for (i = 0, b = NULL; i < MAX_BLOCKS && !b; i++) + if (!cl.blocks[i].size) + b = &cl.blocks[i]; + size = (size + 4095) & ~4095u; + if (!size) + return api_error(f, ERR_VALUE); + if (!b) + return api_error(f, ERR_HANDLE); + if (cl.next_lin + size > cl.lin_end) + return api_error(f, ERR_LINEAR); + if (!map_fresh(cl.next_lin, size)) + return api_error(f, ERR_PHYSICAL); + b->lin = cl.next_lin; + b->size = size; + cl.next_lin += size + 4096; /* guard page */ + BX(f) = b->lin >> 16; + CX(f) = b->lin & 0xffff; + SI(f) = b->lin >> 16; + DI(f) = b->lin & 0xffff; + set_cf(f, 0); +} + +static void api_free(struct frame *f, uint32_t handle) +{ + struct block *b = block_find(handle); + uint32_t lin; + + if (!b) + return api_error(f, ERR_HANDLE); + for (lin = b->lin; lin < b->lin + b->size; lin += 4096) + page_free(unmap_page(lin)); + b->lin = b->size = 0; + set_cf(f, 0); +} + +static void api_resize(struct frame *f, uint32_t handle, uint32_t size) +{ + struct block *b = block_find(handle); + uint32_t off, nlin; + + size = (size + 4095) & ~4095u; + if (!b) + return api_error(f, ERR_HANDLE); + if (!size) + return api_error(f, ERR_VALUE); + if (size <= b->size) + { + for (off = size; off < b->size; off += 4096) + page_free(unmap_page(b->lin + off)); + b->size = size; + } + else if (b->lin + b->size + 4096 == cl.next_lin) + { + /* last block: grow in place */ + if (b->lin + size > cl.lin_end) + return api_error(f, ERR_LINEAR); + if (!map_fresh(b->lin + b->size, size - b->size)) + return api_error(f, ERR_PHYSICAL); + b->size = size; + cl.next_lin = b->lin + size + 4096; + } + else + { + /* move the pages to a new linear range, then add more */ + nlin = cl.next_lin; + if (nlin + size > cl.lin_end) + return api_error(f, ERR_LINEAR); + if (!map_fresh(nlin + b->size, size - b->size)) + return api_error(f, ERR_PHYSICAL); + for (off = 0; off < b->size; off += 4096) + map_page(nlin + off, unmap_page(b->lin + off), 7); + b->lin = nlin; + b->size = size; + cl.next_lin = nlin + size + 4096; + } + BX(f) = b->lin >> 16; + CX(f) = b->lin & 0xffff; + SI(f) = b->lin >> 16; + DI(f) = b->lin & 0xffff; + set_cf(f, 0); +} + +static void api_meminfo(struct frame *f) +{ + uint32_t *m = pm_ptr(f->pes, off32(f->edi)); + uint32_t freep = pages_free() > 8 ? pages_free() - 8 : 0; + int i; + + for (i = 0; i < 12; i++) + m[i] = 0xffffffffu; + m[0] = freep * 4096; /* largest free block */ + m[1] = freep; /* max unlocked allocation */ + m[2] = freep; /* max locked allocation */ + m[3] = (cl.lin_end - cl.lin_base) / 4096; + m[4] = pages_total(); + m[5] = freep; + m[6] = pages_total(); + m[7] = (cl.lin_end - cl.next_lin) / 4096; + m[8] = 0; /* no paging file */ + set_cf(f, 0); +} + +static void api_physmap(struct frame *f) +{ + uint32_t phys = (uint32_t)BX(f) << 16 | CX(f); + uint32_t size = (uint32_t)SI(f) << 16 | DI(f); + uint32_t lin, off, first = phys & ~0xfffu; + + if (phys + size <= 0x110000) + lin = phys; /* below 1MB: identity */ + else + { + size = ((phys & 0xfff) + size + 4095) & ~4095u; + if (!size || cl.next_phys + size > cl.phys_end) + return api_error(f, ERR_LINEAR); + for (off = 0; off < size; off += 4096) + { + /* DOS extended memory (UEFI boot: XMS window), else devices */ + uint32_t ext = boot.boot_type == BOOT_UEFI ? ext_phys(first + off) : 0; + if (!map_page(cl.next_phys + off, ext ? ext : first + off, ext ? 7 : 0x17)) /* PCD */ + return api_error(f, ERR_PHYSICAL); + } + lin = cl.next_phys + (phys & 0xfff); + cl.next_phys += size + 4096; + } + BX(f) = lin >> 16; + CX(f) = lin & 0xffff; + set_cf(f, 0); +} + +/* ---------------------------------------------------------------- */ +/* real mode calls */ + +/* DPMI 0300h/0301h/0302h */ +static void api_rmcall(struct frame *f, int fn) +{ + struct rmregs *r = pm_ptr(f->pes, off32(f->edi)); + struct frame v; + uint16_t words = CX(f); + + memset(&v, 0, sizeof(v)); + v.eax = r->eax; + v.ebx = r->ebx; + v.ecx = r->ecx; + v.edx = r->edx; + v.esi = r->esi; + v.edi = r->edi; + v.ebp = r->ebp; + v.ds = r->ds; + v.es = r->es; + v.fs = r->fs; + v.gs = r->gs; + if (r->ss || r->sp) + { + v.ss = r->ss; + v.esp = r->sp; + } + else + { + v.ss = rm_ss_cur; + v.esp = rm_sp_cur; + } + v.eflags = EFL_VM | EFL_IF | 0x2 | (r->flags & EFL_USER & ~EFL_TF); + + if (words) /* copy parameters from the PM stack */ + { + const uint8_t *src = (const uint8_t *)sel_base(f->ss) + + (sel_big(f->ss) ? f->esp : (f->esp & 0xffff)); + v.esp = (uint16_t)(v.esp - words * 2); + memcpy(rm_ptr(v.ss, v.esp), src, words * 2u); + } + + if (fn == 0x300) + rm_int(&v, BL(f), r->flags); + else + { + if (fn == 0x302) + v86_push16(&v, r->flags | EFL_IF); + v86_push16(&v, boot.stub_seg); + v86_push16(&v, boot.stub_bp + BP_RM_RETURN); + v.cs = r->cs; + v.eip = r->ip; + vm1.vif = fn == 0x301 ? (r->flags & EFL_IF) != 0 : 0; + } + rm_go(&v, f, T_PM_CALL, (uint32_t)r, 0, 0); +} + +/* DPMI 0100h-0102h: DOS memory through INT 21h in real mode */ +static void api_dosmem(struct frame *f, int fn) +{ + struct frame v; + uint32_t sel = DX(f); + + rm_setup(&v, f); + if (fn == 0x100) + AH(&v) = 0x48; + else + { + if (!sel_client(sel)) + return api_error(f, ERR_SELECTOR); + v.es = sel_base(sel) >> 4; + AH(&v) = fn == 0x101 ? 0x49 : 0x4a; + } + rm_int(&v, 0x21, v.eflags); + rm_go(&v, f, T_PM_DOSMEM, fn, sel, BX(f)); +} + +static void dosmem_done(struct frame *pm, struct trans *t, struct frame *v) +{ + int fn = t->a, i; + uint16_t paras = (uint16_t)t->c; + + if (v->eflags & EFL_CF) + { + AX(pm) = AX(v); + BX(pm) = BX(v); + set_cf(pm, 1); + return; + } + set_cf(pm, 0); + switch (fn) + { + case 0x100: + i = ldt_alloc(1); + if (i < 0) + { + AX(pm) = 8; + BX(pm) = 0; + set_cf(pm, 1); + return; + } + desc_init(i, (uint32_t)AX(v) << 4, paras * 16u - 1, 0xf2, cl.bits32 ? 0x40 : 0); + AX(pm) = AX(v); + DX(pm) = LSEL(i); + break; + case 0x101: + ldt_free(t->b >> 3); + break; + case 0x102: + desc_set_limit(&ldt[t->b >> 3], paras * 16u - 1); + break; + } +} + +/* V86 breakpoint BP_RM_RETURN: a host initiated real mode call is done */ +static void rm_return(struct frame *v) +{ + struct trans *t = trans_pop(); + struct frame pm; + uint32_t fl; + + if (t->bios) + vm_bios_done(); + memcpy(&pm, &t->f, sizeof(pm)); + switch (t->kind) + { + case T_PM_INT: + case T_PM_DEFINT: + pm.eax = v->eax; + pm.ebx = v->ebx; + pm.ecx = v->ecx; + pm.edx = v->edx; + pm.esi = v->esi; + pm.edi = v->edi; + pm.ebp = v->ebp; + pm.eflags = (pm.eflags & ~EFL_USER) | (v->eflags & EFL_USER & ~EFL_TF); + if (t->kind == T_PM_DEFINT) + { + /* finish the IRET of the chained handler, with the result flags */ + pm.eip = pm_pop(&pm, isize()); + pm.cs = pm_pop(&pm, isize()) & 0xffff; + fl = pm_pop(&pm, isize()); + if (!cl.bits32) + fl = (pm.eflags & 0xffff0000u) | (fl & 0xffff); + pm.eflags = pm_flags((fl & ~EFL_USER) | (v->eflags & EFL_USER & ~EFL_TF)); + } + break; + case T_PM_IRQ: + if (t->b == 2) + vm_kbd_done(); /* the keyboard interrupt's handler is through */ + if (t->b == 1) + vm_tick_done(); /* ... the timer's */ + break; + case T_PM_CALL: + { + struct rmregs *r = (struct rmregs *)t->a; + r->eax = v->eax; + r->ebx = v->ebx; + r->ecx = v->ecx; + r->edx = v->edx; + r->esi = v->esi; + r->edi = v->edi; + r->ebp = v->ebp; + r->flags = (uint16_t)v86_vflags(v); + r->ds = v->ds; + r->es = v->es; + r->fs = v->fs; + r->gs = v->gs; + set_cf(&pm, 0); + break; + } + case T_PM_DOSMEM: + dosmem_done(&pm, t, v); + break; + default: + panic("dpmi: bad real mode return (kind %d)", t->kind); + } + vm1.vif = 1; + sanitize_sregs(&pm); + dpmi_take_pending(&pm); + vm_kbd_next(&pm); /* the next keystroke, if one waits */ + enter_frame(&pm); +} + +/* ---------------------------------------------------------------- */ +/* real mode callbacks and raw switches */ + +static void rm_callback(struct frame *v, int i) +{ + struct callback *c = &cl.cb[i]; + struct rmregs *r; + struct frame n; + + if (!c->used) + { + /* not this client's: one that waits for it registered it (or it was + freed): return to the caller, a far return */ + v->eip = v86_pop16(v); + v->cs = v86_pop16(v); + return; + } + r = pm_ptr(c->regs.sel, c->regs.off); + r->eax = v->eax; + r->ebx = v->ebx; + r->ecx = v->ecx; + r->edx = v->edx; + r->esi = v->esi; + r->edi = v->edi; + r->ebp = v->ebp; + r->flags = (uint16_t)v86_vflags(v); + r->es = v->es; + r->ds = v->ds; + r->fs = v->fs; + r->gs = v->gs; + r->cs = v->cs; + r->ip = (uint16_t)v->eip; + r->ss = v->ss; + r->sp = (uint16_t)v->esp; + desc_set_base(&ldt[c->stack_sel >> 3], v->ss << 4); + + /* the real mode caller's stack is in use below its SP */ + memcpy(&n, v, sizeof(n)); + n.pds = c->stack_sel; + n.esi = (uint16_t)v->esp; + n.pes = c->regs.sel; + n.edi = c->regs.off; + n.pfs = n.pgs = 0; + n.eflags = pm_flags(v86_vflags(v)); /* a PM context: keep DS/ES above */ + rm_ss_cur = (uint16_t)v->ss; + rm_sp_cur = (uint16_t)(v->esp - 0x40); + pm_handler(&n, c->proc, T_CALLBACK, i, v86_vflags(v)); +} + +static void callback_done(struct trans *t) +{ + struct callback *c = &cl.cb[t->a]; + struct rmregs *r = pm_ptr(c->regs.sel, c->regs.off); + struct frame v; + + memset(&v, 0, sizeof(v)); + v.eax = r->eax; + v.ebx = r->ebx; + v.ecx = r->ecx; + v.edx = r->edx; + v.esi = r->esi; + v.edi = r->edi; + v.ebp = r->ebp; + v.es = r->es; + v.ds = r->ds; + v.fs = r->fs; + v.gs = r->gs; + v.cs = r->cs; + v.eip = r->ip; + v.ss = r->ss; + v.esp = r->sp; + v.eflags = EFL_VM | EFL_IF | 0x2 | (r->flags & EFL_USER); + vm1.vif = (r->flags & EFL_IF) != 0; + enter_frame(&v); +} + +/* V86 breakpoint BP_RAW_TO_PM */ +static void raw_to_pm(struct frame *v) +{ + struct frame p; + + memcpy(&p, v, sizeof(p)); + p.pds = AX(v); + p.pes = CX(v); + p.ss = DX(v); + p.esp = off32(v->ebx); + p.cs = SI(v); + p.eip = off32(v->edi); + p.pfs = p.pgs = 0; + p.eflags = pm_flags(v86_vflags(v)); + sanitize_sregs(&p); + enter_frame(&p); +} + +/* PM breakpoint HBP_RAW */ +static void raw_to_rm(struct frame *f) +{ + struct frame v; + + memcpy(&v, f, sizeof(v)); + v.ds = AX(f); + v.es = CX(f); + v.ss = DX(f); + v.esp = BX(f); + v.cs = SI(f); + v.eip = DI(f); + v.fs = v.gs = 0; + v.eflags = EFL_VM | EFL_IF | 0x2 | (f->eflags & EFL_USER); + vm1.vif = (f->eflags & EFL_IF) != 0; + enter_frame(&v); +} + +/* V86 breakpoints */ +void dpmi_v86_bp(struct frame *v, int bp) +{ + if (bp == BP_DPMI_ENTRY) + return client_enter(v); + if (!cl.active) + panic_frame(v, "DPMI breakpoint without client"); + if (bp == BP_RM_RETURN) + rm_return(v); + else if (bp == BP_RAW_TO_PM) + raw_to_pm(v); + else if (bp >= BP_CALLBACK && bp < BP_CALLBACK + MAX_CALLBACKS) + rm_callback(v, bp - BP_CALLBACK); + panic_frame(v, "bad DPMI breakpoint"); +} + +/* ---------------------------------------------------------------- */ +/* interrupts and exceptions from the client */ + +/* a debug exception in the client: the monitor's VGA port breakpoints? */ +int dpmi_vga_debug(struct frame *f) +{ + const uint8_t *code = pm_ptr(f->cs, sel_big(f->cs) ? f->eip : (f->eip & 0xffff)); + uint32_t esi = sel_big(f->pds) ? f->esi : (f->esi & 0xffff); + + return vga_debug(f, code, pm_ptr(f->pds, esi - 1), sel_big(f->cs)); +} + +uint32_t dpmi_sel_base(uint16_t sel) +{ + return sel_base(sel); +} + +/* a page fault in the client: on the monitor's VGA memory? */ +int dpmi_vga_fault(struct frame *f, uint32_t addr) +{ + return vga_fault(f, addr, 0, sel_big(f->cs)); +} + +/* has the running session's client a handler of its own for this IRQ? */ +int dpmi_irq_hooked(int irq) +{ + return cl.active && cl.pmint[irq < 8 ? 0x08 + irq : 0x70 + irq - 8].sel != 0; +} + +int dpmi_active(void) +{ + return cl.active; +} + +/* the running session if it has a client, else -1 */ +int dpmi_owner(void) +{ + return cl.active ? cl.session : -1; +} + +/* The session scheduler goes from session `from` to session `to`: put the + host's state away and take the other session's. from < 0: that session + is gone (its client's memory is released). */ +void dpmi_session_switch(int from, int to) +{ + struct saved *a, *b = &saved[to]; + int i; + + if (from < 0) + { + while (cl.active) /* with the clients that wait for it */ + { + kprintf("dpmi: the client's session ended\n"); + free_blocks(); + cl.active = 0; + nest_pop(); + } + } + else + { + a = &saved[from]; + a->valid = cl.active; + if (cl.active) + state_save(a); + } + if (b->valid) + { + state_load(b); + b->valid = 0; + } + else + { + memset(ldt, 0, sizeof(ldt)); + memset(ldt_used, 0, sizeof(ldt_used)); + cl.active = 0; + tsp = 0; + hstack_cur = HOST_STACK; + } + for (i = 0; i < (int)HSTACK_PAGES; i++) + map_page(HOST_AREA + 4096u * (uint32_t)(i + 1), hstack_pages[to][i], 7); +} + +/* real mode INT 21h AH=4Ch while a client is active (e.g. via 0300h) */ +void dpmi_rm_exit(void) +{ + int psp = dos_current_psp(); + + if (!cl.active || !tsp || cl.session != vm_current()) + return; + if (psp >= 0 && psp != cl.psp) + return; /* a program the client started */ + kprintf("dpmi: client terminated from real mode\n"); + if (cl.env_sel) + *(uint16_t *)rm_ptr(cl.psp, 0x2c) = cl.env_seg; + free_blocks(); + memset(ldt_used, 0, sizeof(ldt_used)); + cl.active = 0; + tsp = 0; + hstack_cur = HOST_STACK; + nest_pop(); +} + +/* IRQs the CPU accepted while the monitor waited (or V86 had IF off) are + delivered when we resume the client. Does not return if one is pending. */ +int dpmi_take_pending(struct frame *pm) +{ + int irq; + + if ((pm->eflags & EFL_IF) && !vm1.pending && vm_owed_tick()) + vm1.pending |= 1; /* a tick it missed: marked done at its return */ + for (irq = 0; irq < 16; irq++) + if (vm1.pending & (1u << irq)) + { + vm1.pending &= ~(1u << irq); + dpmi_irq(pm, irq); + } + return 0; +} + +/* hardware IRQ while in V86: run the client's PM handler if it has one. + Returns 0 if the IRQ should go to real mode as usual. */ +int dpmi_irq_v86(struct frame *v, int irq) +{ + uint8_t vec = irq < 8 ? 0x08 + irq : 0x70 + irq - 8; + + if (!cl.active || !cl.pmint[vec].sel || cl.session != vm_current()) + return 0; + rm_ss_cur = (uint16_t)v->ss; + rm_sp_cur = (uint16_t)(v->esp - 0x40); + mark_irq = (uint32_t)irq + 1; + pm_handler(v, cl.pmint[vec], T_TO_PM_HANDLER, 0, v86_vflags(v)); + return 1; +} + +/* hardware IRQ taken while the client runs in PM: the session scheduler + (timer) and the session hotkeys (keyboard) first, as in V86 */ +void dpmi_hwirq(struct frame *f, int irq) +{ + if (irq == 0 && !(vm1.pending & 1u)) + { + vm1.pending |= 1u; /* another session gets this tick */ + vm_tick(f); /* does not return if it switched */ + vm1.pending &= ~1u; + } + else if (irq == 1 && vm_kbd(f, 1)) + enter_frame(f); /* a hotkey or another session's key */ + dpmi_irq(f, irq); +} + +/* hardware IRQ while the client runs */ +void dpmi_irq(struct frame *f, int irq) +{ + uint8_t vec = irq < 8 ? 0x08 + irq : 0x70 + irq - 8; + struct frame v; + + mark_irq = (uint32_t)irq + 1; + if (cl.pmint[vec].sel) + pm_handler(f, cl.pmint[vec], T_TO_PM_HANDLER, 0, f->eflags); + mark_irq = 0; + rm_setup(&v, f); + rm_int(&v, vec, f->eflags); + rm_go(&v, f, T_PM_IRQ, 0, (uint32_t)irq + 1, 0); +} + +static void pm_int(struct frame *f, uint8_t vec); +static void dpmi_api(struct frame *f); + +/* PM breakpoints in the host code page */ +static void host_bp(struct frame *f, uint32_t off) +{ + struct trans *t; + + if (off == HBP_IRET) + { + t = trans_pop(); + if (t->kind == T_CALLBACK) + callback_done(t); + if (t->kind != T_TO_PM_HANDLER) + panic("dpmi: bad handler return (kind %d)", t->kind); + if (!(t->f.eflags & EFL_VM)) + sanitize_sregs(&t->f); + if (t->b == 1) + vm_tick_done(); + if (t->b == 2) + { + vm_kbd_done(); + vm_kbd_next(&t->f); + } + enter_frame(&t->f); + } + if (off == HBP_EXC_RET) + { + /* stack: error code, eip, cs, eflags, esp, ss (as left by handler) */ + struct frame r; + memcpy(&r, f, sizeof(r)); + pm_pop(&r, isize()); /* error code */ + r.eip = pm_pop(&r, isize()); + r.cs = pm_pop(&r, isize()) & 0xffff; + r.eflags = pm_flags(pm_pop(&r, isize())); + { + uint32_t esp = pm_pop(&r, isize()); + r.ss = pm_pop(&r, isize()) & 0xffff; + r.esp = esp; + } + sanitize_sregs(&r); +#ifdef DPMI_TRACE + kprintf("dpmi: exception handler returns to %04x:%08x ss:esp %04x:%08x\n", r.cs, r.eip, r.ss, r.esp); +#endif + enter_frame(&r); + } + if (off == HBP_RAW) + raw_to_rm(f); + if (off >= HBP_DEFINT && off < HBP_DEFINT + 256) + { + /* client chained to the default handler: reflect, then IRET */ + struct frame v; + uint8_t vec = (uint8_t)(off - HBP_DEFINT); + if (vec == 0x21 && AH(f) == 0x4c) + client_exit(AL(f)); + if (vec == 0x31) + { + /* the host's services: on the caller's frame, as if it had called */ + struct frame r; + uint32_t fl; + memcpy(&r, f, sizeof(r)); + r.eip = pm_pop(&r, isize()); + r.cs = pm_pop(&r, isize()) & 0xffff; + fl = pm_pop(&r, isize()); + if (!cl.bits32) + fl = (r.eflags & 0xffff0000u) | (fl & 0xffff); + r.eflags = pm_flags(fl); + dpmi_api(&r); + enter_frame(&r); + } + rm_setup(&v, f); + rm_int(&v, (uint8_t)(off - HBP_DEFINT), f->eflags); + rm_go(&v, f, T_PM_DEFINT, 0, 0, 0); + } + if (off >= HBP_DEFEXC && off < HBP_DEFEXC + 32) + { + f->vector = off - HBP_DEFEXC; + client_fault(f, "unhandled exception (default handler)"); + } + client_fault(f, "jump into host code"); +} + +static void dpmi_api(struct frame *f); + +/* software INT n executed by the client */ +static void pm_int(struct frame *f, uint8_t vec) +{ + struct frame v; + + /* the client's own handler first, also for INT 31h and for INT 21h + AH=4Ch: DOS extenders that run as a client hook both - CauseWay adds + its services to INT 31h, DOS/4GW cleans up in its INT 21h handler + before the program ends. They chain to the host (host_bp). */ + if (cl.pmint[vec].sel) + { + pm_push(f, f->eflags, isize()); + pm_push(f, f->cs, isize()); + pm_push(f, f->eip, isize()); + f->eflags &= ~(EFL_IF | EFL_TF); + f->cs = cl.pmint[vec].sel; + f->eip = cl.pmint[vec].off; + return; + } + if (vec == 0x31) + return dpmi_api(f); + if (vec == 0x21 && AH(f) == 0x4c) + client_exit(AL(f)); + rm_setup(&v, f); + rm_int(&v, vec, f->eflags); + rm_go(&v, f, T_PM_INT, 0, 0, 0); +} + +static void pm_exception(struct frame *f) +{ + unsigned n = f->vector; + struct frame e; + uint32_t esp; + + if (n >= 32 || !cl.exc[n].sel) + client_fault(f, "unhandled exception"); + esp = (f->ss == HDATA_SEL && f->esp - 0x100 < hstack_cur) ? (f->esp - 0x100) & ~3u : hstack_cur; + memcpy(&e, f, sizeof(e)); + e.ss = HDATA_SEL; + e.esp = esp; + pm_push(&e, f->ss, isize()); + pm_push(&e, f->esp, isize()); + pm_push(&e, f->eflags, isize()); + pm_push(&e, f->cs, isize()); + pm_push(&e, f->eip, isize()); + pm_push(&e, f->err, isize()); + pm_push(&e, HCODE_SEL, isize()); + pm_push(&e, HBP_EXC_RET, isize()); + e.cs = cl.exc[n].sel; + e.eip = cl.exc[n].off; + e.eflags &= ~EFL_TF; +#ifdef DPMI_TRACE + kprintf("dpmi: exception %u at %04x:%08x err %x -> %04x:%08x\n", n, f->cs, f->eip, f->err, e.cs, e.eip); +#endif + enter_frame(&e); +} + +/* traps from the client (ring 3, not V86) */ +void dpmi_trap(struct frame *f) +{ + /* INT n through a DPL 0 gate faults with error (n << 3) | 2 (IDT bit); + HLT and other privileged instructions with error 0 */ + if (f->vector == 0x0d && (f->err == 0 || (f->err & 7) == 2)) + { + const uint8_t *code = (const uint8_t *)(sel_base(f->cs) + f->eip); + int len = 0; + + while (len < 8 && (code[len] == 0x66 || code[len] == 0x67 || code[len] == 0x26 || + code[len] == 0x2e || code[len] == 0x36 || code[len] == 0x3e || + code[len] == 0x64 || code[len] == 0x65)) + len++; + if (code[len] == 0xf4 && (f->cs & ~3u) == (HCODE_SEL & ~3u)) + return host_bp(f, f->eip); + if (code[len] == 0xcd) + { + uint8_t vec = code[len + 1]; + f->eip += len + 2; + if (!sel_big(f->cs)) + f->eip &= 0xffff; + return pm_int(f, vec); + } + if (code[len] == 0xcc) + { + f->eip += len + 1; + return pm_int(f, 3); + } + if (code[len] == 0xf4) /* HLT: wait for an interrupt */ + { + f->eip += len + 1; + vm_yield(f); /* another session may run instead */ + while (!vm1.pending) + __asm__ volatile("sti; hlt; cli" ::: "memory"); + dpmi_take_pending(f); + return; + } + } + if (f->vector >= 0x20 && f->vector < 0x30) + return dpmi_hwirq(f, (int)f->vector - 0x20); + pm_exception(f); +} + +/* ---------------------------------------------------------------- */ +/* INT 31h */ + +static void api_descriptor(struct frame *f) +{ + uint16_t sel = BX(f); + int i = sel >> 3, n; + + if (AX(f) != 0x0000 && AX(f) != 0x0002 && AX(f) != 0x0003 && !sel_client(sel)) + return api_error(f, ERR_SELECTOR); + switch (AX(f)) + { + case 0x0000: /* allocate CX descriptors */ + n = ldt_alloc(CX(f) ? CX(f) : 1); + if (n < 0) + return api_error(f, ERR_DESC); + AX(f) = LSEL(n); + break; + case 0x0001: /* free descriptor */ + ldt_free(i); + if (f->pds == sel) f->pds = 0; + if (f->pes == sel) f->pes = 0; + if (f->pfs == sel) f->pfs = 0; + if (f->pgs == sel) f->pgs = 0; + break; + case 0x0002: /* segment to descriptor */ + { + uint32_t base = (uint32_t)BX(f) << 4; + for (n = 1; n < LDT_ENTRIES; n++) + if (ldt_used[n] == 2 && desc_base(&ldt[n]) == base) + break; + if (n == LDT_ENTRIES) + { + n = ldt_alloc(1); + if (n < 0) + return api_error(f, ERR_DESC); + desc_init(n, base, 0xffff, 0xf2, 0x00); + ldt_used[n] = 2; /* not freeable by convention */ + } + AX(f) = LSEL(n); + break; + } + case 0x0003: /* selector increment */ + AX(f) = 8; + break; + case 0x0006: /* get base */ + { + uint32_t b = desc_base(&ldt[i]); + CX(f) = b >> 16; + DX(f) = b & 0xffff; + break; + } + case 0x0007: /* set base */ + desc_set_base(&ldt[i], (uint32_t)CX(f) << 16 | DX(f)); + break; + case 0x0008: /* set limit */ + { + uint32_t l = (uint32_t)CX(f) << 16 | DX(f); + if (l > 0xfffff && (l & 0xfff) != 0xfff) + return api_error(f, ERR_VALUE); + desc_set_limit(&ldt[i], l); + break; + } + case 0x0009: /* set access rights */ + if ((CL(f) & 0x70) != 0x70) /* must be DPL 3, code/data */ + return api_error(f, ERR_VALUE); + ldt[i].access = CL(f) | 0x01; + ldt[i].gran = (ldt[i].gran & 0x0f) | (CH(f) & 0xd0); + break; + case 0x000a: /* data alias */ + n = ldt_alloc(1); + if (n < 0) + return api_error(f, ERR_DESC); + ldt[n] = ldt[i]; + ldt[n].access = (ldt[n].access & 0xf0) | 0x02; + AX(f) = LSEL(n); + break; + case 0x000b: /* get descriptor */ + memcpy(pm_ptr(f->pes, off32(f->edi)), &ldt[i], 8); + break; + case 0x000c: /* set descriptor */ + { + struct desc d; + memcpy(&d, pm_ptr(f->pes, off32(f->edi)), 8); + if ((d.access & 0x70) != 0x70) + return api_error(f, ERR_VALUE); + ldt[i] = d; + break; + } + default: + return api_error(f, ERR_UNSUPPORTED); + } + set_cf(f, 0); +} + +static void set_farptr(struct frame *f, struct farptr p) +{ + CX(f) = p.sel; + if (cl.bits32) + f->edx = p.off; + else + DX(f) = (uint16_t)p.off; +} + +static struct farptr get_farptr(struct frame *f) +{ + struct farptr p; + p.sel = CX(f); + p.off = off32(f->edx); + return p; +} + +static void dpmi_api(struct frame *f) +{ + uint8_t n = BL(f); + struct farptr p; + int i; + +#ifdef DPMI_TRACE + kprintf("int31 %04x bx=%04x cx=%04x dx=%04x si=%04x di=%08x ss:esp=%04x:%08x cs:eip=%04x:%08x\n", + AX(f), BX(f), CX(f), DX(f), SI(f), f->edi, f->ss, f->esp, f->cs, f->eip); +#endif + if (AH(f) == 0x00) + return api_descriptor(f); + set_cf(f, 0); + switch (AX(f)) + { + case 0x0100: + case 0x0101: + case 0x0102: + return api_dosmem(f, AX(f)); + case 0x0200: /* get real mode vector */ + { + uint16_t *vec = rm_ptr(0, n * 4u); + DX(f) = vec[0]; + CX(f) = vec[1]; + return; + } + case 0x0201: /* set real mode vector */ + { + uint16_t *vec = rm_ptr(0, n * 4u); + v86_vector_set(cl.psp, (uint8_t)n); + vec[0] = DX(f); + vec[1] = CX(f); + return; + } + case 0x0202: /* get exception handler */ + if (n >= 32) + return api_error(f, ERR_VALUE); + p = cl.exc[n]; + if (!p.sel) + { + p.sel = HCODE_SEL; + p.off = HBP_DEFEXC + n; + } + return set_farptr(f, p); + case 0x0203: /* set exception handler */ + if (n >= 32) + return api_error(f, ERR_VALUE); + p = get_farptr(f); + cl.exc[n] = p.sel == HCODE_SEL ? (struct farptr){ 0, 0 } : p; + return; + case 0x0204: /* get PM interrupt vector */ + p = cl.pmint[n]; + if (!p.sel) + { + p.sel = HCODE_SEL; + p.off = HBP_DEFINT + n; + } + return set_farptr(f, p); + case 0x0205: /* set PM interrupt vector */ + p = get_farptr(f); + cl.pmint[n] = p.sel == HCODE_SEL ? (struct farptr){ 0, 0 } : p; + return; + case 0x0300: + case 0x0301: + case 0x0302: + return api_rmcall(f, AX(f)); + case 0x0303: /* allocate real mode callback */ + for (i = 0; i < MAX_CALLBACKS && cl.cb[i].used; i++) + ; + if (i == MAX_CALLBACKS) + return api_error(f, ERR_CALLBACK); + { + int s = ldt_alloc(1); + if (s < 0) + return api_error(f, ERR_DESC); + desc_init(s, 0, 0xffff, 0xf2, 0x00); + cl.cb[i].stack_sel = LSEL(s); + } + cl.cb[i].used = 1; + cl.cb[i].proc.sel = (uint16_t)f->pds; + cl.cb[i].proc.off = off32(f->esi); + cl.cb[i].regs.sel = (uint16_t)f->pes; + cl.cb[i].regs.off = off32(f->edi); + CX(f) = boot.stub_seg; + DX(f) = boot.stub_bp + BP_CALLBACK + i; + return; + case 0x0304: /* free real mode callback */ + i = DX(f) - boot.stub_bp - BP_CALLBACK; + if (CX(f) != boot.stub_seg || i < 0 || i >= MAX_CALLBACKS || !cl.cb[i].used) + return api_error(f, ERR_CALLBACK); + cl.cb[i].used = 0; + ldt_free(cl.cb[i].stack_sel >> 3); + return; + case 0x0305: /* state save/restore addresses */ + AX(f) = 0; + BX(f) = boot.stub_seg; + CX(f) = boot.stub_retf; + SI(f) = HCODE_SEL; + if (cl.bits32) + f->edi = HBP_RETF; + else + DI(f) = HBP_RETF; + return; + case 0x0306: /* raw mode switch addresses */ + BX(f) = boot.stub_seg; + CX(f) = boot.stub_bp + BP_RAW_TO_PM; + SI(f) = HCODE_SEL; + if (cl.bits32) + f->edi = HBP_RAW; + else + DI(f) = HBP_RAW; + return; + case 0x0400: /* version */ + AX(f) = 0x005a; + BX(f) = 0x0001; /* 32 bit host */ + CL(f) = 5; + DX(f) = 0x0870; /* PIC bases as seen by clients */ + return; + case 0x0500: + return api_meminfo(f); + case 0x0501: + return api_alloc(f, (uint32_t)BX(f) << 16 | CX(f)); + case 0x0502: + return api_free(f, (uint32_t)SI(f) << 16 | DI(f)); + case 0x0503: + return api_resize(f, (uint32_t)SI(f) << 16 | DI(f), (uint32_t)BX(f) << 16 | CX(f)); + case 0x0600: case 0x0601: case 0x0602: case 0x0603: + case 0x0702: case 0x0703: + return; /* no virtual memory: nothing to do */ + case 0x0604: /* page size */ + BX(f) = 0; + CX(f) = 4096; + return; + case 0x0800: + return api_physmap(f); + case 0x0801: + return; + case 0x0900: /* get and disable virtual IF */ + AL(f) = (f->eflags & EFL_IF) != 0; + f->eflags &= ~EFL_IF; + return; + case 0x0901: /* get and enable */ + AL(f) = (f->eflags & EFL_IF) != 0; + f->eflags |= EFL_IF; + return; + case 0x0902: /* get */ + AL(f) = (f->eflags & EFL_IF) != 0; + return; + } + api_error(f, ERR_UNSUPPORTED); +} + +/* ---------------------------------------------------------------- */ + +void dpmi_init(void) +{ + uint32_t off, p; + uint8_t *code = (uint8_t *)HOST_AREA; + + /* host code page (read only for clients) and host PM stack */ + p = page_alloc(); + if (!p || !map_page(HOST_AREA, p, 5)) + panic("dpmi: no memory"); + memset(code, 0xf4, 4096); /* HLT everywhere ... */ + code[HBP_RETF] = 0xcb; /* ... except the no-op RETF */ + /* a host stack per session; session 0's is mapped now */ + for (off = 0; off < MAX_SESSIONS * HSTACK_PAGES; off++) + if (!(hstack_pages[off / HSTACK_PAGES][off % HSTACK_PAGES] = page_alloc())) + panic("dpmi: no memory"); + for (off = 0; off < HSTACK_PAGES; off++) + if (!map_page(HOST_AREA + 4096 * (off + 1), hstack_pages[0][off], 7)) + panic("dpmi: no memory"); + gdt_set(HCODE_SEL >> 3, HOST_AREA, 0xfff, 0xfa, 0x40); + gdt_set(HDATA_SEL >> 3, HOST_AREA, HOST_STACK - 1, 0xf2, 0x40); + /* selector 0040h: the BIOS data area, as real mode segment 0040h is. + DOS programs moved to protected mode count on it (DOS/4GW reads the + timer ticks through it; without it, it divided by nonsense - only at + times, so only some programs failed) */ + gdt_set(BDA_SEL >> 3, 0x400, 0xffff, 0xf2, 0x00); + ldt_load(ldt, LDT_ENTRIES); +} diff --git a/mdvmm/core/entry.asm b/mdvmm/core/entry.asm new file mode 100644 index 00000000..3e4c0f4e --- /dev/null +++ b/mdvmm/core/entry.asm @@ -0,0 +1,226 @@ +; MDVMM core entry, paging bootstrap and interrupt stubs. +; +; A loader jumps to _start in 32-bit protected mode, paging off, flat +; segments, with +; EAX = physical address the core image was loaded at (4K aligned) +; EBX = linear address of struct bootinfo (below 1MB) +; The core is linked at KBASE. Before paging is on, this code runs at its +; physical address and must be position independent. + +%include "bootinfo.inc" + +KBASE equ 0xF0000000 +KCODE equ 0x08 +KDATA equ 0x10 + +bits 32 + +section .text.entry +global _start +extern __bss_start, __bss_end, core_main + +_start: + push dword 2 ; known EFLAGS: IF=0, IOPL=0, NT=0 + popfd + cld + mov ebp, eax ; ebp = physical base + + ; zero .bss (physical addresses) + lea edi, [ebp + (__bss_start - KBASE)] + mov ecx, __bss_end + sub ecx, __bss_start + shr ecx, 2 + xor eax, eax + rep stosd + + ; page directory, identity PT for the first 4MB, PTs for the pool + lea esi, [ebp + (__bss_end - KBASE)] ; esi = PD (phys) + mov edx, [ebx + bootinfo.pool_size] + add edx, 0x3FFFFF + shr edx, 22 ; edx = number of pool PTs + lea ecx, [edx + 2] + shl ecx, 10 + mov edi, esi + xor eax, eax + rep stosd + + ; PT0: identity map 0-4MB. Only the V86 address space (0-10FFFFh) + ; is user accessible; the rest belongs to XMS and the monitor. + lea edi, [esi + 4096] + mov eax, 7 + mov ecx, 1024 +.pt0: cmp eax, 110000h + jb .user + and al, ~4 +.user: stosd + add eax, 4096 + loop .pt0 + lea eax, [esi + 4096 + 7] + mov [esi], eax + + ; pool PTs: KBASE.. -> pool, supervisor only + lea edi, [esi + 8192] + mov eax, ebp + or eax, 3 + mov ecx, [ebx + bootinfo.pool_size] + shr ecx, 12 +.ptk: stosd + add eax, 4096 + loop .ptk + lea edi, [esi + (KBASE >> 22) * 4] + lea eax, [esi + 8192 + 3] + mov ecx, edx +.pdk: stosd + add eax, 4096 + loop .pdk + + ; recursive mapping: PTs at 0xFFC00000, PD at 0xFFFFF000 + lea eax, [esi + 3] + mov [esi + 1023 * 4], eax + + ; first free physical page after the tables + lea edi, [edx + 2] + shl edi, 12 + add edi, esi + + ; turn paging on from identity mapped low memory, continue high + mov ecx, high_entry + mov eax, [ebx + bootinfo.trampoline] + jmp eax + +high_entry: + mov esp, kstack_top + push edi ; first free physical page + push ebx ; struct bootinfo * + call core_main +.hang: cli + hlt + jmp .hang + +section .text + +; void gdt_load(void *gdtr) +global gdt_load +gdt_load: + mov eax, [esp + 4] + lgdt [eax] + mov ax, KDATA + mov ds, ax + mov es, ax + mov fs, ax + mov gs, ax + mov ss, ax + jmp KCODE:.flush +.flush: ret + +; void enter_frame(const struct frame *f) - resume a trap frame (e.g. enter +; V86). The frame is copied to the top of the kernel stack, the C caller's +; stack is abandoned. +FRAME_SIZE equ 92 +global enter_frame +enter_frame: + mov esi, [esp + 4] + mov edi, kstack_top - FRAME_SIZE + mov ecx, FRAME_SIZE / 4 + cld + rep movsd + mov esp, kstack_top - FRAME_SIZE + jmp trap_return + +; Interrupt stubs: push a dummy error code where the CPU does not, then +; the vector number. Frame layout matches struct frame in core.h. +%assign i 0 +%rep 256 +isr%[i]: + %if i == 8 || (i >= 10 && i <= 14) || i == 17 || i == 21 || i == 29 || i == 30 + %else + push dword 0 + %endif + push dword i + jmp isr_common +%assign i i+1 +%endrep + +extern trap_dispatch +isr_common: + pushad + push ds + push es + push fs + push gs + mov ax, KDATA + mov ds, ax + mov es, ax + cld + push esp + call trap_dispatch + add esp, 4 +; Returning to a ring 3 protected mode client: IRET to a 16 bit stack +; segment only reloads SP, so ESP[31:16] would leak the monitor's stack +; address. "espfix": IRET from an alias stack segment whose ESP already +; has the client's upper 16 bits. +EFL_VM equ 0x20000 +ESPFIX_SEL equ 0x38 +extern gdt_table +global trap_return +trap_return: + test dword [esp + 64], EFL_VM ; frame eflags + jnz .plain + test byte [esp + 60], 3 ; frame cs: back to ring 3? + jz .plain + mov eax, [esp + 56] ; eip, cs, eflags, esp, ss + mov [espfix_buf], eax + mov eax, [esp + 60] + mov [espfix_buf + 4], eax + mov eax, [esp + 64] + mov [espfix_buf + 8], eax + mov eax, [esp + 68] + mov [espfix_buf + 12], eax + mov eax, [esp + 72] + mov [espfix_buf + 16], eax + mov ecx, [esp + 68] + and ecx, 0xffff0000 ; new ESP: client's upper half + mov [espfix_ptr], ecx + mov eax, espfix_buf + sub eax, ecx ; segment base + mov [gdt_table + ESPFIX_SEL + 2], ax + shr eax, 16 + mov [gdt_table + ESPFIX_SEL + 4], al + mov [gdt_table + ESPFIX_SEL + 7], ah + pop gs + pop fs + pop es + pop ds + popad + lss esp, [cs:espfix_ptr] + iretd +.plain: + pop gs + pop fs + pop es + pop ds + popad + add esp, 8 ; vector, error code + iretd + +section .rodata +global isr_table +isr_table: +%assign i 0 +%rep 256 + dd isr%[i] +%assign i i+1 +%endrep + +section .data +espfix_ptr: + dd 0 + dw ESPFIX_SEL + +section .bss +align 16 +espfix_buf: + resb 32 + resb 16384 +global kstack_top +kstack_top: diff --git a/mdvmm/core/fbcon.c b/mdvmm/core/fbcon.c new file mode 100644 index 00000000..c8d391cf --- /dev/null +++ b/mdvmm/core/fbcon.c @@ -0,0 +1,290 @@ +/* MDVMM core - text screen on a UEFI framebuffer + * + * The virtual BIOS keeps the 80x25 text screen in RAM at B8000h (the + * pages in vram_phys). On every timer tick the cells that changed since + * the last update are drawn on the GOP framebuffer with an 8x16 font, + * scaled up when the framebuffer has room, plus a blinking cursor. + * + * Before DOS starts, and after a panic, the framebuffer shows the + * monitor's own log (kprintf) instead: on real machines there is no other + * way to see why a boot stopped. + */ +#include "core.h" + +#define COLS 80 +#define ROWS 25 + +extern const uint8_t font8x16[4096]; + +static uint32_t *fb; +static uint32_t pitch, scale, x0, y0; +static uint32_t palette[16]; +static uint16_t shadow[COLS * ROWS]; +static int cur_cell = -1, blink; +static int suspended; /* a program owns the framebuffer */ +static int mouse_cell = -1; /* where the mouse cursor was drawn */ +static uint32_t ticks; +static uint16_t cursor_shape = 0x0d0e; + +/* the monitor's log: the last lines are kept, and drawn while log_on */ +#define LOG_LINES 64 +#define LOG_COLS 120 +static char ring[LOG_LINES][LOG_COLS + 1]; +static uint32_t ring_line, ring_col; /* line being written (not modulo) */ +static int log_on; +static uint32_t lcols, lrows, lrow, lcol, lscale; + +static const uint8_t cga[16][3] = { + { 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0xaa }, { 0x00, 0xaa, 0x00 }, { 0x00, 0xaa, 0xaa }, + { 0xaa, 0x00, 0x00 }, { 0xaa, 0x00, 0xaa }, { 0xaa, 0x55, 0x00 }, { 0xaa, 0xaa, 0xaa }, + { 0x55, 0x55, 0x55 }, { 0x55, 0x55, 0xff }, { 0x55, 0xff, 0x55 }, { 0x55, 0xff, 0xff }, + { 0xff, 0x55, 0x55 }, { 0xff, 0x55, 0xff }, { 0xff, 0xff, 0x55 }, { 0xff, 0xff, 0xff }, +}; + +static void log_replay(uint32_t lines); + +void fbcon_init(void) +{ + uint32_t i, pages; + + if (!boot.fb_phys || boot.fb_width < COLS * 8 || boot.fb_height < ROWS * 16) + { + kprintf("fbcon: no usable framebuffer\n"); + return; + } + if (boot.fb_size > FB_MAX) + boot.fb_size = FB_MAX; + pages = (boot.fb_size + 4095) / 4096; + for (i = 0; i < pages; i++) + if (!map_page(FB_VIRT + i * 4096, boot.fb_phys + i * 4096, 3)) + return; + fb = (uint32_t *)FB_VIRT; + pitch = boot.fb_pitch; + scale = boot.fb_width / (COLS * 8); + if (boot.fb_height / (ROWS * 16) < scale) + scale = boot.fb_height / (ROWS * 16); + if (scale > 2) + scale = 2; + x0 = (boot.fb_width - COLS * 8 * scale) / 2; + y0 = (boot.fb_height - ROWS * 16 * scale) / 2; + for (i = 0; i < 16; i++) + palette[i] = boot.fb_format == FB_RGBX + ? (uint32_t)cga[i][0] | cga[i][1] << 8 | cga[i][2] << 16 + : (uint32_t)cga[i][2] | cga[i][1] << 8 | cga[i][0] << 16; + for (i = 0; i < pitch * boot.fb_height; i++) + fb[i] = 0; + for (i = 0; i < COLS * ROWS; i++) + shadow[i] = 0xffff; /* draw everything once */ + lscale = boot.fb_width >= 1600 && boot.fb_height >= 900 ? 2 : 1; /* readable on a photo */ + lcols = boot.fb_width / (8 * lscale); + if (lcols > LOG_COLS) + lcols = LOG_COLS; + lrows = boot.fb_height / (16 * lscale); + log_on = 1; + log_replay(lrows - 1); /* what was logged before this */ + kprintf("fbcon: %ux%u framebuffer at %08x, pitch %u, scale %u\n", boot.fb_width, + boot.fb_height, boot.fb_phys, pitch, scale); +} + +/* the log ends, the DOS text screen begins */ +void fbcon_text(void) +{ + int i; + + if (!fb) + return; + log_on = 0; + fbcon_clear(); + for (i = 0; i < COLS * ROWS; i++) + shadow[i] = 0xffff; + cur_cell = -1; +} + +/* a panic: back to the log, with its last lines */ +void fbcon_panic(void) +{ + if (!fb || log_on) + return; + log_on = 1; + log_replay(lrows > 24 ? lrows - 12 : lrows - 1); +} + +static void log_glyph(uint32_t row, uint32_t col, uint8_t ch) +{ + const uint8_t *glyph = font8x16 + ch * 16; + uint32_t y, x, sy, sx; + + for (y = 0; y < 16; y++) + for (sy = 0; sy < lscale; sy++) + { + uint32_t *p = fb + ((row * 16 + y) * lscale + sy) * pitch + col * 8 * lscale; + for (x = 0; x < 8; x++) + for (sx = 0; sx < lscale; sx++) + *p++ = glyph[y] & (0x80 >> x) ? palette[7] : 0; + } +} + +/* clear, then draw the last `lines` lines of the log */ +static void log_replay(uint32_t lines) +{ + uint32_t first, l, c; + + fbcon_clear(); + first = ring_line + 1 > lines ? ring_line + 1 - lines : 0; + if (ring_line >= LOG_LINES && first < ring_line - (LOG_LINES - 1)) + first = ring_line - (LOG_LINES - 1); + for (l = first; l <= ring_line; l++) + for (c = 0; c < lcols && ring[l % LOG_LINES][c]; c++) + log_glyph(l - first, c, (uint8_t)ring[l % LOG_LINES][c]); + lrow = ring_line - first; + lcol = ring_col < lcols ? ring_col : lcols; +} + +/* one character of the monitor's log (from kprintf) */ +void fbcon_log(char c) +{ + char *line = ring[ring_line % LOG_LINES]; + + if (c == '\r') + return; + if (c == '\n') + { + ring_line++; + ring_col = 0; + ring[ring_line % LOG_LINES][0] = 0; + if (log_on && fb && ++lrow >= lrows) + log_replay(lrows / 2); /* full: keep the newer half */ + lcol = 0; + return; + } + if (ring_col < LOG_COLS) + { + line[ring_col++] = c; + line[ring_col] = 0; + } + if (log_on && fb && lcol < lcols) + log_glyph(lrow, lcol++, (uint8_t)c); +} + +/* the last `lines` lines of the log (0: all that are kept) as text */ +uint32_t fbcon_log_copy(char *dst, uint32_t room, uint32_t lines) +{ + uint32_t first = ring_line >= LOG_LINES ? ring_line - (LOG_LINES - 1) : 0, l, n = 0; + const char *s; + + if (lines && ring_line + 1 > lines && ring_line + 1 - lines > first) + first = ring_line + 1 - lines; + for (l = first; l <= ring_line; l++) + { + for (s = ring[l % LOG_LINES]; *s && n + 2 < room; s++) + dst[n++] = *s; + if (n + 2 < room && l < ring_line) + { + dst[n++] = '\r'; + dst[n++] = '\n'; + } + } + return n; +} + +/* clear the whole framebuffer */ +void fbcon_clear(void) +{ + uint32_t i; + + if (fb) + for (i = 0; i < pitch * boot.fb_height; i++) + fb[i] = 0; +} + +/* a VBE graphics mode starts (on) or ends: stop or resume drawing text */ +void fbcon_graphics(int on) +{ + int i; + + suspended = on; + if (!on) + { + fbcon_clear(); + for (i = 0; i < COLS * ROWS; i++) + shadow[i] = 0xffff; /* redraw everything */ + cur_cell = -1; + mouse_cell = -1; + } +} + +static void draw_cell(int n, uint16_t v, int cursor, int invert) +{ + const uint8_t *glyph = font8x16 + (v & 0xff) * 16; + uint32_t fg = palette[(v >> 8) & 15], bg = palette[(v >> 12) & 7]; + + if (invert) /* the mouse cursor */ + { + fg = palette[((v >> 12) & 7) ^ 15]; + bg = palette[((v >> 8) & 7) ^ 7]; + } + uint32_t x = x0 + (uint32_t)(n % COLS) * 8 * scale; + uint32_t y = y0 + (uint32_t)(n / COLS) * 16 * scale; + uint16_t shape = cursor_shape; + int cs = shape >> 8 & 0x1f, ce = shape & 0x1f, row, col, sy, sx; + + if (shape & 0x2000) + cursor = 0; /* hidden */ + if (ce < 8 && cs < 8) + { + cs *= 2; /* CGA style shape: 8 lines */ + ce = ce * 2 + 1; + } + for (row = 0; row < 16; row++) + { + uint8_t bits = glyph[row]; + if (cursor && row >= cs && row <= ce) + bits = 0xff; + for (sy = 0; sy < (int)scale; sy++) + { + uint32_t *p = fb + (y + row * scale + sy) * pitch + x; + for (col = 0; col < 8; col++) + for (sx = 0; sx < (int)scale; sx++) + *p++ = bits & (0x80 >> col) ? fg : bg; + } + } +} + +/* timer tick: draw what changed on the visible page */ +void fbcon_update(void) +{ + const uint16_t *page; + uint16_t pos; + int n, c, mc; + uint8_t active; + const uint8_t *fbda; + + if (!fb || suspended || log_on) + return; + /* page, cursor and its shape of the session on the display (not of + whichever session happens to run) */ + fbda = vm_focus_bda(); + active = fbda[0x62] & 7; + page = pool_ptr(vram_phys[active]); /* 4K per text page */ + pos = *(uint16_t *)(fbda + 0x50 + active * 2); + cursor_shape = *(uint16_t *)(fbda + 0x60); + c = (pos >> 8) * COLS + (pos & 0xff); + if ((pos >> 8) >= ROWS || (pos & 0xff) >= COLS) + c = -1; + if (++ticks % 4 == 0) + blink = !blink; + + mc = mouse_text_cell(); + for (n = 0; n < COLS * ROWS; n++) + { + int cursor = n == c && blink; + if (page[n] != shadow[n] || n == cur_cell || n == c || + (mc != mouse_cell && (n == mc || n == mouse_cell))) + { + draw_cell(n, page[n], cursor, n == mc); + shadow[n] = page[n]; + } + } + mouse_cell = mc; + cur_cell = c; +} diff --git a/mdvmm/core/font.c b/mdvmm/core/font.c new file mode 100644 index 00000000..6be64567 --- /dev/null +++ b/mdvmm/core/font.c @@ -0,0 +1,263 @@ +/* 8x16 code page 437 console font, 256 glyphs x 16 rows. + * From the Linux kernel, lib/fonts/font_8x16.c (SPDX: GPL-2.0), + * generated there by cpi2fnt. */ +#include + +const uint8_t font8x16[4096] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00 */ + 0x00, 0x00, 0x7e, 0x81, 0xa5, 0x81, 0x81, 0xbd, 0x99, 0x81, 0x81, 0x7e, 0x00, 0x00, 0x00, 0x00, /* 01 */ + 0x00, 0x00, 0x7e, 0xff, 0xdb, 0xff, 0xff, 0xc3, 0xe7, 0xff, 0xff, 0x7e, 0x00, 0x00, 0x00, 0x00, /* 02 */ + 0x00, 0x00, 0x00, 0x00, 0x6c, 0xfe, 0xfe, 0xfe, 0xfe, 0x7c, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, /* 03 */ + 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x7c, 0xfe, 0x7c, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, /* 04 */ + 0x00, 0x00, 0x00, 0x18, 0x3c, 0x3c, 0xe7, 0xe7, 0xe7, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 05 */ + 0x00, 0x00, 0x00, 0x18, 0x3c, 0x7e, 0xff, 0xff, 0x7e, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 06 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3c, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 07 */ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe7, 0xc3, 0xc3, 0xe7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 08 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x66, 0x42, 0x42, 0x66, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, /* 09 */ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xc3, 0x99, 0xbd, 0xbd, 0x99, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0a */ + 0x00, 0x00, 0x1e, 0x0e, 0x1a, 0x32, 0x78, 0xcc, 0xcc, 0xcc, 0xcc, 0x78, 0x00, 0x00, 0x00, 0x00, /* 0b */ + 0x00, 0x00, 0x3c, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, /* 0c */ + 0x00, 0x00, 0x3f, 0x33, 0x3f, 0x30, 0x30, 0x30, 0x30, 0x70, 0xf0, 0xe0, 0x00, 0x00, 0x00, 0x00, /* 0d */ + 0x00, 0x00, 0x7f, 0x63, 0x7f, 0x63, 0x63, 0x63, 0x63, 0x67, 0xe7, 0xe6, 0xc0, 0x00, 0x00, 0x00, /* 0e */ + 0x00, 0x00, 0x00, 0x18, 0x18, 0xdb, 0x3c, 0xe7, 0x3c, 0xdb, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, /* 0f */ + 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfe, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, /* 10 */ + 0x00, 0x02, 0x06, 0x0e, 0x1e, 0x3e, 0xfe, 0x3e, 0x1e, 0x0e, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00, /* 11 */ + 0x00, 0x00, 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, /* 12 */ + 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, /* 13 */ + 0x00, 0x00, 0x7f, 0xdb, 0xdb, 0xdb, 0x7b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x00, 0x00, 0x00, 0x00, /* 14 */ + 0x00, 0x7c, 0xc6, 0x60, 0x38, 0x6c, 0xc6, 0xc6, 0x6c, 0x38, 0x0c, 0xc6, 0x7c, 0x00, 0x00, 0x00, /* 15 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xfe, 0xfe, 0xfe, 0x00, 0x00, 0x00, 0x00, /* 16 */ + 0x00, 0x00, 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x7e, 0x00, 0x00, 0x00, 0x00, /* 17 */ + 0x00, 0x00, 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, /* 18 */ + 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00, /* 19 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x0c, 0xfe, 0x0c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1a */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x60, 0xfe, 0x60, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1b */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1c */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x6c, 0xfe, 0x6c, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1d */ + 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x38, 0x7c, 0x7c, 0xfe, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1e */ + 0x00, 0x00, 0x00, 0x00, 0xfe, 0xfe, 0x7c, 0x7c, 0x38, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1f */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 20 */ + 0x00, 0x00, 0x18, 0x3c, 0x3c, 0x3c, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, /* 21 */ + 0x00, 0x66, 0x66, 0x66, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 22 */ + 0x00, 0x00, 0x00, 0x6c, 0x6c, 0xfe, 0x6c, 0x6c, 0x6c, 0xfe, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00, /* 23 */ + 0x18, 0x18, 0x7c, 0xc6, 0xc2, 0xc0, 0x7c, 0x06, 0x06, 0x86, 0xc6, 0x7c, 0x18, 0x18, 0x00, 0x00, /* 24 */ + 0x00, 0x00, 0x00, 0x00, 0xc2, 0xc6, 0x0c, 0x18, 0x30, 0x60, 0xc6, 0x86, 0x00, 0x00, 0x00, 0x00, /* 25 */ + 0x00, 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x76, 0xdc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* 26 */ + 0x00, 0x30, 0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 27 */ + 0x00, 0x00, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x18, 0x0c, 0x00, 0x00, 0x00, 0x00, /* 28 */ + 0x00, 0x00, 0x30, 0x18, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, /* 29 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x3c, 0xff, 0x3c, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2a */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2b */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, /* 2c */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2d */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, /* 2e */ + 0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, /* 2f */ + 0x00, 0x00, 0x38, 0x6c, 0xc6, 0xc6, 0xd6, 0xd6, 0xc6, 0xc6, 0x6c, 0x38, 0x00, 0x00, 0x00, 0x00, /* 30 */ + 0x00, 0x00, 0x18, 0x38, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7e, 0x00, 0x00, 0x00, 0x00, /* 31 */ + 0x00, 0x00, 0x7c, 0xc6, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00, /* 32 */ + 0x00, 0x00, 0x7c, 0xc6, 0x06, 0x06, 0x3c, 0x06, 0x06, 0x06, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 33 */ + 0x00, 0x00, 0x0c, 0x1c, 0x3c, 0x6c, 0xcc, 0xfe, 0x0c, 0x0c, 0x0c, 0x1e, 0x00, 0x00, 0x00, 0x00, /* 34 */ + 0x00, 0x00, 0xfe, 0xc0, 0xc0, 0xc0, 0xfc, 0x06, 0x06, 0x06, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 35 */ + 0x00, 0x00, 0x38, 0x60, 0xc0, 0xc0, 0xfc, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 36 */ + 0x00, 0x00, 0xfe, 0xc6, 0x06, 0x06, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00, /* 37 */ + 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 38 */ + 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0x7e, 0x06, 0x06, 0x06, 0x0c, 0x78, 0x00, 0x00, 0x00, 0x00, /* 39 */ + 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, /* 3a */ + 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, /* 3b */ + 0x00, 0x00, 0x00, 0x06, 0x0c, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x00, 0x00, 0x00, 0x00, /* 3c */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 3d */ + 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x0c, 0x18, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, /* 3e */ + 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0x0c, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, /* 3f */ + 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xde, 0xde, 0xde, 0xdc, 0xc0, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 40 */ + 0x00, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, /* 41 */ + 0x00, 0x00, 0xfc, 0x66, 0x66, 0x66, 0x7c, 0x66, 0x66, 0x66, 0x66, 0xfc, 0x00, 0x00, 0x00, 0x00, /* 42 */ + 0x00, 0x00, 0x3c, 0x66, 0xc2, 0xc0, 0xc0, 0xc0, 0xc0, 0xc2, 0x66, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 43 */ + 0x00, 0x00, 0xf8, 0x6c, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x6c, 0xf8, 0x00, 0x00, 0x00, 0x00, /* 44 */ + 0x00, 0x00, 0xfe, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x62, 0x66, 0xfe, 0x00, 0x00, 0x00, 0x00, /* 45 */ + 0x00, 0x00, 0xfe, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x00, /* 46 */ + 0x00, 0x00, 0x3c, 0x66, 0xc2, 0xc0, 0xc0, 0xde, 0xc6, 0xc6, 0x66, 0x3a, 0x00, 0x00, 0x00, 0x00, /* 47 */ + 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, /* 48 */ + 0x00, 0x00, 0x3c, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 49 */ + 0x00, 0x00, 0x1e, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0xcc, 0xcc, 0xcc, 0x78, 0x00, 0x00, 0x00, 0x00, /* 4a */ + 0x00, 0x00, 0xe6, 0x66, 0x66, 0x6c, 0x78, 0x78, 0x6c, 0x66, 0x66, 0xe6, 0x00, 0x00, 0x00, 0x00, /* 4b */ + 0x00, 0x00, 0xf0, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x62, 0x66, 0xfe, 0x00, 0x00, 0x00, 0x00, /* 4c */ + 0x00, 0x00, 0xc6, 0xee, 0xfe, 0xfe, 0xd6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, /* 4d */ + 0x00, 0x00, 0xc6, 0xe6, 0xf6, 0xfe, 0xde, 0xce, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, /* 4e */ + 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 4f */ + 0x00, 0x00, 0xfc, 0x66, 0x66, 0x66, 0x7c, 0x60, 0x60, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x00, /* 50 */ + 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xd6, 0xde, 0x7c, 0x0c, 0x0e, 0x00, 0x00, /* 51 */ + 0x00, 0x00, 0xfc, 0x66, 0x66, 0x66, 0x7c, 0x6c, 0x66, 0x66, 0x66, 0xe6, 0x00, 0x00, 0x00, 0x00, /* 52 */ + 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0x60, 0x38, 0x0c, 0x06, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 53 */ + 0x00, 0x00, 0x7e, 0x7e, 0x5a, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 54 */ + 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 55 */ + 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x6c, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, /* 56 */ + 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xd6, 0xd6, 0xd6, 0xfe, 0xee, 0x6c, 0x00, 0x00, 0x00, 0x00, /* 57 */ + 0x00, 0x00, 0xc6, 0xc6, 0x6c, 0x7c, 0x38, 0x38, 0x7c, 0x6c, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, /* 58 */ + 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 59 */ + 0x00, 0x00, 0xfe, 0xc6, 0x86, 0x0c, 0x18, 0x30, 0x60, 0xc2, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00, /* 5a */ + 0x00, 0x00, 0x3c, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 5b */ + 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0x70, 0x38, 0x1c, 0x0e, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00, /* 5c */ + 0x00, 0x00, 0x3c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 5d */ + 0x10, 0x38, 0x6c, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 5e */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, /* 5f */ + 0x00, 0x30, 0x18, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 60 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* 61 */ + 0x00, 0x00, 0xe0, 0x60, 0x60, 0x78, 0x6c, 0x66, 0x66, 0x66, 0x66, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 62 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc0, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 63 */ + 0x00, 0x00, 0x1c, 0x0c, 0x0c, 0x3c, 0x6c, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* 64 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 65 */ + 0x00, 0x00, 0x1c, 0x36, 0x32, 0x30, 0x78, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00, 0x00, 0x00, 0x00, /* 66 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0xcc, 0x78, 0x00, /* 67 */ + 0x00, 0x00, 0xe0, 0x60, 0x60, 0x6c, 0x76, 0x66, 0x66, 0x66, 0x66, 0xe6, 0x00, 0x00, 0x00, 0x00, /* 68 */ + 0x00, 0x00, 0x18, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 69 */ + 0x00, 0x00, 0x06, 0x06, 0x00, 0x0e, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x66, 0x66, 0x3c, 0x00, /* 6a */ + 0x00, 0x00, 0xe0, 0x60, 0x60, 0x66, 0x6c, 0x78, 0x78, 0x6c, 0x66, 0xe6, 0x00, 0x00, 0x00, 0x00, /* 6b */ + 0x00, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 6c */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xec, 0xfe, 0xd6, 0xd6, 0xd6, 0xd6, 0xc6, 0x00, 0x00, 0x00, 0x00, /* 6d */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xdc, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, /* 6e */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 6f */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xdc, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7c, 0x60, 0x60, 0xf0, 0x00, /* 70 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0x0c, 0x1e, 0x00, /* 71 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xdc, 0x76, 0x66, 0x60, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x00, /* 72 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0x60, 0x38, 0x0c, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 73 */ + 0x00, 0x00, 0x10, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x30, 0x30, 0x36, 0x1c, 0x00, 0x00, 0x00, 0x00, /* 74 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* 75 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x6c, 0x38, 0x00, 0x00, 0x00, 0x00, /* 76 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0xc6, 0xd6, 0xd6, 0xd6, 0xfe, 0x6c, 0x00, 0x00, 0x00, 0x00, /* 77 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0x6c, 0x38, 0x38, 0x38, 0x6c, 0xc6, 0x00, 0x00, 0x00, 0x00, /* 78 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7e, 0x06, 0x0c, 0xf8, 0x00, /* 79 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xcc, 0x18, 0x30, 0x60, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00, /* 7a */ + 0x00, 0x00, 0x0e, 0x18, 0x18, 0x18, 0x70, 0x18, 0x18, 0x18, 0x18, 0x0e, 0x00, 0x00, 0x00, 0x00, /* 7b */ + 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, /* 7c */ + 0x00, 0x00, 0x70, 0x18, 0x18, 0x18, 0x0e, 0x18, 0x18, 0x18, 0x18, 0x70, 0x00, 0x00, 0x00, 0x00, /* 7d */ + 0x00, 0x76, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 7e */ + 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, /* 7f */ + 0x00, 0x00, 0x3c, 0x66, 0xc2, 0xc0, 0xc0, 0xc0, 0xc0, 0xc2, 0x66, 0x3c, 0x18, 0x70, 0x00, 0x00, /* 80 */ + 0x00, 0x00, 0xcc, 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* 81 */ + 0x00, 0x0c, 0x18, 0x30, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 82 */ + 0x00, 0x10, 0x38, 0x6c, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* 83 */ + 0x00, 0x00, 0xcc, 0x00, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* 84 */ + 0x00, 0x60, 0x30, 0x18, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* 85 */ + 0x00, 0x38, 0x6c, 0x38, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* 86 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc0, 0xc0, 0xc0, 0xc6, 0x7c, 0x18, 0x70, 0x00, 0x00, /* 87 */ + 0x00, 0x10, 0x38, 0x6c, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 88 */ + 0x00, 0x00, 0xc6, 0x00, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 89 */ + 0x00, 0x60, 0x30, 0x18, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 8a */ + 0x00, 0x00, 0x66, 0x00, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 8b */ + 0x00, 0x18, 0x3c, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 8c */ + 0x00, 0x60, 0x30, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, /* 8d */ + 0x00, 0xc6, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, /* 8e */ + 0x38, 0x6c, 0x38, 0x10, 0x38, 0x6c, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, /* 8f */ + 0x0c, 0x18, 0x00, 0xfe, 0x66, 0x62, 0x68, 0x78, 0x68, 0x62, 0x66, 0xfe, 0x00, 0x00, 0x00, 0x00, /* 90 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xec, 0x36, 0x36, 0x7e, 0xd8, 0xd8, 0x6e, 0x00, 0x00, 0x00, 0x00, /* 91 */ + 0x00, 0x00, 0x3e, 0x6c, 0xcc, 0xcc, 0xfe, 0xcc, 0xcc, 0xcc, 0xcc, 0xce, 0x00, 0x00, 0x00, 0x00, /* 92 */ + 0x00, 0x10, 0x38, 0x6c, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 93 */ + 0x00, 0x00, 0xc6, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 94 */ + 0x00, 0x60, 0x30, 0x18, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 95 */ + 0x00, 0x30, 0x78, 0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* 96 */ + 0x00, 0x60, 0x30, 0x18, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* 97 */ + 0x00, 0x00, 0xc6, 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7e, 0x06, 0x0c, 0x78, 0x00, /* 98 */ + 0x00, 0xc6, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 99 */ + 0x00, 0xc6, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* 9a */ + 0x00, 0x18, 0x18, 0x7c, 0xc6, 0xc0, 0xc0, 0xc0, 0xc6, 0x7c, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, /* 9b */ + 0x00, 0x38, 0x6c, 0x64, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x60, 0xe6, 0xfc, 0x00, 0x00, 0x00, 0x00, /* 9c */ + 0x00, 0x00, 0x66, 0x66, 0x3c, 0x18, 0x7e, 0x18, 0x7e, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, /* 9d */ + 0x00, 0xf8, 0xcc, 0xcc, 0xf8, 0xc4, 0xcc, 0xde, 0xcc, 0xcc, 0xcc, 0xc6, 0x00, 0x00, 0x00, 0x00, /* 9e */ + 0x00, 0x0e, 0x1b, 0x18, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x18, 0xd8, 0x70, 0x00, 0x00, 0x00, 0x00, /* 9f */ + 0x00, 0x18, 0x30, 0x60, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* a0 */ + 0x00, 0x0c, 0x18, 0x30, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, /* a1 */ + 0x00, 0x18, 0x30, 0x60, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* a2 */ + 0x00, 0x18, 0x30, 0x60, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, /* a3 */ + 0x00, 0x00, 0x76, 0xdc, 0x00, 0xdc, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, /* a4 */ + 0x76, 0xdc, 0x00, 0xc6, 0xe6, 0xf6, 0xfe, 0xde, 0xce, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, /* a5 */ + 0x00, 0x00, 0x3c, 0x6c, 0x6c, 0x3e, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a6 */ + 0x00, 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x00, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a7 */ + 0x00, 0x00, 0x30, 0x30, 0x00, 0x30, 0x30, 0x60, 0xc0, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, /* a8 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, /* a9 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x06, 0x06, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, /* aa */ + 0x00, 0x60, 0xe0, 0x62, 0x66, 0x6c, 0x18, 0x30, 0x60, 0xdc, 0x86, 0x0c, 0x18, 0x3e, 0x00, 0x00, /* ab */ + 0x00, 0x60, 0xe0, 0x62, 0x66, 0x6c, 0x18, 0x30, 0x66, 0xce, 0x9a, 0x3f, 0x06, 0x06, 0x00, 0x00, /* ac */ + 0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x3c, 0x3c, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00, /* ad */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x6c, 0xd8, 0x6c, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ae */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xd8, 0x6c, 0x36, 0x6c, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* af */ + 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, /* b0 */ + 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, /* b1 */ + 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, /* b2 */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* b3 */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* b4 */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* b5 */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xf6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* b6 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* b7 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* b8 */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0xf6, 0x06, 0xf6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* b9 */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* ba */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x06, 0xf6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* bb */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0xf6, 0x06, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* bc */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* bd */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* be */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* bf */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c0 */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c1 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* c2 */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* c3 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c4 */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* c5 */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* c6 */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* c7 */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c8 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* c9 */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0xf7, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ca */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xf7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* cb */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* cc */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* cd */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0xf7, 0x00, 0xf7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* ce */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* cf */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d0 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* d1 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* d2 */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d3 */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d4 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* d5 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* d6 */ + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xff, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, /* d7 */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0x18, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* d8 */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d9 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* da */ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* db */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* dc */ + 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, /* dd */ + 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, /* de */ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* df */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xdc, 0xd8, 0xd8, 0xd8, 0xdc, 0x76, 0x00, 0x00, 0x00, 0x00, /* e0 */ + 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0xd8, 0xcc, 0xc6, 0xc6, 0xc6, 0xcc, 0x00, 0x00, 0x00, 0x00, /* e1 */ + 0x00, 0x00, 0xfe, 0xc6, 0xc6, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0x00, 0x00, 0x00, /* e2 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00, /* e3 */ + 0x00, 0x00, 0xfe, 0xc6, 0x60, 0x30, 0x18, 0x18, 0x30, 0x60, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00, /* e4 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0x70, 0x00, 0x00, 0x00, 0x00, /* e5 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7c, 0x60, 0x60, 0xc0, 0x00, /* e6 */ + 0x00, 0x00, 0x00, 0x00, 0x76, 0xdc, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, /* e7 */ + 0x00, 0x00, 0x7e, 0x18, 0x3c, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x7e, 0x00, 0x00, 0x00, 0x00, /* e8 */ + 0x00, 0x00, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0x6c, 0x38, 0x00, 0x00, 0x00, 0x00, /* e9 */ + 0x00, 0x00, 0x38, 0x6c, 0xc6, 0xc6, 0xc6, 0x6c, 0x6c, 0x6c, 0x6c, 0xee, 0x00, 0x00, 0x00, 0x00, /* ea */ + 0x00, 0x00, 0x1e, 0x30, 0x18, 0x0c, 0x3e, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x00, 0x00, 0x00, 0x00, /* eb */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0xdb, 0xdb, 0xdb, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ec */ + 0x00, 0x00, 0x00, 0x03, 0x06, 0x7e, 0xdb, 0xdb, 0xf3, 0x7e, 0x60, 0xc0, 0x00, 0x00, 0x00, 0x00, /* ed */ + 0x00, 0x00, 0x1c, 0x30, 0x60, 0x60, 0x7c, 0x60, 0x60, 0x60, 0x30, 0x1c, 0x00, 0x00, 0x00, 0x00, /* ee */ + 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, /* ef */ + 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x00, 0xfe, 0x00, 0x00, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, /* f0 */ + 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, /* f1 */ + 0x00, 0x00, 0x00, 0x30, 0x18, 0x0c, 0x06, 0x0c, 0x18, 0x30, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, /* f2 */ + 0x00, 0x00, 0x00, 0x0c, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0c, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, /* f3 */ + 0x00, 0x00, 0x0e, 0x1b, 0x1b, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, /* f4 */ + 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xd8, 0xd8, 0xd8, 0x70, 0x00, 0x00, 0x00, /* f5 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x7e, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f6 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xdc, 0x00, 0x76, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f7 */ + 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f8 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f9 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* fa */ + 0x00, 0x0f, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0xec, 0x6c, 0x6c, 0x3c, 0x1c, 0x00, 0x00, 0x00, 0x00, /* fb */ + 0x00, 0x6c, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* fc */ + 0x00, 0x3c, 0x66, 0x0c, 0x18, 0x32, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* fd */ + 0x00, 0x00, 0x00, 0x00, 0x7e, 0x7e, 0x7e, 0x7e, 0x7e, 0x7e, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, /* fe */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ff */ +}; diff --git a/mdvmm/core/ipxenic.c b/mdvmm/core/ipxenic.c new file mode 100644 index 00000000..b0c6d4ca --- /dev/null +++ b/mdvmm/core/ipxenic.c @@ -0,0 +1,129 @@ +/* MDVMM core - network cards through iPXE's drivers + * + * mdvmm/ipxe builds iPXE's PCI network drivers into one object with a + * handful of entry points (ipxe_*, glue.c there). This file gives that + * object what it needs from the monitor (log, device memory, delays) and + * registers each network device it finds as a `struct nic`. + */ +#include "core.h" + +int ipxe_init(void); +int ipxe_get(int index, char *name, unsigned char *mac); +int ipxe_send(int index, const void *frame, int len); +int ipxe_recv(int index, void *frame, int room); +int ipxe_link(int index); +void ipxe_debug(int index); +void ipxe_set_virt_offset(unsigned long offset); + +#define MAX_CARDS 4 + +struct card { + struct nic nic; + int index; + char name[32]; +}; + +static struct card cards[MAX_CARDS]; + +/* services for the iPXE object */ +void mdvmm_log(const char *text); +void *mdvmm_ioremap(unsigned long phys, unsigned long len); +void mdvmm_udelay(unsigned long usecs); + +void mdvmm_log(const char *text) +{ + kprintf("%s\n", text); +} + +void *mdvmm_ioremap(unsigned long phys, unsigned long len) +{ + return mmio_map(phys, len); +} + +void mdvmm_udelay(unsigned long usecs) +{ + udelay(usecs); +} + +/* milliseconds since the start, from the time stamp counter (calibrated + against the 8254 in ipxenic_init): iPXE's timeouts need a clock that + runs while the monitor does not take interrupts */ +static uint32_t tsc_per_ms; +static uint64_t tsc_start; + +static uint64_t rdtsc(void) +{ + uint32_t lo, hi; + __asm__ volatile("rdtsc" : "=a"(lo), "=d"(hi)); + return (uint64_t)hi << 32 | lo; +} + +unsigned long mdvmm_ms(void); +unsigned long mdvmm_ms(void) +{ + uint64_t d = rdtsc() - tsc_start; + uint32_t lo = (uint32_t)d, hi = (uint32_t)(d >> 32), q, r; + + if (!tsc_per_ms || hi >= tsc_per_ms) + return 0; /* not calibrated (or 49 days on) */ + __asm__("divl %4" : "=a"(q), "=d"(r) : "a"(lo), "d"(hi), "rm"(tsc_per_ms)); + (void)r; + return q; +} + +static int c_send(struct nic *n, const void *frame, int len) +{ + return ipxe_send(((struct card *)n)->index, frame, len); +} + +static int c_recv(struct nic *n, void *frame, int room) +{ + return ipxe_recv(((struct card *)n)->index, frame, room); +} + +static int c_link(struct nic *n) +{ + return ipxe_link(((struct card *)n)->index); +} + +static void c_debug(struct nic *n) +{ + ipxe_debug(((struct card *)n)->index); +} + +void ipxenic_init(void) +{ + int n, i; + + /* the clock: time stamp counter ticks in two timer ticks (109.85 ms) */ + tsc_start = rdtsc(); + if (pit_wait(2)) + { + uint64_t d = rdtsc() - tsc_start; + uint32_t q, r; + d = d * 100; /* / 10985 = per ms */ + __asm__("divl %4" : "=a"(q), "=d"(r) : "a"((uint32_t)d), "d"((uint32_t)(d >> 32)), "rm"((uint32_t)10985)); + (void)r; + tsc_per_ms = q; + } + if (!tsc_per_ms) + kprintf("ipxe: no clock (the 8254 does not tick): driver timeouts will not work\n"); + tsc_start = rdtsc(); + + /* iPXE's memory model: physical = virtual + offset, true for the pool */ + ipxe_set_virt_offset(boot.pool_phys - KBASE); + n = ipxe_init(); + for (i = 0; i < n && i < MAX_CARDS; i++) + { + struct card *c = &cards[i]; + c->index = i; + if (!ipxe_get(i, c->name, c->nic.mac)) + continue; + c->nic.name = c->name; + c->nic.send = c_send; + c->nic.recv = c_recv; + c->nic.link = c_link; + c->nic.debug = c_debug; + nic_register(&c->nic); + } +} diff --git a/mdvmm/core/lib.c b/mdvmm/core/lib.c new file mode 100644 index 00000000..553dea47 --- /dev/null +++ b/mdvmm/core/lib.c @@ -0,0 +1,228 @@ +/* MDVMM core - minimal C library and logging (QEMU/Bochs debug port E9h) */ +#include "core.h" + +void *memcpy(void *d, const void *s, size_t n) +{ + uint8_t *dp = d; + const uint8_t *sp = s; + while (n--) + *dp++ = *sp++; + return d; +} + +void *memset(void *d, int c, size_t n) +{ + uint8_t *dp = d; + while (n--) + *dp++ = (uint8_t)c; + return d; +} + +int memcmp(const void *a, const void *b, size_t n) +{ + const uint8_t *x = a, *y = b; + for (; n; n--, x++, y++) + if (*x != *y) + return *x - *y; + return 0; +} + +size_t strlen(const char *s) +{ + size_t n = 0; + while (s[n]) + n++; + return n; +} + +static void putc_log(char c) +{ + if (c == '\n') + outb(0xe9, '\r'); + outb(0xe9, (uint8_t)c); + fbcon_log(c); /* UEFI boots: on the screen too */ +} + +static void put_num(uint32_t v, unsigned base, int width, char pad, int neg) +{ + char buf[12]; + int n = 0; + do + { + buf[n++] = "0123456789ABCDEF"[v % base]; + v /= base; + } while (v); + if (neg) + buf[n++] = '-'; + while (width-- > n) + putc_log(pad); + while (n) + putc_log(buf[--n]); +} + +/* supports %s %c %d %u %x %X %p with optional 0 padding and width */ +void kvprintf(const char *fmt, va_list ap) +{ + for (; *fmt; fmt++) + { + char pad = ' '; + int width = 0; + + if (*fmt != '%') + { + putc_log(*fmt); + continue; + } + fmt++; + if (*fmt == '0') + { + pad = '0'; + fmt++; + } + while (*fmt >= '0' && *fmt <= '9') + width = width * 10 + (*fmt++ - '0'); + switch (*fmt) + { + case 's': + { + const char *s = va_arg(ap, const char *); + while (*s) + putc_log(*s++); + break; + } + case 'c': + putc_log((char)va_arg(ap, int)); + break; + case 'd': + { + int v = va_arg(ap, int); + put_num(v < 0 ? -(uint32_t)v : (uint32_t)v, 10, width, pad, v < 0); + break; + } + case 'u': + put_num(va_arg(ap, uint32_t), 10, width, pad, 0); + break; + case 'x': + case 'X': + case 'p': + put_num(va_arg(ap, uint32_t), 16, width, pad, 0); + break; + default: + putc_log(*fmt); + } + } +} + +void kprintf(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + kvprintf(fmt, ap); + va_end(ap); +} + +/* a trial boot (BOOTF_TRIAL) was confirmed: it may stay */ +int trial_confirmed; + +/* restart the machine: reset control register, keyboard controller, + triple fault */ +void machine_reset(void) +{ + static const struct { uint16_t limit; uint32_t base; } __attribute__((packed)) no_idt = { 0, 0 }; + + __asm__ volatile("cli"); + outb(0xcf9, 0x02); + udelay(50); + outb(0xcf9, 0x06); + udelay(50000); + outb(0x64, 0xfe); + udelay(50000); + __asm__ volatile("lidt %0; int3" :: "m"(no_idt)); + for (;;) + ; +} + +static void halt_forever(void) +{ + /* an unconfirmed trial boot must not strand the machine: leave the + message on the screen for a minute, then restart (into the installed + system) */ + if ((boot.flags & BOOTF_TRIAL) && !trial_confirmed) + { + kprintf("trial boot: restarting in 60 seconds\n"); + udelay(60000000); + machine_reset(); + } + for (;;) + __asm__ volatile("cli; hlt"); +} + +void panic(const char *fmt, ...) +{ + va_list ap; + fbcon_panic(); + kprintf("\nMDVMM PANIC: "); + va_start(ap, fmt); + kvprintf(fmt, ap); + va_end(ap); + kprintf("\n"); + halt_forever(); + __builtin_unreachable(); +} + +void panic_frame(struct frame *f, const char *why) +{ + fbcon_panic(); + kprintf("\nMDVMM PANIC: %s (vector %u, error %08x)\n", why, f->vector, f->err); + kprintf(" EAX=%08x EBX=%08x ECX=%08x EDX=%08x\n", f->eax, f->ebx, f->ecx, f->edx); + kprintf(" ESI=%08x EDI=%08x EBP=%08x CR2=%08x\n", f->esi, f->edi, f->ebp, read_cr2()); + kprintf(" EIP=%08x CS=%04x EFLAGS=%08x\n", f->eip, f->cs, f->eflags); + if (f->eflags & EFL_VM) + { + const uint8_t *code = rm_ptr(f->cs, f->eip); + int i; + kprintf(" V86 SS:SP=%04x:%04x DS=%04x ES=%04x FS=%04x GS=%04x\n", + f->ss, f->esp & 0xffff, f->ds, f->es, f->fs, f->gs); + kprintf(" code:"); + for (i = 0; i < 12; i++) + kprintf(" %02x", code[i]); + kprintf("\n"); + } + halt_forever(); + __builtin_unreachable(); +} + +/* IRQ0 pending at the master PIC? Acknowledges it there (poll mode). */ +static int pic_poll_irq0(void) +{ + uint8_t v; + + outb(0x20, 0x0c); /* OCW3: poll */ + v = inb(0x20); + if (!(v & 0x80)) + return 0; + outb(0x20, 0x60 | (v & 7)); /* specific EOI */ + return (v & 7) == 0; +} + +/* wait `ticks` timer ticks (55 ms each) with interrupts off, by polling + the PIC; returns 0 if the timer does not tick */ +int pit_wait(uint32_t ticks) +{ + uint8_t mask = inb(0x21); + uint32_t i, spin; + + outb(0x21, 0xfe); /* only IRQ0 */ + for (i = 0; i < ticks; i++) + { + for (spin = 0; spin < 3000000 && !pic_poll_irq0(); spin++) + ; + if (spin == 3000000) + { + outb(0x21, mask); + return 0; + } + } + outb(0x21, mask); + return 1; +} diff --git a/mdvmm/core/main.c b/mdvmm/core/main.c new file mode 100644 index 00000000..17ccc64b --- /dev/null +++ b/mdvmm/core/main.c @@ -0,0 +1,81 @@ +/* MDVMM core - initialization and trap dispatch */ +#include "core.h" + +void trap_dispatch(struct frame *f); +void core_main(struct bootinfo *bi, uint32_t free_phys); + +void trap_dispatch(struct frame *f) +{ + int user = !(f->eflags & EFL_VM) && (f->cs & 3) == 3; + + if (f->vector == 0xff) + return; /* local APIC spurious interrupt: no EOI */ + if (f->vector == 2) + { + /* NMI: on PCs a PCI system error (SERR#) or an I/O channel check. + Note it and go on: stopping would hide what the machine was doing. */ + static int nmis; + uint8_t why = inb(0x61); + if (nmis++ < 5) + kprintf("NMI: port 61h = %02x (%s) at %04x:%08x\n", why, + why & 0x80 ? "PCI SERR#" : why & 0x40 ? "I/O check" : "unknown source", + f->cs, f->eip); + outb(0x61, (why & 0x0f) | 0x0c); /* clear and disable both sources */ + return; + } + if (f->vector >= 0x20 && f->vector < 0x30) + { + dma_irq(); /* bounced DMA data before any handler */ + if (user) + dpmi_hwirq(f, (int)f->vector - 0x20); + else + v86_irq(f, (int)f->vector - 0x20); + return; + } + if (f->vector == 14 && ((f->eflags & EFL_VM) || user)) + { + /* a page fault on the monitor's VGA memory (planar modes): the + instruction is run by the monitor */ + uint32_t cr2; + __asm__("mov %%cr2, %0" : "=r"(cr2)); + if ((f->eflags & EFL_VM) ? vga_fault(f, cr2, 1, 0) : dpmi_vga_fault(f, cr2)) + return; + } + if (f->eflags & EFL_VM) + { + v86_exception(f); + return; + } + if (user) + { + if (f->vector == 1 && dpmi_vga_debug(f)) + return; /* an I/O breakpoint of the monitor's VGA */ + dpmi_trap(f); + return; + } + panic_frame(f, "exception in monitor"); +} + +void core_main(struct bootinfo *bi, uint32_t free_phys) +{ + /* the loader's copy lives in memory DOS will reuse */ + memcpy(&boot, bi, sizeof(boot)); + + kprintf("\nMDVMM core: loaded at %08x, %u KB pool\n", boot.pool_phys, + boot.pool_size / 1024); + if (boot.magic != BOOTINFO_MAGIC || boot.version != BOOTINFO_VERSION) + panic("bad boot information"); + + mm_init(free_phys); + cpu_init(); + if (boot.boot_type == BOOT_UEFI) + fbcon_init(); /* the log on the screen from here on */ + dma_init(); + dpmi_init(); + if (boot.boot_type == BOOT_UEFI) + bios_init(); /* no PC BIOS: provide one, boot DOS; it + starts the network cards (after the timer) */ + else + nic_init(); + v86_start(); +} diff --git a/mdvmm/core/mm.c b/mdvmm/core/mm.c new file mode 100644 index 00000000..de529af5 --- /dev/null +++ b/mdvmm/core/mm.c @@ -0,0 +1,185 @@ +/* MDVMM core - physical memory and page mapping + * + * The loader hands over one contiguous physical pool. entry.asm maps it + * at KBASE and identity maps the first 4MB (V86 view of the machine). + * Page tables are reachable through the recursive mapping at 0xFFC00000. + */ +#include "core.h" + +#define PT_BASE 0xFFC00000u /* recursive: all page tables */ +#define PD_BASE 0xFFFFF000u /* recursive: page directory */ +#define KMAP_BASE 0xEFC00000u /* temporary physical windows */ +#define KMAP_SLOTS 4 + +struct bootinfo boot; +static uint32_t next_free, pool_end; +static uint32_t free_list; /* freed pages, linked through page */ +static uint32_t free_count; /* pages on free_list */ + +static inline uint32_t *pte(uint32_t lin) { return (uint32_t *)(PT_BASE + (lin >> 12) * 4); } +static inline uint32_t *pde(uint32_t lin) { return (uint32_t *)(PD_BASE + (lin >> 22) * 4); } + +static void *pool_virt(uint32_t phys) { return (void *)(KBASE + (phys - boot.pool_phys)); } + +/* allocate one zeroed physical page from the pool (no freeing yet) */ +uint32_t page_alloc(void) +{ + uint32_t p; + + if (free_list) + { + p = free_list; + free_list = *(uint32_t *)pool_virt(p); + free_count--; + } + else + { + if (next_free >= pool_end) + return 0; + p = next_free; + next_free += 4096; + } + memset(pool_virt(p), 0, 4096); + return p; +} + +void page_free(uint32_t phys) +{ + *(uint32_t *)pool_virt(phys) = free_list; + free_list = phys; + free_count++; +} + +uint32_t pages_free(void) +{ + return free_count + (pool_end - next_free) / 4096; +} + +uint32_t pages_total(void) +{ + return boot.pool_size / 4096; +} + +/* map one page at linear address lin; flags: 7 = user rw, 3 = supervisor. + Page tables for user regions are created on demand. 0 on failure. */ +int map_page(uint32_t lin, uint32_t phys, uint32_t flags) +{ + if (!(*pde(lin) & 1)) + { + uint32_t pt = page_alloc(); + if (!pt) + return 0; + *pde(lin) = pt | 7; + invlpg((uint32_t)pte(lin)); + memset((void *)((uint32_t)pte(lin) & ~0xfffu), 0, 4096); + } + *pte(lin) = (phys & ~0xfffu) | flags; + invlpg(lin); + return 1; +} + +/* map 4MB of device registers above 4GB at lin (4MB aligned, unused) + with a PSE-36 large page: the PDE holds physical address bits 32-39. + Uncached. 0 if the CPU cannot do it. */ +int map_large_mmio(uint32_t lin, uint64_t phys) +{ + uint32_t a, b, c, d, cr4; + + __asm__ volatile("cpuid" : "=a"(a), "=b"(b), "=c"(c), "=d"(d) : "a"(1)); + if (!(d & (1u << 3)) || !(d & (1u << 17)) || phys >> 40 || (phys & 0x3fffff) || + (lin & 0x3fffff) || (*pde(lin) & 1)) + return 0; + __asm__ volatile("mov %%cr4,%0" : "=r"(cr4)); + __asm__ volatile("mov %0,%%cr4" :: "r"(cr4 | 0x10)); /* PSE */ + *pde(lin) = (uint32_t)phys | ((uint32_t)(phys >> 32) & 0xff) << 13 | 0x9b; /* PS PCD PWT RW P */ + invlpg(lin); + return 1; +} + +/* unmap a page, returns its physical address (0 if not mapped) */ +uint32_t unmap_page(uint32_t lin) +{ + uint32_t e; + + if (!(*pde(lin) & 1)) + return 0; + e = *pte(lin); + *pte(lin) = 0; + invlpg(lin); + return (e & 1) ? (e & ~0xfffu) : 0; +} + +uint32_t lin_to_pte(uint32_t lin) +{ + if (!(*pde(lin) & 1)) + return 0; + return *pte(lin); +} + +void mm_init(uint32_t free_phys) +{ + uint32_t pt; + + next_free = free_phys; + pool_end = boot.pool_phys + boot.pool_size; + + /* page table for the kmap window */ + pt = page_alloc(); + if (!pt) + panic("no memory for page tables"); + *pde(KMAP_BASE) = pt | 3; + invlpg((uint32_t)pte(KMAP_BASE)); + memset((void *)((uint32_t)pte(KMAP_BASE) & ~0xfffu), 0, 4096); + + kprintf("mm: pool %08x-%08x, %u KB free\n", boot.pool_phys, pool_end, + (pool_end - next_free) / 1024); +} + +void *pool_ptr(uint32_t phys) +{ + return pool_virt(phys); +} + +/* physically contiguous, size aligned block below 16MB (ISA DMA), taken + from the untouched part of the pool; call early. 0 if not possible. */ +uint32_t page_alloc_isa(uint32_t size) +{ + uint32_t p = (next_free + size - 1) & ~(size - 1); + + if (p + size > pool_end || p + size > 0x1000000) + return 0; + while (next_free < p) /* skipped pages stay usable */ + { + page_free(next_free); + next_free += 4096; + } + next_free = p + size; + return p; +} + +/* map a physical page into a temporary window slot */ +void *kmap(int slot, uint32_t phys) +{ + uint32_t lin = KMAP_BASE + slot * 4096; + + *pte(lin) = (phys & ~0xfffu) | 3; + invlpg(lin); + return (void *)(lin + (phys & 0xfff)); +} + +/* copy between arbitrary physical addresses */ +void phys_copy(uint32_t dst, uint32_t src, uint32_t len) +{ + while (len) + { + uint32_t n = 4096 - (src & 0xfff); + if (n > 4096 - (dst & 0xfff)) + n = 4096 - (dst & 0xfff); + if (n > len) + n = len; + memcpy(kmap(1, dst), kmap(0, src), n); + src += n; + dst += n; + len -= n; + } +} diff --git a/mdvmm/core/mouse.c b/mdvmm/core/mouse.c new file mode 100644 index 00000000..79fc001b --- /dev/null +++ b/mdvmm/core/mouse.c @@ -0,0 +1,187 @@ +/* MDVMM core - mouse driver (INT 33h) for UEFI boots + * + * A Microsoft compatible mouse driver in the virtual BIOS, fed by USB + * boot protocol mice (xhci.c). Motion arrives in mickeys and is scaled + * by the mickey/pixel ratio (function 0Fh, default 8 horizontal and 16 + * vertical mickeys per 8 pixels) into the virtual screen, which is + * 640x200 in text mode as with every DOS mouse driver: the text cell is + * x/8, y/8. In text mode the cursor is drawn by fbcon.c as an inverted + * cell; graphics programs draw their own. Not yet: event handlers + * (function 0Ch), PS/2 mice. + */ +#include "core.h" + +#define BUTTONS 3 + +static struct { + int present; + int x, y; /* virtual screen position */ + int fx, fy; /* fractions, in 1/8 mickey */ + int buttons; + int shown; /* cursor counter: visible at 0 */ + int xmin, xmax, ymin, ymax; + int hratio, vratio; /* mickeys per 8 pixels */ + int mickey_x, mickey_y; /* since function 0Bh */ + int presses[BUTTONS], releases[BUTTONS]; + int press_x[BUTTONS], press_y[BUTTONS], release_x[BUTTONS], release_y[BUTTONS]; +} m; + +static void reset(void) +{ + int present = m.present; + + memset(&m, 0, sizeof(m)); + m.present = present; + m.xmax = 639; + m.ymax = 199; + m.x = 320; + m.y = 100; + m.shown = -1; + m.hratio = 8; + m.vratio = 16; +} + +static void init(void) +{ + static int done; + + if (!done) + { + done = 1; + reset(); + } +} + +static int clamp(int v, int lo, int hi) +{ + return v < lo ? lo : v > hi ? hi : v; +} + +/* a USB mouse report: buttons (bit 0 left, 1 right, 2 middle), motion */ +void mouse_input(int buttons, int dx, int dy) +{ + int i; + + init(); + if (!m.present) + { + m.present = 1; + kprintf("mouse: first report\n"); + } + m.mickey_x += dx; + m.mickey_y += dy; + m.fx += dx * 64 / (m.hratio ? m.hratio : 8); /* 1/8 pixel units */ + m.fy += dy * 64 / (m.vratio ? m.vratio : 16); + m.x = clamp(m.x + m.fx / 8, m.xmin, m.xmax); + m.y = clamp(m.y + m.fy / 8, m.ymin, m.ymax); + m.fx %= 8; + m.fy %= 8; + for (i = 0; i < BUTTONS; i++) + { + int bit = 1 << i; + if ((buttons & bit) && !(m.buttons & bit)) + { + m.presses[i]++; + m.press_x[i] = m.x; + m.press_y[i] = m.y; + } + else if (!(buttons & bit) && (m.buttons & bit)) + { + m.releases[i]++; + m.release_x[i] = m.x; + m.release_y[i] = m.y; + } + } + m.buttons = buttons & 7; +} + +/* text cell under a visible mouse cursor, or -1 (fbcon.c) */ +int mouse_text_cell(void) +{ + if (!m.present || m.shown < 0 || m.y / 8 >= 25 || m.x / 8 >= 80) + return -1; + return (m.y / 8) * 80 + m.x / 8; +} + +void int33(struct frame *f) +{ + int b; + + init(); + switch (AX(f)) + { + case 0x0000: /* reset and status */ + case 0x0021: /* software reset */ + reset(); + AX(f) = 0xffff; /* installed (a USB mouse may come later) */ + BX(f) = BUTTONS; + break; + case 0x0001: + if (m.shown < 0) + m.shown++; + break; + case 0x0002: + m.shown--; + break; + case 0x0003: + BX(f) = (uint16_t)m.buttons; + CX(f) = (uint16_t)m.x; + DX(f) = (uint16_t)m.y; + break; + case 0x0004: + m.x = clamp((int16_t)CX(f), m.xmin, m.xmax); + m.y = clamp((int16_t)DX(f), m.ymin, m.ymax); + break; + case 0x0005: /* button press information */ + b = BX(f) < BUTTONS ? BX(f) : 0; + AX(f) = (uint16_t)m.buttons; + BX(f) = (uint16_t)m.presses[b]; + CX(f) = (uint16_t)m.press_x[b]; + DX(f) = (uint16_t)m.press_y[b]; + m.presses[b] = 0; + break; + case 0x0006: /* button release information */ + b = BX(f) < BUTTONS ? BX(f) : 0; + AX(f) = (uint16_t)m.buttons; + BX(f) = (uint16_t)m.releases[b]; + CX(f) = (uint16_t)m.release_x[b]; + DX(f) = (uint16_t)m.release_y[b]; + m.releases[b] = 0; + break; + case 0x0007: + m.xmin = (int16_t)CX(f); + m.xmax = (int16_t)DX(f); + if (m.xmin > m.xmax) + { + int t = m.xmin; m.xmin = m.xmax; m.xmax = t; + } + m.x = clamp(m.x, m.xmin, m.xmax); + break; + case 0x0008: + m.ymin = (int16_t)CX(f); + m.ymax = (int16_t)DX(f); + if (m.ymin > m.ymax) + { + int t = m.ymin; m.ymin = m.ymax; m.ymax = t; + } + m.y = clamp(m.y, m.ymin, m.ymax); + break; + case 0x000b: /* motion counters */ + CX(f) = (uint16_t)m.mickey_x; + DX(f) = (uint16_t)m.mickey_y; + m.mickey_x = m.mickey_y = 0; + break; + case 0x000f: + m.hratio = CX(f) ? CX(f) : 8; + m.vratio = DX(f) ? DX(f) : 16; + break; + case 0x001b: /* get sensitivity */ + BX(f) = CX(f) = 50; + DX(f) = 0; + break; + case 0x0024: /* driver version, type */ + BX(f) = 0x0700; + CX(f) = 0x0400; /* PS/2 type, no IRQ */ + break; + } +} diff --git a/mdvmm/core/nic.c b/mdvmm/core/nic.c new file mode 100644 index 00000000..3bcc4d21 --- /dev/null +++ b/mdvmm/core/nic.c @@ -0,0 +1,359 @@ +/* MDVMM core - network cards + * + * Drivers (iPXE's, through ipxenic.c) register a `struct nic`; DOS reaches the + * first one through INT 2Fh AH=DEh (PKTDRV.COM turns that into a standard + * packet driver): + * AX=DE10h info: ES:DI <- 6-byte MAC, AX = MTU (frame bytes without + * CRC), BX = 1 if the link is up, CX = cards; CF if none + * AX=DE11h send the frame at DS:SI, CX bytes (14..1514); CF on error + * AX=DE12h receive: the next frame into ES:DI (CX = room); CX = its + * length, 0 if there is none + * AX=DE13h the driver's state into the monitor's log + * AX=DE14h the monitor's log: its last BX lines (0: all kept) as text + * into ES:DI (CX = room); CX = bytes (works without a card; + * UEFI boots only, MDLOG.COM shows it) + * and the system calls of MDSYS.COM: + * AX=DE15h state: AX bit 0 = UEFI boot, bit 1 = trial boot, bit 2 = trial + * confirmed + * AX=DE16h confirm the trial boot (no automatic restart) + * AX=DE17h restart the machine + * Drivers poll (no interrupts), like the disk drivers. Works on DOS and + * UEFI boots. + */ +#include "core.h" + +#define MAX_NICS 4 + +static struct nic *nics[MAX_NICS]; +static int nnic; + +/* ---------------------------------------------------------------- */ +/* One card, several DOS sessions, each with its own TCP/IP stack (the + packet driver is loaded before the sessions are forked, a program's + Watt-32 asks DHCP and gets the card's one address). Frames from the + card are sorted here: + - TCP and UDP of a connection a session has sent on: to that session + - TCP to a port a session has accepted on (it sent SYN+ACK): there + - everything else (ARP, DHCP, ICMP, a first SYN): to every session + that polls + and on the way out, the answers stacks give to segments that were not + theirs are dropped: a TCP reset on a connection that is another + session's, or - while several sessions are on the network - on one + that is nobody's yet, and ICMP "unreachable". */ +#define NQ 24 /* frames queued per session */ +#define NFLOWS 128 +#define NLISTEN 16 +#define POLL_AGE 40 /* ticks: a session that polled is "on" */ + +struct nq { + uint16_t len[NQ]; + uint8_t data[NQ][1514]; + int head, count; + uint32_t last_poll; + int polled; + uint32_t got, dropped, sent; /* frames: queued for it, lost at a full queue, sent by it */ +}; +struct flow { + uint8_t used, proto, ses; + uint16_t lport, rport; + uint32_t rip, stamp; +}; +static struct nq nq[MAX_SESSIONS]; +static struct flow flows[NFLOWS]; +static struct { uint16_t port; uint8_t used, ses; } listeners[NLISTEN]; +static uint32_t flow_clock; +static uint32_t send_failed; +static uint32_t unclaimed; /* frames received that no session took */ + +static int net_on(int s) +{ + return nq[s].polled && vm_ticks() - nq[s].last_poll < POLL_AGE; +} + +static int sessions_on(void) +{ + int s, n = 0; + + for (s = 0; s < MAX_SESSIONS; s++) + n += net_on(s); + return n; +} + +/* an IPv4 TCP or UDP frame: protocol, addresses and ports, the TCP flags */ +struct l4 { uint8_t proto, flags; uint32_t sip, dip; uint16_t sport, dport; }; + +static int parse(const uint8_t *fr, int len, struct l4 *k) +{ + const uint8_t *ip = fr + 14, *t; + int ihl; + + if (len < 14 + 20 + 8 || fr[12] != 0x08 || fr[13] != 0x00 || (ip[0] >> 4) != 4) + return 0; + ihl = (ip[0] & 15) * 4; + k->proto = ip[9]; + if ((k->proto != 6 && k->proto != 17) || len < 14 + ihl + (k->proto == 6 ? 20 : 8)) + return 0; + if ((ip[6] & 0x1f) || ip[7]) + return 0; /* not the first fragment */ + memcpy(&k->sip, ip + 12, 4); + memcpy(&k->dip, ip + 16, 4); + t = ip + ihl; + k->sport = (uint16_t)(t[0] << 8 | t[1]); + k->dport = (uint16_t)(t[2] << 8 | t[3]); + k->flags = k->proto == 6 ? t[13] : 0; + return 1; +} + +static struct flow *flow_find(uint8_t proto, uint16_t lport, uint32_t rip, uint16_t rport) +{ + int i; + + for (i = 0; i < NFLOWS; i++) + if (flows[i].used && flows[i].proto == proto && flows[i].lport == lport && + flows[i].rip == rip && flows[i].rport == rport) + return &flows[i]; + return 0; +} + +/* a frame a session sends: 0 if it must not go out */ +static int outbound(int ses, const uint8_t *fr, int len) +{ + struct l4 k; + struct flow *fl; + int i, old = 0; + + if (len >= 14 + 20 + 8 && fr[12] == 0x08 && fr[13] == 0x00 && fr[14 + 9] == 1 && + fr[14 + (fr[14] & 15) * 4] == 3 && sessions_on() > 1) + return 0; /* ICMP unreachable */ + if (!parse(fr, len, &k)) + return 1; + if (k.proto == 17 && (k.sport == 68 || k.dport == 67)) + return 1; /* DHCP: every stack's own, answers to all */ + fl = flow_find(k.proto, k.sport, k.dip, k.dport); + if (k.flags & 0x04) /* TCP reset */ + { + if (fl ? fl->ses != ses : sessions_on() > 1) + return 0; + return 1; + } + if ((k.flags & 0x12) == 0x12) /* SYN+ACK: this session accepts on the port */ + { + for (i = 0; i < NLISTEN && listeners[i].used && listeners[i].port != k.sport; i++) + ; + if (i == NLISTEN) + i = k.sport % NLISTEN; + listeners[i].used = 1; + listeners[i].port = k.sport; + listeners[i].ses = (uint8_t)ses; + } + if (!fl) + { + for (i = 0; i < NFLOWS && flows[i].used; i++) + if (flows[i].stamp < flows[old].stamp) + old = i; + fl = &flows[i < NFLOWS ? i : old]; /* a free one, else the oldest */ + fl->used = 1; + fl->proto = k.proto; + fl->lport = k.sport; + fl->rip = k.dip; + fl->rport = k.dport; + } + fl->ses = (uint8_t)ses; + fl->stamp = ++flow_clock; + return 1; +} + +/* the session a received frame is for, -1: all that are on */ +static int inbound(const uint8_t *fr, int len) +{ + struct l4 k; + struct flow *fl; + int i; + + if (!parse(fr, len, &k) || (k.proto == 17 && k.dport == 68)) + return -1; + if ((fl = flow_find(k.proto, k.dport, k.sip, k.sport))) + { + fl->stamp = ++flow_clock; + return fl->ses; + } + for (i = 0; i < NLISTEN && k.proto == 6; i++) + if (listeners[i].used && listeners[i].port == k.dport) + return listeners[i].ses; + return -1; +} + +static void enqueue(int s, const uint8_t *fr, int len) +{ + struct nq *q = &nq[s]; + int at; + + if (q->count == NQ) + { + q->dropped++; + return; /* full: dropped, as on a busy card */ + } + q->got++; + at = (q->head + q->count++) % NQ; + q->len[at] = (uint16_t)len; + memcpy(q->data[at], fr, (uint32_t)len); +} + +/* frames from the card into the sessions' queues */ +static void pump(struct nic *n) +{ + static uint8_t fr[1514]; + int len, i, s, to, any; + + for (i = 0; i < 16 && (len = n->recv(n, fr, sizeof(fr))) > 0; i++) + { + to = inbound(fr, len); + if (to >= 0 && !net_on(to)) + to = -1; /* its program is gone */ + for (s = 0, any = 0; s < MAX_SESSIONS; s++) + if (to < 0 ? net_on(s) : s == to) + { + enqueue(s, fr, len); + any = 1; + } + if (!any) + unclaimed++; + } +} + +/* the cards' and the sessions' network state into the log */ +void nic_debug(void) +{ + int i, s, nf = 0; + + for (i = 0; i < nnic; i++) + if (nics[i]->debug) + nics[i]->debug(nics[i]); + for (i = 0; i < NFLOWS; i++) + nf += flows[i].used; + for (s = 0; s < MAX_SESSIONS; s++) + if (nq[s].polled) + kprintf("nic: session %d: asked %u ticks ago, %d frames wait, %u received, %u lost (queue full), %u sent\n", + s, vm_ticks() - nq[s].last_poll, nq[s].count, nq[s].got, nq[s].dropped, nq[s].sent); + kprintf("nic: %d connections known, frames no session took: %u, sends failed: %u\n", nf, unclaimed, send_failed); +} + +void nic_register(struct nic *n) +{ + if (nnic == MAX_NICS) + return; + nics[nnic++] = n; + kprintf("nic: %s, MAC %02x:%02x:%02x:%02x:%02x:%02x\n", n->name, n->mac[0], n->mac[1], + n->mac[2], n->mac[3], n->mac[4], n->mac[5]); +} + +void nic_init(void) +{ + if (boot.flags & BOOTF_NO_NET) + { + kprintf("nic: network drivers skipped (\\MDOS\\NONET)\n"); + return; + } + ipxenic_init(); /* iPXE's drivers, on DOS and UEFI boots */ +} + +static void set_cf(struct frame *f, int on) +{ + if (on) + f->eflags |= EFL_CF; + else + f->eflags &= ~EFL_CF; +} + +/* INT 2Fh AX=DE10h-DE1Fh */ +void nic_api(struct frame *f) +{ + struct nic *n = nnic ? nics[0] : 0; + uint8_t *buf; + int len; + + if (AL(f) == 0x15) + { + AX(f) = (uint16_t)((boot.boot_type == BOOT_UEFI) | (boot.flags & BOOTF_TRIAL ? 2 : 0) | + (trial_confirmed ? 4 : 0) | + (boot.boot_type != BOOT_UEFI || (boot.flags & BOOTF_DISK_WRITE) ? 8 : 0)); + set_cf(f, 0); + return; + } + if (AL(f) == 0x16) + { + if ((boot.flags & BOOTF_TRIAL) && !trial_confirmed) + kprintf("trial boot: confirmed\n"); + trial_confirmed = 1; + set_cf(f, 0); + return; + } + if (AL(f) == 0x17) + { + kprintf("restart requested\n"); + machine_reset(); + } + if (AL(f) == 0x14) + { + CX(f) = (uint16_t)fbcon_log_copy((char *)rm_ptr(f->es, 0) + DI(f), CX(f), BX(f)); + set_cf(f, !CX(f)); + return; + } + if (!n) + { + set_cf(f, 1); + return; + } + switch (AL(f)) + { + case 0x10: + memcpy(rm_ptr(f->es, DI(f)), n->mac, 6); + AX(f) = 1514; + BX(f) = (uint16_t)(n->link ? n->link(n) : 1); + CX(f) = (uint16_t)nnic; + set_cf(f, 0); + return; + case 0x11: + len = CX(f); + buf = rm_ptr(f->ds, 0) + SI(f); + if (len < 14 || len > 1514) + { + kprintf("nic: send of %d bytes refused\n", len); + set_cf(f, 1); + return; + } + { + int bad = outbound(vm_current(), buf, len) ? n->send(n, buf, len) : 0; + nq[vm_current()].sent++; + if (bad) + send_failed++; + set_cf(f, bad); + return; + } + case 0x12: + buf = rm_ptr(f->es, 0) + DI(f); + { + struct nq *q = &nq[vm_current()]; + q->polled = 1; + q->last_poll = vm_ticks(); + pump(n); + len = 0; + if (q->count) + { + len = q->len[q->head] <= CX(f) ? q->len[q->head] : 0; + memcpy(buf, q->data[q->head], (uint32_t)len); + q->head = (q->head + 1) % NQ; + q->count--; + } + CX(f) = (uint16_t)len; + set_cf(f, 0); + return; + } + case 0x13: + nic_debug(); + vm_debug(); /* and where the sessions are */ + set_cf(f, 0); + return; + } + set_cf(f, 1); +} diff --git a/mdvmm/core/nobios.c b/mdvmm/core/nobios.c new file mode 100644 index 00000000..d9a01050 --- /dev/null +++ b/mdvmm/core/nobios.c @@ -0,0 +1,93 @@ +/* MDVMM core - stubs for the core linked into MDVMM.COM. Started from + DOS, the machine has a PC BIOS: the virtual BIOS and the native drivers + for disks, screen and input (bios.c, fbcon.c, font.c, rom.asm, ahci.c, + ...) are only linked into the UEFI loader's core. */ +#include "core.h" + +void bios_init(void) +{ + panic("this core has no virtual BIOS (use BOOTX64.EFI)"); +} + +int bios_bp(struct frame *f, uint16_t ip) +{ + (void)f; + (void)ip; + return 0; +} + +uint32_t ext_phys(uint32_t a) +{ + return a; /* DOS boot: extended memory is physical */ +} + +int bios_mouse_install(void) +{ + return 0; /* DOS boot: load a mouse driver */ +} + +/* no framebuffer console: the BIOS has the screen */ +void fbcon_init(void) +{ +} + +void fbcon_log(char c) +{ + (void)c; +} + +void fbcon_panic(void) +{ +} + +uint32_t fbcon_log_copy(char *dst, uint32_t room, uint32_t lines) +{ + (void)dst; + (void)room; + (void)lines; + return 0; /* the log is not kept on DOS boots */ +} + +/* VGA mode 13h: the machine's video BIOS and card do that */ +int vga_active(void) +{ + return 0; +} + +int vga_port_in(uint16_t port, int size, uint32_t *v) +{ + (void)port; + (void)size; + (void)v; + return 0; +} + +int vga_port_out(uint16_t port, int size, uint32_t v) +{ + (void)port; + (void)size; + (void)v; + return 0; +} + +int vga_debug(struct frame *f, const uint8_t *code, const uint8_t *esi_byte, int code32) +{ + (void)f; + (void)code; + (void)esi_byte; + (void)code32; + return 0; +} + +int vga_fault(struct frame *f, uint32_t addr, int v86, int code32) +{ + (void)f; + (void)addr; + (void)v86; + (void)code32; + return 0; +} + +void bios_program_end(void) +{ +} diff --git a/mdvmm/core/nvme.c b/mdvmm/core/nvme.c new file mode 100644 index 00000000..cd23a0c9 --- /dev/null +++ b/mdvmm/core/nvme.c @@ -0,0 +1,333 @@ +/* MDVMM core - NVMe disk driver for the virtual BIOS + * + * Finds NVMe controllers on PCI (class 01:08:02), resets them, sets up + * the admin queue and one I/O queue pair, and registers every active + * namespace with 512-byte blocks as a BIOS hard disk (bios.c). Commands + * are issued one at a time and their completion is polled, interrupts + * stay off. Transfers use the caller's pool pages through PRP entries + * (a PRP list for more than two pages). Not used on DOS boots. + */ +#include "core.h" + +#define MAX_CTRL 4 +#define MAX_NS 8 +#define QSIZE 16 /* entries per queue */ + +/* controller registers */ +#define R_CAP 0x00 +#define R_VS 0x08 +#define R_CC 0x14 +#define R_CSTS 0x1c +#define R_AQA 0x24 +#define R_ASQ 0x28 +#define R_ACQ 0x30 + +#define CC_EN 0x00000001u +#define CC_IOSQES (6u << 16) /* 64 byte submission entries */ +#define CC_IOCQES (4u << 20) /* 16 byte completion entries */ +#define CSTS_RDY 0x1 +#define CSTS_CFS 0x2 + +/* admin commands */ +#define A_CREATE_SQ 0x01 +#define A_CREATE_CQ 0x05 +#define A_IDENTIFY 0x06 +/* I/O commands */ +#define IO_FLUSH 0x00 +#define IO_WRITE 0x01 +#define IO_READ 0x02 + +struct queue { + uint32_t sq, cq; /* physical pages */ + uint16_t tail, head; + uint8_t phase; + int id; +}; + +struct ctrl { + volatile uint8_t *regs; + uint32_t dstrd; /* doorbell stride, bytes */ + uint32_t timeout_ms; + struct queue admin, io; + uint32_t prp_list; /* page for PRP lists */ + uint16_t cid; + char model[41]; +}; + +struct ns { + struct disk disk; + struct ctrl *c; + uint32_t nsid; +}; + +static struct ctrl ctrls[MAX_CTRL]; +static struct ns nss[MAX_NS]; +static int nctrl, nns; + +static uint32_t rd32(struct ctrl *c, int r) +{ + return *(volatile uint32_t *)(c->regs + r); +} + +static void wr32(struct ctrl *c, int r, uint32_t v) +{ + *(volatile uint32_t *)(c->regs + r) = v; +} + +static void wr64(struct ctrl *c, int r, uint32_t v) +{ + wr32(c, r, v); + wr32(c, r + 4, 0); +} + +static int wait_ready(struct ctrl *c, uint32_t want) +{ + uint32_t i; + + for (i = 0; i < c->timeout_ms * 1000; i++) + { + uint32_t s = rd32(c, R_CSTS); + if (s & CSTS_CFS) + return 0; + if ((s & CSTS_RDY) == want) + return 1; + udelay(1); + } + return 0; +} + +/* submit one command (cmd[16] dwords) on q and wait for its completion; + returns the status field (0 = success), or -1 on timeout */ +static int submit(struct ctrl *c, struct queue *q, uint32_t *cmd) +{ + uint32_t *sqe = (uint32_t *)pool_ptr(q->sq) + q->tail * 16; + volatile uint32_t *cqe; + uint16_t cid = ++c->cid; + uint32_t i, status; + + cmd[0] = (cmd[0] & 0xffff) | (uint32_t)cid << 16; + memcpy(sqe, cmd, 64); + q->tail = (q->tail + 1) % QSIZE; + wr32(c, 0x1000 + (2 * q->id) * c->dstrd, q->tail); + + cqe = (volatile uint32_t *)pool_ptr(q->cq) + q->head * 4; + for (i = 0; i < c->timeout_ms * 1000; i++) + { + if (((cqe[3] >> 16) & 1) == q->phase) + break; + udelay(1); + } + if (((cqe[3] >> 16) & 1) != q->phase) + return -1; + status = cqe[3] >> 17; + q->head = (q->head + 1) % QSIZE; + if (!q->head) + q->phase ^= 1; + wr32(c, 0x1000 + (2 * q->id + 1) * c->dstrd, q->head); + return (int)(status & 0x7fff); +} + +static int queue_alloc(struct queue *q, int id) +{ + q->sq = page_alloc(); + q->cq = page_alloc(); + q->tail = q->head = 0; + q->phase = 1; + q->id = id; + return q->sq && q->cq; +} + +static int identify(struct ctrl *c, uint32_t cns, uint32_t nsid, uint32_t page) +{ + uint32_t cmd[16]; + + memset(cmd, 0, sizeof(cmd)); + cmd[0] = A_IDENTIFY; + cmd[1] = nsid; + cmd[6] = page; + cmd[10] = cns; + return submit(c, &c->admin, cmd); +} + +static int nvme_rw(struct disk *d, uint64_t lba, uint32_t n, const uint32_t *pages, int write) +{ + struct ns *s = d->drv; + struct ctrl *c = s->c; + uint32_t cmd[16], npages = (n * 512 + 4095) / 4096, i; + int st; + + if (!n || n > DISK_MAX_SECTORS || lba + n > d->sectors) + return 0x04; + memset(cmd, 0, sizeof(cmd)); + cmd[0] = write ? IO_WRITE : IO_READ; + cmd[1] = s->nsid; + cmd[6] = pages[0]; + if (npages == 2) + cmd[8] = pages[1]; + else if (npages > 2) + { + uint64_t *list = pool_ptr(c->prp_list); + for (i = 1; i < npages; i++) + list[i - 1] = pages[i]; + cmd[8] = c->prp_list; + } + cmd[10] = (uint32_t)lba; + cmd[11] = (uint32_t)(lba >> 32); + cmd[12] = n - 1; + st = submit(c, &c->io, cmd); + if (st) + { + kprintf("nvme: %s: %s at %u failed, status %x\n", d->model, write ? "write" : "read", + (uint32_t)lba, (uint32_t)st); + return st < 0 ? 0x80 : write ? 0x03 : 0x10; + } + return 0; +} + +static int nvme_flush(struct disk *d) +{ + struct ns *s = d->drv; + uint32_t cmd[16]; + + memset(cmd, 0, sizeof(cmd)); + cmd[0] = IO_FLUSH; + cmd[1] = s->nsid; + return submit(s->c, &s->c->io, cmd) ? 0x80 : 0; +} + +static void copy_string(char *dst, const uint8_t *src, int len) +{ + int i; + + memcpy(dst, src, len); + for (i = len; i > 0 && (dst[i - 1] == ' ' || !dst[i - 1]); i--) + ; + dst[i] = 0; +} + +static void ctrl_init(struct ctrl *c) +{ + uint32_t cap_lo = rd32(c, R_CAP), cap_hi = rd32(c, R_CAP + 4); + uint32_t page, cmd[16], nn, i; + const uint8_t *id; + + c->dstrd = 4u << (cap_hi & 0xf); + if (0x1000 + 4 * c->dstrd > 0x2000) + { + kprintf("nvme: doorbell stride %u not supported\n", c->dstrd); + return; + } + c->timeout_ms = ((cap_lo >> 24) & 0xff) * 500 + 500; + if ((cap_hi >> 16) & 0xf) + { + kprintf("nvme: controller does not support 4K pages\n"); + return; + } + if ((cap_lo & 0xffff) + 1 < QSIZE) + { + kprintf("nvme: queues too small\n"); + return; + } + + /* reset, admin queue, enable */ + wr32(c, R_CC, rd32(c, R_CC) & ~CC_EN); + if (!wait_ready(c, 0)) + { + kprintf("nvme: controller does not stop\n"); + return; + } + if (!queue_alloc(&c->admin, 0) || !queue_alloc(&c->io, 1) || !(c->prp_list = page_alloc()) || + !(page = page_alloc())) + return; + wr32(c, R_AQA, (QSIZE - 1) << 16 | (QSIZE - 1)); + wr64(c, R_ASQ, c->admin.sq); + wr64(c, R_ACQ, c->admin.cq); + wr32(c, R_CC, CC_EN | CC_IOSQES | CC_IOCQES); + if (!wait_ready(c, CSTS_RDY)) + { + kprintf("nvme: controller does not start\n"); + return; + } + + /* controller: model, number of namespaces */ + if (identify(c, 1, 0, page)) + return; + id = pool_ptr(page); + copy_string(c->model, id + 24, 40); + nn = *(const uint32_t *)(id + 516); + + /* I/O queue pair 1, physically contiguous, no interrupts */ + memset(cmd, 0, sizeof(cmd)); + cmd[0] = A_CREATE_CQ; + cmd[6] = c->io.cq; + cmd[10] = (QSIZE - 1) << 16 | 1; + cmd[11] = 1; + if (submit(c, &c->admin, cmd)) + return; + memset(cmd, 0, sizeof(cmd)); + cmd[0] = A_CREATE_SQ; + cmd[6] = c->io.sq; + cmd[10] = (QSIZE - 1) << 16 | 1; + cmd[11] = 1u << 16 | 1; + if (submit(c, &c->admin, cmd)) + return; + kprintf("nvme: %s, version %x, %u namespace(s)\n", c->model, rd32(c, R_VS), nn); + + for (i = 1; i <= nn && i <= 16 && nns < MAX_NS; i++) + { + struct ns *s = &nss[nns]; + uint32_t lbads; + uint64_t size; + + if (identify(c, 0, i, page)) + continue; + size = *(const uint64_t *)id; + lbads = id[128 + (id[26] & 0xf) * 4 + 2]; + if (!size) + continue; /* inactive */ + if (lbads != 9) + { + kprintf("nvme: namespace %u: %u byte blocks, not supported\n", i, 1u << lbads); + continue; + } + memset(s, 0, sizeof(*s)); + s->c = c; + s->nsid = i; + s->disk.sectors = size; + s->disk.drv = s; + s->disk.rw = nvme_rw; + s->disk.flush = nvme_flush; + memcpy(s->disk.model, c->model, sizeof(s->disk.model)); + kprintf("nvme: namespace %u: %u MB\n", i, (uint32_t)(size >> 11)); + nns++; + disk_register(&s->disk); + } + page_free(page); +} + +static void found(int bus, int dev, int fn) +{ + uint64_t bar = pci_bar(bus, dev, fn, 0x10); + struct ctrl *c; + + if (nctrl == MAX_CTRL || !bar) + return; + c = &ctrls[nctrl++]; + memset(c, 0, sizeof(*c)); + pci_enable(bus, dev, fn); + c->regs = mmio_map(bar, 0x2000); + if (!c->regs) + { + kprintf("nvme: %02x:%02x.%x: cannot map registers at %x:%08x\n", bus, dev, fn, + (uint32_t)(bar >> 32), (uint32_t)bar); + return; + } + kprintf("nvme: controller %02x:%02x.%x, registers at %x:%08x\n", bus, dev, fn, + (uint32_t)(bar >> 32), (uint32_t)bar); + ctrl_init(c); +} + +void nvme_init(void) +{ + pci_scan(0x010802, found); /* mass storage, NVM, NVMe */ +} diff --git a/mdvmm/core/pci.c b/mdvmm/core/pci.c new file mode 100644 index 00000000..16f06498 --- /dev/null +++ b/mdvmm/core/pci.c @@ -0,0 +1,99 @@ +/* MDVMM core - PCI configuration space (mechanism #1) and device MMIO */ +#include "core.h" + +static uint32_t mmio_next = MMIO_VIRT; + +static uint32_t cfg_addr(int bus, int dev, int fn, int reg) +{ + return 0x80000000u | (uint32_t)bus << 16 | (uint32_t)dev << 11 | (uint32_t)fn << 8 | (reg & 0xfc); +} + +uint32_t pci_read32(int bus, int dev, int fn, int reg) +{ + outl(0xcf8, cfg_addr(bus, dev, fn, reg)); + return inl(0xcfc); +} + +void pci_write32(int bus, int dev, int fn, int reg, uint32_t v) +{ + outl(0xcf8, cfg_addr(bus, dev, fn, reg)); + outl(0xcfc, v); +} + +/* call found() for every function with class:subclass:progif == cls + (24 bits); the firmware has numbered all buses */ +void pci_scan(uint32_t cls, void (*found)(int bus, int dev, int fn)) +{ + int bus, dev, fn; + + for (bus = 0; bus < 256; bus++) + for (dev = 0; dev < 32; dev++) + for (fn = 0; fn < 8; fn++) + { + uint32_t id = pci_read32(bus, dev, fn, 0x00); + if ((id & 0xffff) == 0xffff) + { + if (fn == 0) + break; /* no device */ + continue; + } + if (pci_read32(bus, dev, fn, 0x08) >> 8 == cls) + found(bus, dev, fn); + if (fn == 0 && !(pci_read32(bus, dev, fn, 0x0c) & 0x00800000)) + break; /* single function device */ + } +} + +/* memory space + bus master on, legacy INTx off (the drivers poll) */ +void pci_enable(int bus, int dev, int fn) +{ + uint32_t cmd = pci_read32(bus, dev, fn, 0x04); + pci_write32(bus, dev, fn, 0x04, (cmd & 0xffff) | 0x0006 | 0x0400); +} + +/* memory BAR at reg (64-bit BARs use the next register too) */ +uint64_t pci_bar(int bus, int dev, int fn, int reg) +{ + uint32_t lo = pci_read32(bus, dev, fn, reg); + + if (lo & 1) + return 0; /* I/O space */ + if ((lo & 6) == 4) + return (lo & ~0xfull) | (uint64_t)pci_read32(bus, dev, fn, reg + 4) << 32; + return lo & ~0xfull; +} + +/* map device registers (uncached) into the monitor; NULL if no room. + Registers above 4GB (64-bit BARs) get 4MB PSE-36 pages. */ +void *mmio_map(uint64_t phys, uint32_t size) +{ + uint32_t off = phys & 0xfff, lin = mmio_next, p; + + if (phys + size > 0x100000000ull) + { + uint64_t base = phys & ~0x3fffffull; + uint32_t span = (uint32_t)(phys + size - base); + lin = (mmio_next + 0x3fffff) & ~0x3fffffu; + for (p = 0; p < span; p += 0x400000) + if (lin + p + 0x400000 > MMIO_VIRT + MMIO_MAX || !map_large_mmio(lin + p, base + p)) + return 0; + mmio_next = lin + ((span + 0x3fffff) & ~0x3fffffu); + return (void *)(lin + (uint32_t)(phys - base)); + } + + size = (off + size + 4095) & ~4095u; + if (mmio_next + size > MMIO_VIRT + MMIO_MAX) + return 0; + for (p = 0; p < size; p += 4096) + if (!map_page(lin + p, (phys & ~0xfffu) + p, 0x1b)) /* PCD PWT */ + return 0; + mmio_next += size; + return (void *)(lin + off); +} + +/* about one microsecond (a port 80h write takes ~1us on PCs) */ +void udelay(uint32_t us) +{ + while (us--) + outb(0x80, 0); +} diff --git a/mdvmm/core/rom.asm b/mdvmm/core/rom.asm new file mode 100644 index 00000000..1a74f63b --- /dev/null +++ b/mdvmm/core/rom.asm @@ -0,0 +1,149 @@ +; MDVMM virtual BIOS ROM (UEFI boot), mapped at F000:0000. +; +; There is no PC BIOS on a UEFI machine; the monitor provides one. BIOS +; services are breakpoints: the interrupt vector points at a HLT, which +; traps into the monitor (bios.c). The monitor does the work on the V86 +; registers and continues after the HLT, at a RETF 2 that keeps the flags +; it set (CF, ZF). Hardware interrupt handlers are real 16-bit code with +; a breakpoint inside, so DOS and TSRs can hook and chain every vector. +; +; Offset 0 holds a table of the addresses the monitor needs, in the order +; of enum rom_id in bios.c. + +%include "bootinfo.inc" + +VBE_MODE equ 141h ; the framebuffer's mode (bios.c) + + cpu 386 + bits 16 + org 0 + +header: + db 'MDBR' + dw (table_end - table) / 2 +table: + dw int10, int11, int12, int13, int14, int15, int16, int17 + dw int18, int19, int1a, irq0_bp, irq1_bp, int16_wait + dw dpt, config_table, stub_bp, stub_entry, stub_psp, stub_retf + dw irq0, irq1, irq_master, irq_slave, dummy_iret + dw vbe_oem, vbe_vendor, vbe_product, vbe_rev, vbe_modes + dw int33 +table_end: + +; ---- BIOS services: HLT (to the monitor), then RETF 2 ---- +int10: hlt + retf 2 +int11: hlt + retf 2 +int12: hlt + retf 2 +int13: hlt + retf 2 +int14: hlt + retf 2 +int15: hlt + retf 2 +int16: hlt + retf 2 +int17: hlt + retf 2 +int18: hlt + retf 2 +int19: hlt + retf 2 +int1a: hlt + retf 2 +int33: hlt ; mouse driver + retf 2 + +; INT 16h read with an empty buffer: the monitor continues here +int16_wait: + sti + hlt ; a real idle HLT: wait for a key + jmp int16 + +; ---- hardware interrupts ---- +irq0: ; INT 08h: timer +irq0_bp: + hlt ; monitor: BIOS tick count + int 1ch + push ax + mov al, 20h + out 20h, al + pop ax + iret + +irq1: ; INT 09h: keyboard + push ax + in al, 60h + mov ah, 4fh ; keyboard intercept (KEYB etc.) + stc + int 15h + jnc irq1_done +irq1_bp: + hlt ; monitor: translate scancode in AL +irq1_done: + cli + mov al, 20h + out 20h, al + pop ax + iret + +irq_master: + push ax + mov al, 20h + out 20h, al + pop ax + iret + +irq_slave: + push ax + mov al, 20h + out 0a0h, al + out 20h, al + pop ax +dummy_iret: + iret + +; ---- DPMI V86 stubs (as in the DOS loader's resident part) ---- +stub_bp: + times BP_COUNT hlt + align 2 +stub_psp dw 0 + +stub_entry: + push ax + push bx + mov ah, 62h ; current PSP, for the client's ES + int 21h + mov [cs:stub_psp], bx + pop bx + pop ax + jmp stub_bp + BP_DPMI_ENTRY + +stub_retf: + retf + +; ---- tables ---- +; diskette parameter table (INT 1Eh), 1.44 MB +dpt: db 0afh, 02h, 25h, 02h, 18, 1bh, 0ffh, 6ch, 0f6h, 0fh, 08h + +; INT 15h AH=C0h system configuration +config_table: + dw 8 ; bytes following + db 0fch ; model: AT + db 01h ; submodel + db 0 ; revision + db 01110000b ; 2nd PIC, RTC, INT 15h/4Fh hook + db 0, 0, 0, 0 + +; VBE controller information (INT 10h AX=4F00h) +vbe_oem db 'modernDOS MDVMM GOP', 0 +vbe_vendor db 'modernDOS', 0 +vbe_product db 'UEFI framebuffer', 0 +vbe_rev db '1.0', 0 + align 2 +vbe_modes dw VBE_MODE, 0ffffh + +; (the reset vector, BIOS date and model byte at F000:FFF0 are written +; by bios_init: this image is kept small, it is part of MDVMM.COM) diff --git a/mdvmm/core/romimg.asm b/mdvmm/core/romimg.asm new file mode 100644 index 00000000..bde1065e --- /dev/null +++ b/mdvmm/core/romimg.asm @@ -0,0 +1,6 @@ +; the virtual BIOS ROM image (rom.asm), copied to F0000h on UEFI boots +section .rodata +global rom_image, rom_image_end +rom_image: + incbin "rom.bin" +rom_image_end: diff --git a/mdvmm/core/uhci.c b/mdvmm/core/uhci.c new file mode 100644 index 00000000..0ba16824 --- /dev/null +++ b/mdvmm/core/uhci.c @@ -0,0 +1,521 @@ +/* MDVMM core - USB keyboards and mice on UHCI controllers + * + * For machines without xHCI (Intel chipsets up to ICH10, older Macs): the + * USB 1.1 host controller, polled. It serves HID boot keyboards and mice + * on its root ports and behind hubs. + * + * USB 2.0 ports belong to an EHCI controller with UHCI "companions". There + * is no EHCI driver here; instead the EHCI controllers are taken from the + * firmware and left unconfigured, which routes every port to its + * companion. High speed devices (a USB 2.0 hub, as in Apple keyboards) + * then work at full speed, and hubs need no transaction translators. + * + * Schedule: every frame runs the interrupt queue heads (one per HID + * endpoint, a ring of transfer descriptors each) and then the control + * queue head. Control transfers are done synchronously at start-up; the + * reports are collected on timer ticks (uhci_poll). Devices are found at + * start-up only. + */ +#include "core.h" + +#define MAX_HC 8 +#define MAX_EP 8 /* HID endpoints, all controllers */ +#define NTD 8 /* reports queued per endpoint */ +#define MAX_DEPTH 4 /* hubs behind hubs */ + +/* I/O registers */ +#define USBCMD 0x00 +#define USBSTS 0x02 +#define USBINTR 0x04 +#define FRNUM 0x06 +#define FRBASEADD 0x08 +#define SOFMOD 0x0c +#define PORTSC(n) (0x10 + (n) * 2) + +#define CMD_RS 0x0001 +#define CMD_HCRESET 0x0002 +#define CMD_GRESET 0x0004 +#define CMD_CF 0x0040 +#define CMD_MAXP 0x0080 + +#define PORT_CCS 0x0001 +#define PORT_CSC 0x0002 +#define PORT_PE 0x0004 +#define PORT_PEC 0x0008 +#define PORT_LSDA 0x0100 +#define PORT_PR 0x0200 + +/* transfer descriptor */ +#define TD_ACTIVE (1u << 23) +#define TD_STALLED (1u << 22) +#define TD_ERRORS (0x7eu << 16) /* stalled, buffer, babble, NAK, CRC, bitstuff */ +#define TD_FATAL (0x76u << 16) /* all but NAK */ +#define TD_LS (1u << 26) +#define TD_CERR3 (3u << 27) +#define TD_SPD (1u << 29) +#define PID_SETUP 0x2d +#define PID_IN 0x69 +#define PID_OUT 0xe1 +#define LINK_T 1u +#define LINK_QH 2u +#define LINK_VF 4u + +struct td { + volatile uint32_t link, status, token, buffer; + uint32_t pad[4]; /* 32 bytes: 16 byte alignment and room */ +}; + +struct qh { + volatile uint32_t link, element; + uint32_t pad[2]; +}; + +struct uhci { + uint16_t io; + uint32_t frames; /* frame list page */ + uint32_t page; /* queue heads, control TDs, data */ + int next_addr; +}; + +/* layout of uhci.page */ +#define QH_START 0x000 /* every frame starts here */ +#define QH_CTRL 0x010 +#define CTRL_TDS 0x040 /* up to 62 */ +#define CTRL_MAXTD 62 +#define CTRL_SETUP 0x800 +#define CTRL_DATA 0x840 /* up to 1984 bytes */ +#define CTRL_MAXDATA 1984 + +struct hidep { + struct uhci *hc; + int mouse; + uint32_t page; /* QH at 0, TDs at 0x20.., buffers at 0x800.. */ + uint32_t token; /* without the toggle */ + uint32_t status; + uint32_t next; /* next TD to complete */ +}; + +static struct uhci hcs[MAX_HC]; +static struct hidep eps[MAX_EP]; +static int nhc, nep; + +static void mdelay(uint32_t ms) +{ + udelay(ms * 1000); +} + +/* ---------------------------------------------------------------- */ +/* control transfers */ + +/* one control transfer on device `addr` (0: the default address); + returns the number of data bytes moved, -1 on failure */ +static int control(struct uhci *h, int addr, int ls, int mps, uint8_t type, uint8_t req, + uint16_t value, uint16_t index, uint16_t len, void *data) +{ + uint8_t *page = pool_ptr(h->page); + struct qh *qc = (struct qh *)(page + QH_CTRL); + struct td *td = (struct td *)(page + CTRL_TDS); + uint8_t *setup = page + CTRL_SETUP, *buf = page + CTRL_DATA; + uint32_t base = h->page, flags = TD_ACTIVE | TD_CERR3 | (ls ? TD_LS : 0), dev = (uint32_t)addr << 8; + int in = type & 0x80, n = 0, i, toggle = 1, moved = 0, ms; + uint16_t left = len; + + if (len > CTRL_MAXDATA || (len + mps - 1) / mps + 2 > CTRL_MAXTD) + return -1; + setup[0] = type; + setup[1] = req; + setup[2] = (uint8_t)value; + setup[3] = (uint8_t)(value >> 8); + setup[4] = (uint8_t)index; + setup[5] = (uint8_t)(index >> 8); + setup[6] = (uint8_t)len; + setup[7] = (uint8_t)(len >> 8); + if (!in && len) + memcpy(buf, data, len); + + td[n].status = flags; + td[n].token = PID_SETUP | dev | 7u << 21; + td[n].buffer = base + CTRL_SETUP; + n++; + while (left) + { + uint16_t k = left > mps ? (uint16_t)mps : left; + td[n].status = flags | (in ? TD_SPD : 0); + td[n].token = (in ? PID_IN : PID_OUT) | dev | (uint32_t)toggle << 19 | (uint32_t)(k - 1) << 21; + td[n].buffer = base + CTRL_DATA + (len - left); + toggle ^= 1; + left -= k; + n++; + } + td[n].status = flags; /* status stage: other direction, DATA1 */ + td[n].token = (in ? PID_OUT : PID_IN) | dev | 1u << 19 | 0x7ffu << 21; + td[n].buffer = 0; + n++; + for (i = 0; i < n; i++) + td[i].link = i + 1 < n ? (base + CTRL_TDS + (i + 1) * sizeof(struct td)) | LINK_VF : LINK_T; + qc->element = base + CTRL_TDS; + + for (ms = 0; ms < 2000; ms++) + { + int a; /* the first TD not done yet */ + + for (a = 0; a < n && !(td[a].status & TD_ACTIVE); a++) + if (td[a].status & TD_FATAL) + { + qc->element = LINK_T; + return -1; + } + if (a == n) + break; + /* a short data packet ends the data stage and stops the queue (SPD): + drop the remaining data TDs and go on with the status stage */ + if (in && a >= 2 && a < n - 1 && + ((td[a - 1].status + 1) & 0x7ff) < (((td[a - 1].token >> 21) + 1) & 0x7ff)) + { + for (i = a; i < n - 1; i++) + td[i].status = 0x7ff; /* inactive, no data */ + qc->element = base + CTRL_TDS + (n - 1) * sizeof(struct td); + } + mdelay(1); + } + qc->element = LINK_T; + if (ms == 2000) + { + mdelay(2); /* the controller may still be in it */ + return -1; + } + for (i = 1; i < n - 1; i++) + moved += (int)((td[i].status + 1) & 0x7ff); + if (in && moved) + memcpy(data, buf, (size_t)moved); + return moved; +} + +/* ---------------------------------------------------------------- */ +/* devices */ + +static void hid_endpoint(struct uhci *h, int addr, int ls, int ep, int mps, int mouse) +{ + struct hidep *e; + uint8_t *page; + struct qh *q, *start; + struct td *td; + int i; + + if (nep == MAX_EP) + return; + e = &eps[nep]; + memset(e, 0, sizeof(*e)); + if (!(e->page = page_alloc())) + return; + if (mps > 64) + mps = 64; + if (mps < 3) + mps = 3; + page = pool_ptr(e->page); + q = (struct qh *)page; + td = (struct td *)(page + 0x20); + e->hc = h; + e->mouse = mouse; + e->token = PID_IN | (uint32_t)addr << 8 | (uint32_t)(ep & 0xf) << 15 | (uint32_t)(mps - 1) << 21; + e->status = TD_ACTIVE | TD_CERR3 | (ls ? TD_LS : 0); + for (i = 0; i < NTD; i++) /* a ring: the controller takes one per frame */ + { + td[i].link = e->page + 0x20 + ((i + 1) % NTD) * sizeof(struct td); + td[i].token = e->token | (uint32_t)(i & 1) << 19; /* DATA0, DATA1, ... */ + td[i].buffer = e->page + 0x800 + i * 64; + td[i].status = e->status; + } + q->element = e->page + 0x20; + start = (struct qh *)((uint8_t *)pool_ptr(h->page) + QH_START); + q->link = start->link; + start->link = e->page | LINK_QH; + nep++; +} + +static void hub(struct uhci *h, int addr, int mps, int depth); + +/* a device answers at address 0: give it an address and look at it */ +static void new_device(struct uhci *h, int ls, int depth, const char *where) +{ + uint8_t d[18], cfg[256]; + int mps = 8, addr, total, off, n, cur = -1, nif = 0, i, is_hub = 0; + struct { int ifnum, ep, mps, mouse; } ifs[2]; + + if (h->next_addr > 127) + return; + if (control(h, 0, ls, 8, 0x80, 6, 0x0100, 0, 8, d) < 8) + { + kprintf("uhci: %s: no answer from the device\n", where); + return; + } + if (d[7] == 16 || d[7] == 32 || d[7] == 64) + mps = d[7]; + addr = h->next_addr++; + if (control(h, 0, ls, mps, 0x00, 5, (uint16_t)addr, 0, 0, 0) < 0) + { + kprintf("uhci: %s: cannot set the address\n", where); + return; + } + mdelay(10); + if (control(h, addr, ls, mps, 0x80, 6, 0x0100, 0, 18, d) < 18 || + control(h, addr, ls, mps, 0x80, 6, 0x0200, 0, 9, cfg) < 9) + { + kprintf("uhci: %s: cannot read the descriptors\n", where); + return; + } + total = cfg[2] | cfg[3] << 8; + if (total > (int)sizeof(cfg)) + total = sizeof(cfg); + n = control(h, addr, ls, mps, 0x80, 6, 0x0200, 0, (uint16_t)total, cfg); + if (n < 9) + return; + total = n; + is_hub = d[4] == 9; + for (off = 0; off + 2 <= total && cfg[off] >= 2; off += cfg[off]) + { + if (cfg[off + 1] == 4 && off + 9 <= total) /* interface */ + { + cur = -1; + if (cfg[off + 5] == 9) + is_hub = 1; + if (nif < 2 && cfg[off + 5] == 3 && cfg[off + 6] == 1 && + (cfg[off + 7] == 1 || cfg[off + 7] == 2)) /* HID boot keyboard / mouse */ + { + cur = nif++; + ifs[cur].ifnum = cfg[off + 2]; + ifs[cur].mouse = cfg[off + 7] == 2; + ifs[cur].ep = 0; + } + } + else if (cfg[off + 1] == 5 && off + 7 <= total && cur >= 0 && !ifs[cur].ep && + (cfg[off + 2] & 0x80) && (cfg[off + 3] & 3) == 3) /* interrupt IN */ + { + ifs[cur].ep = cfg[off + 2]; + ifs[cur].mps = (cfg[off + 4] | cfg[off + 5] << 8) & 0x7ff; + } + } + kprintf("uhci: %s: device %04x:%04x, address %d%s\n", where, d[8] | d[9] << 8, + d[10] | d[11] << 8, addr, ls ? ", low speed" : ""); + if (control(h, addr, ls, mps, 0x00, 9, cfg[5], 0, 0, 0) < 0) /* SET_CONFIGURATION */ + return; + if (is_hub) + { + if (depth < MAX_DEPTH) + hub(h, addr, mps, depth + 1); + return; + } + for (i = 0; i < nif; i++) + { + if (!ifs[i].ep) + continue; + control(h, addr, ls, mps, 0x21, 0x0b, 0, (uint16_t)ifs[i].ifnum, 0, 0); /* boot protocol */ + control(h, addr, ls, mps, 0x21, 0x0a, 0, (uint16_t)ifs[i].ifnum, 0, 0); /* SET_IDLE: on change */ + hid_endpoint(h, addr, ls, ifs[i].ep, ifs[i].mps, ifs[i].mouse); + kprintf("uhci: %s: %s\n", where, ifs[i].mouse ? "mouse" : "keyboard"); + } +} + +/* a hub: power its ports, reset the connected ones, look at the devices */ +static void hub(struct uhci *h, int addr, int mps, int depth) +{ + uint8_t d[16], st[4]; + int ports, p, i; + char where[24]; + + if (control(h, addr, 0, mps, 0xa0, 6, 0x2900, 0, 8, d) < 7) + return; + ports = d[2]; + if (ports > 15) + ports = 15; + kprintf("uhci: hub at address %d, %d ports\n", addr, ports); + for (p = 1; p <= ports; p++) + control(h, addr, 0, mps, 0x23, 3, 8, (uint16_t)p, 0, 0); /* PORT_POWER */ + mdelay(d[5] * 2 + 100); + for (p = 1; p <= ports; p++) + { + if (control(h, addr, 0, mps, 0xa3, 0, 0, (uint16_t)p, 4, st) < 4 || !(st[0] & 1)) + continue; /* nothing connected */ + control(h, addr, 0, mps, 0x23, 3, 4, (uint16_t)p, 0, 0); /* PORT_RESET */ + for (i = 0; i < 50; i++) + { + mdelay(10); + if (control(h, addr, 0, mps, 0xa3, 0, 0, (uint16_t)p, 4, st) == 4 && !(st[0] & 0x10) && + (st[2] & 0x10)) + break; + } + control(h, addr, 0, mps, 0x23, 1, 20, (uint16_t)p, 0, 0); /* clear C_PORT_RESET */ + control(h, addr, 0, mps, 0x23, 1, 16, (uint16_t)p, 0, 0); /* clear C_PORT_CONNECTION */ + if (!(st[0] & 2)) + continue; /* not enabled */ + mdelay(20); + where[0] = 'h'; where[1] = 'u'; where[2] = 'b'; where[3] = ' '; + where[4] = (char)('0' + addr / 10 % 10); where[5] = (char)('0' + addr % 10); + where[6] = ' '; where[7] = 'p'; where[8] = 'o'; where[9] = 'r'; where[10] = 't'; where[11] = ' '; + where[12] = (char)('0' + p / 10); where[13] = (char)('0' + p % 10); where[14] = 0; + new_device(h, st[1] & 2 ? 1 : 0, depth, where); /* bit 9: low speed */ + } +} + +/* ---------------------------------------------------------------- */ +/* controllers */ + +static void root_port(struct uhci *h, int n, int index) +{ + uint16_t reg = h->io + PORTSC(n), v; + char where[] = "controller 0 port 0"; + int i; + + v = inw(reg); + if (!(v & PORT_CCS)) + return; + outw(reg, PORT_PR); + mdelay(50); + outw(reg, 0); + mdelay(10); + for (i = 0; i < 10; i++) /* enable; changes are cleared by writing 1 */ + { + outw(reg, PORT_PE | PORT_CSC | PORT_PEC); + mdelay(10); + v = inw(reg); + if (v & PORT_PE) + break; + } + where[11] = (char)('0' + index); + where[18] = (char)('1' + n); + if (!(v & PORT_PE)) + { + kprintf("uhci: %s: device does not come up (status %04x)\n", where, v); + return; + } + mdelay(20); + new_device(h, v & PORT_LSDA ? 1 : 0, 0, where); +} + +static void uhci_found(int bus, int dev, int fn) +{ + struct uhci *h; + uint32_t *frames; + struct qh *q; + uint16_t io = (uint16_t)(pci_read32(bus, dev, fn, 0x20) & ~3u); + int i; + + if (nhc == MAX_HC || !io) + return; + h = &hcs[nhc]; + memset(h, 0, sizeof(*h)); + h->io = io; + h->next_addr = 1; + if (!(h->frames = page_alloc()) || !(h->page = page_alloc())) + return; + pci_enable(bus, dev, fn); + /* no legacy keyboard emulation, no SMIs: the controller is ours */ + pci_write32(bus, dev, fn, 0xc0, (pci_read32(bus, dev, fn, 0xc0) & 0xffff0000u) | 0x8f00); + outw(io + USBCMD, CMD_GRESET); + mdelay(50); + outw(io + USBCMD, 0); + mdelay(10); + outw(io + USBCMD, CMD_HCRESET); + for (i = 0; i < 100 && (inw(io + USBCMD) & CMD_HCRESET); i++) + mdelay(1); + outw(io + USBINTR, 0); /* polled */ + outw(io + USBSTS, 0x3f); + + q = (struct qh *)((uint8_t *)pool_ptr(h->page) + QH_START); + q->element = LINK_T; + q->link = (h->page + QH_CTRL) | LINK_QH; + q = (struct qh *)((uint8_t *)pool_ptr(h->page) + QH_CTRL); + q->element = LINK_T; + q->link = LINK_T; + frames = pool_ptr(h->frames); + for (i = 0; i < 1024; i++) + frames[i] = (h->page + QH_START) | LINK_QH; + outl(io + FRBASEADD, h->frames); + outw(io + FRNUM, 0); + outb(io + SOFMOD, 0x40); + outw(io + USBCMD, CMD_RS | CMD_CF | CMD_MAXP); + mdelay(100); /* ports settle (and come over from EHCI) */ + kprintf("uhci: controller %d at %02x:%02x.%x, ports %04x %04x\n", nhc, bus, dev, fn, + inw(io + PORTSC(0)), inw(io + PORTSC(1))); + nhc++; + for (i = 0; i < 2; i++) + root_port(h, i, nhc - 1); +} + +/* EHCI: take it from the firmware, stop it, leave it unconfigured: all + ports then belong to the UHCI companions */ +static void ehci_found(int bus, int dev, int fn) +{ + volatile uint8_t *cap, *op; + uint32_t hcc, eecp; + int i; + + pci_enable(bus, dev, fn); + cap = mmio_map(pci_bar(bus, dev, fn, 0x10), 0x400); + if (!cap) + return; + hcc = *(volatile uint32_t *)(cap + 8); + for (eecp = (hcc >> 8) & 0xff; eecp >= 0x40; eecp = (pci_read32(bus, dev, fn, (int)eecp) >> 8) & 0xff) + { + uint32_t v = pci_read32(bus, dev, fn, (int)eecp); + if ((v & 0xff) != 1) + continue; /* not the legacy support capability */ + pci_write32(bus, dev, fn, (int)eecp, v | 1u << 24); /* OS owns it */ + for (i = 0; i < 100 && (pci_read32(bus, dev, fn, (int)eecp) & (1u << 16)); i++) + mdelay(10); + pci_write32(bus, dev, fn, (int)eecp + 4, 0); /* no SMIs */ + break; + } + op = cap + cap[0]; + *(volatile uint32_t *)(op + 0x00) &= ~1u; /* stop */ + for (i = 0; i < 50 && !(*(volatile uint32_t *)(op + 0x04) & 0x1000); i++) + mdelay(1); + *(volatile uint32_t *)(op + 0x00) = 2; /* reset */ + for (i = 0; i < 100 && (*(volatile uint32_t *)(op + 0x00) & 2); i++) + mdelay(1); + *(volatile uint32_t *)(op + 0x08) = 0; /* no interrupts */ + *(volatile uint32_t *)(op + 0x40) = 0; /* CONFIGFLAG: companions */ + kprintf("ehci: controller at %02x:%02x.%x left to its UHCI companions\n", bus, dev, fn); +} + +void uhci_init(void) +{ + pci_scan(0x0c0320, ehci_found); + mdelay(100); + pci_scan(0x0c0300, uhci_found); +} + +/* timer tick: collect the reports */ +void uhci_poll(void) +{ + int i; + + for (i = 0; i < nep; i++) + { + struct hidep *e = &eps[i]; + uint8_t *page = pool_ptr(e->page); + struct td *td = (struct td *)(page + 0x20); + int n; + + for (n = 0; n < NTD; n++) + { + struct td *t = &td[e->next % NTD]; + uint32_t st = t->status; + const uint8_t *r = page + 0x800 + (e->next % NTD) * 64; + if (st & TD_ACTIVE) + break; + if (!(st & TD_FATAL)) + { + int len = (int)((st + 1) & 0x7ff); + if (e->mouse && len >= 3) + mouse_input(r[0] & 7, (int8_t)r[1], (int8_t)r[2]); + else if (!e->mouse && len >= 8) + usbkbd_report(r); + } + /* again: the ring has an even number of TDs, so each one keeps its + data toggle */ + t->status = e->status; + e->next++; + } + } +} diff --git a/mdvmm/core/usbkbd.c b/mdvmm/core/usbkbd.c new file mode 100644 index 00000000..7b770bc7 --- /dev/null +++ b/mdvmm/core/usbkbd.c @@ -0,0 +1,132 @@ +/* MDVMM core - USB keyboards (HID boot protocol) as a PC keyboard + * + * An 8-byte boot report holds the modifier keys (bit map) and up to six + * pressed keys (HID usage IDs). Comparing a report with the previous one + * gives key presses and releases, which become scancode set 1 make and + * break codes for vm_key(): DOS sees the keystrokes as from the PS/2 + * controller (virtual IRQ1, scancode at port 60h). USB keyboards do not + * repeat keys themselves, so the last key pressed repeats here (500 ms + * delay, then 9 per second). By the clock, not by counting timer ticks: + * every DOS session has its ticks, and ticks it missed come in a burst. + * Only time in which the keyboards were asked counts: when the machine + * was busy elsewhere for a while, the key may be up long since. + */ +#include "core.h" + +#define REPEAT_DELAY 500 /* ms */ +#define REPEAT_RATE 110 + +/* HID usage 00h-64h -> scancode set 1 (E0xxh: extended key, 0: none) */ +static const uint16_t usage_sc[0x65] = { + /* 00 */ 0, 0, 0, 0, + /* 04 a-z */ 0x1e, 0x30, 0x2e, 0x20, 0x12, 0x21, 0x22, 0x23, 0x17, 0x24, 0x25, + 0x26, 0x32, 0x31, 0x18, 0x19, 0x10, 0x13, 0x1f, 0x14, 0x16, 0x2f, + 0x11, 0x2d, 0x15, 0x2c, + /* 1e 1-0 */ 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, + /* 28 */ 0x1c, 0x01, 0x0e, 0x0f, 0x39, 0x0c, 0x0d, 0x1a, 0x1b, 0x2b, + /* 32 */ 0x2b, 0x27, 0x28, 0x29, 0x33, 0x34, 0x35, 0x3a, + /* 3a F1-F12 */ 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x57, 0x58, + /* 46 PrtSc ScrLk Pause Ins Home PgUp Del End PgDn Right Left Down Up */ + 0xe037, 0x46, 0, 0xe052, 0xe047, 0xe049, 0xe053, 0xe04f, 0xe051, + 0xe04d, 0xe04b, 0xe050, 0xe048, + /* 53 NumLk KP/ KP* KP- KP+ KPEnter */ 0x45, 0xe035, 0x37, 0x4a, 0x4e, 0xe01c, + /* 59 KP1-9 */ 0x4f, 0x50, 0x51, 0x4b, 0x4c, 0x4d, 0x47, 0x48, 0x49, + /* 62 KP0 KP. non-US \ */ 0x52, 0x53, 0x56, +}; + +/* modifier bits 0-7: LCtrl LShift LAlt LGUI RCtrl RShift RAlt RGUI */ +static const uint16_t mod_sc[8] = { 0x1d, 0x2a, 0x38, 0xe05b, 0xe01d, 0x36, 0xe038, 0xe05c }; + +unsigned long mdvmm_ms(void); + +static uint8_t last[8]; +static uint16_t repeat_sc; +static uint32_t held_ms, repeat_at; /* how long it is held; the next repeat */ +static uint32_t press_ms, press_ticks, repeats_logged; /* diagnostics */ +static uint32_t tick_ms; /* mdvmm_ms() at the last tick */ +static int logged; + +static void send(uint16_t sc, int release) +{ + if (!sc) + return; + if (sc >> 8) + vm_key(0xe0); + vm_key((uint8_t)(sc | (release ? 0x80 : 0))); +} + +static int has(const uint8_t *r, uint8_t key) +{ + int i; + for (i = 2; i < 8; i++) + if (r[i] == key) + return 1; + return 0; +} + +static uint16_t key_sc(uint8_t usage) +{ + return usage < sizeof(usage_sc) / sizeof(usage_sc[0]) ? usage_sc[usage] : 0; +} + +void usbkbd_report(const uint8_t *r) +{ + uint8_t changed = r[0] ^ last[0]; + int i; + + if (r[2] == 0x01) + return; /* phantom state (rollover) */ + if (!logged) + { + kprintf("usbkbd: first key report\n"); + logged = 1; + } + for (i = 0; i < 8; i++) + if (changed & (1 << i)) + send(mod_sc[i], !(r[0] & (1 << i))); + for (i = 2; i < 8; i++) /* releases */ + if (last[i] > 3 && !has(r, last[i])) + { + send(key_sc(last[i]), 1); + if (key_sc(last[i]) == repeat_sc) + repeat_sc = 0; + } + for (i = 2; i < 8; i++) /* presses */ + if (r[i] > 3 && !has(last, r[i])) + { + uint16_t sc = key_sc(r[i]); + send(sc, 0); + if (sc != 0x3a && sc != 0x45 && sc != 0x46) /* locks do not repeat */ + { + repeat_sc = sc; + held_ms = 0; + repeat_at = REPEAT_DELAY; + press_ms = (uint32_t)mdvmm_ms(); + press_ticks = 0; + } + } + memcpy(last, r, 8); +} + +/* timer tick: typematic repeat of the last key held down */ +void usbkbd_tick(void) +{ + uint32_t now = (uint32_t)mdvmm_ms(), dt = now && tick_ms ? now - tick_ms : 55; + + tick_ms = now; + if (!repeat_sc) + return; + held_ms += dt > 110 ? 110 : dt; /* at most two ticks' time between two looks */ + press_ticks++; + if (held_ms >= repeat_at) + { + if (repeat_at == REPEAT_DELAY && repeats_logged < 40) /* the first of a key press */ + { + repeats_logged++; + kprintf("usbkbd: key %02x repeats: held %u ms (%u ms by the clock, %u looks)\n", repeat_sc, held_ms, + now - press_ms, press_ticks); + } + send(repeat_sc, 0); + repeat_at = held_ms + REPEAT_RATE; + } +} diff --git a/mdvmm/core/v86.c b/mdvmm/core/v86.c new file mode 100644 index 00000000..31326913 --- /dev/null +++ b/mdvmm/core/v86.c @@ -0,0 +1,752 @@ +/* MDVMM core - virtual 8086 monitor + * + * DOS runs in V86 mode with IOPL 0, so CLI/STI/PUSHF/POPF/INT/IRET/HLT + * raise #GP and are emulated here against a virtual interrupt flag. The + * real IF stays set while in V86 so hardware interrupts always reach the + * monitor; they are reflected into the DOS interrupt vector table when + * the virtual IF allows it, otherwise kept pending. + */ +#include "core.h" + +struct vm vm1; + +/* ---------------------------------------------------------------- */ +/* V86 memory and stack */ + +static uint8_t fetch8(struct frame *f, uint32_t off) +{ + return *(uint8_t *)rm_ptr(f->cs, off); +} + +void v86_push16(struct frame *f, uint16_t v) +{ + uint16_t sp = (uint16_t)(f->esp - 2); + *(uint16_t *)rm_ptr(f->ss, sp) = v; + f->esp = (f->esp & 0xffff0000u) | sp; +} + +static void push32(struct frame *f, uint32_t v) +{ + uint16_t sp = (uint16_t)(f->esp - 4); + *(uint32_t *)rm_ptr(f->ss, sp) = v; + f->esp = (f->esp & 0xffff0000u) | sp; +} + +uint16_t v86_pop16(struct frame *f) +{ + uint16_t sp = (uint16_t)f->esp; + uint16_t v = *(uint16_t *)rm_ptr(f->ss, sp); + f->esp = (f->esp & 0xffff0000u) | (uint16_t)(sp + 2); + return v; +} + +static uint32_t pop32(struct frame *f) +{ + uint16_t sp = (uint16_t)f->esp; + uint32_t v = *(uint32_t *)rm_ptr(f->ss, sp); + f->esp = (f->esp & 0xffff0000u) | (uint16_t)(sp + 4); + return v; +} + +/* ---------------------------------------------------------------- */ +/* virtual flags */ + +/* flags as the V86 program sees them */ +uint32_t v86_vflags(struct frame *f) +{ + return (f->eflags & (EFL_USER | EFL_AC | EFL_ID)) | 0x2 | + (vm1.vif ? EFL_IF : 0) | EFL_IOPL | (vm1.vflags & EFL_NT); +} + +static void vflags_set(struct frame *f, uint32_t v, int size32) +{ + uint32_t mask = EFL_USER | (size32 ? EFL_AC | EFL_ID : 0); + + f->eflags = (f->eflags & ~mask) | (v & mask) | EFL_IF | EFL_VM; + vm1.vif = (v & EFL_IF) != 0; + /* The I/O privilege level a program sees is 3 and stays 3, as under the + V86 monitors DOS programs know (EMM386, Windows): that it cannot be + changed is how programs tell V86 mode from real mode (DOS/32A; with a + changeable one it took the machine for real mode and tried to switch + to protected mode itself). */ + vm1.vflags = v & EFL_NT; +} + +static void set_cf(struct frame *f, int on) +{ + if (on) + f->eflags |= EFL_CF; + else + f->eflags &= ~EFL_CF; +} + +/* ---------------------------------------------------------------- */ +/* interrupt reflection */ + +/* simulate a real mode INT vec: f->eip must point at the return address */ +void v86_reflect(struct frame *f, uint8_t vec) +{ + const uint16_t *ivt = (const uint16_t *)(uint32_t)(vec * 4); + + v86_push16(f, (uint16_t)v86_vflags(f)); + v86_push16(f, (uint16_t)f->cs); + v86_push16(f, (uint16_t)f->eip); + vm1.vif = 0; + f->eflags &= ~(EFL_TF | EFL_AC); + f->eip = ivt[0]; + f->cs = ivt[1]; +} + +/* Reflect an interrupt so that the monitor hears of the handler's return: + below the handler's return frame (to breakpoint bp in the stub) lies the + real one, which v86_bp_return takes. Nothing but the stack keeps the + way back, so this nests and survives a handler that never returns. */ +void v86_reflect_bp(struct frame *f, uint8_t vec, int bp) +{ + v86_reflect(f, vec); + v86_push16(f, (uint16_t)v86_vflags(f)); + v86_push16(f, boot.stub_seg); + v86_push16(f, (uint16_t)(boot.stub_bp + bp)); +} + +/* at that breakpoint: back to the interrupted code. hw: a hardware + interrupt (all flags as they were); else a software interrupt (the + handler's flags are its result, only the interrupt flag is restored). */ +void v86_bp_return(struct frame *f, int hw) +{ + uint16_t fl; + + f->eip = v86_pop16(f); + f->cs = v86_pop16(f); + fl = v86_pop16(f); + if (hw) + vflags_set(f, fl, 0); + else + vm1.vif = (fl & EFL_IF) != 0; +} + +static uint8_t irq_vector(int irq) +{ + return irq < 8 ? 0x08 + irq : 0x70 + irq - 8; +} + +/* deliver the highest priority pending IRQ if the VM accepts interrupts */ +void v86_deliver(struct frame *f) +{ + static const uint8_t prio[16] = { 0, 1, 8, 9, 10, 11, 12, 13, 14, 15, 3, 4, 5, 6, 7, 2 }; + int i; + + if (vm1.vif && !vm1.pending && vm_owed_tick()) + { + /* a tick it missed: to a DPMI client's own handler if it has one, + else to the real mode one; the monitor hears of the return */ + if (!dpmi_irq_v86(f, 0)) + v86_reflect_bp(f, 0x08, BP_TICK); + return; + } + if (!vm1.vif || !vm1.pending) + return; + for (i = 0; i < 16; i++) + { + int irq = prio[i]; + if (vm1.pending & (1u << irq)) + { + vm1.pending &= ~(1u << irq); + if (!dpmi_irq_v86(f, irq)) + v86_reflect(f, irq_vector(irq)); + return; + } + } +} + +void v86_irq(struct frame *f, int irq) +{ + /* the keyboard: the monitor takes the scancode (also while it waits in + HLT for the VM: then the keystroke is queued) */ + if (irq == 1 && vm_kbd(f, (f->eflags & EFL_VM) != 0)) + return; + vm1.pending |= 1u << irq; + /* from the monitor itself (HLT wait): just record it */ + if (!(f->eflags & EFL_VM)) + return; + if (irq == 0) + vm_tick(f); /* may switch sessions */ + v86_deliver(f); +} + +/* emulate HLT: wait for an interrupt the VM will accept */ +static void halt(struct frame *f) +{ + if (vm1.vif && vm_key_pending()) + { + vm_poll(f); /* a queued keystroke wakes it up */ + return; + } + { + uint16_t at = (uint16_t)f->eip, cs = (uint16_t)f->cs; + vm_yield(f); /* another session may run instead */ + if ((uint16_t)f->eip != at || (uint16_t)f->cs != cs) + return; /* it waited itself and an interrupt came: its handler runs */ + } + while (!(vm1.vif && (vm1.pending || vm_key_pending()))) + __asm__ volatile("sti; hlt; cli" ::: "memory"); + v86_deliver(f); + vm_poll(f); /* a keystroke that came meanwhile */ +} + +/* ---------------------------------------------------------------- */ +/* intercepted software interrupts */ + +/* physical address of a block move address: the V86 address space (first + 1MB + 64K) is paged (private session memory); extended memory goes + through ext_phys (UEFI boots). 0 if invalid. */ +static uint32_t move_phys(uint32_t a) +{ + if (a >= 0x110000) + return ext_phys(a); + return (lin_to_pte(a) & ~0xfffu) | (a & 0xfff); +} + +/* INT 15h AH=87h: move extended memory block (used by XMS drivers) */ +static void int15_move(struct frame *f) +{ + const uint8_t *gdt = rm_ptr(f->es, SI(f)); + uint32_t src = gdt[0x12] | gdt[0x13] << 8 | gdt[0x14] << 16 | (uint32_t)gdt[0x17] << 24; + uint32_t dst = gdt[0x1a] | gdt[0x1b] << 8 | gdt[0x1c] << 16 | (uint32_t)gdt[0x1f] << 24; + uint32_t len = (uint32_t)CX(f) * 2; + + if (len > 0x10000) + { + AH(f) = 0x01; + set_cf(f, 1); + return; + } + while (len) + { + uint32_t n = 4096 - (src & 0xfff); + if (n > 4096 - (dst & 0xfff)) + n = 4096 - (dst & 0xfff); + if (n > len) + n = len; + uint32_t pd = move_phys(dst), ps = move_phys(src); + if (!pd || !ps) + { + AH(f) = 0x02; /* outside extended memory */ + set_cf(f, 1); + return; + } + phys_copy(pd, ps, n); + src += n; + dst += n; + len -= n; + } + AH(f) = 0; + set_cf(f, 0); + f->eflags |= EFL_ZF; +} + +/* returns 1 if handled by the monitor, 0 to reflect to the VM */ +/* Interrupt vectors a program sets and does not put back. DOS restores + only INT 22h-24h when a program ends. A DOS extender that finds a DPMI + host may leave the vector it took in real mode before it switched + (DOS/4GW: INT 15h) - its own end-of-program code does not get to run in + real mode under a host - and the next program then calls into freed + memory. So the monitor notes what a vector was before a program first + set it, and when the program ends (not: stays resident) puts back those + that still point into the program's own memory. */ +#define NVECS 96 +static struct { uint16_t psp; uint8_t vec, used; uint32_t old; } vecs[NVECS]; + +void v86_vector_set(int psp, uint8_t vec) +{ + int i, slot = -1; + + if (psp <= 0) + return; + for (i = 0; i < NVECS; i++) + { + if (vecs[i].used && vecs[i].psp == psp && vecs[i].vec == vec) + return; /* the first value is the one to keep */ + if (!vecs[i].used && slot < 0) + slot = i; + } + if (slot < 0) + return; + vecs[slot].used = 1; + vecs[slot].psp = (uint16_t)psp; + vecs[slot].vec = vec; + vecs[slot].old = *(const uint32_t *)(uint32_t)(vec * 4); +} + +void v86_vectors_end(int psp, int resident) +{ + uint32_t *ivt = (uint32_t *)0, first, end; + int i; + + if (psp <= 0) + return; + /* the program's memory block: from its PSP, the size in the MCB before it */ + first = (uint32_t)psp; + end = first + *(const uint16_t *)rm_ptr((uint16_t)(psp - 1), 3); + for (i = 0; i < NVECS; i++) + if (vecs[i].used && vecs[i].psp == psp) + { + uint32_t seg = ivt[vecs[i].vec] >> 16; + vecs[i].used = 0; + if (!resident && seg >= first && seg < end && vecs[i].vec != 0x22 && vecs[i].vec != 0x23 && + vecs[i].vec != 0x24) + { + kprintf("v86: INT %02xh was left pointing into the program that ended: put back\n", vecs[i].vec); + ivt[vecs[i].vec] = vecs[i].old; + } + } +} + +static int intercept(struct frame *f, uint8_t vec) +{ + if (vec == 0x21 && AH(f) == 0x25) + v86_vector_set(dos_current_psp(), AL(f)); + else if ((vec == 0x21 && (AH(f) == 0x4c || AH(f) == 0x00)) || vec == 0x20) + { + v86_vectors_end(dos_current_psp(), 0); + bios_program_end(); + } + else if ((vec == 0x21 && AH(f) == 0x31) || vec == 0x27) + v86_vectors_end(dos_current_psp(), 1); + + if (vec == 0x15) + { + if (AH(f) == 0x87) + { + int15_move(f); + return 1; + } + if (AH(f) == 0x89) /* switch to protected mode: refuse */ + { + AH(f) = 0xff; + set_cf(f, 1); + return 1; + } + } + else if (vec == 0x2f && AX(f) == 0x1687) + { + dpmi_detect(f); + return 1; + } + else if (vec == 0x21 && AH(f) == 0x4c) + dpmi_rm_exit(); /* then terminate in DOS as usual */ + else if (vec == 0x2a) + vm_crit(f); /* then reflect */ + else if (vec == 0x28 || (vec == 0x2f && AX(f) == 0x1680)) + vm_yield(f); /* DOS idle: let other sessions run */ + else if (vec == 0x2f && AH(f) == 0xde) + { + if (AL(f) >= 0x10 && AL(f) <= 0x1f) + { + nic_api(f); /* network (nic.c) */ + return 1; + } + if (vm_api(f)) + return 1; + switch (AL(f)) + { + case 0x00: /* installation check */ + AL(f) = 0xff; + BX(f) = 0x4d44; /* "MD" */ + CX(f) = 0x0001; /* API version */ + return 1; + case 0x01: /* log ASCIZ string at DS:DX */ + { + const char *s = rm_ptr(f->ds, DX(f)); + int n; + for (n = 0; n < 256 && s[n]; n++) + kprintf("%c", s[n]); + return 1; + } + } + } + return 0; +} + +/* the monitor's services for an interrupt that is not an INT instruction + in V86 mode (the DPMI host reflecting one from protected mode) */ +int v86_intercept(struct frame *f, uint8_t vec) +{ + return intercept(f, vec); +} + +/* ---------------------------------------------------------------- */ +/* port I/O */ + +static uint16_t disk_call_ax, disk_call_dx; /* the last INT 13h call reflected */ +static int kbc_output_port; /* next 60h write is KBC output port data */ + +static uint32_t io_in(uint16_t port, int size) +{ + uint32_t v; + uint8_t b; + + if (size == 1 && dma_port(port)) + return dma_in(port); + if (port == 0x60 && size == 1 && vm_port60(&b)) + return b; /* keystroke replayed by the session code */ + if (vga_port_in(port, size, &v)) + return v; /* the monitor's VGA (mode 13h on a UEFI boot) */ + v = size == 1 ? inb(port) : size == 2 ? inw(port) : inl(port); + + /* a scancode the monitor has taken from the keyboard controller waits + for the session: the controller's status must say so (a BIOS that + looks there first - SeaBIOS - else drops the key, and the scancode + would later be read in place of a mouse byte) */ + if (port == 0x64 && size == 1 && vm_port60_waiting()) + v = (v | 0x01) & ~0x20u; + if (port == 0x92) + v |= 0x02; /* A20 reported (and kept) on */ + return v; +} + +static void io_out(uint16_t port, int size, uint32_t v) +{ + if (size == 1 && dma_port(port)) + { + dma_out(port, (uint8_t)v); + return; + } + if (port >= 0x3b0 && port <= 0x3df && vm_vga_blocked()) + return; /* not on the display: the hardware is not its */ + if (vga_port_out(port, size, v)) + return; + switch (port) + { + case 0x92: + v |= 0x02; /* never disable A20; bit 0 still resets */ + break; + case 0x64: + if ((v & 0xff) == 0xd1) /* write output port: swallow with data */ + { + kbc_output_port = 1; + return; + } + if ((v & 0xff) == 0xdd || (v & 0xff) == 0xdf) + return; /* A20 disable/enable commands */ + if (((v & 0xff) == 0xad || (v & 0xff) == 0xae) && vm_kbd_owned()) + return; /* keyboard off/on, as BIOS keyboard handlers + do around their work: the keyboard side of + the controller is the monitor's (vm_kbd) */ + break; + case 0x60: + if (kbc_output_port) + { + kbc_output_port = 0; + return; + } + break; + } + if (size == 1) + outb(port, (uint8_t)v); + else if (size == 2) + outw(port, (uint16_t)v); + else + outl(port, v); +} + +static void io_reg_in(struct frame *f, uint16_t port, int size) +{ + uint32_t v = io_in(port, size); + if (size == 1) + AL(f) = (uint8_t)v; + else if (size == 2) + AX(f) = (uint16_t)v; + else + f->eax = v; +} + +/* ---------------------------------------------------------------- */ +/* #GP: emulate the sensitive instruction at CS:IP */ + +static void v86_gp(struct frame *f) +{ + uint16_t ip = (uint16_t)f->eip; + int o32 = 0, len = 0; + uint8_t op; + + /* prefixes */ + for (;;) + { + op = fetch8(f, ip + len); + if (op == 0x66) + o32 = 1; + else if (!(op == 0x67 || op == 0xf2 || op == 0xf3 || op == 0xf0 || + op == 0x26 || op == 0x2e || op == 0x36 || op == 0x3e || + op == 0x64 || op == 0x65)) + break; + if (++len > 14) + panic_frame(f, "too many prefixes"); + } + len++; + + switch (op) + { + case 0xfa: /* CLI */ + f->eip = (uint16_t)(ip + len); + vm1.vif = 0; + return; + case 0xfb: /* STI */ + f->eip = (uint16_t)(ip + len); + vm1.vif = 1; + v86_deliver(f); + vm_poll(f); + return; + case 0x9c: /* PUSHF(D) */ + f->eip = (uint16_t)(ip + len); + if (o32) + push32(f, v86_vflags(f)); + else + v86_push16(f, (uint16_t)v86_vflags(f)); + return; + case 0x9d: /* POPF(D) */ + f->eip = (uint16_t)(ip + len); + vflags_set(f, o32 ? pop32(f) : v86_pop16(f), o32); + v86_deliver(f); + vm_poll(f); + return; + case 0xcf: /* IRET(D) */ + if (o32) + { + f->eip = pop32(f) & 0xffff; + f->cs = pop32(f) & 0xffff; + vflags_set(f, pop32(f), 1); + } + else + { + f->eip = v86_pop16(f); + f->cs = v86_pop16(f); + vflags_set(f, v86_pop16(f), 0); + } + v86_deliver(f); + vm_poll(f); + return; + case 0xcd: /* INT n */ + { + uint8_t vec = fetch8(f, ip + len); + f->eip = (uint16_t)(ip + len + 1); + if (!intercept(f, vec)) + { + if (vec == 0x10) + { + int v = vm_video_int(f); + if (v == 1) + return; /* done for a session that is not on the display */ + if (v == 2) + { + /* it needs the display: wait for it, then ask again */ + f->eip = ip; + vm1.vif = 1; + halt(f); + return; + } + } + if (vec == 0x16 && vm_key_wait(f)) + { + /* no key yet: wait here, not in the BIOS, and ask again */ + f->eip = ip; + vm1.vif = 1; + halt(f); + return; + } + if (vm_bios_call(vec)) + { + if (vec == 0x13) + { + disk_call_ax = AX(f); /* for the log, should it fail */ + disk_call_dx = DX(f); + } + v86_reflect_bp(f, vec, BP_INT13); + } + else + v86_reflect(f, vec); + } + return; + } + case 0xcc: /* INT3 */ + f->eip = (uint16_t)(ip + len); + v86_reflect(f, 3); + return; + case 0xce: /* INTO */ + f->eip = (uint16_t)(ip + len); + if (f->eflags & EFL_OF) + v86_reflect(f, 4); + return; + case 0xf4: /* HLT (or a DPMI breakpoint) */ + if (f->cs == boot.stub_seg && ip >= boot.stub_bp && ip < boot.stub_bp + BP_COUNT) + { + if (ip - boot.stub_bp == BP_INT13) + { + /* back from a BIOS service. As at an IRET: interrupts that came + while the handler had them off are due now. (Without this a + timer interrupt that arrived inside the BIOS stayed pending - + and in service at the interrupt controller, so no other came + - until the program's next IRET or STI: a loop that only reads + the time through the BIOS waited forever.) */ + v86_bp_return(f, 0); + vm_bios_done(); + /* a failed disk call of the machine's BIOS is worth a line in the + log (not the questions programs ask it: drive parameters, ...) */ + { + uint8_t fn = (uint8_t)(disk_call_ax >> 8); + if ((fn == 2 || fn == 3 || fn == 0x42 || fn == 0x43) && ((f->eflags & EFL_CF) || (AX(f) >> 8))) + kprintf("bios: INT 13h AX=%04x DL=%02x failed: AX=%04x, carry %u\n", disk_call_ax, + disk_call_dx & 0xff, AX(f), (unsigned)(f->eflags & EFL_CF)); + } + disk_call_ax = 0; + v86_deliver(f); + vm_poll(f); + } + else if (ip - boot.stub_bp == BP_TICK) + { + v86_bp_return(f, 1); + vm_tick_done(); + v86_deliver(f); + vm_poll(f); + } + else if (ip - boot.stub_bp == BP_KBD) + { + v86_bp_return(f, 1); + vm_kbd_done(); + v86_deliver(f); + vm_poll(f); /* with the next keystroke, if one waits */ + } + else + dpmi_v86_bp(f, ip - boot.stub_bp); + return; + } + if (bios_bp(f, ip)) + return; + f->eip = (uint16_t)(ip + len); + halt(f); + return; + case 0xe4: /* IN AL/AX, imm8 */ + case 0xe5: + f->eip = (uint16_t)(ip + len + 1); + io_reg_in(f, fetch8(f, ip + len), op == 0xe4 ? 1 : o32 ? 4 : 2); + return; + case 0xe6: /* OUT imm8, AL/AX */ + case 0xe7: + f->eip = (uint16_t)(ip + len + 1); + io_out(fetch8(f, ip + len), op == 0xe6 ? 1 : o32 ? 4 : 2, f->eax); + return; + case 0xec: /* IN AL/AX, DX */ + case 0xed: + f->eip = (uint16_t)(ip + len); + io_reg_in(f, DX(f), op == 0xec ? 1 : o32 ? 4 : 2); + return; + case 0xee: /* OUT DX, AL/AX */ + case 0xef: + f->eip = (uint16_t)(ip + len); + io_out(DX(f), op == 0xee ? 1 : o32 ? 4 : 2, f->eax); + return; + case 0x0f: /* system instructions */ + { + uint8_t op2 = fetch8(f, ip + len), modrm = fetch8(f, ip + len + 1); + uint32_t *regs[8] = { &f->eax, &f->ecx, &f->edx, &f->ebx, &f->esp, &f->ebp, &f->esi, &f->edi }; + uint32_t *r = regs[modrm & 7]; + int n = (modrm >> 3) & 7; + + if (op2 == 0x20 && (modrm & 0xc0) == 0xc0) + { + /* MOV r32, CRn: DOS extenders look at CR0 to see that the machine + is in protected mode (V86) before they ask for DPMI. They get + that, without the paging bit, and nothing of CR2-CR4. */ + uint32_t cr0; + __asm__("mov %%cr0, %0" : "=r"(cr0)); + *r = n == 0 ? (cr0 & 0x0000003fu) | 1 : 0; + f->eip = (uint16_t)(ip + len + 2); + return; + } + if (op2 == 0x21 && (modrm & 0xc0) == 0xc0) + { + *r = 0; /* MOV r32, DRn */ + f->eip = (uint16_t)(ip + len + 2); + return; + } + if ((op2 == 0x22 || op2 == 0x23) && (modrm & 0xc0) == 0xc0) + { + /* MOV CRn/DRn, r32: not the program's to set. Cache control and + the like in CR0 are ignored; clearing the protected mode bit (a + switch to real mode) cannot be done: the program is ended. */ + if (op2 == 0x22 && n == 0 && !(*r & 1)) + break; + f->eip = (uint16_t)(ip + len + 2); + return; + } + if (op2 == 0x06 || op2 == 0x08 || op2 == 0x09) + { + f->eip = (uint16_t)(ip + len + 1); /* CLTS, INVD, WBINVD: nothing */ + return; + } + break; + } + } + /* An instruction a DOS program cannot use under the monitor (a switch + to protected mode of its own, ...): the program is ended, as by Ctrl+C, + not the machine - unless that does not help. */ + { + static uint32_t last_cs, last_ip, again; + if (last_cs == f->cs && last_ip == f->eip && ++again >= 3) + panic_frame(f, "unhandled #GP in V86 mode"); + if (last_cs != f->cs || last_ip != f->eip) + again = 0; + last_cs = f->cs; + last_ip = f->eip; + kprintf("v86: a program used an instruction it cannot use here at %04x:%04x (%02x %02x %02x %02x %02x): ended\n", + f->cs, ip, fetch8(f, ip), fetch8(f, ip + 1), fetch8(f, ip + 2), fetch8(f, ip + 3), fetch8(f, ip + 4)); + dpmi_rm_exit(); + AX(f) = 0x4cff; + vm1.vif = 1; + v86_reflect(f, 0x21); + } +} + +/* ---------------------------------------------------------------- */ + +void v86_exception(struct frame *f) +{ + switch (f->vector) + { + case 0x0d: + v86_gp(f); + return; + case 0x00: /* divide error */ + case 0x01: /* debug / single step */ + case 0x02: /* NMI */ + case 0x04: /* overflow */ + case 0x05: /* bound */ + case 0x06: /* invalid opcode */ + case 0x07: /* no FPU */ + v86_reflect(f, (uint8_t)f->vector); + return; + } + panic_frame(f, "exception in V86 mode"); +} + +/* first entry into V86: resume the loader where it switched to us */ +void v86_start(void) +{ + static struct frame start; /* not on the stack: enter_frame copies it there */ + struct frame *f = &start; + + memset(f, 0, sizeof(*f)); + f->eip = boot.ip; + f->cs = boot.cs; + f->esp = boot.sp; + f->ss = boot.ss; + f->ds = boot.ds; + f->es = boot.es; + f->fs = boot.fs; + f->gs = boot.gs; + f->eflags = EFL_VM | EFL_IF | 0x2 | (boot.eflags & EFL_USER); + vm1.vif = boot.boot_type == BOOT_UEFI; /* the DOS loader executes STI */ + vm1.pending = 0; + kprintf("v86: entering VM1 at %04x:%04x\n", boot.cs, boot.ip); + enter_frame(f); +} diff --git a/mdvmm/core/vga.c b/mdvmm/core/vga.c new file mode 100644 index 00000000..eb7e15c9 --- /dev/null +++ b/mdvmm/core/vga.c @@ -0,0 +1,922 @@ +/* MDVMM core - the VGA graphics modes on the UEFI framebuffer + * + * A UEFI machine has no video BIOS to set VGA modes, and often no VGA + * hardware behind the legacy ports and A0000h either. For the mode DOS + * games use - 13h, 320x200 in 256 colours, one byte per pixel at A000:0 - + * the monitor is the display card: + * - INT 10h AH=00h AL=13h puts 64 KB of memory at A0000h + * - the palette (DAC, ports 3C6h-3C9h) and the status port 3DAh are the + * monitor's: V86 programs through the I/O bitmap; DPMI clients, which + * run with I/O privilege, through I/O breakpoints in the debug + * registers (the access is seen after it happened: a write is noted, a + * read gets its value put into AL afterwards) + * - INT 10h palette and pixel functions + * - about 30 times a second the picture is drawn on the framebuffer, + * enlarged by a whole factor and centred + * - "unchained" 256 colours (mode X and its relatives: mode 13h with the + * sequencer's chain-4 bit off, which games set for page flipping and + * 320x240): four memory planes, the card's write modes and latches. + * A0000h is unmapped then; every access faults and the instruction is + * run by the monitor (vgaemu.c). The picture's height and start come + * from the CRT controller's registers. + * - the 16 colour modes 0Dh (320x200), 0Eh (640x200), 10h (640x350) and + * 12h (640x480): the same four planes, a bit of each per pixel, and the + * attribute controller's 16 palette registers in front of the DAC. + * Drawn only when video memory, a register or the palette changed. + * - text through INT 10h in the graphics modes (the 8x16 font; 14 and 8 + * lines of it in the 350 and 200 line modes) + * Not here: split screen, pixel panning, blinking, the CGA modes 04h-06h + * and the monochrome ones 0Fh, 11h. One program at a time has the mode: + * the one on the display. + */ +#include "core.h" + +#define VGA_LIN 0xA0000u +#define VGA_PAGES 16 + +static uint32_t W = 320, H = 200; /* the mode's size */ +static uint8_t vmode = 0x13; +static int ega; /* a 16 colour mode: planar, and through attr[] */ +static uint8_t attr[32], attr_idx; /* attribute controller (3C0h) */ +static int attr_flip; /* its next write is data */ +static int dirty; /* planes or registers changed since the last picture */ + +static int active, owner; +static uint32_t pages[VGA_PAGES]; +static uint8_t dac[256][3]; /* 6 bit components */ +static uint32_t pal[256]; /* as framebuffer pixels */ +static int widx, wsub, ridx, rsub; +static uint8_t wcomp[3]; +static uint32_t status_reads, last_ms; +static int pal_dirty; +static int dac_reading; /* 3C7h was written last, not 3C8h */ + +/* the registers programs set, and the four planes of the unchained mode */ +#define PLANES_VIRT 0xEF000000u /* 4 x 64 KB (core.h) */ +static uint8_t *const plane_mem = (uint8_t *)PLANES_VIRT; +static int planes_mapped; +static int planar; /* chain-4 off: A0000h goes through vga_mem_* */ +static uint8_t seq[8], gc[16], crtc[32], latch[4]; +static uint8_t seq_idx, gc_idx, crtc_idx; +static uint32_t shown_h, shown_s; /* the picture's geometry on the framebuffer */ + +#define PLANE(p, a) plane_mem[((uint32_t)(p) << 16) | ((a) & 0xffff)] + +unsigned long mdvmm_ms(void); + +static void set_dac(int i, uint8_t r, uint8_t g, uint8_t b) +{ + uint32_t r8, g8, b8; + + i &= 255; + dac[i][0] = r & 63; + dac[i][1] = g & 63; + dac[i][2] = b & 63; + r8 = (uint32_t)(dac[i][0] << 2 | dac[i][0] >> 4); + g8 = (uint32_t)(dac[i][1] << 2 | dac[i][1] >> 4); + b8 = (uint32_t)(dac[i][2] << 2 | dac[i][2] >> 4); + pal[i] = boot.fb_format == FB_RGBX ? r8 | g8 << 8 | b8 << 16 : b8 | g8 << 8 | r8 << 16; + pal_dirty = 1; +} + +/* the palette a VGA BIOS sets for mode 13h: 16 EGA colours, 16 greys, + then a colour circle in three brightnesses (close to the original) */ +static void default_palette(void) +{ + static const uint8_t ega[16][3] = { + { 0, 0, 0 }, { 0, 0, 42 }, { 0, 42, 0 }, { 0, 42, 42 }, { 42, 0, 0 }, { 42, 0, 42 }, { 42, 21, 0 }, + { 42, 42, 42 }, { 21, 21, 21 }, { 21, 21, 63 }, { 21, 63, 21 }, { 21, 63, 63 }, { 63, 21, 21 }, + { 63, 21, 63 }, { 63, 63, 21 }, { 63, 63, 63 } }; + static const uint8_t grey[16] = { 0, 5, 8, 11, 14, 17, 20, 24, 28, 32, 36, 40, 45, 50, 56, 63 }; + static const uint8_t top[3] = { 63, 28, 16 }, low[3][3] = { { 0, 31, 45 }, { 0, 14, 20 }, { 0, 8, 11 } }; + int i, level, sat, hue; + + for (i = 0; i < 16; i++) + set_dac(i, ega[i][0], ega[i][1], ega[i][2]); + for (i = 0; i < 16; i++) + set_dac(16 + i, grey[i], grey[i], grey[i]); + i = 32; + for (level = 0; level < 3; level++) + for (sat = 0; sat < 3; sat++) + for (hue = 0; hue < 24; hue++) + { + /* around the circle: blue, magenta, red, yellow, green, cyan */ + uint32_t hi = top[level], lo = low[sat][level], seg = (uint32_t)hue / 4, step = (uint32_t)hue % 4; + uint32_t up = lo + (hi - lo) * step / 4, down = hi - (hi - lo) * step / 4, r, g, b; + switch (seg) + { + case 0: r = up; g = lo; b = hi; break; + case 1: r = hi; g = lo; b = down; break; + case 2: r = hi; g = up; b = lo; break; + case 3: r = down; g = hi; b = lo; break; + case 4: r = lo; g = hi; b = up; break; + default: r = lo; g = down; b = hi; break; + } + set_dac(i++, (uint8_t)r, (uint8_t)g, (uint8_t)b); + } + while (i < 256) + set_dac(i++, 0, 0, 0); +} + +/* the 16 colour modes: the palette registers and the DAC as a VGA BIOS + sets them. 200 line modes: registers 8-15 point at 10h-17h (the CGA + colours with intensity); the others at the EGA's 64 colours. */ +static void ega_palette(int lines200) +{ + static const uint8_t reg64[16] = { 0, 1, 2, 3, 4, 5, 0x14, 7, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f }; + static const uint8_t cga[16][3] = { + { 0, 0, 0 }, { 0, 0, 42 }, { 0, 42, 0 }, { 0, 42, 42 }, { 42, 0, 0 }, { 42, 0, 42 }, { 42, 21, 0 }, + { 42, 42, 42 }, { 21, 21, 21 }, { 21, 21, 63 }, { 21, 63, 21 }, { 21, 63, 63 }, { 63, 21, 21 }, + { 63, 21, 63 }, { 63, 63, 21 }, { 63, 63, 63 } }; + int i; + + memset(attr, 0, sizeof(attr)); + for (i = 0; i < 16; i++) + attr[i] = lines200 ? (uint8_t)(i < 8 ? i : 0x10 + (i - 8)) : reg64[i]; + attr[0x10] = 0x01; + attr[0x12] = 0x0f; + for (i = 0; i < 64; i++) + if (lines200) + { + const uint8_t *c = cga[((i >> 4) & 1) << 3 | (i & 7)]; + set_dac(i, c[0], c[1], c[2]); + } + else /* bits 0-2 blue green red: 2/3; bits 3-5: 1/3 */ + set_dac(i, (uint8_t)(((i >> 2) & 1) * 42 + ((i >> 5) & 1) * 21), + (uint8_t)(((i >> 1) & 1) * 42 + ((i >> 4) & 1) * 21), + (uint8_t)((i & 1) * 42 + ((i >> 3) & 1) * 21)); + for (i = 64; i < 256; i++) + set_dac(i, 0, 0, 0); +} + +/* the DAC entry a 16 colour pixel value is shown with */ +static uint8_t attr_colour(int v) +{ + uint8_t c = attr[v & 15] & 0x3f; + + if (attr[0x10] & 0x80) /* bits 4, 5 from the colour select register */ + c = (uint8_t)((c & 0x0f) | (attr[0x14] & 3) << 4); + return (uint8_t)(c | (attr[0x14] & 0x0c) << 4); +} + +static void debug_ports(int on) +{ + uint32_t cr4; + + __asm__("mov %%cr4, %0" : "=r"(cr4)); + if (on) + { + /* I/O breakpoints (CR4.DE) over the card's registers, 3C0h-3DFh: four + of eight ports each, read or written, in every task */ + __asm__ volatile("mov %0, %%cr4" :: "r"(cr4 | 0x08)); + __asm__ volatile("mov %0, %%dr0" :: "r"(0x3c0u)); + __asm__ volatile("mov %0, %%dr1" :: "r"(0x3c8u)); + __asm__ volatile("mov %0, %%dr2" :: "r"(0x3d0u)); + __asm__ volatile("mov %0, %%dr3" :: "r"(0x3d8u)); + __asm__ volatile("mov %0, %%dr7" :: "r"(0xaaaa00aau | 0x400)); + } + else + { + __asm__ volatile("mov %0, %%dr7" :: "r"(0x400u)); + __asm__ volatile("mov %0, %%cr4" :: "r"(cr4 & ~0x08u)); + } +} + +static void ports(int on) +{ + uint16_t p; + + for (p = 0x3c0; p <= 0x3cf; p++) + io_trap(p, on); + io_trap(0x3d4, on); + io_trap(0x3d5, on); + io_trap(0x3da, on); + debug_ports(on); +} + +static void map_linear(int on) +{ + int i; + + for (i = 0; i < VGA_PAGES; i++) + if (on) + map_page(VGA_LIN + (uint32_t)i * 4096, pages[i], 7); + else + unmap_page(VGA_LIN + (uint32_t)i * 4096); +} + +/* the sequencer's chain-4 bit changed: one byte per pixel at A0000h (on), + or four planes behind it (off) */ +static void set_planar(int on) +{ + uint8_t *lin = (uint8_t *)VGA_LIN; + uint32_t o; + + if (on == planar) + return; + if (on) + { + /* as on the card: byte o of the chained memory is plane o & 3 */ + for (o = 0; o < 0x10000; o++) + PLANE(o & 3, o & ~3u) = lin[o]; + map_linear(0); + } + else + { + map_linear(1); + for (o = 0; o < 0x10000; o++) + lin[o] = PLANE(o & 3, o & ~3u); + } + planar = on; + shown_h = 0; + kprintf("vga: %s\n", on ? "256 colours unchained (four planes)" : "256 colours chained"); +} + +/* a byte of video memory read in the planar mode: the latches are loaded */ +uint8_t vga_mem_read(uint32_t off) +{ + int p; + + for (p = 0; p < 4; p++) + latch[p] = PLANE(p, off); + if (gc[5] & 8) /* read mode 1: colour compare */ + { + uint8_t r = 0xff; + for (p = 0; p < 4; p++) + if (gc[7] & (1 << p)) + r &= (uint8_t)~(latch[p] ^ ((gc[2] >> p) & 1 ? 0xff : 0)); + return r; + } + return latch[gc[4] & 3]; +} + +/* ... and written: through the write mode, to the planes of the map mask */ +void vga_mem_write(uint32_t off, uint8_t v) +{ + uint8_t mask = seq[2] & 15, bitmask = gc[8], func = (gc[3] >> 3) & 3, rot = gc[3] & 7; + int mode = gc[5] & 3, p; + + dirty = 1; + if (mode == 1) + { + for (p = 0; p < 4; p++) + if (mask & (1 << p)) + PLANE(p, off) = latch[p]; + return; + } + if (mode == 0 || mode == 3) + v = (uint8_t)(v >> rot | v << (8 - rot)); + if (mode == 3) + bitmask &= v; + for (p = 0; p < 4; p++) + { + uint8_t src; + if (!(mask & (1 << p))) + continue; + if (mode == 2) + src = (v >> p) & 1 ? 0xff : 0; + else if (mode == 3 || (gc[1] & (1 << p))) + src = (gc[0] >> p) & 1 ? 0xff : 0; /* set/reset */ + else + src = v; + switch (func) + { + case 1: src &= latch[p]; break; + case 2: src |= latch[p]; break; + case 3: src ^= latch[p]; break; + } + PLANE(p, off) = (uint8_t)((src & bitmask) | (latch[p] & ~bitmask)); + } +} + +/* A page fault at A0000h in the planar mode: the instruction is run by + the monitor. v86: a V86 frame; code32: a 32 bit code segment. 1 if it + was done. */ +int vga_fault(struct frame *f, uint32_t addr, int v86, int code32) +{ + if (!active || !planar || addr < VGA_LIN || addr >= VGA_LIN + 0x10000) + return 0; + if (vgaemu(f, v86, code32)) + return 1; + kprintf("vga: an instruction on video memory the monitor does not know, at %04x:%08x\n", f->cs, f->eip); + return 0; +} + +int vga_active(void) +{ + return active; +} + +/* INT 10h AH=00h with a graphics mode (0Dh, 0Eh, 10h, 12h, 13h; keep: bit + 7 of the mode number, video memory is not cleared): 1 if the mode is set */ +int vga_enter(int mode, int keep) +{ + uint32_t w, h, lines, ya, xs; + int i; + + switch (mode) + { + case 0x0d: w = 320; h = 200; break; + case 0x0e: w = 640; h = 200; break; + case 0x10: w = 640; h = 350; break; + case 0x12: w = 640; h = 480; break; + case 0x13: w = 320; h = 200; break; + default: return 0; + } + ya = mode == 0x0e ? 2 : 1; + if (!boot.fb_phys || boot.fb_width < w || boot.fb_height < h * ya) + return 0; + for (i = 0; i < VGA_PAGES; i++) + if (!pages[i] && !(pages[i] = page_alloc())) + return 0; + if (!planes_mapped) + { + for (i = 0; i < 64; i++) + { + uint32_t ph = page_alloc(); + if (!ph || !map_page(PLANES_VIRT + (uint32_t)i * 4096, ph, 3)) + return 0; + } + planes_mapped = 1; + } + W = w; + H = h; + vmode = (uint8_t)mode; + ega = mode != 0x13; + planar = ega; + map_linear(1); + if (!keep) + { + memset((void *)VGA_LIN, 0, VGA_PAGES * 4096); + memset(plane_mem, 0, 0x40000); + } + if (ega) + map_linear(0); /* every access through the planes */ + /* the registers as a VGA BIOS leaves them */ + memset(seq, 0, sizeof(seq)); + memset(gc, 0, sizeof(gc)); + memset(crtc, 0, sizeof(crtc)); + memset(latch, 0, sizeof(latch)); + lines = h == 200 ? 400 : h; + seq[2] = 0x0f; + seq[4] = ega ? 0x06 : 0x0e; /* chain-4 in mode 13h */ + gc[5] = ega ? 0x00 : 0x40; + gc[6] = 0x05; + gc[7] = 0x0f; + gc[8] = 0xff; + crtc[0x07] = (uint8_t)(0x10 | ((lines - 1) & 0x100) >> 7 | ((lines - 1) & 0x200) >> 3); + crtc[0x09] = mode == 0x13 ? 0x41 : h == 200 ? 0xc0 : 0x40; /* 200 lines: every line twice */ + crtc[0x12] = (uint8_t)(lines - 1); + crtc[0x13] = (uint8_t)(mode == 0x13 ? 40 : w / 16); + crtc[0x14] = mode == 0x13 ? 0x40 : 0x00; + crtc[0x17] = 0xa3; + shown_h = 0; + if (ega) + ega_palette(h == 200); + else + { + default_palette(); + memset(attr, 0, sizeof(attr)); + for (i = 0; i < 16; i++) + attr[i] = (uint8_t)i; + attr[0x10] = 0x41; + } + attr_idx = 0x20; + attr_flip = 0; + dirty = 1; + widx = wsub = ridx = rsub = 0; + owner = vm_current(); + if (!active) + ports(1); + active = 1; + last_ms = 0; + xs = boot.fb_width / w < boot.fb_height / (h * ya) ? boot.fb_width / w : boot.fb_height / (h * ya); + kprintf("vga: mode %02xh for session %d (%ux%u on the framebuffer)\n", (unsigned)mode, owner, w * xs, h * ya * xs); + return 1; +} + +void vga_leave(void) +{ + int i; + + if (!active) + return; + active = 0; + planar = 0; + ega = 0; + ports(0); + for (i = 0; i < VGA_PAGES; i++) + map_page(VGA_LIN + (uint32_t)i * 4096, VGA_LIN + (uint32_t)i * 4096, 7); +} + +/* the picture onto the framebuffer (from the timer tick) */ +void vga_tick(void) +{ + uint32_t *fb = (uint32_t *)FB_VIRT, pitch = boot.fb_pitch, xs, ys, ya, x0, y0, x, y, k, now; + uint32_t h = H, start = 0, rowbytes = W / 8; + const uint8_t *src = (const uint8_t *)VGA_LIN; + uint32_t lut[16]; + + if (!active || vm_current() != owner || !vm_has_focus()) + return; + now = (uint32_t)mdvmm_ms(); + if (last_ms && now - last_ms < 30) + return; + if (ega && !dirty && !pal_dirty && shown_h) + return; /* nothing new to show */ + last_ms = now ? now : 1; + if (planar && !ega) + { + /* the height: the last displayed line, by the lines a row is shown for */ + uint32_t lines = (crtc[0x12] | (uint32_t)(crtc[0x07] & 0x02) << 7 | (uint32_t)(crtc[0x07] & 0x40) << 3) + 1; + uint32_t per_row = ((crtc[0x09] & 0x1f) + 1) * (crtc[0x09] & 0x80 ? 2 : 1); + h = lines / per_row; + if (h < 100 || h > 600) + h = H; + } + if (planar) + { + start = (uint32_t)crtc[0x0c] << 8 | crtc[0x0d]; + rowbytes = crtc[0x13] ? crtc[0x13] * 2u : W / 8; + } + ya = vmode == 0x0e ? 2 : 1; /* 640x200: pixels twice as high as wide */ + xs = boot.fb_width / W < boot.fb_height / (h * ya) ? boot.fb_width / W : boot.fb_height / (h * ya); + if (!xs) + return; /* it does not fit */ + ys = xs * ya; + if (h != shown_h || xs != shown_s) + { + fbcon_clear(); /* another size: what was around it goes */ + shown_h = h; + shown_s = xs; + } + dirty = 0; + pal_dirty = 0; + for (k = 0; k < 16; k++) + lut[k] = pal[attr_colour((int)k)]; + x0 = (boot.fb_width - W * xs) / 2; + y0 = (boot.fb_height - h * ys) / 2; + for (y = 0; y < h; y++) + { + uint32_t *row = fb + (y0 + y * ys) * pitch + x0, *p = row; + uint32_t line = start + y * rowbytes; + if (ega) + for (x = 0; x < W / 8; x++) + { + uint32_t b0 = PLANE(0, line + x), b1 = PLANE(1, line + x), b2 = PLANE(2, line + x), b3 = PLANE(3, line + x); + int bit; + for (bit = 7; bit >= 0; bit--) + { + uint32_t c = lut[((b0 >> bit) & 1) | ((b1 >> bit) & 1) << 1 | ((b2 >> bit) & 1) << 2 | ((b3 >> bit) & 1) << 3]; + for (k = 0; k < xs; k++) + *p++ = c; + } + } + else + for (x = 0; x < W; x++) + { + uint32_t c = pal[planar ? PLANE(x & 3, line + (x >> 2)) : src[y * W + x]]; + for (k = 0; k < xs; k++) + *p++ = c; + } + for (k = 1; k < ys; k++) + memcpy(row + k * pitch, row, W * xs * 4); + } +} + +/* a port of the display card, read or written by a V86 program (through + the I/O bitmap). 1 if it is one of the monitor's. */ +int vga_port_out(uint16_t port, int size, uint32_t v) +{ + if (!active || port < 0x3c0 || port > 0x3da || (port > 0x3cf && port != 0x3d4 && port != 0x3d5 && port != 0x3da)) + return 0; + if (size != 1 && port != 0x3c0) + { + /* index and data in one word, as programs write the sequencer, the + graphics and the CRT controller */ + vga_port_out(port, 1, v & 0xff); + vga_port_out((uint16_t)(port + 1), 1, (v >> 8) & 0xff); + return 1; + } + switch (port) + { + case 0x3c0: /* attribute controller: index, then data */ + if (!attr_flip) + attr_idx = (uint8_t)v; + else + { + attr[attr_idx & 31] = (uint8_t)v; + dirty = 1; + } + attr_flip = !attr_flip; + break; + case 0x3c4: seq_idx = (uint8_t)(v & 7); break; + case 0x3c5: + seq[seq_idx] = (uint8_t)v; + if (seq_idx == 4 && !ega) + set_planar(!(v & 8)); + break; + case 0x3ce: gc_idx = (uint8_t)(v & 15); break; + case 0x3cf: gc[gc_idx] = (uint8_t)v; break; + case 0x3d4: crtc_idx = (uint8_t)(v & 31); break; + case 0x3d5: + crtc[crtc_idx] = (uint8_t)v; + dirty = 1; + break; + case 0x3c7: + ridx = (int)(v & 255); + rsub = 0; + dac_reading = 1; + break; + case 0x3c8: + widx = (int)(v & 255); + wsub = 0; + dac_reading = 0; + break; + case 0x3c9: + wcomp[wsub++] = (uint8_t)v; + if (wsub == 3) + { + set_dac(widx, wcomp[0], wcomp[1], wcomp[2]); + widx = (widx + 1) & 255; + wsub = 0; + } + break; + } + return 1; +} + +static uint8_t status(void) +{ + /* vertical retrace comes and goes, so that loops that wait for either go on */ + return (status_reads++ >> 3) & 1 ? 0x09 : 0x00; +} + +int vga_port_in(uint16_t port, int size, uint32_t *v) +{ + if (!active || port < 0x3c0 || port > 0x3da || (port > 0x3cf && port != 0x3d4 && port != 0x3d5 && port != 0x3da)) + return 0; + *v = 0; + if (size != 1) + return 1; + switch (port) + { + case 0x3c0: *v = attr_idx; break; + case 0x3c1: *v = attr[attr_idx & 31]; break; + case 0x3c4: *v = seq_idx; break; + case 0x3c5: *v = seq[seq_idx]; break; + case 0x3ce: *v = gc_idx; break; + case 0x3cf: *v = gc[gc_idx]; break; + case 0x3d4: *v = crtc_idx; break; + case 0x3d5: *v = crtc[crtc_idx]; break; + case 0x3cc: *v = 0x63; break; /* miscellaneous output */ + case 0x3c7: *v = 3; break; /* DAC state: ready for writes */ + case 0x3c8: *v = (uint32_t)widx; break; + case 0x3c6: *v = 0xff; break; + case 0x3c9: + *v = dac[ridx][rsub++]; + if (rsub == 3) + { + ridx = (ridx + 1) & 255; + rsub = 0; + } + break; + case 0x3da: + *v = status(); + attr_flip = 0; /* the attribute controller takes an index next */ + break; + } + return 1; +} + +/* Debug exception in a DPMI client: an I/O breakpoint on the card's + registers? The instruction is done: an OUT is taken note of, an IN gets + the monitor's value. Port, size and direction are read from the + instruction before EIP (code[-1]; at a REP OUTSB in progress EIP is still + at the instruction; code32: a 32 bit code segment). 1 if the exception + was the monitor's. */ +int vga_debug(struct frame *f, const uint8_t *code, const uint8_t *esi_byte, int code32) +{ + uint8_t op = code[-1], op2 = code[-2]; + uint32_t dr6, v; + uint16_t port; + int in, size = 1, outs = 0, known = 1; + + if (!active) + return 0; + __asm__("mov %%dr6, %0" : "=r"(dr6)); + if (dr6 & 0xc000) + return 0; /* single step, task switch: the client's */ + __asm__ volatile("mov %0, %%dr6" :: "r"(dr6 & ~15u)); + if (code[0] == 0x6e || (code[0] == 0xf3 && code[1] == 0x6e) || op == 0x6e) + { + outs = 1; + in = 0; + port = (uint16_t)f->edx; + } + else if (op >= 0xec && op <= 0xef) /* IN/OUT with DX */ + { + in = op < 0xee; + if (op & 1) + size = (code32 != (op2 == 0x66)) ? 4 : 2; + port = (uint16_t)f->edx; + } + else if (op2 >= 0xe4 && op2 <= 0xe7) /* IN/OUT with a port number */ + { + in = op2 < 0xe6; + if (op2 & 1) + size = (code32 != (code[-3] == 0x66)) ? 4 : 2; + port = op; + } + else + { + known = 0; + in = 0; + port = 0; + } + if (known && in) + { + if (vga_port_in(port, 1, &v)) + *(uint8_t *)&f->eax = (uint8_t)v; + if (size > 1 && vga_port_in((uint16_t)(port + 1), 1, &v)) + *((uint8_t *)&f->eax + 1) = (uint8_t)v; + } + else if (known) + vga_port_out(port, size > 1 ? 2 : 1, outs ? *esi_byte : f->eax & 0xffff); + /* The trap flag set without a single step reported: not the client's + doing (seen with QEMU, which hands over wrong flags with an IN on a + breakpoint port); with it the next instruction would trap. */ + if ((f->eflags & EFL_TF) && !(dr6 & 0x4000)) + f->eflags &= ~EFL_TF; + return 1; /* (also one with nothing to say: not the client's) */ +} + +/* ---------------------------------------------------------------- */ +/* INT 10h in the graphics modes */ + +extern const uint8_t font8x16[4096]; + +static uint32_t char_h(void) +{ + return H == 200 ? 8 : H == 350 ? 14 : 16; +} + +/* line r of a character: the 8x16 font, for 14 lines without its first and + last one, for 8 lines two of its lines in one */ +static uint8_t glyph_row(uint8_t ch, uint32_t r) +{ + const uint8_t *g = font8x16 + ch * 16; + + switch (char_h()) + { + case 8: return g[r * 2] | g[r * 2 + 1]; + case 14: return g[r + 1]; + default: return g[r]; + } +} + +static void put_pixel(uint32_t x, uint32_t y, uint8_t c) +{ + if (x >= W || y >= H) + return; + if (ega) + { + uint32_t off = y * (W / 8) + x / 8; + uint8_t m = (uint8_t)(0x80 >> (x & 7)); + int p; + for (p = 0; p < 4; p++) + if (c & 0x80) /* XOR with what is there */ + PLANE(p, off) ^= (c >> p) & 1 ? m : 0; + else + PLANE(p, off) = (uint8_t)((PLANE(p, off) & ~m) | ((c >> p) & 1 ? m : 0)); + dirty = 1; + } + else if (!planar) + *(uint8_t *)(VGA_LIN + y * W + x) = c; +} + +static uint8_t get_pixel(uint32_t x, uint32_t y) +{ + if (x >= W || y >= H) + return 0; + if (ega) + { + uint32_t off = y * (W / 8) + x / 8; + int bit = 7 - (int)(x & 7); + return (uint8_t)(((PLANE(0, off) >> bit) & 1) | ((PLANE(1, off) >> bit) & 1) << 1 | + ((PLANE(2, off) >> bit) & 1) << 2 | ((PLANE(3, off) >> bit) & 1) << 3); + } + return planar ? 0 : *(uint8_t *)(VGA_LIN + y * W + x); +} + +/* a character at a text position: its colour on the background 0 (bit 7 + of the colour in the 16 colour modes: XOR) */ +static void draw_char(uint32_t col, uint32_t row, uint8_t ch, uint8_t colour) +{ + uint32_t r, x, ch_h = char_h(); + + if (col >= W / 8 || row >= H / ch_h || (planar && !ega)) + return; + for (r = 0; r < ch_h; r++) + { + uint8_t bits = glyph_row(ch, r); + uint32_t y = row * ch_h + r; + if (ega) + { + uint32_t off = y * (W / 8) + col; + int p; + for (p = 0; p < 4; p++) + if (colour & 0x80) + PLANE(p, off) ^= (colour >> p) & 1 ? bits : 0; + else + PLANE(p, off) = (colour >> p) & 1 ? bits : 0; + } + else + for (x = 0; x < 8; x++) + *(uint8_t *)(VGA_LIN + y * W + col * 8 + x) = bits & (0x80 >> x) ? colour : 0; + } + dirty = 1; +} + +/* text lines r0..r1, columns c0..c1, moved by n lines (0: all), up or + down; what becomes free gets the colour fill */ +static void scroll_text(uint32_t r0, uint32_t c0, uint32_t r1, uint32_t c1, uint32_t n, int up, uint8_t fill) +{ + uint32_t ch_h = char_h(), rows = H / ch_h, cols = W / 8, y0, y1, dy, y, i, width, unit = ega ? 1 : 8; + int p; + + if (planar && !ega) + return; + if (r1 >= rows) + r1 = rows - 1; + if (c1 >= cols) + c1 = cols - 1; + if (r0 > r1 || c0 > c1) + return; + y0 = r0 * ch_h; + y1 = (r1 + 1) * ch_h; /* past the last pixel line */ + dy = n == 0 || n > r1 - r0 + 1 ? y1 - y0 : n * ch_h; + width = (c1 - c0 + 1) * unit; + for (i = 0; i < y1 - y0; i++) + { + uint32_t from; + int blank; + y = up ? y0 + i : y1 - 1 - i; + blank = up ? y + dy >= y1 : y < y0 + dy; + from = up ? y + dy : y - dy; + if (ega) + for (p = 0; p < 4; p++) + { + uint8_t *d = &PLANE(p, y * cols + c0); + if (blank) + memset(d, (fill >> p) & 1 ? 0xff : 0, width); + else + memcpy(d, &PLANE(p, from * cols + c0), width); + } + else + { + uint8_t *d = (uint8_t *)(VGA_LIN + y * W + c0 * 8); + if (blank) + memset(d, fill, width); + else + memcpy(d, (uint8_t *)(VGA_LIN + from * W + c0 * 8), width); + } + } + dirty = 1; +} + +/* a character as on a teletype, at the cursor of page 0 (BIOS data area) */ +static void teletype(uint8_t ch, uint8_t colour) +{ + uint8_t *cur = rm_ptr(0x40, 0x50); /* column, row */ + uint32_t cols = W / 8, rows = H / char_h(); + + serial_putc(ch); + switch (ch) + { + case 7: return; + case 8: + if (cur[0]) + cur[0]--; + return; + case 13: cur[0] = 0; return; + case 10: cur[1]++; break; + default: + draw_char(cur[0], cur[1], ch, colour); + if (++cur[0] >= cols) + { + cur[0] = 0; + cur[1]++; + } + } + if (cur[1] >= rows) + { + scroll_text(0, 0, rows - 1, cols - 1, 1, 1, 0); + cur[1] = (uint8_t)(rows - 1); + } +} + +/* INT 10h in a graphics mode. 1 if the function was done here. */ +int vga_int10(struct frame *f) +{ + uint8_t ah = *((uint8_t *)&f->eax + 1), al = *(uint8_t *)&f->eax; + uint16_t bx = (uint16_t)f->ebx, cx = (uint16_t)f->ecx, dx = (uint16_t)f->edx; + uint8_t *p; + int i; + + if (!active) + return 0; + switch (ah) + { + case 0x0c: /* write pixel */ + put_pixel(cx, dx, al); + return 1; + case 0x0d: /* read pixel */ + *(uint8_t *)&f->eax = get_pixel(cx, dx); + return 1; + case 0x0e: /* teletype, colour BL */ + teletype(al, (uint8_t)bx); + return 1; + case 0x09: /* CX times a character at the cursor, colour BL */ + case 0x0a: + p = rm_ptr(0x40, 0x50); + for (i = 0; i < cx; i++) + draw_char((uint32_t)p[0] + (uint32_t)i, p[1], al, (uint8_t)bx); + return 1; + case 0x13: /* a string at DH, DL: ES:BP, CX characters */ + { + const uint8_t *str = rm_ptr((uint16_t)f->es, (uint16_t)f->ebp); + uint8_t *cur = rm_ptr(0x40, 0x50), col = cur[0], row = cur[1]; + cur[0] = (uint8_t)dx; + cur[1] = (uint8_t)(dx >> 8); + for (i = 0; i < cx; i++) + { + uint8_t ch = *str++, colour = (uint8_t)bx; + if (al & 2) + colour = *str++; + teletype(ch, colour); + } + if (!(al & 1)) + { + cur[0] = col; + cur[1] = row; + } + return 1; + } + case 0x06: /* scroll a window up, down: AL lines, CH,CL - DH,DL */ + case 0x07: + scroll_text(cx >> 8, cx & 255, dx >> 8, dx & 255, al, ah == 6, (uint8_t)(bx >> 8)); + return 1; + case 0x08: /* read the character at the cursor: not known */ + f->eax &= ~0xffffu; + return 1; + case 0x0b: /* CGA palette, border */ + return 1; + case 0x10: + switch (al) + { + case 0x00: /* palette register BL = BH */ + attr[bx & 31] = (uint8_t)(bx >> 8); + dirty = 1; + return 1; + case 0x01: /* border */ + attr[0x11] = (uint8_t)(bx >> 8); + return 1; + case 0x02: /* all 16 registers and the border from ES:DX */ + memcpy(attr, rm_ptr((uint16_t)f->es, dx), 16); + attr[0x11] = *(const uint8_t *)rm_ptr((uint16_t)f->es, (uint16_t)(dx + 16)); + dirty = 1; + return 1; + case 0x07: /* read register BL */ + *((uint8_t *)&f->ebx + 1) = attr[bx & 31]; + return 1; + case 0x08: + *((uint8_t *)&f->ebx + 1) = attr[0x11]; + return 1; + case 0x09: + p = rm_ptr((uint16_t)f->es, dx); + memcpy(p, attr, 16); + p[16] = attr[0x11]; + return 1; + case 0x10: /* set one colour: BX, DH red, CH green, CL blue */ + set_dac(bx, (uint8_t)(dx >> 8), (uint8_t)(cx >> 8), (uint8_t)cx); + return 1; + case 0x12: /* set colours BX.., CX of them, from ES:DX */ + p = rm_ptr((uint16_t)f->es, dx); + for (i = 0; i < cx && bx + i < 256; i++) + set_dac(bx + i, p[i * 3], p[i * 3 + 1], p[i * 3 + 2]); + return 1; + case 0x15: /* read one colour */ + *((uint8_t *)&f->edx + 1) = dac[bx & 255][0]; + f->ecx = (f->ecx & ~0xffffu) | (uint32_t)(dac[bx & 255][1] << 8 | dac[bx & 255][2]); + return 1; + case 0x17: /* read colours */ + p = rm_ptr((uint16_t)f->es, dx); + for (i = 0; i < cx && bx + i < 256; i++) + memcpy(p + i * 3, dac[bx + i], 3); + return 1; + } + return 1; + } + return 0; +} diff --git a/mdvmm/core/vgaemu.c b/mdvmm/core/vgaemu.c new file mode 100644 index 00000000..c3425ac3 --- /dev/null +++ b/mdvmm/core/vgaemu.c @@ -0,0 +1,464 @@ +/* MDVMM core - the instructions that reach VGA memory, run by the monitor + * + * In the planar VGA modes one byte written at A000:xxxx goes to up to four + * memory planes, through the card's write modes and latches (vga.c). The + * monitor leaves A0000h unmapped there; a program's access faults, and the + * instruction is done here instead: the usual ones for video memory - MOV, + * the string instructions with REP, the logical and arithmetic ones, TEST, + * XCHG, INC/DEC, NOT/NEG, MOVZX/MOVSX - in 16 and 32 bit code, V86 mode + * and DPMI clients. A REP runs to its end in one go. + */ +#include "core.h" + +#define VGA_LO 0xA0000u +#define VGA_HI 0xB0000u + +struct ctx { + struct frame *f; + int v86, op32, addr32; + uint32_t ip; /* offset of the next byte to fetch */ + uint32_t cs_base; + int seg_override; /* -1, or 0 ES 1 CS 2 SS 3 DS 4 FS 5 GS */ + int rep; /* 0, 0xf3, 0xf2 */ +}; + +static uint32_t seg_base(struct ctx *c, int seg) +{ + struct frame *f = c->f; + uint32_t sel; + + if (c->v86) + { + switch (seg) + { + case 0: sel = f->es; break; + case 1: sel = f->cs; break; + case 2: sel = f->ss; break; + case 3: sel = f->ds; break; + case 4: sel = f->fs; break; + default: sel = f->gs; break; + } + return (sel & 0xffff) << 4; + } + switch (seg) + { + case 0: sel = f->pes; break; + case 1: sel = f->cs; break; + case 2: sel = f->ss; break; + case 3: sel = f->pds; break; + case 4: sel = f->pfs; break; + default: sel = f->pgs; break; + } + return dpmi_sel_base((uint16_t)sel); +} + +static uint8_t rd8(uint32_t lin) +{ + if (lin >= VGA_LO && lin < VGA_HI) + return vga_mem_read(lin - VGA_LO); + return *(uint8_t *)lin; +} + +static void wr8(uint32_t lin, uint8_t v) +{ + if (lin >= VGA_LO && lin < VGA_HI) + vga_mem_write(lin - VGA_LO, v); + else + *(uint8_t *)lin = v; +} + +static uint32_t rd(uint32_t lin, int size) +{ + uint32_t v = rd8(lin); + + if (size > 1) + v |= (uint32_t)rd8(lin + 1) << 8; + if (size > 2) + v |= (uint32_t)rd8(lin + 2) << 16 | (uint32_t)rd8(lin + 3) << 24; + return v; +} + +static void wr(uint32_t lin, int size, uint32_t v) +{ + wr8(lin, (uint8_t)v); + if (size > 1) + wr8(lin + 1, (uint8_t)(v >> 8)); + if (size > 2) + { + wr8(lin + 2, (uint8_t)(v >> 16)); + wr8(lin + 3, (uint8_t)(v >> 24)); + } +} + +static uint8_t fetch(struct ctx *c) +{ + uint32_t ip = c->v86 ? (c->ip & 0xffff) : c->ip; + + c->ip++; + return *(uint8_t *)(c->cs_base + ip); +} + +static uint32_t fetch_n(struct ctx *c, int size) +{ + uint32_t v = fetch(c); + + if (size > 1) + v |= (uint32_t)fetch(c) << 8; + if (size > 2) + { + v |= (uint32_t)fetch(c) << 16; + v |= (uint32_t)fetch(c) << 24; + } + return v; +} + +static uint32_t *reg32(struct ctx *c, int n) +{ + struct frame *f = c->f; + uint32_t *r[8] = { &f->eax, &f->ecx, &f->edx, &f->ebx, &f->esp, &f->ebp, &f->esi, &f->edi }; + + return r[n & 7]; +} + +static uint32_t reg_get(struct ctx *c, int n, int size) +{ + if (size == 1) + return n < 4 ? *(uint8_t *)reg32(c, n) : *((uint8_t *)reg32(c, n - 4) + 1); + return size == 2 ? *(uint16_t *)reg32(c, n) : *reg32(c, n); +} + +static void reg_set(struct ctx *c, int n, int size, uint32_t v) +{ + if (size == 1) + { + if (n < 4) + *(uint8_t *)reg32(c, n) = (uint8_t)v; + else + *((uint8_t *)reg32(c, n - 4) + 1) = (uint8_t)v; + } + else if (size == 2) + *(uint16_t *)reg32(c, n) = (uint16_t)v; + else + *reg32(c, n) = v; +} + +/* the operand of a ModRM byte: a register (*is_reg, its number in *lin) or + the linear address of memory */ +static void modrm(struct ctx *c, uint8_t m, int *is_reg, uint32_t *lin) +{ + int mod = m >> 6, rm = m & 7, seg = 3; + uint32_t ea = 0; + + if (mod == 3) + { + *is_reg = 1; + *lin = (uint32_t)rm; + return; + } + *is_reg = 0; + if (!c->addr32) + { + uint16_t bx = (uint16_t)c->f->ebx, bp = (uint16_t)c->f->ebp, si = (uint16_t)c->f->esi, + di = (uint16_t)c->f->edi; + switch (rm) + { + case 0: ea = bx + si; break; + case 1: ea = bx + di; break; + case 2: ea = bp + si; seg = 2; break; + case 3: ea = bp + di; seg = 2; break; + case 4: ea = si; break; + case 5: ea = di; break; + case 6: + if (mod == 0) + ea = fetch_n(c, 2); + else + { + ea = bp; + seg = 2; + } + break; + default: ea = bx; break; + } + if (mod == 1) + ea += (uint32_t)(int8_t)fetch(c); + else if (mod == 2) + ea += fetch_n(c, 2); + ea &= 0xffff; + } + else + { + if (rm == 4) + { + uint8_t sib = fetch(c); + int base = sib & 7, index = (sib >> 3) & 7; + if (base == 5 && mod == 0) + ea = fetch_n(c, 4); + else + { + ea = *reg32(c, base); + if (base == 4 || base == 5) + seg = 2; + } + if (index != 4) + ea += *reg32(c, index) << (sib >> 6); + } + else if (rm == 5 && mod == 0) + ea = fetch_n(c, 4); + else + { + ea = *reg32(c, rm); + if (rm == 5) + seg = 2; + } + if (mod == 1) + ea += (uint32_t)(int8_t)fetch(c); + else if (mod == 2) + ea += fetch_n(c, 4); + } + *lin = seg_base(c, c->seg_override >= 0 ? c->seg_override : seg) + ea; +} + +static uint32_t operand_get(struct ctx *c, int is_reg, uint32_t lin, int size) +{ + return is_reg ? reg_get(c, (int)lin, size) : rd(lin, size); +} + +static void operand_set(struct ctx *c, int is_reg, uint32_t lin, int size, uint32_t v) +{ + if (is_reg) + reg_set(c, (int)lin, size, v); + else + wr(lin, size, v); +} + +/* the arithmetic and logical operations, with the flags the CPU gives: + done by the CPU itself. op: 0 ADD 1 OR 2 ADC 3 SBB 4 AND 5 SUB 6 XOR + 7 CMP 8 TEST 9 INC 10 DEC 11 NOT 12 NEG */ +#define ALU1(insn, type) \ + do { type a_ = (type)a, b_ = (type)b; \ + __asm__("push %[fl]; popf; " insn "; pushf; pop %[fl]" : [a] "+q"(a_), [fl] "+r"(fl) : [b] "q"(b_) : "cc"); \ + a = a_; } while (0) +#define ALU(insn8, insn16, insn32) \ + do { if (size == 1) ALU1(insn8, uint8_t); else if (size == 2) ALU1(insn16, uint16_t); else ALU1(insn32, uint32_t); } while (0) + +static uint32_t alu(struct ctx *c, int op, int size, uint32_t a, uint32_t b) +{ + uint32_t fl = (c->f->eflags & 0x8d5) | 0x2; /* the arithmetic flags, interrupts off */ + + switch (op) + { + case 0: ALU("addb %[b], %[a]", "addw %[b], %[a]", "addl %[b], %[a]"); break; + case 1: ALU("orb %[b], %[a]", "orw %[b], %[a]", "orl %[b], %[a]"); break; + case 2: ALU("adcb %[b], %[a]", "adcw %[b], %[a]", "adcl %[b], %[a]"); break; + case 3: ALU("sbbb %[b], %[a]", "sbbw %[b], %[a]", "sbbl %[b], %[a]"); break; + case 4: ALU("andb %[b], %[a]", "andw %[b], %[a]", "andl %[b], %[a]"); break; + case 5: ALU("subb %[b], %[a]", "subw %[b], %[a]", "subl %[b], %[a]"); break; + case 6: ALU("xorb %[b], %[a]", "xorw %[b], %[a]", "xorl %[b], %[a]"); break; + case 7: { uint32_t keep = a; ALU("cmpb %[b], %[a]", "cmpw %[b], %[a]", "cmpl %[b], %[a]"); a = keep; break; } + case 8: { uint32_t keep = a; ALU("testb %[b], %[a]", "testw %[b], %[a]", "testl %[b], %[a]"); a = keep; break; } + case 9: ALU("incb %[a]", "incw %[a]", "incl %[a]"); break; + case 10: ALU("decb %[a]", "decw %[a]", "decl %[a]"); break; + case 11: a = ~a; return a; /* NOT: no flags */ + default: ALU("negb %[a]", "negw %[a]", "negl %[a]"); break; + } + c->f->eflags = (c->f->eflags & ~0x8d5u) | (fl & 0x8d5); + return a; +} + +/* the string instructions: MOVS, STOS, LODS, with REP */ +static void string_op(struct ctx *c, uint8_t op) +{ + struct frame *f = c->f; + int size = (op & 1) ? (c->op32 ? 4 : 2) : 1; + uint32_t mask = c->addr32 ? 0xffffffffu : 0xffffu, count = 1, n; + uint32_t step = (f->eflags & 0x400) ? (uint32_t)-size : (uint32_t)size; + uint32_t src_base = seg_base(c, c->seg_override >= 0 ? c->seg_override : 3), dst_base = seg_base(c, 0); + uint32_t si = f->esi & mask, di = f->edi & mask; + + if (c->rep) + count = f->ecx & mask; + for (n = 0; n < count; n++) + { + switch (op & 0xfe) + { + case 0xa4: /* MOVS */ + wr(dst_base + di, size, rd(src_base + si, size)); + si = (si + step) & mask; + di = (di + step) & mask; + break; + case 0xaa: /* STOS */ + wr(dst_base + di, size, f->eax); + di = (di + step) & mask; + break; + default: /* LODS */ + reg_set(c, 0, size, rd(src_base + si, size)); + si = (si + step) & mask; + break; + } + } + if (c->rep) + f->ecx = (f->ecx & ~mask); + f->esi = (f->esi & ~mask) | si; + f->edi = (f->edi & ~mask) | di; +} + +/* The instruction at the frame's CS:EIP, which touched VGA memory. v86: a + V86 frame; code32: the code segment is a 32 bit one. 1 if it was done; + 0: not one of those above (nothing is changed then). */ +int vgaemu(struct frame *f, int v86, int code32) +{ + struct ctx c; + struct frame saved; + uint8_t op, m; + uint32_t lin, a, b; + int is_reg, size, n; + + memcpy(&saved, f, sizeof(saved)); + c.f = f; + c.v86 = v86; + c.op32 = c.addr32 = code32; + c.ip = f->eip; + c.seg_override = -1; + c.rep = 0; + c.cs_base = v86 ? (f->cs & 0xffff) << 4 : dpmi_sel_base((uint16_t)f->cs); + + for (n = 0; n < 8; n++) + { + op = fetch(&c); + if (op == 0x66) + c.op32 = !code32; + else if (op == 0x67) + c.addr32 = !code32; + else if (op == 0x26) + c.seg_override = 0; + else if (op == 0x2e) + c.seg_override = 1; + else if (op == 0x36) + c.seg_override = 2; + else if (op == 0x3e) + c.seg_override = 3; + else if (op == 0x64) + c.seg_override = 4; + else if (op == 0x65) + c.seg_override = 5; + else if (op == 0xf3 || op == 0xf2) + c.rep = op; + else if (op != 0xf0) + break; + } + size = (op & 1) ? (c.op32 ? 4 : 2) : 1; + + if (op >= 0xa4 && op <= 0xad && op != 0xa6 && op != 0xa7 && op != 0xa8 && op != 0xa9) + string_op(&c, op); + else if (op < 0x40 && (op & 7) < 4) /* ALU r/m,r and r,r/m */ + { + m = fetch(&c); + modrm(&c, m, &is_reg, &lin); + if (op & 2) + { + a = reg_get(&c, (m >> 3) & 7, size); + b = operand_get(&c, is_reg, lin, size); + a = alu(&c, op >> 3, size, a, b); + if ((op >> 3) != 7) + reg_set(&c, (m >> 3) & 7, size, a); + } + else + { + a = operand_get(&c, is_reg, lin, size); + b = reg_get(&c, (m >> 3) & 7, size); + a = alu(&c, op >> 3, size, a, b); + if ((op >> 3) != 7) + operand_set(&c, is_reg, lin, size, a); + } + } + else if (op == 0x80 || op == 0x81 || op == 0x83) /* ALU r/m, imm */ + { + m = fetch(&c); + modrm(&c, m, &is_reg, &lin); + b = op == 0x81 ? fetch_n(&c, size) : (uint32_t)(int8_t)fetch(&c); + a = alu(&c, (m >> 3) & 7, size, operand_get(&c, is_reg, lin, size), b); + if (((m >> 3) & 7) != 7) + operand_set(&c, is_reg, lin, size, a); + } + else if (op == 0x84 || op == 0x85) /* TEST r/m, r */ + { + m = fetch(&c); + modrm(&c, m, &is_reg, &lin); + alu(&c, 8, size, operand_get(&c, is_reg, lin, size), reg_get(&c, (m >> 3) & 7, size)); + } + else if (op == 0x86 || op == 0x87) /* XCHG r/m, r */ + { + m = fetch(&c); + modrm(&c, m, &is_reg, &lin); + a = operand_get(&c, is_reg, lin, size); + operand_set(&c, is_reg, lin, size, reg_get(&c, (m >> 3) & 7, size)); + reg_set(&c, (m >> 3) & 7, size, a); + } + else if (op == 0x88 || op == 0x89) /* MOV r/m, r */ + { + m = fetch(&c); + modrm(&c, m, &is_reg, &lin); + operand_set(&c, is_reg, lin, size, reg_get(&c, (m >> 3) & 7, size)); + } + else if (op == 0x8a || op == 0x8b) /* MOV r, r/m */ + { + m = fetch(&c); + modrm(&c, m, &is_reg, &lin); + reg_set(&c, (m >> 3) & 7, size, operand_get(&c, is_reg, lin, size)); + } + else if (op >= 0xa0 && op <= 0xa3) /* MOV accumulator, moffs and back */ + { + lin = seg_base(&c, c.seg_override >= 0 ? c.seg_override : 3) + fetch_n(&c, c.addr32 ? 4 : 2); + if (op < 0xa2) + reg_set(&c, 0, size, rd(lin, size)); + else + wr(lin, size, f->eax); + } + else if (op == 0xc6 || op == 0xc7) /* MOV r/m, imm */ + { + m = fetch(&c); + modrm(&c, m, &is_reg, &lin); + operand_set(&c, is_reg, lin, size, fetch_n(&c, size)); + } + else if (op == 0xf6 || op == 0xf7) /* TEST imm, NOT, NEG */ + { + m = fetch(&c); + modrm(&c, m, &is_reg, &lin); + n = (m >> 3) & 7; + if (n == 0 || n == 1) + alu(&c, 8, size, operand_get(&c, is_reg, lin, size), fetch_n(&c, size)); + else if (n == 2 || n == 3) + operand_set(&c, is_reg, lin, size, alu(&c, n == 2 ? 11 : 12, size, operand_get(&c, is_reg, lin, size), 0)); + else + goto unknown; + } + else if (op == 0xfe || op == 0xff) /* INC, DEC */ + { + m = fetch(&c); + n = (m >> 3) & 7; + if (n > 1) + goto unknown; /* CALL, JMP, PUSH through video memory: no */ + modrm(&c, m, &is_reg, &lin); + operand_set(&c, is_reg, lin, size, alu(&c, n ? 10 : 9, size, operand_get(&c, is_reg, lin, size), 0)); + } + else if (op == 0x0f) + { + uint8_t op2 = fetch(&c); + if (op2 != 0xb6 && op2 != 0xb7 && op2 != 0xbe && op2 != 0xbf) + goto unknown; + m = fetch(&c); /* MOVZX, MOVSX */ + modrm(&c, m, &is_reg, &lin); + a = operand_get(&c, is_reg, lin, (op2 & 1) ? 2 : 1); + if (op2 & 8) + a = (op2 & 1) ? (uint32_t)(int16_t)a : (uint32_t)(int8_t)a; + reg_set(&c, (m >> 3) & 7, c.op32 ? 4 : 2, a); + } + else + goto unknown; + f->eip = v86 ? (c.ip & 0xffff) : c.ip; + return 1; + +unknown: + memcpy(f, &saved, sizeof(saved)); + return 0; +} diff --git a/mdvmm/core/vm.c b/mdvmm/core/vm.c new file mode 100644 index 00000000..9fac0e6b --- /dev/null +++ b/mdvmm/core/vm.c @@ -0,0 +1,1220 @@ +/* MDVMM core - DOS sessions + * + * All sessions share one DOS kernel, as with Windows 386 enhanced mode: + * - memory below the loader's resident block is global (shared pages); + * from there to 640K every session has private pages + * - "instance data" (IVT, BIOS data area, the DOS data segment from the + * kernel's 1605h table, the CDS array) is swapped on every switch + * - a session is only switched out while it is not inside a DOS critical + * section (INT 2Ah AH=80h..82h), so global DOS structures (buffers, + * FAT, SFTs) are never seen half updated + * - all hardware interrupts go to the running session; keystrokes for a + * focused session that is not running are queued and replayed + * - text mode video: the focused session owns B8000h, the others write + * to shadow pages + * - a DPMI client belongs to the session it started in; the others keep + * running (as plain V86) around it, switches happen in PM as well + * Session 0 is the original DOS (identity mapped memory). + */ +#include "core.h" + +#define MAX_RANGES 8 +#define SLICE_TICKS 2 /* ~110 ms per time slice */ +#define KQ_SIZE 128 +#define VRAM 0xB8000u +#define INST_BASE 0xEE000000u /* instance data copies, 1MB each */ + +struct range { uint32_t lin, size; }; + +struct session { + int used; + struct frame f; /* saved V86 state */ + uint32_t vif, vflags, crit; + uint32_t pages[160]; /* private page per 4K below 640K */ + uint32_t vram[VRAM_PAGES]; /* shadow video pages */ + uint32_t inst; /* linear address of instance copy */ + uint32_t tick_mark; + uint32_t owed; /* timer ticks it missed and still gets */ + int tick_busy; /* the handler of one of those runs */ + uint32_t tick_since; + uint8_t kq[KQ_SIZE]; /* queued scancodes */ + int kq_head, kq_tail; + int slot; /* a job slot (SSHSLOT.COM) */ + int inbios; /* inside BIOS services, how deep (flat mode) */ + uint32_t inbios_since; + int kbd_busy; /* its keyboard interrupt handler runs */ + uint32_t kbd_since; + int job; /* JOB_* */ + uint16_t job_flags, job_code; + char cmd[128]; +}; + +enum { JOB_NONE, JOB_ASSIGNED, JOB_RUNNING, JOB_DONE }; + +/* physical pages of the visible text screen: VGA memory, or RAM that + fbcon.c draws on a UEFI framebuffer */ +uint32_t vram_phys[VRAM_PAGES] = { + 0xB8000, 0xB9000, 0xBA000, 0xBB000, 0xBC000, 0xBD000, 0xBE000, 0xBF000 +}; + +static struct session ses[MAX_SESSIONS]; + +static struct range ranges[MAX_RANGES]; +static int nranges; +static uint32_t inst_size; /* bytes of instance data */ +static uint32_t first_private; /* first private page number */ +static uint32_t end_private = 0xa0; /* the page after the last private one */ +/* DOS boots: session memory is not remapped but copied on a switch, so + that a linear address below 640K is always the physical one. The + machine's BIOS counts on that: disk code that runs in system management + mode (USB sticks, SeaBIOS and real firmware alike) reads the caller's + buffers and stack by physical address, and so does bus master and ISA + DMA hardware. pages[] then holds a session's memory while it is not the + running one. UEFI boots (the monitor's own BIOS) remap instead. */ +static int flat; +/* (and no switch while a session is inside the BIOS disk service: its + transfer may be under way to physical memory) */ +static int registered; +static int cur, focus, nsessions = 1; +static int want = -1; /* session to switch to */ +static uint32_t ticks; /* timer interrupts */ +static uint32_t slice_start; /* when the running session got the CPU (ms) */ +static uint32_t idle_streak; /* sessions that gave up the CPU one after the other */ + +/* The time in units of a normal timer tick (55 ms), for the monitor's own + timeouts and time slices. Not the count of timer interrupts: programs + set the timer to many times its normal rate (games, for sound and + timing), and a session switch at every other interrupt then took most + of the machine's time. From the time stamp counter (ipxenic.c); the + interrupt count where that is not calibrated. */ +unsigned long mdvmm_ms(void); +static uint32_t tnow(void) +{ + uint32_t ms = (uint32_t)mdvmm_ms(); + + return ms ? ms / 55 : ticks; +} +static uint32_t crit; /* critical section depth */ +static int kbd_ctrl, kbd_alt; +static int kbc_planted; /* a scancode put into the keyboard controller (kbc_plant) */ +static int vm_trace; /* log every session switch */ +static int latch_valid; /* port 60h replay */ +static uint8_t latch; +static uint32_t latch_tick; /* when it was set */ +static uint8_t last_scancode; /* the last one a session read */ + + +/* ---------------------------------------------------------------- */ + +static void add_range(uint32_t lin, uint32_t size) +{ + if (!size || nranges == MAX_RANGES) + return; + ranges[nranges].lin = lin; + ranges[nranges].size = size; + inst_size += size; + nranges++; + kprintf("vm: instance data %05x, %u bytes\n", lin, size); +} + +static uint32_t far_lin(uint32_t fp) +{ + return ((fp >> 16) << 4) + (fp & 0xffff); +} + +/* INT 2Fh AX=DE04h: the loader registers per session data (DS:DX) */ +static uint32_t indos_lin; /* DOS InDOS flag: SDA + 1 */ + +/* DOS's current PSP (SDA + 10h), or -1 if DOS has not told us where */ +int dos_current_psp(void) +{ + if (!indos_lin) + return -1; + return *(const uint16_t *)(indos_lin - 1 + 0x10); +} + +static int vm_register(struct frame *f) +{ + const uint8_t *r = rm_ptr(f->ds, DX(f)); + uint32_t sis = *(const uint32_t *)r; + uint32_t cds = *(const uint32_t *)(r + 8); + uint16_t cds_size = *(const uint16_t *)(r + 12); + uint16_t boundary = *(const uint16_t *)(r + 14); + int guard; + + if (!indos_lin && *(const uint32_t *)(r + 4)) + indos_lin = far_lin(*(const uint32_t *)(r + 4)); + if (registered || !sis || (boundary & 0xff)) + return 0; + add_range(0, 0x600); /* IVT, BIOS data, DOS 500h area */ + for (guard = 0; sis && guard < 16; guard++) + { + const uint8_t *s = (const uint8_t *)far_lin(sis); + uint32_t inst = *(const uint32_t *)(s + 0x0e); + const uint8_t *e; + + for (e = inst ? (const uint8_t *)far_lin(inst) : 0; e && *(const uint32_t *)e; e += 6) + add_range(far_lin(*(const uint32_t *)e), *(const uint16_t *)(e + 4)); + sis = *(const uint32_t *)(s + 2); + } + if (nranges < 2) + { + kprintf("vm: kernel reported no instance data\n"); + return 0; + } + add_range(far_lin(cds), cds_size); + first_private = (uint32_t)boundary >> 8; + { + /* The BIOS's own memory at the top of the 640 KB (the extended BIOS + data area, above the size in 40:13) is one for all sessions and + stays where it is: a BIOS disk driver has its controller's data + there (SeaBIOS: USB), which the hardware reads by physical address. + DOS memory in the same page as its start is copied on a switch. */ + uint32_t top = (uint32_t)*(const uint16_t *)rm_ptr(0x40, 0x13) << 10; + if (top > 0xa0000 || top < 0x80000) + top = 0xa0000; + end_private = top >> 12; + if (top & 0xfff) + add_range(end_private << 12, top & 0xfff); + } + if (boot.boot_type != BOOT_UEFI) + { + uint32_t p; + flat = 1; + for (p = first_private; p < end_private; p++) + if (!(ses[0].pages[p] = page_alloc())) + return 0; + } + ses[0].used = 1; + registered = 1; + kprintf("vm: sessions enabled, private memory %05x-%05x%s\n", first_private << 12, + (end_private << 12) - 1, flat ? " (copied on a switch)" : ""); + return 1; +} + +/* instance data: live memory <-> a session's saved copy */ +static void inst_copy(struct session *s, int save) +{ + uint8_t *buf = (uint8_t *)s->inst; + int i; + + for (i = 0; i < nranges; i++) + { + if (save) + memcpy(buf, (void *)ranges[i].lin, ranges[i].size); + else + memcpy((void *)ranges[i].lin, buf, ranges[i].size); + buf += ranges[i].size; + } +} + +/* the BIOS data area of a session: live, or in its instance copy */ +static uint8_t *bda(int n) +{ + return n == cur ? (uint8_t *)rm_ptr(0x40, 0) : (uint8_t *)ses[n].inst + 0x400; +} + +/* Flat mode (the machine's own video BIOS): a session that is not on the + display must not reach the video hardware. Its text goes into its own + screen memory (map_session); its writes to the VGA ports are dropped + (v86.c), and a mode set does not go to the BIOS (vm_video_int). */ +static int vga_trapped; + +int vm_vga_blocked(void) +{ + return flat && cur != focus; +} + +static void vga_ports(void) +{ + int on = vm_vga_blocked(); + uint16_t p; + + if (on == vga_trapped) + return; + vga_trapped = on; + for (p = 0x3b0; p <= 0x3df; p++) + io_trap(p, on); +} + +/* INT 10h of the running session. 0: to the BIOS; 1: done here; 2: the + session has to wait until it is on the display. */ +int vm_video_int(struct frame *f) +{ + uint8_t ah = *((uint8_t *)&f->eax + 1), al = *(uint8_t *)&f->eax, mode = al & 0x7f; + uint8_t *b; + uint32_t i; + + if (!vm_vga_blocked()) + return 0; + if (AX(f) == 0x4f02) + return 2; /* a VESA mode */ + if (ah != 0x00) + return 0; + if (mode > 3 && mode != 7) + return 2; /* a graphics mode */ + /* a text mode: what the BIOS would leave, in the session's own screen */ + b = rm_ptr(0x40, 0); + b[0x49] = mode; + *(uint16_t *)(b + 0x4a) = mode < 2 ? 40 : 80; + *(uint16_t *)(b + 0x4c) = mode < 2 ? 2048 : 4096; + *(uint16_t *)(b + 0x4e) = 0; + memset(b + 0x50, 0, 16); /* cursor positions */ + *(uint16_t *)(b + 0x60) = 0x0607; /* cursor shape */ + b[0x62] = 0; + b[0x84] = 24; + if (!(al & 0x80)) + for (i = 0; i < VRAM_PAGES * 4096u; i += 2) + *(uint16_t *)(VRAM + i) = 0x0720; + return 1; +} + +static void map_session(int n) +{ + struct session *s = &ses[n]; + uint32_t p; + + for (p = first_private; p < end_private && !flat; p++) + map_page(p << 12, s->pages[p] ? s->pages[p] : p << 12, 7); + for (p = 0; p < VRAM_PAGES; p++) + map_page(VRAM + p * 4096, n == focus ? vram_phys[p] : s->vram[p], 7); + vga_ports(); +} + +/* in-service IRQs at the PICs */ +static uint16_t pic_isr(void) +{ + uint16_t isr; + + outb(0x20, 0x0b); + outb(0xa0, 0x0b); + isr = inb(0x20) | inb(0xa0) << 8; + outb(0x20, 0x0a); + outb(0xa0, 0x0a); + return isr; +} + +/* Is a scancode waiting to be read at port 60h? If the keyboard + interrupt handler it was given to has not read it after two timer + ticks it never will: it must not turn up later in place of another + byte (a mouse byte). */ +static int latch_ok(void) +{ + if (latch_valid && tnow() - latch_tick > 2) + { + kprintf("kbd: scancode %02x was not read by the session's handler\n", latch); + latch_valid = 0; + } + return latch_valid; +} + +int vm_current(void) +{ + return cur; +} + +/* A timer tick the running session missed (switch_to) is due: 1 if it + can be given now - none pending, no interrupt in service, the handler + of the one before has returned (vm_tick_done). The caller then runs the + session's timer interrupt handler. Until that returns the session is + not switched out, as with a real interrupt in service: a BIOS runs its + handlers on one stack of its own. */ +int vm_owed_tick(void) +{ + struct session *s = &ses[cur]; + + if (s->tick_busy && tnow() - s->tick_since > 9) + s->tick_busy = 0; + if (!s->owed || s->tick_busy || (vm1.pending & 1) || vm_hold || pic_isr()) + return 0; + s->owed--; + s->tick_busy = 1; + s->tick_since = tnow(); + return 1; +} + +void vm_tick_done(void) +{ + ses[cur].tick_busy = 0; +} + +/* where every session is (MDLOG /N): for a look at one that does not go on */ +void vm_debug(void) +{ + int n; + uint8_t irr; + + outb(0x20, 0x0a); + irr = inb(0x20); + kprintf("vm: interrupts: mask %02x, requested %02x, in service %04x, pending %x, IF %u, hold %d, " + "scancode planted %d\n", inb(0x21), irr, pic_isr(), vm1.pending, vm1.vif, vm_hold, kbc_planted); + + for (n = 0; n < MAX_SESSIONS; n++) + { + struct session *s = &ses[n]; + const uint8_t *b; + if (!s->used) + continue; + b = bda(n); + if (n == cur) + kprintf("vm: session %d runs; focus %d, PSP %04x, crit %u, in BIOS %d, kbd busy %d, tick busy %d, " + "DPMI client %d\n", n, focus, indos_lin ? *(const uint16_t *)(indos_lin - 1 + 0x10) : 0, crit, + s->inbios, s->kbd_busy, s->tick_busy, dpmi_active()); + else + kprintf("vm: session %d at %04x:%04x %s ss:sp %04x:%04x if %u, job %d, in BIOS %d, kbd busy %d, " + "tick busy %d, owed %u, crit %u, keys %u\n", n, s->f.cs, (uint16_t)s->f.eip, + (s->f.eflags & EFL_VM) ? "v86" : "pm", (s->f.eflags & EFL_VM) ? s->f.ss : 0, + (s->f.eflags & EFL_VM) ? (uint16_t)s->f.esp : 0, s->vif, s->job, s->inbios, s->kbd_busy, + s->tick_busy, s->owed, s->crit, + (unsigned)((*(const uint16_t *)(b + 0x1c) - *(const uint16_t *)(b + 0x1a)) & 0x1f) / 2); + if (n != cur && n != focus && s->vram[0]) + { + /* the last lines of its text screen (to the cursor) */ + int row = b[0x51], r, c; + for (r = row > 3 ? row - 3 : 0; r <= row && r < 25; r++) + { + char line[81]; + const uint8_t *cells = (const uint8_t *)kmap(2, s->vram[(r * 160) >> 12]) + ((r * 160) & 4095); + for (c = 0; c < 80 && ((r * 160) & 4095) + c * 2 < 4096; c++) + line[c] = (char)(cells[c * 2] >= ' ' && cells[c * 2] < 127 ? cells[c * 2] : ' '); + while (c > 0 && line[c - 1] == ' ') + c--; + line[c] = 0; + kprintf("vm: screen %2d| %s\n", r, line); + } + } + } +} + +uint32_t vm_ticks(void) +{ + return tnow(); +} + +/* does the running session own the display? */ +int vm_has_focus(void) +{ + return cur == focus; +} + +/* the BIOS data area of the session on the display */ +uint8_t *vm_focus_bda(void) +{ + return bda(focus); +} + +/* set while the DPMI host runs a monitor service for its client with a + V86 frame that is never entered: switches wait for the next chance */ +int vm_hold; + +static int switchable(const struct frame *f, uint16_t isr_ignore) +{ + int ifl = (f->eflags & EFL_VM) ? (int)vm1.vif : !!(f->eflags & EFL_IF); + + /* inside the BIOS disk service (unless that call is 20 seconds old: + then the program has left it some other way) */ + if (ses[cur].inbios && tnow() - ses[cur].inbios_since < 20 * 18) + return 0; + /* nor inside its keyboard interrupt handler: as with a real interrupt + in service (below). A BIOS may run its interrupt handlers on one stack + of its own (SeaBIOS), which two sessions must not be on at once. */ + if (ses[cur].kbd_busy && tnow() - ses[cur].kbd_since <= 9) + return 0; + if (ses[cur].tick_busy && tnow() - ses[cur].tick_since <= 9) + return 0; + return ifl && !vm_hold && !crit && !(pic_isr() & ~isr_ignore); +} + +/* The running session calls a BIOS service (a software interrupt 10h to + 1Ah). Flat mode - the machine's own BIOS: 1, and no session switch + until the call has returned (the caller sees to it that the monitor + hears of that: vm_bios_done). Two reasons: a disk transfer may be under + way to physical memory, and a BIOS is written for one thread of + execution - SeaBIOS runs its services on one stack of its own, and a + second session coming in there while the first is inside takes that + stack from under it. */ +int vm_bios_call(uint8_t vec) +{ + struct session *s = &ses[cur]; + + if (!flat || vec < 0x10 || vec > 0x1a || vec == 0x18 || vec == 0x19) + return 0; + if (s->inbios && tnow() - s->inbios_since >= 20 * 18) + s->inbios = 0; /* old calls that were abandoned */ + if (!s->inbios++) + s->inbios_since = tnow(); + return 1; +} + +void vm_bios_done(void) +{ + if (ses[cur].inbios) + ses[cur].inbios--; +} + +/* Would INT 16h AH=00h/10h (read a key) wait inside the BIOS? Then the + monitor waits in its place (v86.c), so the session can be switched: + in flat mode, with the vector still the BIOS's own and no key there. */ +int vm_key_wait(const struct frame *f) +{ + const uint8_t *b = rm_ptr(0x40, 0); + uint8_t ah = *((const uint8_t *)&f->eax + 1); + + return flat && nsessions > 1 && (ah == 0x00 || ah == 0x10) && + *(const uint16_t *)(uint32_t)(0x16 * 4 + 2) >= 0xa000 && + *(const uint16_t *)(b + 0x1a) == *(const uint16_t *)(b + 0x1c); +} + +static int next_session(void) +{ + int i, n; + + for (i = 1; i <= MAX_SESSIONS; i++) + { + n = (cur + i) % MAX_SESSIONS; + if (ses[n].used) + return n; + } + return cur; +} + +/* a scancode into a session's queue */ +static void kq_put(int n, uint8_t sc) +{ + struct session *s = &ses[n]; + int next = (s->kq_tail + 1) % KQ_SIZE; + + if (next != s->kq_head) + { + s->kq[s->kq_tail] = sc; + s->kq_tail = next; + } + else + kprintf("kbd: session %d does not take its keystrokes, scancode %02x dropped\n", n, sc); +} + +/* A DPMI client's own keyboard interrupt handler reads port 60h itself, + and the monitor does not see it: clients have I/O privilege. (Every + DJGPP program has such a handler, for Ctrl+C; games have theirs.) What + the controller holds then must be the scancode the handler is called + for - a later one that waits there already would be read in its place + and be lost. So the scancode is planted in the controller: the keyboard + interface off (ADh), what waits there into the queue, then "write + keyboard output buffer" (D2h) with the scancode; kbc_unplant() undoes + it when the handler has returned. (The controller raises the keyboard + interrupt for the planted byte: vm_kbd() lets it pass.) + 0: not now (a mouse byte is in the controller: the mouse's handler + takes it first). No controller (USB keyboards only): nothing to do, + the handler then reads nothing of use. */ + +static void kbc_ready(void) +{ + int i; + + for (i = 0; i < 20000 && (inb(0x64) & 2); i++) + ; +} + +static int kbc_plant(uint8_t sc) +{ + uint8_t st = inb(0x64); + int i; + + if (st == 0xff) + return 1; + if ((st & 0x21) == 0x21) + return 0; + kbc_ready(); + outb(0x64, 0xad); + for (i = 0; i < 16 && ((st = inb(0x64)) & 0x21) == 0x01; i++) + { + uint8_t b = inb(0x60); + switch (b & 0x7f) + { + case 0x1d: kbd_ctrl = !(b & 0x80); break; + case 0x38: kbd_alt = !(b & 0x80); break; + } + kq_put(cur, b); + } + if ((st & 0x21) == 0x21) /* a mouse byte came in: not now */ + { + kbc_ready(); + outb(0x64, 0xae); + return 0; + } + kbc_ready(); + outb(0x64, 0xd2); + kbc_ready(); + outb(0x60, sc); + for (i = 0; i < 20000 && !(inb(0x64) & 1); i++) + ; + kbc_planted = 1; + return 1; +} + +static void kbc_unplant(void) +{ + if (!kbc_planted) + return; + kbc_planted = 0; + if ((inb(0x64) & 0x21) == 0x01) + inb(0x60); /* not read by the handler: taken back */ + kbc_ready(); + outb(0x64, 0xae); +} + +/* Give the running session its next queued keystroke: a keyboard + interrupt of its own (in protected mode - a DPMI client - through the + client's IRQ1 path), with the scancode at port 60h. One at a time, as + with the interrupt controller: not before the handler of the one before + has returned (kbd_busy; a handler that never returns loses that claim + after half a second). */ +static void kbd_inject(struct frame *f) +{ + struct session *s = &ses[cur]; + int pm = !(f->eflags & EFL_VM); + + if (s->kbd_busy && tnow() - s->kbd_since > 9) + { + s->kbd_busy = 0; + kbc_unplant(); + } + if (vm_hold || s->kq_head == s->kq_tail || s->kbd_busy || latch_ok() || pic_isr()) + return; + if (pm ? !(f->eflags & EFL_IF) : !vm1.vif) + return; + if (dpmi_irq_hooked(1) && !kbc_plant(s->kq[s->kq_head])) + return; /* later */ + latch = s->kq[s->kq_head]; + s->kq_head = (s->kq_head + 1) % KQ_SIZE; + latch_valid = 1; + latch_tick = tnow(); + s->kbd_busy = 1; + s->kbd_since = tnow(); + if (pm) + dpmi_irq(f, 1); /* does not return */ + if (dpmi_irq_v86(f, 1)) /* a client's own handler */ + return; + v86_reflect_bp(f, 0x09, BP_KBD); /* the monitor hears of its return */ +} + +void vm_kbd_done(void) +{ + ses[cur].kbd_busy = 0; + latch_valid = 0; /* read or not: that keystroke is done */ + kbc_unplant(); +} + +void vm_kbd_next(struct frame *f) +{ + kbd_inject(f); +} + +static struct frame next_frame; + + +static void __attribute__((noreturn)) switch_to(struct frame *f, int n, int save) +{ + struct session *a = &ses[cur], *b = &ses[n]; + uint32_t missed; + + if (save) + { + memcpy(&a->f, f, sizeof(*f)); + a->vif = vm1.vif; + a->vflags = vm1.vflags; + a->crit = crit; + a->tick_mark = tnow(); + inst_copy(a, 1); + } + if (vm_trace) + kprintf("vm: %d -> %d (%s)\n", cur, n, (b->f.eflags & EFL_VM) ? "v86" : "pm"); + if (flat) + { + uint32_t p; + for (p = first_private; p < end_private && save; p++) + memcpy(kmap(2, a->pages[p]), (void *)(p << 12), 4096); + for (p = first_private; p < end_private; p++) + memcpy((void *)(p << 12), kmap(2, b->pages[p]), 4096); + } + dpmi_session_switch(save ? cur : -1, n); + cur = n; + map_session(n); + inst_copy(b, 0); + vm1.vif = b->vif; + vm1.vflags = b->vflags; + crit = b->crit; + want = -1; + slice_start = tnow(); + + /* The timer ticks this session missed while it was not running: it gets + them now, one timer interrupt after the other (vm_owed_tick) - its + clock, and what the programs in it hang on the timer, keep time. At + most two seconds' worth. */ + missed = tnow() - b->tick_mark; + if (missed > 1) + b->owed += missed - 1; + if (b->owed > 36) + b->owed = 36; + + /* not into *f: a trap frame from protected mode is 16 bytes shorter + than struct frame (no V86 segment registers), at the top of the stack */ + f = &next_frame; + memcpy(f, &b->f, sizeof(*f)); + if (f->eflags & EFL_VM) + v86_deliver(f); + else + dpmi_take_pending(f); /* a DPMI client: IRQs in PM */ + kbd_inject(f); + enter_frame(f); +} + +/* called at points where a pending switch may be done (STI, IRET, ...) */ +void vm_poll(struct frame *f) +{ + if (want >= 0 && want != cur && ses[want].used && switchable(f, 0)) + switch_to(f, want, 1); + kbd_inject(f); +} + +/* timer interrupt (IRQ0 pending, not yet delivered) */ +void vm_tick(struct frame *f) +{ + ticks++; + if (nsessions < 2) + return; + if (want == cur || (want >= 0 && !ses[want].used)) + want = -1; /* nothing to switch to */ + if (tnow() - slice_start >= SLICE_TICKS && want < 0) + { + want = next_session(); + idle_streak = 0; /* this one had work for all of its time slice */ + } + if (want >= 0 && want != cur && ses[want].used && switchable(f, 1)) + { + /* this timer interrupt goes to the next session: the one that leaves + gets it later (it is back within the same tick when the others are + idle, and would never see a timer interrupt while it has work) */ + if (ses[cur].owed < 36) + ses[cur].owed++; + switch_to(f, want, 1); + } +} + +/* the running session gives up the CPU (idle, HLT) */ +void vm_yield(struct frame *f) +{ + if (nsessions < 2) + return; + /* Round the sessions as ever. But when all have given up the CPU in + turn, none of them between two interrupts having run its time slice + out, nobody has work: the CPU rests until the next interrupt before + the next round (on DOS boots every switch copies the sessions' memory, + and the machine did little else). */ + if (++idle_streak >= (uint32_t)nsessions && !vm_hold && (f->eflags & EFL_VM) && vm1.vif && !vm1.pending && + !vm_key_pending() && want < 0) + { + uint16_t at = (uint16_t)f->eip, cs = (uint16_t)f->cs; + idle_streak = 0; + __asm__ volatile("sti; hlt; cli" ::: "memory"); + v86_deliver(f); /* what woke the CPU */ + if ((uint16_t)f->eip != at || (uint16_t)f->cs != cs) + return; /* its handler runs first */ + } + if (want < 0) + want = next_session(); + vm_poll(f); +} + +/* ---------------------------------------------------------------- */ +/* focus, keyboard */ + +static void set_focus(int n) +{ + int old = focus, i; + uint8_t *b; + uint16_t pos; + + if (n == focus || n < 0 || n >= MAX_SESSIONS || !ses[n].used) + return; + for (i = 0; i < VRAM_PAGES; i++) + { + phys_copy(ses[old].vram[i], vram_phys[i], 4096); + phys_copy(vram_phys[i], ses[n].vram[i], 4096); + } + focus = n; + map_session(cur); + + /* the hotkey's Ctrl/Alt presses went to the old session: release them */ + b = bda(old); + b[0x17] &= ~0x0c; + b[0x18] &= ~0x03; + /* cursor of the new session (page 0) */ + b = bda(n); + pos = b[0x51] * 80 + b[0x50]; + outb(0x3d4, 0x0e); + outb(0x3d5, pos >> 8); + outb(0x3d4, 0x0f); + outb(0x3d5, pos & 0xff); + if (n != cur) + want = n; /* show it running soon */ + kprintf("vm: focus session %d\n", n); +} + +/* IRQ1: the monitor takes the scancode from the keyboard controller + (hotkeys are its own) and gives it to the session on the display as a + keyboard interrupt of its own, with the scancode at port 60h and the + controller's status saying so (kbd_inject, v86.c io_in) - the same way + for the running session and for another one, and as for USB keyboards. + inject: f is the session's frame (else the monitor's own, waiting for + the session). Returns 1: the interrupt is dealt with (f may now be in + the session's handler). */ +int vm_kbd(struct frame *f, int inject) +{ + uint8_t sc; + + if (!registered) + return 0; + if (kbc_planted || (inb(0x64) & 0x21) != 0x01) + { + /* the planted scancode's interrupt, or nothing of the keyboard's is + there: taken already (kbc_plant) */ + outb(0x20, 0x61); + vm1.pending &= ~2u; + return 1; + } + sc = inb(0x60); + outb(0x20, 0x61); /* EOI IRQ1 ourselves */ + vm1.pending &= ~2u; + switch (sc & 0x7f) + { + case 0x1d: kbd_ctrl = !(sc & 0x80); break; + case 0x38: kbd_alt = !(sc & 0x80); break; + } + if (kbd_ctrl && kbd_alt && sc >= 0x3b && sc <= 0x3e) /* F1..F4 */ + { + set_focus(sc - 0x3b); + return 1; + } + if (kbd_ctrl && kbd_alt && sc == 0x58) /* F12: the sessions' state to the log */ + { + nic_debug(); + vm_debug(); + return 1; + } + kq_put(focus, sc); + if (focus != cur && nsessions > 1) + want = focus; + else if (inject) + kbd_inject(f); /* now if it can; else at the next chance */ + return 1; +} + +/* a keystroke from a keyboard other than the PS/2 controller (USB): + hotkeys as on IRQ1, otherwise queued for the focused session, which + gets it as a virtual IRQ1 with the scancode at port 60h */ +void vm_key(uint8_t sc) +{ + struct session *s = &ses[focus]; + int next = (s->kq_tail + 1) % KQ_SIZE; + + switch (sc & 0x7f) + { + case 0x1d: kbd_ctrl = !(sc & 0x80); break; + case 0x38: kbd_alt = !(sc & 0x80); break; + } + if (registered && kbd_ctrl && kbd_alt && sc >= 0x3b && sc <= 0x3e) + { + set_focus(sc - 0x3b); + return; + } + if (next != s->kq_head) + { + s->kq[s->kq_tail] = sc; + s->kq_tail = next; + } + else + kprintf("kbd: session %d does not take its keystrokes, scancode %02x dropped\n", focus, sc); + if (focus != cur && nsessions > 1) + want = focus; +} + +/* scancodes waiting for the running session */ +int vm_key_pending(void) +{ + return ses[cur].kq_head != ses[cur].kq_tail; +} + +/* does the monitor take the scancodes from the controller itself? */ +int vm_kbd_owned(void) +{ + return registered; +} + +int vm_port60_waiting(void) +{ + return latch_ok(); +} + +/* port 60h read by a session: replay the latched scancode once */ +int vm_port60(uint8_t *v) +{ + if (latch_ok()) + { + *v = latch; + latch_valid = 0; + last_scancode = latch; + return 1; + } + /* No new scancode: as with the controller itself, port 60h still reads + the last one - keyboard handlers of games read it more than once - + unless the controller has a byte to give: the mouse's, or the + keyboard's answer to a command the BIOS sent it. */ + if (registered && !(inb(0x64) & 1)) + { + *v = last_scancode; + return 1; + } + return 0; +} + +/* ---------------------------------------------------------------- */ +/* session lifetime */ + +static int alloc_session_pages(struct session *s) +{ + uint32_t p, n; + + for (p = first_private; p < end_private; p++) + if (!(s->pages[p] = page_alloc())) + return 0; + for (p = 0; p < VRAM_PAGES; p++) + if (!(s->vram[p] = page_alloc())) + return 0; + for (n = 0; n < (inst_size + 4095) / 4096; n++) + { + p = page_alloc(); + if (!p || !map_page(INST_BASE + (uint32_t)(s - ses) * 0x100000 + n * 4096, p, 3)) + return 0; + } + s->inst = INST_BASE + (uint32_t)(s - ses) * 0x100000; + return 1; +} + +static void free_session_pages(struct session *s) +{ + uint32_t p, n; + + for (p = first_private; p < end_private; p++) + if (s->pages[p]) + page_free(s->pages[p]); + for (p = 0; p < VRAM_PAGES; p++) + if (s->vram[p]) + page_free(s->vram[p]); + for (n = 0; n < (inst_size + 4095) / 4096; n++) + { + uint32_t phys = unmap_page(s->inst + n * 4096); + if (phys) + page_free(phys); + } + memset(s, 0, sizeof(*s)); +} + +/* INT 2Fh AX=DE02h: fork the running session. + Parent: AX = new session number; child: AX = 0, BX = its number. */ +static void vm_fork(struct frame *f) +{ + struct session *s; + uint32_t p; + int n; + + for (n = 0; n < MAX_SESSIONS && ses[n].used; n++) + ; + if (!registered || n == MAX_SESSIONS || dpmi_owner() == cur) + goto fail; + s = &ses[n]; + memset(s, 0, sizeof(*s)); + if (!alloc_session_pages(s)) + { + free_session_pages(s); + goto fail; + } + /* private memory and screen: copies of the current session's */ + for (p = first_private; p < end_private; p++) + phys_copy(s->pages[p], !flat && ses[cur].pages[p] ? ses[cur].pages[p] : p << 12, 4096); + for (p = 0; p < VRAM_PAGES; p++) + memcpy(kmap(2, s->vram[p]), (void *)(VRAM + p * 4096), 4096); + inst_copy(s, 1); + memcpy(&s->f, f, sizeof(*f)); + s->f.eflags &= ~EFL_CF; + *(uint16_t *)&s->f.eax = 0; + *(uint16_t *)&s->f.ebx = (uint16_t)n; + s->vif = vm1.vif; + s->vflags = vm1.vflags; + s->crit = 0; + s->tick_mark = tnow(); + s->used = 1; + nsessions++; + kprintf("vm: session %d started (%u sessions)\n", n, nsessions); + AX(f) = (uint16_t)n; + f->eflags &= ~EFL_CF; + return; +fail: + AX(f) = 0xffff; + f->eflags |= EFL_CF; +} + +/* INT 2Fh AX=DE03h: end the running session (not session 0) */ +static void vm_end(struct frame *f) +{ + int n = cur; + + if (n == 0) + { + f->eflags |= EFL_CF; + return; + } + if (focus == n) + { + int i; + for (i = 0; i < VRAM_PAGES; i++) + phys_copy(vram_phys[i], ses[0].vram[i], 4096); + focus = 0; + } + free_session_pages(&ses[n]); + nsessions--; + kprintf("vm: session %d ended (%u sessions)\n", n, nsessions); + switch_to(f, 0, 0); +} + +/* ---------------------------------------------------------------- */ +/* remote consoles: screens, keys and jobs of other sessions */ + +/* INT 2Fh AX=DE08h: BL = session, ES:DI buffer, CX its size. + Copies the visible text page (cells of char + attribute). + Returns AH:AL = cursor row:column, BX = cursor shape, CL = video mode, + CH = columns, DL = rows, DH = active page, SI = bytes copied. */ +static void api_screen(struct frame *f) +{ + int n = BL(f), cols, rows; + uint32_t start, len, done = 0, room = CX(f); + uint8_t *b, *dst; + struct session *s; + + if (n < 0 || n >= MAX_SESSIONS || !ses[n].used) + { + f->eflags |= EFL_CF; + return; + } + s = &ses[n]; + b = bda(n); + cols = b[0x4a] ? b[0x4a] : 80; + rows = b[0x84] ? b[0x84] + 1 : 25; + start = *(uint16_t *)(b + 0x4e); + len = (uint32_t)cols * rows * 2; + if (len > room) + len = room; + if (start + len > VRAM_PAGES * 4096u) + len = start < VRAM_PAGES * 4096u ? VRAM_PAGES * 4096u - start : 0; + dst = rm_ptr((uint16_t)f->es, DI(f)); + while (done < len) + { + uint32_t off = start + done, p = off >> 12, chunk = 4096 - (off & 4095); + uint32_t phys = n == focus ? vram_phys[p] : s->vram[p]; + if (chunk > len - done) + chunk = len - done; + memcpy(dst + done, (uint8_t *)kmap(2, phys) + (off & 4095), chunk); + done += chunk; + } + AX(f) = (uint16_t)(b[0x50 + b[0x62] * 2 + 1] << 8 | b[0x50 + b[0x62] * 2]); + BX(f) = *(uint16_t *)(b + 0x60); + *(uint8_t *)&f->ecx = b[0x49]; + *((uint8_t *)&f->ecx + 1) = (uint8_t)cols; + *(uint8_t *)&f->edx = (uint8_t)rows; + *((uint8_t *)&f->edx + 1) = b[0x62]; + SI(f) = (uint16_t)done; + f->eflags &= ~EFL_CF; +} + +/* INT 2Fh AX=DE09h: BL = session, DS:SI keys (words: scan << 8 | ASCII), + CX count -> into its BIOS keyboard buffer; CX = keys taken */ +static void api_keys(struct frame *f) +{ + int n = BL(f), i; + uint8_t *b; + uint16_t *keys, start, end; + + if (n < 0 || n >= MAX_SESSIONS || !ses[n].used) + { + f->eflags |= EFL_CF; + return; + } + b = bda(n); + keys = rm_ptr((uint16_t)f->ds, SI(f)); + start = *(uint16_t *)(b + 0x80); + end = *(uint16_t *)(b + 0x82); + if (!start || end <= start) + { + start = 0x1e; + end = 0x3e; + } + for (i = 0; i < CX(f); i++) + { + uint16_t tail = *(uint16_t *)(b + 0x1c), next = tail + 2; + if (next >= end) + next = start; + if (next == *(uint16_t *)(b + 0x1a)) + break; /* full */ + *(uint16_t *)(b + tail) = keys[i]; + *(uint16_t *)(b + 0x1c) = next; + } + CX(f) = (uint16_t)i; + if (i && n != cur) + want = n; /* let it see them soon */ + f->eflags &= ~EFL_CF; +} + +/* INT 2Fh AX=DE0Ah (a job slot asks for work): ES:DI 128 byte buffer. + CF if there is none; else the command (ASCIZ, empty: interactive + shell) and AX = flags. */ +static void api_job_get(struct frame *f) +{ + struct session *s = &ses[cur]; + + s->slot = 1; + if (s->job != JOB_ASSIGNED) + { + f->eflags |= EFL_CF; + return; + } + memcpy(rm_ptr((uint16_t)f->es, DI(f)), s->cmd, sizeof(s->cmd)); + s->job = JOB_RUNNING; + kprintf("vm: session %d runs job \"%s\"\n", cur, s->cmd); + AX(f) = s->job_flags; + f->eflags &= ~EFL_CF; +} + +/* INT 2Fh AX=DE0Bh (a job slot is done): BX = exit code */ +static void api_job_done(struct frame *f) +{ + struct session *s = &ses[cur]; + + if (s->job == JOB_RUNNING) + { + s->job = JOB_DONE; + s->job_code = BX(f); + kprintf("vm: session %d job done, exit code %d\n", cur, BX(f)); + } + f->eflags &= ~EFL_CF; +} + +/* INT 2Fh AX=DE0Ch: start a job in a free slot: DS:SI command (ASCIZ, + empty: interactive shell), DX flags. AX = session, CF if none free. */ +static void api_job_start(struct frame *f) +{ + const char *cmd = rm_ptr((uint16_t)f->ds, SI(f)); + int n; + + for (n = 1; n < MAX_SESSIONS; n++) + if (ses[n].used && ses[n].slot && ses[n].job == JOB_NONE) + { + struct session *s = &ses[n]; + int i; + for (i = 0; i < (int)sizeof(s->cmd) - 1 && cmd[i]; i++) + s->cmd[i] = cmd[i]; + s->cmd[i] = 0; + s->job_flags = DX(f); + s->job_code = 0; + s->job = JOB_ASSIGNED; + want = n; + AX(f) = (uint16_t)n; + f->eflags &= ~EFL_CF; + return; + } + f->eflags |= EFL_CF; +} + +/* INT 2Fh AX=DE0Dh: BL = session -> AX = job state (0 none, 1 assigned, + 2 running, 3 done), BX = exit code. Reading "done" frees the slot; + AX = FFFFh if the session is not a job slot. */ +static void api_job_state(struct frame *f) +{ + int n = BL(f); + struct session *s; + + if (n < 0 || n >= MAX_SESSIONS || !ses[n].used || !ses[n].slot) + { + AX(f) = 0xffff; + f->eflags |= EFL_CF; + return; + } + s = &ses[n]; + AX(f) = (uint16_t)s->job; + BX(f) = s->job_code; + if (s->job == JOB_DONE) + s->job = JOB_NONE; + f->eflags &= ~EFL_CF; +} + +/* INT 2Fh AH=DEh, AL=02h..0Dh; returns 1 if handled */ +int vm_api(struct frame *f) +{ + switch (AL(f)) + { + case 0x02: + vm_fork(f); + return 1; + case 0x03: + vm_end(f); + return 1; + case 0x04: + if (vm_register(f)) + { + int i; + /* session 0 keeps its identity memory but needs shadow video + pages and an instance buffer */ + struct session *s = &ses[0]; + for (i = 0; i < VRAM_PAGES; i++) + s->vram[i] = page_alloc(); + for (i = 0; i < (int)((inst_size + 4095) / 4096); i++) + map_page(INST_BASE + i * 4096, page_alloc(), 3); + s->inst = INST_BASE; + f->eflags &= ~EFL_CF; + } + else + f->eflags |= EFL_CF; + return 1; + case 0x05: /* set focus: BL = session */ + set_focus(BL(f)); + AX(f) = (uint16_t)focus; + return 1; + case 0x07: /* install the virtual BIOS mouse driver */ + AX(f) = (uint16_t)bios_mouse_install(); + return 1; + case 0x08: api_screen(f); return 1; + case 0x09: api_keys(f); return 1; + case 0x0a: api_job_get(f); return 1; + case 0x0b: api_job_done(f); return 1; + case 0x0c: api_job_start(f); return 1; + case 0x0d: api_job_state(f); return 1; + case 0x06: /* AX = running, BX = focus, CX = count, + DX = 1 if sessions are set up */ + DX(f) = (uint16_t)registered; + AX(f) = (uint16_t)cur; + BX(f) = (uint16_t)focus; + CX(f) = (uint16_t)nsessions; + return 1; + } + return 0; +} + +/* INT 2Ah: DOS critical sections */ +void vm_crit(struct frame *f) +{ + switch (AH(f)) + { + case 0x80: crit++; break; + case 0x81: if (crit) crit--; break; + case 0x82: crit = 0; break; + } +} diff --git a/mdvmm/core/xhci.c b/mdvmm/core/xhci.c new file mode 100644 index 00000000..e1a46e2f --- /dev/null +++ b/mdvmm/core/xhci.c @@ -0,0 +1,575 @@ +/* MDVMM core - xHCI (USB 3) host controller driver for USB keyboards + * + * Takes each xHCI controller from the firmware (legacy support handoff), + * resets it and sets up the command ring, one event ring and the device + * context array. Every device on a root port is addressed; up to two HID + * boot interfaces of each (keyboard, mouse) are configured and get a ring + * of interrupt IN transfers. Reports go to usbkbd.c and mouse.c. + * + * No interrupts: the event ring is polled on every timer tick and from + * INT 16h. Not yet: devices behind hubs, hotplug after boot, keyboard + * LEDs. All rings and contexts are pool pages (below 4GB). + */ +#include "core.h" + +#define MAX_HC 4 +#define MAX_KBD 8 /* HID interfaces, all devices */ +#define MAX_SLOTS 16 +#define NBUF 8 /* queued report transfers */ +#define MAX_IF 2 /* HID interfaces used per device */ + +/* capability registers */ +#define CAP_LENGTH 0x00 +#define CAP_HCS1 0x04 +#define CAP_HCS2 0x08 +#define CAP_HCC1 0x10 +#define CAP_DBOFF 0x14 +#define CAP_RTSOFF 0x18 +/* operational registers */ +#define OP_USBCMD 0x00 +#define OP_USBSTS 0x04 +#define OP_CRCR 0x18 +#define OP_DCBAAP 0x30 +#define OP_CONFIG 0x38 +#define OP_PORTSC(p) (0x400 + ((p) - 1) * 0x10) + +#define CMD_RS 0x1 +#define CMD_HCRST 0x2 +#define STS_HCH 0x1 +#define STS_CNR 0x800 + +#define PORT_CCS (1u << 0) +#define PORT_PED (1u << 1) +#define PORT_PR (1u << 4) +#define PORT_PP (1u << 9) +#define PORT_PRC (1u << 21) +#define PORT_KEEP (PORT_PP | 3u << 14 | 7u << 25) /* safe to write back */ + +/* TRB types */ +#define TRB_NORMAL 1 +#define TRB_SETUP 2 +#define TRB_DATA 3 +#define TRB_STATUS 4 +#define TRB_LINK 6 +#define TRB_ENABLE_SLOT 9 +#define TRB_ADDRESS 11 +#define TRB_CONFIG_EP 12 +#define TRB_EVALUATE 13 +#define EV_TRANSFER 32 +#define EV_COMMAND 33 + +#define CC_SUCCESS 1 +#define CC_SHORT 13 + +struct ring { + uint32_t phys; + uint32_t idx, cycle; +}; + +struct kbd { /* a HID boot interface */ + struct hc *hc; + int slot, dci; + int mouse; /* else a keyboard */ + struct ring ring; + uint32_t bufs; /* page: NBUF reports, 64 bytes apart */ + uint32_t next; /* buffer of the next completion */ +}; + +struct hc { + volatile uint8_t *cap, *op, *rt; + volatile uint32_t *db; + uint32_t csz; /* context size: 32 or 64 */ + uint32_t ports, slots; + uint32_t dcbaa; + struct ring cmd; + uint32_t ev_phys, ev_idx, ev_cycle; + /* last command completion / control transfer event */ + int cmd_done, cmd_cc, cmd_slot; + int xfer_done, xfer_cc; + uint32_t xfer_left; +}; + +static struct hc hcs[MAX_HC]; +static struct kbd kbds[MAX_KBD]; +static int nhc, nkbd; + +static uint32_t r32(volatile uint8_t *base, int r) +{ + return *(volatile uint32_t *)(base + r); +} + +static void w32(volatile uint8_t *base, int r, uint32_t v) +{ + *(volatile uint32_t *)(base + r) = v; +} + +static void w64(volatile uint8_t *base, int r, uint32_t v) +{ + w32(base, r, v); + w32(base, r + 4, 0); +} + +static int wait32(volatile uint8_t *base, int r, uint32_t mask, uint32_t val, uint32_t ms) +{ + uint32_t i; + for (i = 0; i < ms * 1000; i++) + { + if ((r32(base, r) & mask) == val) + return 1; + udelay(1); + } + return 0; +} + +/* ---------------------------------------------------------------- */ +/* rings: one page, 255 TRBs and a link TRB back to the start */ + +static int ring_init(struct ring *r) +{ + uint32_t *t; + + if (!(r->phys = page_alloc())) + return 0; + t = pool_ptr(r->phys); + t[255 * 4] = r->phys; + t[255 * 4 + 3] = TRB_LINK << 10 | 2; /* toggle cycle */ + r->idx = 0; + r->cycle = 1; + return 1; +} + +static void ring_push(struct ring *r, uint32_t d0, uint32_t d1, uint32_t d2, uint32_t d3) +{ + uint32_t *t = (uint32_t *)pool_ptr(r->phys) + r->idx * 4; + + t[0] = d0; + t[1] = d1; + t[2] = d2; + __asm__ volatile("" ::: "memory"); + t[3] = (d3 & ~1u) | r->cycle; /* hand it to the controller last */ + if (++r->idx == 255) + { + uint32_t *link = (uint32_t *)pool_ptr(r->phys) + 255 * 4; + link[3] = (link[3] & ~1u) | r->cycle; + r->cycle ^= 1; + r->idx = 0; + } +} + +/* ---------------------------------------------------------------- */ +/* events */ + +static void kbd_complete(struct kbd *k, uint32_t cc) +{ + uint32_t buf = k->bufs + (k->next % NBUF) * 64; + + if (cc == CC_SUCCESS || cc == CC_SHORT) + { + const uint8_t *r = pool_ptr(buf); + if (k->mouse) + mouse_input(r[0] & 7, (int8_t)r[1], (int8_t)r[2]); + else + usbkbd_report(r); + } + /* give the buffer back */ + ring_push(&k->ring, buf, 0, 8, TRB_NORMAL << 10 | 1 << 5 | 1 << 2); /* IOC ISP */ + k->next++; + k->hc->db[k->slot] = (uint32_t)k->dci; +} + +/* handle every pending event; returns the number handled */ +static int events(struct hc *h) +{ + int n = 0; + + for (;;) + { + uint32_t *e = (uint32_t *)pool_ptr(h->ev_phys) + h->ev_idx * 4; + uint32_t type, cc, slot, ep; + int i; + + if ((e[3] & 1) != h->ev_cycle) + break; + type = (e[3] >> 10) & 0x3f; + cc = e[2] >> 24; + slot = e[3] >> 24; + ep = (e[3] >> 16) & 0x1f; + if (type == EV_COMMAND) + { + h->cmd_done = 1; + h->cmd_cc = (int)cc; + h->cmd_slot = (int)slot; + } + else if (type == EV_TRANSFER) + { + for (i = 0; i < nkbd; i++) + if (kbds[i].hc == h && kbds[i].slot == (int)slot && kbds[i].dci == (int)ep) + break; + if (i < nkbd) + kbd_complete(&kbds[i], cc); + else if (ep == 1) + { + h->xfer_done = 1; + h->xfer_cc = (int)cc; + h->xfer_left = e[2] & 0xffffff; + } + } + if (++h->ev_idx == 256) + { + h->ev_idx = 0; + h->ev_cycle ^= 1; + } + w64(h->rt, 0x38, (h->ev_phys + h->ev_idx * 16) | 8); /* ERDP, clear EHB */ + n++; + } + return n; +} + +void xhci_poll(void) +{ + int i; + for (i = 0; i < nhc; i++) + events(&hcs[i]); +} + +static int command(struct hc *h, uint32_t d0, uint32_t d3) +{ + uint32_t i; + + h->cmd_done = 0; + ring_push(&h->cmd, d0, 0, 0, d3); + h->db[0] = 0; + for (i = 0; i < 500000 && !h->cmd_done; i++) /* 500 ms */ + { + events(h); + if (!h->cmd_done) + udelay(1); + } + return h->cmd_done ? h->cmd_cc : -1; +} + +/* control transfer on EP0 of slot; data (if any) in the page buf */ +static int control(struct hc *h, struct ring *ep0, int slot, uint8_t type, uint8_t req, + uint16_t value, uint16_t index, uint16_t len, uint32_t buf) +{ + int in = (type & 0x80) != 0; + uint32_t i, trt = len ? (in ? 3 : 2) : 0; + + h->xfer_done = 0; + ring_push(ep0, (uint32_t)type | (uint32_t)req << 8 | (uint32_t)value << 16, + (uint32_t)index | (uint32_t)len << 16, 8, TRB_SETUP << 10 | 1 << 6 | trt << 16); + if (len) + ring_push(ep0, buf, 0, len, TRB_DATA << 10 | (in ? 1u << 16 : 0)); + ring_push(ep0, 0, 0, 0, TRB_STATUS << 10 | 1 << 5 | (len && in ? 0 : 1u << 16)); + h->db[slot] = 1; + for (i = 0; i < 500000 && !h->xfer_done; i++) + { + events(h); + if (!h->xfer_done) + udelay(1); + } + if (!h->xfer_done) + return -1; + return h->xfer_cc == CC_SUCCESS || h->xfer_cc == CC_SHORT ? 0 : h->xfer_cc; +} + +/* ---------------------------------------------------------------- */ +/* devices */ + +static uint32_t *ctx(uint32_t page, struct hc *h, int n) +{ + return (uint32_t *)((uint8_t *)pool_ptr(page) + n * h->csz); +} + +/* xHCI interval (2^n x 125 us) from bInterval */ +static uint32_t ep_interval(int speed, uint8_t binterval) +{ + uint32_t n = 3, frames = binterval ? binterval : 1; + + if (speed >= 3) /* high/super speed: 2^(b-1) */ + return binterval >= 1 && binterval <= 16 ? binterval - 1u : 3; + while (n < 10 && (1u << (n + 1)) <= frames * 8) + n++; + return n; /* full/low speed: frames */ +} + +static void port_device(struct hc *h, uint32_t port) +{ + uint32_t ps = r32(h->op, OP_PORTSC(port)), speed, mps, in, out, buf, cfgval; + struct ring ep0; + struct kbd *k; + uint8_t *b; + uint32_t *c; + struct { int ifnum, mouse, ep, mps, interval; } ifs[MAX_IF]; + int slot, cc, off, total, nif = 0, cur = -1, i, n, maxdci; + + if (!(ps & PORT_CCS)) + return; + if (!(ps & PORT_PED)) /* USB 2 ports need a reset */ + { + w32(h->op, OP_PORTSC(port), (ps & PORT_KEEP) | PORT_PR); + if (!wait32(h->op, OP_PORTSC(port), PORT_PRC, PORT_PRC, 500)) + return; + ps = r32(h->op, OP_PORTSC(port)); + w32(h->op, OP_PORTSC(port), (ps & PORT_KEEP) | PORT_PRC); + udelay(20000); /* reset recovery */ + ps = r32(h->op, OP_PORTSC(port)); + if (!(ps & PORT_PED)) + return; + } + speed = (ps >> 10) & 0xf; + mps = speed == 4 ? 512 : speed == 3 ? 64 : 8; + + cc = command(h, 0, TRB_ENABLE_SLOT << 10); + slot = h->cmd_slot; + if (cc != CC_SUCCESS || slot <= 0 || slot > (int)h->slots) + return; + in = page_alloc(); + out = page_alloc(); + buf = page_alloc(); + if (!in || !out || !buf || !ring_init(&ep0)) + return; + ((uint32_t *)pool_ptr(h->dcbaa))[slot * 2] = out; + + /* address the device: slot context and EP0 */ + c = ctx(in, h, 0); + c[1] = 3; /* add slot, EP0 */ + c = ctx(in, h, 1); + c[0] = speed << 20 | 1u << 27; + c[1] = port << 16; + c = ctx(in, h, 2); + c[1] = 3u << 1 | 4u << 3 | mps << 16; /* CErr 3, control */ + c[2] = ep0.phys | 1; + c[4] = 8; + if ((cc = command(h, in, TRB_ADDRESS << 10 | (uint32_t)slot << 24)) != CC_SUCCESS) + { + kprintf("xhci: port %u: address device failed (%d)\n", port, cc); + return; + } + + /* device descriptor: max packet size of EP0 */ + b = pool_ptr(buf); + if (control(h, &ep0, slot, 0x80, 6, 0x0100, 0, 8, buf)) + return; + if (speed < 4 && b[7] && b[7] != mps) + { + mps = b[7]; + memset(pool_ptr(in), 0, 4096); + ctx(in, h, 0)[1] = 2; /* evaluate EP0 */ + c = ctx(in, h, 2); + c[1] = 3u << 1 | 4u << 3 | mps << 16; + c[2] = ep0.phys | ep0.cycle; + c[4] = 8; + command(h, in, TRB_EVALUATE << 10 | (uint32_t)slot << 24); + } + + /* configuration descriptor: HID boot interfaces (keyboard, mouse) */ + if (control(h, &ep0, slot, 0x80, 6, 0x0200, 0, 9, buf)) + return; + total = b[2] | b[3] << 8; + if (total > 4096) + total = 4096; + if (control(h, &ep0, slot, 0x80, 6, 0x0200, 0, (uint16_t)total, buf)) + return; + cfgval = b[5]; + for (off = 0; off + 2 <= total && b[off] >= 2; off += b[off]) + { + if (b[off + 1] == 4) /* interface */ + { + cur = -1; + if (nif < MAX_IF && b[off + 5] == 3 && b[off + 6] == 1 && + (b[off + 7] == 1 || b[off + 7] == 2)) + { + cur = nif++; + ifs[cur].ifnum = b[off + 2]; + ifs[cur].mouse = b[off + 7] == 2; + ifs[cur].ep = 0; + } + } + else if (b[off + 1] == 5 && cur >= 0 && !ifs[cur].ep && /* interrupt IN */ + (b[off + 2] & 0x80) && (b[off + 3] & 3) == 3) + { + ifs[cur].ep = b[off + 2]; + ifs[cur].mps = (b[off + 4] | b[off + 5] << 8) & 0x7ff; + ifs[cur].interval = b[off + 6]; + } + } + for (i = n = 0; i < nif; i++) /* keep those with an endpoint */ + if (ifs[i].ep) + ifs[n++] = ifs[i]; + nif = n; + if (!nif || nkbd + nif > MAX_KBD) + { + kprintf("xhci: port %u: no keyboard or mouse, ignored\n", port); + return; + } + + /* configure: boot protocol, report on change only */ + if (control(h, &ep0, slot, 0x00, 9, (uint16_t)cfgval, 0, 0, 0)) + return; + memset(pool_ptr(in), 0, 4096); + ctx(in, h, 0)[1] = 1; + maxdci = 0; + for (i = 0; i < nif; i++) + { + control(h, &ep0, slot, 0x21, 0x0b, 0, (uint16_t)ifs[i].ifnum, 0, 0); /* SET_PROTOCOL boot */ + control(h, &ep0, slot, 0x21, 0x0a, 0, (uint16_t)ifs[i].ifnum, 0, 0); /* SET_IDLE 0 */ + k = &kbds[nkbd + i]; + memset(k, 0, sizeof(*k)); + k->hc = h; + k->slot = slot; + k->mouse = ifs[i].mouse; + k->dci = (ifs[i].ep & 0xf) * 2 + 1; + if (!ring_init(&k->ring) || !(k->bufs = page_alloc())) + return; + if (k->dci > maxdci) + maxdci = k->dci; + ctx(in, h, 0)[1] |= 1u << k->dci; + c = ctx(in, h, k->dci + 1); + c[0] = ep_interval((int)speed, (uint8_t)ifs[i].interval) << 16; + c[1] = 3u << 1 | 7u << 3 | (uint32_t)ifs[i].mps << 16; /* CErr 3, interrupt IN */ + c[2] = k->ring.phys | 1; + c[4] = 8 | (uint32_t)ifs[i].mps << 16; + } + c = ctx(in, h, 1); + c[0] = speed << 20 | (uint32_t)maxdci << 27; + c[1] = port << 16; + if ((cc = command(h, in, TRB_CONFIG_EP << 10 | (uint32_t)slot << 24)) != CC_SUCCESS) + { + kprintf("xhci: port %u: configure endpoint failed (%d)\n", port, cc); + return; + } + for (i = 0; i < nif; i++) + { + k = &kbds[nkbd + i]; + for (off = 0; off < NBUF; off++) + ring_push(&k->ring, k->bufs + off * 64, 0, 8, TRB_NORMAL << 10 | 1 << 5 | 1 << 2); + h->db[slot] = (uint32_t)k->dci; + kprintf("xhci: port %u: %s (speed %u, slot %d)\n", port, k->mouse ? "mouse" : "keyboard", + speed, slot); + } + nkbd += nif; + page_free(in); + page_free(buf); +} + +/* ---------------------------------------------------------------- */ +/* controller */ + +static void handoff(volatile uint8_t *cap) +{ + uint32_t off = (r32(cap, CAP_HCC1) >> 16) * 4; + int guard; + + for (guard = 0; off && guard < 32; guard++) + { + uint32_t v = r32(cap, (int)off); + if ((v & 0xff) == 1) /* USB legacy support */ + { + w32(cap, (int)off, v | 1u << 24); /* OS owned */ + if (!wait32(cap, (int)off, 1u << 16, 0, 1000)) + kprintf("xhci: firmware does not release the controller\n"); + v = r32(cap, (int)off + 4); /* no SMIs, clear their status */ + w32(cap, (int)off + 4, (v & ~0xe01fu) | 0xe0000000u); + return; + } + if (!((v >> 8) & 0xff)) + return; + off += ((v >> 8) & 0xff) * 4; + } +} + +static void found(int bus, int dev, int fn) +{ + uint64_t bar = pci_bar(bus, dev, fn, 0x10); + volatile uint8_t *cap; + struct hc *h; + uint32_t hcs1, hcs2, need, sp, i, *erst, *dcbaa; + + if (!bar || nhc == MAX_HC) + return; + pci_enable(bus, dev, fn); + if (!(cap = mmio_map(bar, 0x1000))) + return; + hcs1 = r32(cap, CAP_HCS1); + need = r32(cap, CAP_DBOFF) + 4 * 256; + if (r32(cap, CAP_RTSOFF) + 0x40 > need) + need = r32(cap, CAP_RTSOFF) + 0x40; + if ((r32(cap, CAP_LENGTH) & 0xff) + OP_PORTSC((hcs1 >> 24) + 1) > need) + need = (r32(cap, CAP_LENGTH) & 0xff) + OP_PORTSC((hcs1 >> 24) + 1); + if (need > 0x1000 && !(cap = mmio_map(bar, need))) + return; + + h = &hcs[nhc]; + memset(h, 0, sizeof(*h)); + h->cap = cap; + h->op = cap + (r32(cap, CAP_LENGTH) & 0xff); + h->rt = cap + (r32(cap, CAP_RTSOFF) & ~0x1fu); + h->db = (volatile uint32_t *)(cap + (r32(cap, CAP_DBOFF) & ~3u)); + h->csz = r32(cap, CAP_HCC1) & 4 ? 64 : 32; + h->ports = hcs1 >> 24; + h->slots = (hcs1 & 0xff) < MAX_SLOTS ? hcs1 & 0xff : MAX_SLOTS; + kprintf("xhci: controller %02x:%02x.%x, version %x, %u ports\n", bus, dev, fn, + r32(cap, CAP_LENGTH) >> 16, h->ports); + + handoff(cap); + w32(h->op, OP_USBCMD, r32(h->op, OP_USBCMD) & ~CMD_RS); + if (!wait32(h->op, OP_USBSTS, STS_HCH, STS_HCH, 100)) + return; + w32(h->op, OP_USBCMD, CMD_HCRST); + if (!wait32(h->op, OP_USBCMD, CMD_HCRST, 0, 1000) || + !wait32(h->op, OP_USBSTS, STS_CNR, 0, 1000)) + { + kprintf("xhci: reset failed\n"); + return; + } + w32(h->op, OP_CONFIG, h->slots); + + /* device context array (+ scratchpad buffers), command and event ring */ + if (!(h->dcbaa = page_alloc()) || !ring_init(&h->cmd) || !(h->ev_phys = page_alloc())) + return; + dcbaa = pool_ptr(h->dcbaa); + hcs2 = r32(cap, CAP_HCS2); + sp = (hcs2 >> 27 & 0x1f) | (hcs2 >> 21 & 0x1f) << 5; + if (sp) + { + uint32_t arr = page_alloc(), *a; + if (!arr || sp > 512) + return; + a = pool_ptr(arr); + for (i = 0; i < sp; i++) + if (!(a[i * 2] = page_alloc())) + return; + dcbaa[0] = arr; + } + w64(h->op, OP_DCBAAP, h->dcbaa); + w64(h->op, OP_CRCR, h->cmd.phys | 1); + h->ev_cycle = 1; + erst = (uint32_t *)pool_ptr(h->dcbaa) + 512; /* upper half of that page */ + erst[0] = h->ev_phys; + erst[1] = 0; + erst[2] = 256; + w32(h->rt, 0x28, 1); /* ERSTSZ */ + w64(h->rt, 0x38, h->ev_phys); /* ERDP */ + w64(h->rt, 0x30, h->dcbaa + 2048); /* ERSTBA */ + w32(h->op, OP_USBCMD, CMD_RS); + if (!wait32(h->op, OP_USBSTS, STS_HCH, 0, 100)) + return; + nhc++; + + /* power the ports, let connections settle, then set up the devices */ + for (i = 1; i <= h->ports; i++) + { + uint32_t ps = r32(h->op, OP_PORTSC(i)); + if (!(ps & PORT_PP)) + w32(h->op, OP_PORTSC(i), (ps & PORT_KEEP) | PORT_PP); + } + udelay(200000); + for (i = 1; i <= h->ports; i++) + port_device(h, i); +} + +void xhci_init(void) +{ + pci_scan(0x0c0330, found); /* serial bus, USB, xHCI */ +} diff --git a/mdvmm/include/bootinfo.h b/mdvmm/include/bootinfo.h new file mode 100644 index 00000000..5cc9c046 --- /dev/null +++ b/mdvmm/include/bootinfo.h @@ -0,0 +1,67 @@ +/* MDVMM boot information, passed from a loader to the core. + * Must match bootinfo.inc. The DOS loader fills it in conventional + * memory; a future UEFI loader fills the same structure. */ +#ifndef MDVMM_BOOTINFO_H +#define MDVMM_BOOTINFO_H + +#include + +#define BOOTINFO_MAGIC 0x4D56444Du /* "MDVM" */ + +/* V86 breakpoints: HLT instructions at stub_seg:stub_bp + n */ +#define BP_DPMI_ENTRY 0 +#define BP_RM_RETURN 1 +#define BP_RAW_TO_PM 2 +#define BP_CALLBACK 3 /* 16 real mode callbacks */ +#define BP_INT13 19 /* a V86 INT 13h call returned */ +#define BP_KBD 20 /* a session's keyboard interrupt handler returned */ +#define BP_TICK 21 /* a session's handler of a timer tick it was owed returned */ +#define BP_COUNT 22 +#define BOOTINFO_VERSION 5 + +#define BOOT_DOS 0 /* started from DOS: real BIOS, DOS running */ +#define BOOT_UEFI 1 /* started from UEFI: no BIOS, core boots DOS */ + +#define BOOTF_DISK_WRITE 0x1 /* UEFI: native hard disks may be written */ +#define BOOTF_LOG_PAUSE 0x2 /* UEFI: keep the boot log on the screen for a while */ +#define BOOTF_NO_NET 0x4 /* UEFI: do not start the network card drivers */ +#define BOOTF_TRIAL 0x8 /* UEFI: a trial boot: restart unless it is confirmed */ +#define BOOTF_TRIAL_FAST 0x10 /* ... after two minutes, not ten (tests) */ + +#define FB_RGBX 0 /* GOP PixelRedGreenBlueReserved8BitPerColor */ +#define FB_BGRX 1 /* GOP PixelBlueGreenRedReserved8BitPerColor */ + +struct bootinfo { + uint32_t magic; + uint32_t version; + uint32_t pool_phys; /* 4K aligned physical base; core loaded here */ + uint32_t pool_size; /* bytes, multiple of 4K */ + uint32_t core_size; /* bytes of core image at pool_phys */ + uint32_t trampoline; /* linear address of the paging trampoline */ + uint32_t eflags; /* V86 resume state */ + uint16_t ip, cs, sp, ss, ds, es, fs, gs; + uint16_t psp; /* loader PSP segment */ + uint16_t stub_seg; /* segment of resident V86 stubs */ + uint16_t stub_bp; /* offset of V86 breakpoints (HLT bytes) */ + uint16_t stub_entry; /* offset of the DPMI mode switch entry */ + uint16_t stub_psp; /* offset of word: PSP saved by the entry */ + uint16_t stub_retf; /* offset of a RETF (no-op state save) */ + /* version 3 */ + uint32_t boot_type; /* BOOT_DOS / BOOT_UEFI */ + uint32_t fb_phys; /* UEFI: GOP framebuffer, 32 bpp */ + uint32_t fb_size; + uint32_t fb_width, fb_height; + uint32_t fb_pitch; /* pixels per scan line */ + uint32_t fb_format; /* FB_RGBX / FB_BGRX */ + uint32_t ramdisk_phys; /* UEFI: boot disk image (floppy) */ + uint32_t ramdisk_size; + uint32_t conv_kb; /* UEFI: usable conventional memory */ + uint32_t rsdp; /* UEFI: ACPI RSDP (0 = none) */ + /* version 4 */ + uint32_t xms_phys; /* UEFI: DOS extended memory (from 1MB on, */ + uint32_t xms_size; /* HMA first), physically contiguous */ + /* version 5 */ + uint32_t flags; /* BOOTF_* */ +} __attribute__((packed)); + +#endif diff --git a/mdvmm/include/bootinfo.inc b/mdvmm/include/bootinfo.inc new file mode 100644 index 00000000..1d6a47e1 --- /dev/null +++ b/mdvmm/include/bootinfo.inc @@ -0,0 +1,57 @@ +; MDVMM boot information - must match bootinfo.h +BOOTINFO_MAGIC equ 0x4D56444D +BOOTINFO_VERSION equ 5 +BOOT_DOS equ 0 +BOOT_UEFI equ 1 + +struc bootinfo + .magic resd 1 + .version resd 1 + .pool_phys resd 1 + .pool_size resd 1 + .core_size resd 1 + .trampoline resd 1 + .eflags resd 1 + .ip resw 1 + .cs resw 1 + .sp resw 1 + .ss resw 1 + .ds resw 1 + .es resw 1 + .fs resw 1 + .gs resw 1 + .psp resw 1 + .stub_seg resw 1 + .stub_bp resw 1 + .stub_entry resw 1 + .stub_psp resw 1 + .stub_retf resw 1 + .boot_type resd 1 + .fb_phys resd 1 + .fb_size resd 1 + .fb_width resd 1 + .fb_height resd 1 + .fb_pitch resd 1 + .fb_format resd 1 + .ramdisk_phys resd 1 + .ramdisk_size resd 1 + .conv_kb resd 1 + .rsdp resd 1 + .xms_phys resd 1 + .xms_size resd 1 + .flags resd 1 +endstruc + +; MDVMM INT 2Fh API (AH = MDVMM_MPX) +MDVMM_MPX equ 0xDE +MDVMM_SIGNATURE equ 0x4D44 ; "MD" returned in BX by AX=DE00h + +; V86 breakpoints (HLT at stub_bp + n) +BP_DPMI_ENTRY equ 0 +BP_RM_RETURN equ 1 +BP_RAW_TO_PM equ 2 +BP_CALLBACK equ 3 ; 16 real mode callbacks +BP_INT13 equ 19 ; a V86 INT 13h call returned +BP_KBD equ 20 ; a session's keyboard interrupt handler returned +BP_TICK equ 21 ; a session's handler of a timer tick it was owed returned +BP_COUNT equ 22 diff --git a/mdvmm/ipxe/build.sh b/mdvmm/ipxe/build.sh new file mode 100755 index 00000000..5f0a4488 --- /dev/null +++ b/mdvmm/ipxe/build.sh @@ -0,0 +1,54 @@ +#!/bin/bash +# Build the iPXE network drivers for the monitor: one relocatable object +# whose only global names are the ipxe_* functions of glue.c. +# +# Usage: mdvmm/ipxe/build.sh [debug-objects] +# debug-objects: e.g. "sky2" or "sky2,netdevice" - iPXE's debug messages +# of those source files go to the monitor's log + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +SRC=$(realpath "$1")/src +OUT=$(realpath -m "$2") +DEBUG=$3 +[ -f "$SRC/include/compiler.h" ] || { echo "no iPXE source tree at $1"; exit 1; } +W=$(mktemp -d) +trap 'rm -rf "$W"' EXIT +CC=i686-linux-gnu-gcc + +# the empty local configuration headers iPXE's makefile would create +mkdir -p "$W/overlay/config/local" +grep -rhoE "config/local/[a-z_0-9]+\.h" "$SRC/config" "$SRC/include" | sort -u | + while read -r f; do : > "$W/overlay/$f"; done + +CFLAGS="-m32 -march=i686 -Os -ffreestanding -fno-builtin -fno-pic -fno-pie + -fno-stack-protector -fno-asynchronous-unwind-tables -fno-unwind-tables + -fno-strict-aliasing -fshort-wchar -fcommon -mgeneral-regs-only + -mpreferred-stack-boundary=2 -w + -DARCH=i386 -DPLATFORM=mdvmm -DPLATFORM_mdvmm -DSECUREBOOT=0 -DNVALGRIND + -DASM_TCHAR=@ -DASM_TCHAR_OPS=@ -DPROFILING=0 -DASSERTING=0 -DNDEBUG + -I$HERE/overlay -I$W/overlay -I$SRC/arch/i386/include -I$SRC/arch/x86/include + -I$SRC/include -I$SRC -include $SRC/include/compiler.h" + +objs= +compile() { # compile dir file + local name o dbg= + name=$(basename "$2" .c | tr - _) + o="$W/$name.o" + case ",$DEBUG," in *",$name,"*) dbg="-Ddebug_$name=1" ;; esac + (cd "$1" && $CC $CFLAGS $dbg -DOBJECT="$name" -c "$2" -o "$o") + objs="$objs $o" +} +for f in $(grep -hv '^#' "$HERE/core.list" "$HERE/drivers.list"); do + compile "$SRC" "$f" +done +compile "$HERE" glue.c +# without iPXE's headers +$CC -m32 -Os -ffreestanding -fno-pic -fno-pie -c "$HERE/glue_data.c" -o "$W/glue_data.o" + +i686-linux-gnu-ld -m elf_i386 -r -T "$HERE/ipxe.lds" -o "$W/ipxe.o" $objs "$W/glue_data.o" +i686-linux-gnu-objcopy -G ipxe_init -G ipxe_get -G ipxe_send -G ipxe_recv -G ipxe_link \ + -G ipxe_debug -G ipxe_set_virt_offset "$W/ipxe.o" "$OUT" +und=$(i686-linux-gnu-nm -u "$OUT" | awk '{print $2}' | grep -v '^mdvmm_' || true) +if [ -n "$und" ]; then echo "iPXE drivers: unresolved:" $und; exit 1; fi +i686-linux-gnu-size "$OUT" diff --git a/mdvmm/ipxe/core.list b/mdvmm/ipxe/core.list new file mode 100644 index 00000000..55a0d8db --- /dev/null +++ b/mdvmm/ipxe/core.list @@ -0,0 +1,28 @@ +# parts of iPXE's core the drivers need (paths under iPXE's src/) +net/netdevice.c +net/ethernet.c +net/nullnet.c +core/iobuf.c +core/malloc.c +core/refcnt.c +core/list.c +core/interface.c +core/random.c +core/vsprintf.c +core/string.c +core/ctype.c +arch/x86/core/x86_string.c +arch/x86/core/pcidirect.c +drivers/bus/pci.c +drivers/bus/pciextra.c +drivers/bus/pcibackup.c +drivers/net/mii.c +drivers/nvs/nvs.c +net/iobpad.c +drivers/bitbash/bitbash.c +drivers/bitbash/spi_bit.c +drivers/nvs/threewire.c +drivers/nvs/spi.c +arch/x86/core/x86_io.c +drivers/bitbash/mii_bit.c +drivers/bus/virtio.c diff --git a/mdvmm/ipxe/drivers.list b/mdvmm/ipxe/drivers.list new file mode 100644 index 00000000..90eb405e --- /dev/null +++ b/mdvmm/ipxe/drivers.list @@ -0,0 +1,33 @@ +# iPXE network drivers built into the monitor (paths under iPXE's src/), +# one per line. +# Marvell Yukon-2 (88E80xx, Intel Macs and many notebooks) and Yukon +drivers/net/sky2.c +drivers/net/skge.c +# Intel gigabit (8254x "e1000", 8257x/8258x "e1000e", I210/I350 "igb") and +# 10/100 (8255x) +drivers/net/intel.c +drivers/net/eepro100.c +# Realtek 8139, 8169, 8111/8168 +drivers/net/realtek.c +# Broadcom BCM57xx "tg3" and BCM44xx +drivers/net/tg3/tg3.c +drivers/net/tg3/tg3_hw.c +drivers/net/tg3/tg3_phy.c +drivers/net/b44.c +# Nvidia nForce, Atheros L1E, JMicron, VIA, SiS 190/191, AMD PCnet, +# National Semiconductor, 3Com 3c90x, IC Plus, Myson, RDC +drivers/net/forcedeth.c +drivers/net/atl1e.c +drivers/net/jme.c +drivers/net/rhine.c +drivers/net/velocity.c +drivers/net/sis190.c +drivers/net/pcnet32.c +drivers/net/natsemi.c +drivers/net/3c90x.c +drivers/net/icplus.c +drivers/net/myson.c +drivers/net/rdc.c +# virtual machines: virtio, VMware +drivers/net/virtio-net.c +drivers/net/vmxnet3.c diff --git a/mdvmm/ipxe/glue.c b/mdvmm/ipxe/glue.c new file mode 100644 index 00000000..45f21c2e --- /dev/null +++ b/mdvmm/ipxe/glue.c @@ -0,0 +1,318 @@ +/* iPXE network drivers inside the MDVMM monitor: the glue + * + * iPXE (https://ipxe.org, GPL) has drivers for most PCI network cards, + * written for a polled, single-threaded environment like this monitor. + * build.sh compiles the drivers named in drivers.list and the few parts + * of iPXE's core they need (network device, I/O buffers, heap, PCI) with + * the "mdvmm" platform of overlay/, and this file: + * - what iPXE expects from a platform: mapping device memory, delays, + * debug output; stubs for subsystems that are not here (settings, + * timers) + * - what the monitor calls (ipxe_*, see core/ipxenic.c): probe the PCI + * network cards, send and receive Ethernet frames + * Everything else in the linked object is local to it (objcopy), so + * iPXE's names do not meet the monitor's. + * + * Memory: iPXE's 32-bit model is "physical = virtual + virt_offset". The + * monitor's pool, which holds iPXE's code, data and heap, is mapped at a + * fixed offset from its physical address, so that is exactly true. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* the monitor's side (core/ipxenic.c) */ +extern void mdvmm_log ( const char *text ); +extern void * mdvmm_ioremap ( unsigned long phys, unsigned long len ); +extern void mdvmm_udelay ( unsigned long usecs ); +extern unsigned long mdvmm_ms ( void ); + +#define MAX_DEVS 4 + +static struct net_device *devs[MAX_DEVS]; +static int ndevs; + +/* ---------------------------------------------------------------- */ +/* platform services for iPXE */ + +void * ioremap ( unsigned long bus_addr, size_t len ) { + return mdvmm_ioremap ( bus_addr, len ); +} + +void iounmap ( volatile const void *io __unused ) { + /* mappings stay */ +} + +void udelay ( unsigned long usecs ) { + mdvmm_udelay ( usecs ); +} + +void mdelay ( unsigned long msecs ) { + while ( msecs-- ) + mdvmm_udelay ( 1000 ); +} + +/* iPXE's clock: TICKS_PER_SEC (1024) ticks per second */ +unsigned long currticks ( void ) { + return ( mdvmm_ms() + ( mdvmm_ms() >> 6 ) ); +} + +int errno; + +/* debug and console output: whole lines to the monitor's log */ +static char line[200]; +static size_t line_len; + +int putchar ( int character ) { + if ( character == '\n' || line_len == sizeof ( line ) - 1 ) { + line[line_len] = 0; + mdvmm_log ( line ); + line_len = 0; + } + if ( character != '\n' && character != '\r' ) + line[line_len++] = ( char ) character; + return character; +} + +void dbg_printf ( const char *fmt, ... ) { + char buf[256]; + va_list args; + char *c; + + va_start ( args, fmt ); + vsnprintf ( buf, sizeof ( buf ), fmt, args ); + va_end ( args ); + for ( c = buf ; *c ; c++ ) + putchar ( *c ); +} + +void dbg_autocolourise ( unsigned long id __unused ) { +} + +void dbg_hex_dump_da ( unsigned long dispaddr __unused, + const void *data __unused, unsigned long len __unused ) { +} + +void dbg_md5_da ( unsigned long dispaddr __unused, const void *data __unused, + unsigned long len __unused ) { +} + +void dbg_pause ( void ) { +} + +void dbg_more ( void ) { +} + +/* not here: settings, retry timers, error statistics, the clock */ +struct settings_operations netdev_settings_operations; + +int register_settings ( struct settings *settings __unused, + struct settings *parent __unused, + const char *name __unused ) { + return 0; +} + +void unregister_settings ( struct settings *settings __unused ) { +} + +void clear_settings ( struct settings *settings __unused ) { +} + +void start_timer_fixed ( struct retry_timer *timer __unused, + unsigned long timeout __unused ) { +} + +void stop_timer ( struct retry_timer *timer __unused ) { +} + +void record_stat ( struct error_statistics *stats __unused, int rc __unused ) { +} + +/* options stored in a card's EEPROM: not used */ +void nvo_init ( struct nvo_block *nvo __unused, struct nvs_device *nvs __unused, + size_t address __unused, size_t len __unused, + int ( * resize ) ( struct nvo_block *nvo, size_t len ) __unused, + struct refcnt *refcnt __unused ) { +} + +int register_nvo ( struct nvo_block *nvo __unused, + struct settings *parent __unused ) { + return 0; +} + +void unregister_nvo ( struct nvo_block *nvo __unused ) { +} + +signed long time_offset; + +time_t time_now ( void ) { + return 0; +} + +/* ---------------------------------------------------------------- */ +/* for the monitor */ + +static struct device pci_root = { + .name = "PCI", + .siblings = LIST_HEAD_INIT ( pci_root.siblings ), + .children = LIST_HEAD_INIT ( pci_root.children ), +}; + +/** + * Find the PCI network cards that have a driver and start them + * + * @ret count Number of network devices + */ +int ipxe_init ( void ) { + struct pci_device *pci = NULL; + struct net_device *netdev; + uint32_t busdevfn = 0; + struct init_fn *init_fn; + char msg[160]; + int rc; + + /* iPXE's initialisation functions (the heap, ...) */ + for_each_table_entry ( init_fn, INIT_FNS ) + init_fn->initialise(); + + do { + if ( ! pci ) + pci = malloc ( sizeof ( *pci ) ); + if ( ! pci ) + break; + if ( pci_find_next ( pci, &busdevfn ) != 0 ) + break; + if ( ( pci->class >> 16 ) != 0x02 ) + continue; /* network controllers only */ + if ( pci_find_driver ( pci ) != 0 ) { + snprintf ( msg, sizeof ( msg ), "ipxe: " PCI_FMT + " network card %04x:%04x: no driver", + PCI_ARGS ( pci ), pci->vendor, pci->device ); + mdvmm_log ( msg ); + continue; + } + snprintf ( msg, sizeof ( msg ), "ipxe: " PCI_FMT " %04x:%04x: " + "driver for %s", PCI_ARGS ( pci ), pci->vendor, + pci->device, pci->id->name ); + mdvmm_log ( msg ); + pci->dev.parent = &pci_root; + list_add ( &pci->dev.siblings, &pci_root.children ); + if ( ( rc = pci_probe ( pci ) ) == 0 ) { + pci = NULL; + } else { + snprintf ( msg, sizeof ( msg ), "ipxe: the driver " + "could not start the card (error %08x)", + -rc ); + mdvmm_log ( msg ); + list_del ( &pci->dev.siblings ); + } + } while ( ++busdevfn ); + free ( pci ); + + for_each_netdev ( netdev ) { + if ( ndevs == MAX_DEVS ) + break; + if ( ( rc = netdev_open ( netdev ) ) != 0 ) { + snprintf ( msg, sizeof ( msg ), "ipxe: %s: cannot " + "open (error %08x)", netdev->name, -rc ); + mdvmm_log ( msg ); + continue; + } + devs[ndevs++] = netdev; + } + return ndevs; +} + +/** + * Describe a network device + * + * @v index Device number + * @v name Buffer for the driver's name (32 bytes) + * @v mac Buffer for the MAC address (6 bytes) + * @ret ok The device exists + */ +int ipxe_get ( int index, char *name, unsigned char *mac ) { + struct net_device *netdev; + + if ( index < 0 || index >= ndevs ) + return 0; + netdev = devs[index]; + snprintf ( name, 32, "%s (iPXE)", netdev->dev->driver_name ); + memcpy ( mac, netdev->ll_addr, ETH_ALEN ); + return 1; +} + +/** Send an Ethernet frame; 0 on success */ +int ipxe_send ( int index, const void *frame, int len ) { + struct net_device *netdev = devs[index]; + struct io_buffer *iobuf; + int rc; + + iobuf = alloc_iob ( len < ETH_ZLEN ? ETH_ZLEN : len ); + if ( ! iobuf ) + return -1; + memcpy ( iob_put ( iobuf, len ), frame, len ); + if ( len < ETH_ZLEN ) + memset ( iob_put ( iobuf, ETH_ZLEN - len ), 0, ETH_ZLEN - len ); + rc = netdev_tx ( netdev, iobuf ); /* takes the buffer */ + netdev_poll ( netdev ); + return ( rc ? -1 : 0 ); +} + +/** Receive the next frame; its length, 0 if there is none */ +int ipxe_recv ( int index, void *frame, int room ) { + struct net_device *netdev = devs[index]; + struct io_buffer *iobuf; + int len; + + netdev_poll ( netdev ); + iobuf = netdev_rx_dequeue ( netdev ); + if ( ! iobuf ) + return 0; + len = iob_len ( iobuf ); + if ( len <= room ) + memcpy ( frame, iobuf->data, len ); + else + len = 0; + free_iob ( iobuf ); + return len; +} + +/** Is the link up? */ +int ipxe_link ( int index ) { + netdev_poll ( devs[index] ); + return netdev_link_ok ( devs[index] ); +} + +/** The device's state, to the monitor's log */ +void ipxe_debug ( int index ) { + struct net_device *netdev = devs[index]; + char msg[200]; + + netdev_poll ( netdev ); + snprintf ( msg, sizeof ( msg ), "ipxe: %s %s: link %s (%08x), tx %d " + "ok %d bad, rx %d ok %d bad, state %x", netdev->name, + netdev->dev->driver_name, + ( netdev_link_ok ( netdev ) ? "up" : "down" ), + -netdev->link_rc, netdev->tx_stats.good, + netdev->tx_stats.bad, netdev->rx_stats.good, + netdev->rx_stats.bad, netdev->state ); + mdvmm_log ( msg ); +} diff --git a/mdvmm/ipxe/glue_data.c b/mdvmm/ipxe/glue_data.c new file mode 100644 index 00000000..8f58b48d --- /dev/null +++ b/mdvmm/ipxe/glue_data.c @@ -0,0 +1,15 @@ +/* iPXE in MDVMM: data that iPXE's headers declare in ways this file must + not see (compiled without them). + + virt_offset is "const" for iPXE's code; the monitor sets it once, before + anything of iPXE runs: physical address = virtual address + virt_offset + for everything in the monitor's pool. */ +unsigned long virt_offset; + +void ipxe_set_virt_offset(unsigned long offset) +{ + virt_offset = offset; +} + +/* objects the drivers "require" (iPXE's configuration objects) */ +char obj_config_ethernet, obj_config_pci, obj_config_net80211; diff --git a/mdvmm/ipxe/ipxe.lds b/mdvmm/ipxe/ipxe.lds new file mode 100644 index 00000000..67ed9466 --- /dev/null +++ b/mdvmm/ipxe/ipxe.lds @@ -0,0 +1,10 @@ +/* partial link of the iPXE drivers: one section of each kind, the linker + tables (drivers, ...) sorted into the data */ +SECTIONS +{ + .text : { *(.text .text.*) } + .rodata : { *(.rodata .rodata.*) } + .data : { *(.data .data.*) KEEP(*(SORT(.tbl.*))) } + .bss : { *(.bss .bss.*) *(COMMON) } + /DISCARD/ : { *(.einfo*) *(.comment) *(.note*) *(.discard*) *(.eh_frame*) } +} diff --git a/mdvmm/ipxe/overlay/config/defaults/mdvmm.h b/mdvmm/ipxe/overlay/config/defaults/mdvmm.h new file mode 100644 index 00000000..bca826b4 --- /dev/null +++ b/mdvmm/ipxe/overlay/config/defaults/mdvmm.h @@ -0,0 +1,11 @@ +#ifndef CONFIG_DEFAULTS_MDVMM_H +#define CONFIG_DEFAULTS_MDVMM_H +/* iPXE drivers inside the MDVMM monitor: flat 32 bit, pool memory at a + fixed offset from its physical address, direct I/O, polled */ +#define UACCESS_OFFSET +#define IOAPI_X86 +#define PCIAPI_DIRECT +#define DMAAPI_FLAT +#define NAP_NULL +#define FDT_NULL +#endif diff --git a/mdvmm/ipxe/overlay/ipxe/errno/mdvmm.h b/mdvmm/ipxe/overlay/ipxe/errno/mdvmm.h new file mode 100644 index 00000000..967e5a05 --- /dev/null +++ b/mdvmm/ipxe/overlay/ipxe/errno/mdvmm.h @@ -0,0 +1,5 @@ +#ifndef _IPXE_ERRNO_MDVMM_H +#define _IPXE_ERRNO_MDVMM_H +/* platform error numbers: the generic set */ +#include +#endif diff --git a/mdvmm/loader/loader.asm b/mdvmm/loader/loader.asm new file mode 100644 index 00000000..b29432b1 --- /dev/null +++ b/mdvmm/loader/loader.asm @@ -0,0 +1,588 @@ +; MDVMM.COM - DOS loader for the modernDOS virtual machine monitor +; +; Checks the machine, takes a memory pool from XMS, reads the 32-bit +; core from the end of its own file (see mz.asm) into it, switches to protected mode and jumps to the core. The +; core enables paging (through 'tramp' below), takes over interrupts and +; resumes this program at 'resumed' - now running in V86 mode. The loader +; then stays resident with only its small V86 stub area. + +%include "bootinfo.inc" + + cpu 386 + bits 16 + org 100h + +POOL_KB equ 32768 ; default pool size +POOL_KB_MIN equ 1024 + +start: + jmp main + +; ---------------------------------------------------------------------- +; resident part: V86-side stubs the monitor refers to +; ---------------------------------------------------------------------- +; Breakpoints: the monitor recognizes a HLT at stub_bp + n (see bootinfo.inc) +stub_bp: + times BP_COUNT hlt +stub_psp dw 0 + +; DPMI mode switch entry (returned by INT 2Fh AX=1687h) +stub_entry: + push ax + push bx + mov ah, 62h ; current PSP, for the client's ES + int 21h + mov [cs:stub_psp], bx + pop bx + pop ax + jmp stub_bp + BP_DPMI_ENTRY + +; DPMI 0305h real mode state save/restore: nothing to save +stub_retf: + retf + + align 16 +resident_end: + +; ---------------------------------------------------------------------- +; transient part +; ---------------------------------------------------------------------- +main: + mov dx, msg_banner + call print + + call check_386 + jc err_386 + smsw ax + test al, 1 + jz .not_loaded + mov ax, MDVMM_MPX << 8 ; already running under MDVMM? + int 2fh + cmp bx, MDVMM_SIGNATURE + jne err_pm + jmp command ; yes: MDVMM NEW ... +.not_loaded: + + ; XMS driver + mov ax, 4300h + int 2fh + cmp al, 80h + jne err_xms + push es + mov ax, 4310h + int 2fh + mov [xms_entry], bx + mov [xms_entry + 2], es + pop es + + ; pool size: default, or the largest free block if smaller + mov ah, 08h + call far [xms_entry] + cmp ax, POOL_KB_MIN + 4 + jb err_mem + mov dx, POOL_KB + 4 ; +4K for page alignment + cmp ax, dx + jae .size_ok + mov dx, ax +.size_ok: + mov [pool_kb], dx + mov ah, 09h ; allocate EMB + call far [xms_entry] + test ax, ax + jz err_mem + mov [xms_handle], dx + mov ah, 0ch ; lock EMB -> DX:BX physical + call far [xms_entry] + test ax, ax + jz err_lock + mov [pool_raw], bx + mov [pool_raw + 2], dx + mov ah, 03h ; global enable A20, for good + call far [xms_entry] + + ; page aligned pool inside the EMB + mov eax, [pool_raw] + add eax, 0fffh + and eax, 0fffff000h + mov [bi + bootinfo.pool_phys], eax + sub eax, [pool_raw] + mov [align_skip], eax + movzx ecx, word [pool_kb] + shl ecx, 10 + sub ecx, eax + and ecx, 0fffff000h + mov [bi + bootinfo.pool_size], ecx + + ; read the core from this program's file (it follows the loader + ; there) to the start of the aligned pool, 16 KB at a time + push es + mov es, [2ch] ; environment: strings, 0, count, path + xor di, di + xor al, al + mov cx, 0ffffh +.env: repne scasb + scasb + jne .env + add di, 2 + push ds + push es + pop ds + mov dx, di + mov ax, 3d00h ; open, read only + int 21h + pop ds + pop es + jc err_core + mov bx, ax + mov ax, 4200h + xor cx, cx + mov dx, CORE_OFFSET + int 21h + jc err_core +.read: mov ah, 3fh + mov cx, 4000h + mov dx, iobuf + int 21h + jc err_core + test ax, ax + jz .read_done + push ax + inc ax + and ax, 0fffeh ; XMS moves even lengths + movzx eax, ax + mov [xmove + 0], eax + mov word [xmove + 4], 0 ; source: conventional + mov word [xmove + 6], iobuf + mov [xmove + 8], cs + mov ax, [xms_handle] + mov [xmove + 10], ax + mov eax, [align_skip] + add eax, [core_bytes] + mov [xmove + 12], eax + push bx + mov si, xmove + mov ah, 0bh + call far [xms_entry] + pop bx + pop cx + test ax, ax + jz err_copy + movzx ecx, cx + add [core_bytes], ecx + jmp .read +.read_done: + mov ah, 3eh + int 21h + cmp dword [core_bytes], 1000h + jb err_core + + ; boot information for the core + mov dword [bi + bootinfo.magic], BOOTINFO_MAGIC + mov dword [bi + bootinfo.version], BOOTINFO_VERSION + mov eax, [core_bytes] + mov [bi + bootinfo.core_size], eax + xor ebx, ebx + mov bx, cs + shl ebx, 4 ; ebx = linear base of this segment + mov eax, ebx + add eax, tramp + mov [bi + bootinfo.trampoline], eax + mov word [bi + bootinfo.ip], resumed + mov [bi + bootinfo.cs], cs + mov [bi + bootinfo.ss], ss + mov [bi + bootinfo.ds], ds + mov [bi + bootinfo.es], es + mov [bi + bootinfo.fs], fs + mov [bi + bootinfo.gs], gs + mov [bi + bootinfo.psp], cs + mov [bi + bootinfo.stub_seg], cs + mov word [bi + bootinfo.stub_bp], stub_bp + mov word [bi + bootinfo.stub_entry], stub_entry + mov word [bi + bootinfo.stub_psp], stub_psp + mov word [bi + bootinfo.stub_retf], stub_retf + mov eax, ebx + add eax, tmp_gdt + mov [tmp_gdtr + 2], eax + mov eax, ebx + add eax, pm32 + mov [pm32_ptr], eax + + mov dx, msg_switch + call print + + ; to protected mode + cli + mov [bi + bootinfo.sp], sp + pushfd + pop eax + mov [bi + bootinfo.eflags], eax + o32 lgdt [tmp_gdtr] + mov eax, cr0 + or al, 1 + mov cr0, eax + jmp dword far [pm32_ptr] + + bits 32 +pm32: + mov ax, 10h + mov ds, ax + mov es, ax + mov fs, ax + mov gs, ax + mov ss, ax + lea esp, [ebx + pm_stack_top] + add ebx, bi ; ebx = linear address of bootinfo + mov eax, [ebx + bootinfo.pool_phys] + jmp eax ; core _start(eax = base, ebx = bi) + +; called by the core: ESI = page directory, ECX = high entry point. +; Lives in identity mapped low memory so execution survives enabling paging. +tramp: + mov cr3, esi + mov eax, cr0 + or eax, 80000000h + mov cr0, eax + jmp ecx + + bits 16 +; ---- back in V86 mode, under the monitor ---- +resumed: + sti + mov ax, cs + mov ds, ax + mov es, ax + mov ax, MDVMM_MPX << 8 + int 2fh + cmp bx, MDVMM_SIGNATURE + jne err_resume + mov dx, msg_active + call print + +; Register this block as the end of global memory for DOS sessions and +; stay resident. Also entered from 'command' when the monitor was started +; by the UEFI loader and sessions are not set up yet. +register: + ; Everything below the end of this resident block is global to + ; all DOS sessions, memory above is per session. Round the block + ; up so that the boundary is page aligned. (The environment is + ; kept: freeing it would leave a free hole in global memory.) + mov ax, cs + add ax, (resident_end - $$ + 100h + 15) >> 4 + add ax, 0ffh + xor al, al ; next 4K boundary (256 paragraphs) + mov [reg_boundary], ax + mov bx, cs + sub ax, bx + mov [resident_paras], ax + + ; per session DOS data for the monitor + push es + mov ah, 34h ; InDOS flag + int 21h + mov [reg_indos], bx + mov [reg_indos + 2], es + mov ah, 52h ; list of lists: CDS array + int 21h + mov ax, [es:bx + 16h] + mov [reg_cds], ax + mov ax, [es:bx + 18h] + mov [reg_cds + 2], ax + mov al, [es:bx + 21h] ; LASTDRIVE + mov ah, 58h ; bytes per CDS entry + mul ah + mov [reg_cds_size], ax + ; enhanced mode startup broadcast: the kernel (and TSRs) answer + ; with their instance data tables + push ds + xor bx, bx + mov es, bx + mov ds, bx + xor si, si + xor cx, cx + xor dx, dx ; enhanced mode + mov di, 030ah ; "Windows 3.10" + mov ax, 1605h + int 2fh + pop ds + mov [reg_sis], bx + mov [reg_sis + 2], es + pop es + test cx, cx + jnz .no_sessions ; someone vetoed + mov ax, (MDVMM_MPX << 8) | 04h ; register session data + mov dx, reg_block + int 2fh + jc .no_sessions + jmp .tsr +.no_sessions: + mov dx, msg_nosess + call print +.tsr: + mov dx, [resident_paras] + mov ax, 3100h ; stay resident + int 21h + +; ---------------------------------------------------------------------- +; MDVMM NEW [command]: start a DOS session running COMSPEC (/C command) +command: + mov si, 81h + call skip_spaces + cmp byte [si], 13 + jne .new + ; no arguments (UEFI boot): the virtual BIOS mouse driver, and + ; DOS sessions if nobody set them up + mov ax, (MDVMM_MPX << 8) | 07h + int 2fh + cmp ax, 1 + jne .no_mouse + mov dx, msg_mouse + call print +.no_mouse: + mov ax, (MDVMM_MPX << 8) | 06h + int 2fh + test dx, dx + jnz .already + mov dx, msg_sessions + call print + jmp register +.already: + mov dx, msg_already + call print + mov ax, 4c00h + int 21h +.new: + mov di, kw_new + mov cx, 3 +.cmp: lodsb + and al, 0dfh ; upper case + scasb + jne usage + loop .cmp + call skip_spaces + ; command tail for COMSPEC: " /C " or empty + mov di, tail + 1 + cmp byte [si], 13 + je .tail_done + mov ax, '/' | (' ' << 8) + mov byte [di], ' ' + inc di + mov word [di], 'C' * 256 + '/' + add di, 2 + mov byte [di], ' ' + inc di +.copy: lodsb + cmp al, 13 + je .tail_done + stosb + cmp di, tail + 126 + jb .copy +.tail_done: + mov byte [di], 13 + mov ax, di + sub ax, tail + 1 + mov [tail], al + call find_comspec ; DS:DX -> program + jc err_comspec + + ; release memory above the transient code, so the new session + ; has room to run the shell + mov bx, (transient_end - $$ + 100h + 15) >> 4 + mov ah, 4ah + int 21h + mov sp, transient_end - 2 + + mov ax, (MDVMM_MPX << 8) | 02h ; fork a new session + int 2fh + jc err_new + test ax, ax + jz .child + mov dx, msg_started ; parent: done + call print + mov ax, 4c00h + int 21h +.child: ; new session: run the shell + mov word [epb], 0 ; inherit environment + mov word [epb + 2], tail + mov [epb + 4], cs + mov word [epb + 6], 5ch + mov [epb + 8], cs + mov word [epb + 10], 6ch + mov [epb + 12], cs + mov dx, [comspec_ptr] + push ds + mov ds, [comspec_ptr + 2] + mov bx, epb + push cs + pop es + mov ax, 4b00h + int 21h + pop ds + mov ax, (MDVMM_MPX << 8) | 03h ; end this session + int 2fh + jmp $ ; not reached + +skip_spaces: + cmp byte [si], ' ' + jne .done + inc si + jmp skip_spaces +.done: ret + +; COMSPEC from the environment -> comspec_ptr; CF if not found +find_comspec: + push es + mov es, [2ch] + xor di, di +.var: cmp byte [es:di], 0 + je .none + mov si, kw_comspec + mov bx, di + mov cx, 8 + repe cmpsb + je .found + mov di, bx +.skip: inc di + cmp byte [es:di - 1], 0 + jne .skip + jmp .var +.found: mov [comspec_ptr], di + mov [comspec_ptr + 2], es + pop es + clc + ret +.none: pop es + stc + ret + +usage: mov dx, msg_usage + jmp fail +err_comspec: mov dx, msg_comspec + jmp fail +err_new: mov dx, msg_new + jmp fail + +; ---------------------------------------------------------------------- + +; CF set if not at least a 386 +check_386: + pushf ; preserve the caller's flags + pushf + pop ax + mov cx, ax + and ax, 0fffh + push ax + popf + pushf + pop ax + and ax, 0f000h + cmp ax, 0f000h + je .no ; 8086/80186 + or cx, 7000h + push cx + popf + pushf + pop ax + test ax, 7000h + jz .no ; 80286 + popf + clc + ret +.no: popf + stc + ret + +print: + mov ah, 09h + int 21h + ret + +err_386: mov dx, msg_386 + jmp fail +err_pm: mov dx, msg_pm + jmp fail +err_xms: mov dx, msg_xms + jmp fail +err_mem: mov dx, msg_mem + jmp fail +err_lock: mov dx, msg_lock + jmp fail +err_copy: mov dx, msg_copy + jmp fail +err_core: mov dx, msg_core + jmp fail +err_resume: mov dx, msg_resume +fail: + call print + mov ax, 4c01h + int 21h + +; ---------------------------------------------------------------------- +msg_banner db 'MDVMM - modernDOS virtual machine monitor', 13, 10, '$' +msg_switch db 'Starting monitor...', 13, 10, '$' +msg_sessions db 'Monitor active (UEFI boot): setting up DOS sessions.', 13, 10, '$' +msg_already db 'MDVMM is already active.', 13, 10, '$' +msg_mouse db 'Mouse driver (INT 33h) installed.', 13, 10, '$' +msg_active db 'MDVMM active: DOS is running in a virtual machine.', 13, 10, '$' +msg_386 db 'MDVMM needs a 386 or later CPU.', 13, 10, '$' +msg_pm db 'CPU already in protected/V86 mode (MDVMM, EMM386 or a', 13, 10 + db 'similar memory manager is loaded).', 13, 10, '$' +msg_xms db 'MDVMM needs an XMS driver (e.g. DEVICE=HIMEMX.EXE).', 13, 10, '$' +msg_mem db 'Not enough free extended memory.', 13, 10, '$' +msg_lock db 'Could not lock extended memory.', 13, 10, '$' +msg_copy db 'Could not copy the monitor to extended memory.', 13, 10, '$' +msg_core db 'Could not read the monitor from MDVMM.COM.', 13, 10, '$' +msg_resume db 'Monitor did not answer after start.', 13, 10, '$' +msg_nosess db 'DOS kernel does not support sessions (no instance data).', 13, 10, '$' +msg_usage db 'Usage: MDVMM load the monitor', 13, 10 + db ' MDVMM NEW [cmd] start a DOS session (Ctrl+Alt+F1..F4 switch)', 13, 10, '$' +msg_comspec db 'COMSPEC not set.', 13, 10, '$' +msg_new db 'Could not start a session.', 13, 10, '$' +msg_started db 'DOS session started.', 13, 10, '$' +kw_new db 'NEW' +kw_comspec db 'COMSPEC=' + +; session registration block (INT 2Fh AX=DE04h, DS:DX) +reg_block: +reg_sis dd 0 ; startup info chain (1605h) +reg_indos dd 0 ; InDOS flag +reg_cds dd 0 ; CDS array +reg_cds_size dw 0 +reg_boundary dw 0 ; first per-session paragraph +resident_paras dw 0 +comspec_ptr dd 0 +epb times 14 db 0 ; EXEC parameter block +tail times 128 db 0 ; command tail + + align 4 +xms_entry dd 0 +xms_handle dw 0 +pool_kb dw 0 +pool_raw dd 0 +align_skip dd 0 +core_bytes dd 0 +xmove times 16 db 0 ; XMS move structure +pm32_ptr dd 0 + dw 08h + + align 8 +tmp_gdt dq 0 + dw 0ffffh, 0 ; 08h: flat 32-bit code + db 0, 9ah, 0cfh, 0 + dw 0ffffh, 0 ; 10h: flat 32-bit data + db 0, 92h, 0cfh, 0 +tmp_gdtr dw 3 * 8 - 1 + dd 0 + + align 4 +bi times bootinfo_size db 0 + + align 16 + times 512 db 0 +pm_stack_top: +transient_end: ; MDVMM NEW keeps memory up to here + + align 16 +image_end: +; the core follows the loader in the file (after mz.asm's 32 byte header) +CORE_OFFSET equ 32 + (image_end - $$) +iobuf equ image_end ; 16 KB, in the memory after the image diff --git a/mdvmm/loader/mz.asm b/mdvmm/loader/mz.asm new file mode 100644 index 00000000..382fdd14 --- /dev/null +++ b/mdvmm/loader/mz.asm @@ -0,0 +1,26 @@ +; MDVMM.COM's file layout: an MZ header that starts the loader exactly as +; DOS starts a .COM program (CS = DS = ES = SS = PSP, IP = 100h), then the +; loader (loader.asm, LSIZE bytes), then the 32-bit core as an overlay DOS +; does not load: the loader reads it from the file into extended memory. +; (A plain .COM file cannot be larger than 64 KB.) + +HDR equ 32 + + db 'MZ' + dw (HDR + LSIZE) % 512 ; bytes in the last page + dw (HDR + LSIZE + 511) / 512 ; pages + dw 0 ; relocations + dw HDR / 16 ; header paragraphs + dw (10000h - LSIZE) / 16 ; memory after the image: a full 64 KB segment + dw 0ffffh ; all there is + dw 0fff0h ; SS = PSP + dw 0fffeh ; SP + dw 0 ; checksum + dw 100h ; IP + dw 0fff0h ; CS = PSP + dw 1ch ; relocation table + dw 0 ; overlay number + times HDR - ($ - $$) db 0 + + incbin "loader.bin" + incbin "core_dos.bin" diff --git a/mdvmm/mdlog/mdlog.asm b/mdvmm/mdlog/mdlog.asm new file mode 100644 index 00000000..3387be9e --- /dev/null +++ b/mdvmm/mdlog/mdlog.asm @@ -0,0 +1,76 @@ +; MDLOG.COM - show the MDVMM monitor's log (UEFI boots) +; +; MDLOG the last 20 lines +; MDLOG /A all lines kept (64) +; MDLOG /N first ask the network card driver for its state, then +; the last 20 lines (send a photo of this when the network +; does not work) +; +; The monitor keeps its log (drivers found, errors) in memory; INT 2Fh +; AX=DE14h copies it out, AX=DE13h makes the network driver add its state. + + cpu 386 + bits 16 + org 100h + +start: + mov word [lines], 20 + mov si, 81h +.arg: lodsb + cmp al, 13 + je .go + cmp al, '/' + jne .arg + lodsb + and al, 0dfh + cmp al, 'A' + jne .n + mov word [lines], 0 + jmp .arg +.n: cmp al, 'N' + jne .arg + mov ax, 0de13h ; driver state into the log + int 2fh + jnc .arg + mov dx, msg_nocard + mov ah, 9 + int 21h + jmp .arg +.go: + mov ax, 0de00h ; MDVMM there? + int 2fh + cmp al, 0ffh + jne .nomon + push cs + pop es + mov di, buf + mov cx, buf_size + mov bx, [lines] + mov ax, 0de14h + int 2fh + jc .nolog + mov dx, buf ; write CX bytes to standard output + mov bx, 1 + mov ah, 40h + int 21h + mov dx, crlf + mov ah, 9 + int 21h + mov ax, 4c00h + int 21h +.nomon: mov dx, msg_nomon + jmp .fail +.nolog: mov dx, msg_nolog +.fail: mov ah, 9 + int 21h + mov ax, 4c01h + int 21h + +lines dw 20 +crlf db 13, 10, '$' +msg_nomon db 'MDVMM is not running.', 13, 10, '$' +msg_nolog db 'The monitor keeps no log on this boot (DOS boot: see the debug port).', 13, 10, '$' +msg_nocard db '(no network card driver is active)', 13, 10, '$' + +buf_size equ 8000 +buf: diff --git a/mdvmm/mdsys/mdsys.asm b/mdvmm/mdsys/mdsys.asm new file mode 100644 index 00000000..132ab40c --- /dev/null +++ b/mdvmm/mdsys/mdsys.asm @@ -0,0 +1,148 @@ +; MDSYS.COM - modernDOS system control (through the MDVMM monitor) +; +; MDSYS show the state (kind of boot, trial) +; MDSYS KEEP confirm a trial boot: no automatic restart +; MDSYS REBOOT restart the machine +; MDSYS DISK exit code 0 if hard disks can be written, 1 if they are +; read-only (a start from a stick); prints nothing +; MDSYS WRITE exit code 0 if a file can be made in C:\MDOS\TEMP, 1 if +; not (the system runs from a CD); prints nothing and +; needs no monitor +; +; Exit code: 0 normal boot, 1 unconfirmed trial boot, 2 confirmed trial +; boot, 255 no monitor (so batch files can tell). + + cpu 386 + bits 16 + org 100h + +start: + mov si, 81h +.sp0: lodsb + cmp al, ' ' + je .sp0 + and al, 0dfh + cmp al, 'W' + je wtest + mov ax, 0de00h + int 2fh + cmp al, 0ffh + jne nomon + mov si, 81h +.sp: lodsb + cmp al, ' ' + je .sp + cmp al, 13 + je state + and al, 0dfh + cmp al, 'K' + je keep + cmp al, 'R' + je reboot + cmp al, 'D' + je disk + mov dx, msg_usage + call print + mov ax, 4cffh + int 21h + +keep: mov ax, 0de16h + int 2fh +state: mov ax, 0de15h + int 2fh + jc nomon + mov bx, ax + mov dx, msg_dos + test bl, 1 + jz .p + mov dx, msg_uefi +.p: call print + test bl, 2 + jnz .trial + mov dx, msg_normal + call print + mov ax, 4c00h + int 21h +.trial: test bl, 4 + jnz .kept + mov dx, msg_trial + call print + mov ax, 4c01h + int 21h +.kept: mov dx, msg_kept + call print + mov ax, 4c02h + int 21h + +disk: mov ax, 0de15h + int 2fh + jc nomon + test al, 8 + mov ax, 4c00h + jnz .w + inc ax +.w: int 21h + +; can the system disk be written? A critical error (write protection) must +; fail the call, not ask "Abort, Retry". +wtest: mov dx, int24 + mov ax, 2524h + int 21h + mov dx, wname + xor cx, cx + mov ah, 3ch ; create + int 21h + jc .no + mov bx, ax + mov dx, wname + mov cx, 1 + mov ah, 40h ; a byte: the create alone may sit in a buffer + int 21h + pushf + mov ah, 3eh + int 21h + pushf + mov dx, wname + mov ah, 41h + int 21h + popf + jc .no2 + popf + jc .no + mov ax, 4c00h + int 21h +.no2: popf +.no: mov ax, 4c01h + int 21h +int24: mov al, 3 ; fail the call + iret + +reboot: mov dx, msg_reboot + call print + mov ah, 0dh ; DOS: write its buffers to the disks + int 21h + mov ax, 0de17h + int 2fh + ; not reached with the monitor; without: the keyboard controller + mov al, 0feh + out 64h, al + jmp $ + +nomon: mov dx, msg_nomon + call print + mov ax, 4cffh + int 21h + +print: mov ah, 9 + int 21h + ret + +wname db 'C:\MDOS\TEMP\W.$$$', 0 +msg_uefi db 'UEFI boot. $' +msg_dos db 'DOS boot. $' +msg_normal db 'Installed system.', 13, 10, '$' +msg_trial db 'TRIAL boot: restarts in ten minutes unless confirmed with MDSYS KEEP.', 13, 10, '$' +msg_kept db 'Trial boot, confirmed: it stays until the next restart.', 13, 10, '$' +msg_reboot db 'Restarting...', 13, 10, '$' +msg_nomon db 'MDVMM is not running.', 13, 10, '$' +msg_usage db 'Usage: MDSYS [KEEP | REBOOT | DISK | WRITE]', 13, 10, '$' diff --git a/mdvmm/pktdrv/pktdrv.asm b/mdvmm/pktdrv/pktdrv.asm new file mode 100644 index 00000000..10a0739e --- /dev/null +++ b/mdvmm/pktdrv/pktdrv.asm @@ -0,0 +1,451 @@ +; PKTDRV.COM - packet driver for the MDVMM network cards +; +; A Packet Driver Specification 1.11 driver (class 1, Ethernet) on top of +; the monitor's network API (INT 2Fh AX=DE10h-DE12h, mdvmm/core/nic.c), so +; DOS network software (Watt-32, mTCP, ...) works with the cards MDVMM has +; native drivers for, on DOS and UEFI boots. +; +; PKTDRV [vector] vector: 60..80 (hex), default 60 +; +; Frames are fetched from the monitor on every timer tick (INT 08h), after +; every send and when DOS is idle (INT 28h), and handed to the receivers +; with the usual two upcalls (AX=0: get a buffer, AX=1: it is filled). + + cpu 386 + bits 16 + org 100h + +MAX_HANDLES equ 8 +FRAME_MAX equ 1514 +H_SIZE equ 16 ; used, typelen, type[8], receiver(4), pad + +start: jmp init + +; --------------------------------------------------------------------- +; resident part +; --------------------------------------------------------------------- +pkt_entry: + jmp short pkt_dispatch + nop + db 'PKT DRVR', 0 ; signature at entry + 3 +pkt_dispatch: + cmp ah, 1 + je f_info + cmp ah, 2 + je f_access + cmp ah, 3 + je f_release + cmp ah, 4 + je f_send + cmp ah, 5 + je f_terminate + cmp ah, 6 + je f_address + cmp ah, 7 + je ok + cmp ah, 20 + je ok + cmp ah, 21 + je f_getmode + cmp ah, 24 + je f_stats + mov dh, 11 ; BAD_COMMAND +err: stc + retf 2 +ok: clc + retf 2 + +f_info: ; AL = FFh + mov bx, 1 ; version + mov cx, 0100h ; CH = class 1 (DIX Ethernet), CL = 0 + mov dx, 0ffffh ; type: generic + push cs + pop ds + mov si, drv_name + mov al, 1 ; basic functions + clc + retf 2 + +f_access: ; AL class, BX type, DL number, + cmp al, 1 ; DS:SI type, CX typelen, ES:DI receiver + jne .noclass + cmp cx, 8 + ja .badtype + push bx + push di + mov bx, handles + xor di, di +.find: cmp byte [cs:bx], 0 + je .free + add bx, H_SIZE + inc di + cmp di, MAX_HANDLES + jb .find + pop di + pop bx + mov dh, 9 ; NO_SPACE + jmp err +.free: mov byte [cs:bx], 1 + mov [cs:bx + 1], cl + push cx + push si +.copy: jcxz .copied + lodsb + mov [cs:bx + 2], al + inc bx + dec cx + jmp .copy +.copied: + pop si + pop cx + sub bx, cx ; back to the entry + mov ax, di ; handle = index + 1 + inc ax + pop di + mov [cs:bx + 10], di ; receiver + mov [cs:bx + 12], es + pop bx + clc + retf 2 +.noclass: + mov dh, 2 ; NO_CLASS + jmp err +.badtype: + mov dh, 5 ; BAD_TYPE + jmp err + +; BX = handle -> BX = entry address, CF if bad +handle_entry: + dec bx + cmp bx, MAX_HANDLES + jae .bad + shl bx, 4 ; * H_SIZE + add bx, handles + cmp byte [cs:bx], 0 + je .bad + clc + ret +.bad: stc + ret + +f_release: +f_terminate: + call handle_entry + jc .bad + mov byte [cs:bx], 0 + clc + retf 2 +.bad: mov dh, 1 ; BAD_HANDLE + jmp err + +f_send: ; DS:SI frame, CX length + push ax + mov ax, 0de11h + int 2fh + pop ax + jc .fail + call poll + clc + retf 2 +.fail: mov dh, 12 ; CANT_SEND + jmp err + +f_address: ; ES:DI buffer, CX room -> CX = 6 + cmp cx, 6 + jb .small + push si + push ds + push cs + pop ds + mov si, mac + mov cx, 6 + cld + rep movsb + sub di, 6 + mov cx, 6 + pop ds + pop si + clc + retf 2 +.small: mov dh, 14 ; NO_SPACE (buffer) + jmp err + +f_getmode: + mov ax, 3 ; own address and broadcasts + clc + retf 2 + +f_stats: + push cs + pop ds + mov si, stats + clc + retf 2 + +; --------------------------------------------------------------------- +; receiving +; --------------------------------------------------------------------- +int08: + pushf + call far [cs:old08] + call poll + iret + +int28: + call poll + jmp far [cs:old28] + +; fetch frames from the monitor and hand them to the receivers +poll: + cmp byte [cs:busy], 0 + jne .ret + ; no receiver here: leave the frames to the sessions that have one + push bx + push cx + mov bx, handles + mov cx, MAX_HANDLES +.used: cmp byte [cs:bx], 0 + jne .some + add bx, H_SIZE + loop .used + pop cx + pop bx + ret +.some: pop cx + pop bx + mov byte [cs:busy], 1 + pushad + push ds + push es + mov byte [cs:frames], 8 ; at most 8 per call +.next: push cs + pop es + mov di, rxbuf + mov cx, FRAME_MAX + mov ax, 0de12h + int 2fh + jc .done + jcxz .done + mov [cs:rxlen], cx + call deliver + dec byte [cs:frames] + jnz .next +.done: pop es + pop ds + popad + mov byte [cs:busy], 0 +.ret: ret + +; the frame in rxbuf (rxlen bytes) to the first handle whose type matches +deliver: + mov bx, handles + mov dx, 1 ; handle number +.h: cmp byte [cs:bx], 0 + je .skip + movzx cx, byte [cs:bx + 1] + jcxz .match ; typelen 0: every frame + push cs + pop ds + lea si, [bx + 2] + mov di, rxbuf + 12 + push cs + pop es + cld + repe cmpsb + je .match +.skip: add bx, H_SIZE + inc dx + cmp dx, MAX_HANDLES + jbe .h + ret +.match: + mov eax, [cs:bx + 10] ; receiver + mov [cs:receiver], eax + mov [cs:curhandle], dx + ; first upcall: AX=0, BX=handle, CX=length -> ES:DI buffer or 0:0 + xor ax, ax + mov bx, dx + mov cx, [cs:rxlen] + xor di, di + mov es, di + call far [cs:receiver] + mov ax, es + or ax, di + jz .dropped + ; copy, then the second upcall: AX=1, DS:SI = the buffer + push es + push di + push cs + pop ds + mov si, rxbuf + mov cx, [cs:rxlen] + cld + rep movsb + pop si + pop ds + mov ax, 1 + mov bx, [cs:curhandle] + mov cx, [cs:rxlen] + call far [cs:receiver] +.dropped: + ret + +drv_name db 'MDVMM NIC', 0 +old08 dd 0 +old28 dd 0 +receiver dd 0 +curhandle dw 0 +rxlen dw 0 +busy db 0 +frames db 0 +mac times 6 db 0 +stats times 15 dd 0 + align 2 +handles times MAX_HANDLES * H_SIZE db 0 +rxbuf times FRAME_MAX + 2 db 0 +resident_end: + +; --------------------------------------------------------------------- +; transient part +; --------------------------------------------------------------------- +init: + mov dx, msg_banner + call print + ; vector from the command line (hex), default 60h + mov si, 81h + xor bx, bx +.skip: lodsb + cmp al, ' ' + je .skip + cmp al, 13 + je .parsed +.digit: cmp al, '0' + jb .parsed + cmp al, '9' + jbe .num + or al, 20h + cmp al, 'a' + jb .parsed + cmp al, 'f' + ja .parsed + sub al, 'a' - 10 - '0' +.num: sub al, '0' + shl bx, 4 + add bl, al + lodsb + jmp .digit +.parsed: + test bx, bx + jnz .have + mov bx, 60h +.have: cmp bx, 60h + jb .badvec + cmp bx, 80h + ja .badvec + mov [vector], bl + + ; is there a packet driver already? + xor ax, ax + mov es, ax + shl bx, 2 + les di, [es:bx] + mov ax, es + or ax, di + jz .free + add di, 3 + mov si, sig + mov cx, 8 + repe cmpsb + je .inuse +.free: + ; the monitor's network card + push cs + pop es + mov di, mac + mov ax, 0de10h + int 2fh + jc .nocard + + ; vectors + mov ax, 3508h + int 21h + mov [old08], bx + mov [old08 + 2], es + mov ax, 3528h + int 21h + mov [old28], bx + mov [old28 + 2], es + mov al, [vector] + mov ah, 25h + mov dx, pkt_entry + int 21h + mov ax, 2508h + mov dx, int08 + int 21h + mov ax, 2528h + mov dx, int28 + int 21h + + ; report: "Packet driver at INT 60h, MAC xx:xx:..." + mov al, [vector] + mov di, msg_vec + call hex2 + mov si, mac + mov di, msg_mac + mov cx, 6 +.mac: lodsb + call hex2 + inc di + loop .mac + mov dx, msg_ok + call print + mov ax, 0de01h ; and in the monitor's log + mov dx, msg_ok + int 2fh + + mov es, [2ch] ; free the environment + mov ah, 49h + int 21h + mov dx, (resident_end - $$ + 100h + 15) >> 4 + mov ax, 3100h + int 21h + +.badvec: + mov dx, msg_badvec + jmp fail +.inuse: + mov dx, msg_inuse + jmp fail +.nocard: + mov dx, msg_nocard +fail: call print + mov ax, 4c01h + int 21h + +; AL -> two hex digits at DI +hex2: push ax + shr al, 4 + call .d + pop ax + and al, 0fh +.d: add al, '0' + cmp al, '9' + jbe .s + add al, 'A' - '9' - 1 +.s: mov [di], al + inc di + ret + +print: mov ah, 9 + int 21h + ret + +vector db 0 +sig db 'PKT DRVR' +msg_banner db 'PKTDRV - packet driver for the MDVMM network cards', 13, 10, '$' +msg_ok db 'Packet driver at INT ' +msg_vec db '00h, MAC ' +msg_mac db '00:00:00:00:00:00', 13, 10, 0, '$' ; ASCIZ for the log, $ for DOS +msg_badvec db 'Usage: PKTDRV [vector] (60..80 hex, default 60)', 13, 10, '$' +msg_inuse db 'There is a packet driver at that vector already.', 13, 10, '$' +msg_nocard db 'No network card (MDVMM must be running, with a supported card).', 13, 10, '$' diff --git a/mdvmm/sshslot/sshslot.asm b/mdvmm/sshslot/sshslot.asm new file mode 100644 index 00000000..7b2300b4 --- /dev/null +++ b/mdvmm/sshslot/sshslot.asm @@ -0,0 +1,206 @@ +; SSHSLOT.COM - job slots: DOS sessions that run commands for SSHD +; +; SSHSLOT [n] start n job slots (1..3, default 2) +; +; Forks n MDVMM sessions (before SSHD starts: a session can not be forked +; from a DPMI program). Each one waits for a job from the monitor +; (INT 2Fh AX=DE0Ah), runs it with COMSPEC (an empty command: an +; interactive shell, else "/C command"), reports the exit code (DE0Bh) and +; waits again. SSHD starts jobs (DE0Ch), reads their screens (DE08h) and +; types into them (DE09h). + + cpu 386 + bits 16 + org 100h + +MPX equ 0deh + +start: + mov dx, msg_banner + call print + mov ax, MPX << 8 ; MDVMM installed? + int 2fh + cmp al, 0ffh + jne err_mdvmm + + ; slot count + mov si, 81h +.sp: lodsb + cmp al, ' ' + je .sp + mov byte [count], 2 + cmp al, '1' + jb .count_done + cmp al, '3' + ja usage + sub al, '0' + mov [count], al +.count_done: + call find_comspec + jc err_comspec + + ; keep only this program: the slots need room for the shell + mov bx, (prog_end - $$ + 100h + 15) >> 4 + mov ah, 4ah + int 21h + mov sp, prog_end - 2 + +.fork: mov ax, (MPX << 8) | 02h + int 2fh + jc err_fork + test ax, ax + jz slot + ; wait until the new session asks for work: from then on a job + ; can be started in it (at most about 3 seconds) + mov bl, al + mov cx, 60 +.ready: push bx + push cx + mov ax, (MPX << 8) | 0dh + int 2fh + pop cx + pop bx + jnc .is_ready + sti + hlt + loop .ready +.is_ready: + inc byte [started] + mov al, [started] + cmp al, [count] + jb .fork + add byte [msg_n], al + mov dx, msg_ok + call print + mov ax, 4c00h + int 21h + +; ---------------------------------------------------------------------- +; a job slot (runs forever in its own session) +slot: + mov [saved_sp], sp +.wait: push cs + pop es + mov di, cmdbuf + mov ax, (MPX << 8) | 0ah + int 2fh + jnc .job + sti + hlt ; idle: the monitor runs others + jmp .wait +.job: + ; command tail: empty or " /C " + mov si, cmdbuf + mov di, tail + 1 + cmp byte [si], 0 + je .tail_done + mov dword [di], ' /C ' + add di, 4 +.copy: lodsb + test al, al + jz .tail_done + stosb + cmp di, tail + 126 + jb .copy +.tail_done: + mov byte [di], 13 + mov ax, di + sub ax, tail + 1 + mov [tail], al + + mov ax, 0003h ; a clean screen for the job + int 10h + + mov word [epb], 0 ; inherit the environment + mov word [epb + 2], tail + mov [epb + 4], cs + mov word [epb + 6], 5ch + mov [epb + 8], cs + mov word [epb + 10], 6ch + mov [epb + 12], cs + mov dx, [comspec_ptr] + push ds + mov ds, [comspec_ptr + 2] + mov bx, epb + push cs + pop es + mov ax, 4b00h + int 21h + cli ; EXEC may not keep SS:SP + mov bx, cs + mov ss, bx + mov sp, [cs:saved_sp] + sti + mov ds, bx + mov es, bx + mov bx, 0ffffh ; could not start + jc .done + mov ah, 4dh + int 21h + xor ah, ah + mov bx, ax +.done: mov ax, (MPX << 8) | 0bh + int 2fh + jmp .wait + +; ---------------------------------------------------------------------- + +; COMSPEC from the environment -> comspec_ptr; CF if not found +find_comspec: + push es + mov es, [2ch] + xor di, di +.var: cmp byte [es:di], 0 + je .none + mov si, kw_comspec + mov bx, di + mov cx, 8 + repe cmpsb + je .found + mov di, bx +.skip: inc di + cmp byte [es:di - 1], 0 + jne .skip + jmp .var +.found: mov [comspec_ptr], di + mov [comspec_ptr + 2], es + pop es + clc + ret +.none: pop es + stc + ret + +print: mov ah, 9 + int 21h + ret + +usage: mov dx, msg_usage + jmp fail +err_mdvmm: mov dx, msg_mdvmm + jmp fail +err_comspec: mov dx, msg_comspec + jmp fail +err_fork: mov dx, msg_fork +fail: call print + mov ax, 4c01h + int 21h + +msg_banner db 'SSHSLOT - job slots for SSHD', 13, 10, '$' +msg_ok db 'Job slots started: ' +msg_n db '0', 13, 10, '$' +msg_usage db 'Usage: SSHSLOT [n] (n = 1..3 slots, default 2)', 13, 10, '$' +msg_mdvmm db 'MDVMM is not loaded.', 13, 10, '$' +msg_comspec db 'COMSPEC not set.', 13, 10, '$' +msg_fork db 'Could not start a session (MDVMM sessions set up, a DPMI program running?).', 13, 10, '$' +kw_comspec db 'COMSPEC=' + +count db 2 +started db 0 +saved_sp dw 0 +comspec_ptr dd 0 +epb times 14 db 0 +tail times 128 db 0 +cmdbuf times 128 db 0 + times 256 db 0 ; stack +prog_end: diff --git a/mdvmm/uefi/efi.h b/mdvmm/uefi/efi.h new file mode 100644 index 00000000..cb9a59ba --- /dev/null +++ b/mdvmm/uefi/efi.h @@ -0,0 +1,207 @@ +/* Minimal UEFI definitions for the MDVMM loader (x64), from the UEFI + * specification. Only what the loader uses is typed; other table slots + * are placeholders so the offsets match. */ +#ifndef MDVMM_EFI_H +#define MDVMM_EFI_H + +#include +#include + +#define EFIAPI __attribute__((ms_abi)) + +typedef uint64_t EFI_STATUS; +typedef void *EFI_HANDLE; +typedef uint16_t CHAR16; +typedef uint64_t UINTN; + +#define EFI_SUCCESS 0 +#define EFI_ERROR(s) ((int64_t)(s) < 0) +#define EFI_BUFFER_TOO_SMALL 0x8000000000000005ull + +typedef struct { uint32_t d1; uint16_t d2, d3; uint8_t d4[8]; } EFI_GUID; + +typedef struct { + uint64_t Signature; + uint32_t Revision, HeaderSize, CRC32, Reserved; +} EFI_TABLE_HEADER; + +/* memory */ +enum { AllocateAnyPages, AllocateMaxAddress, AllocateAddress }; +enum { + EfiReservedMemoryType, EfiLoaderCode, EfiLoaderData, EfiBootServicesCode, + EfiBootServicesData, EfiRuntimeServicesCode, EfiRuntimeServicesData, + EfiConventionalMemory, EfiUnusableMemory, EfiACPIReclaimMemory, + EfiACPIMemoryNVS, EfiMemoryMappedIO, EfiMemoryMappedIOPortSpace, + EfiPalCode, EfiPersistentMemory +}; + +typedef struct { + uint32_t Type, Pad; + uint64_t PhysicalStart, VirtualStart, NumberOfPages, Attribute; +} EFI_MEMORY_DESCRIPTOR; + +typedef struct EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL { + void *Reset; + EFI_STATUS (EFIAPI *OutputString)(struct EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *, CHAR16 *); +} EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL; + +typedef struct { + EFI_TABLE_HEADER Hdr; + void *RaiseTPL, *RestoreTPL; + EFI_STATUS (EFIAPI *AllocatePages)(int Type, int MemoryType, UINTN Pages, uint64_t *Memory); + EFI_STATUS (EFIAPI *FreePages)(uint64_t Memory, UINTN Pages); + EFI_STATUS (EFIAPI *GetMemoryMap)(UINTN *Size, EFI_MEMORY_DESCRIPTOR *Map, UINTN *MapKey, + UINTN *DescriptorSize, uint32_t *DescriptorVersion); + EFI_STATUS (EFIAPI *AllocatePool)(int PoolType, UINTN Size, void **Buffer); + EFI_STATUS (EFIAPI *FreePool)(void *Buffer); + void *CreateEvent, *SetTimer, *WaitForEvent, *SignalEvent, *CloseEvent, *CheckEvent; + void *InstallProtocolInterface, *ReinstallProtocolInterface, *UninstallProtocolInterface; + EFI_STATUS (EFIAPI *HandleProtocol)(EFI_HANDLE Handle, EFI_GUID *Protocol, void **Interface); + void *Reserved, *RegisterProtocolNotify, *LocateHandle, *LocateDevicePath; + void *InstallConfigurationTable; + EFI_STATUS (EFIAPI *LoadImage)(uint8_t BootPolicy, EFI_HANDLE Parent, void *DevicePath, + void *SourceBuffer, UINTN SourceSize, EFI_HANDLE *Image); + EFI_STATUS (EFIAPI *StartImage)(EFI_HANDLE Image, UINTN *ExitDataSize, CHAR16 **ExitData); + void *Exit, *UnloadImage; + EFI_STATUS (EFIAPI *ExitBootServices)(EFI_HANDLE ImageHandle, UINTN MapKey); + void *GetNextMonotonicCount; + EFI_STATUS (EFIAPI *Stall)(UINTN Microseconds); + EFI_STATUS (EFIAPI *SetWatchdogTimer)(UINTN Timeout, uint64_t Code, UINTN DataSize, CHAR16 *Data); + void *ConnectController, *DisconnectController, *OpenProtocol, *CloseProtocol; + void *OpenProtocolInformation, *ProtocolsPerHandle; + EFI_STATUS (EFIAPI *LocateHandleBuffer)(int SearchType, EFI_GUID *Protocol, void *SearchKey, + UINTN *Count, EFI_HANDLE **Buffer); + EFI_STATUS (EFIAPI *LocateProtocol)(EFI_GUID *Protocol, void *Registration, void **Interface); +} EFI_BOOT_SERVICES; + +typedef struct { + EFI_GUID VendorGuid; + void *VendorTable; +} EFI_CONFIGURATION_TABLE; + +/* keyboard */ +typedef struct { uint16_t ScanCode; CHAR16 UnicodeChar; } EFI_INPUT_KEY; +typedef struct EFI_SIMPLE_TEXT_INPUT_PROTOCOL { + void *Reset; + EFI_STATUS (EFIAPI *ReadKeyStroke)(struct EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This, EFI_INPUT_KEY *Key); + void *WaitForKey; +} EFI_SIMPLE_TEXT_INPUT_PROTOCOL; + +/* runtime services */ +#define EFI_VARIABLE_NON_VOLATILE 1 +#define EFI_VARIABLE_BOOTSERVICE_ACCESS 2 +#define EFI_VARIABLE_RUNTIME_ACCESS 4 +typedef struct { + EFI_TABLE_HEADER Hdr; + void *GetTime, *SetTime, *GetWakeupTime, *SetWakeupTime; + void *SetVirtualAddressMap, *ConvertPointer; + void *GetVariable, *GetNextVariableName; + EFI_STATUS (EFIAPI *SetVariable)(CHAR16 *Name, EFI_GUID *Vendor, uint32_t Attributes, + UINTN Size, void *Data); + void *GetNextHighMonotonicCount; + void (EFIAPI *ResetSystem)(int Type, EFI_STATUS Status, UINTN Size, void *Data); +} EFI_RUNTIME_SERVICES; + +/* device paths: a list of nodes, the last one of type 7Fh */ +typedef struct { uint8_t Type, SubType, Length[2]; } EFI_DEVICE_PATH; + +typedef struct { + EFI_TABLE_HEADER Hdr; + CHAR16 *FirmwareVendor; + uint32_t FirmwareRevision; + EFI_HANDLE ConsoleInHandle; + EFI_SIMPLE_TEXT_INPUT_PROTOCOL *ConIn; + EFI_HANDLE ConsoleOutHandle; + EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *ConOut; + EFI_HANDLE StandardErrorHandle; + void *StdErr; + EFI_RUNTIME_SERVICES *RuntimeServices; + EFI_BOOT_SERVICES *BootServices; + UINTN NumberOfTableEntries; + EFI_CONFIGURATION_TABLE *ConfigurationTable; +} EFI_SYSTEM_TABLE; + +typedef struct { + uint32_t Revision; + EFI_HANDLE ParentHandle; + EFI_SYSTEM_TABLE *SystemTable; + EFI_HANDLE DeviceHandle; + void *FilePath, *Reserved; + uint32_t LoadOptionsSize; + void *LoadOptions, *ImageBase; + uint64_t ImageSize; + int ImageCodeType, ImageDataType; + void *Unload; +} EFI_LOADED_IMAGE_PROTOCOL; + +/* files */ +#define EFI_FILE_MODE_READ 1ull +#define EFI_FILE_MODE_WRITE 2ull +#define EFI_FILE_MODE_CREATE 0x8000000000000000ull + +typedef struct EFI_FILE_PROTOCOL { + uint64_t Revision; + EFI_STATUS (EFIAPI *Open)(struct EFI_FILE_PROTOCOL *This, struct EFI_FILE_PROTOCOL **New, + CHAR16 *Name, uint64_t Mode, uint64_t Attributes); + EFI_STATUS (EFIAPI *Close)(struct EFI_FILE_PROTOCOL *This); + EFI_STATUS (EFIAPI *Delete)(struct EFI_FILE_PROTOCOL *This); + EFI_STATUS (EFIAPI *Read)(struct EFI_FILE_PROTOCOL *This, UINTN *Size, void *Buffer); + EFI_STATUS (EFIAPI *Write)(struct EFI_FILE_PROTOCOL *This, UINTN *Size, void *Buffer); + EFI_STATUS (EFIAPI *GetPosition)(struct EFI_FILE_PROTOCOL *This, uint64_t *Position); + EFI_STATUS (EFIAPI *SetPosition)(struct EFI_FILE_PROTOCOL *This, uint64_t Position); +} EFI_FILE_PROTOCOL; + +typedef struct EFI_SIMPLE_FILE_SYSTEM_PROTOCOL { + uint64_t Revision; + EFI_STATUS (EFIAPI *OpenVolume)(struct EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *This, EFI_FILE_PROTOCOL **Root); +} EFI_SIMPLE_FILE_SYSTEM_PROTOCOL; + +/* graphics */ +enum { PixelRedGreenBlueReserved8BitPerColor, PixelBlueGreenRedReserved8BitPerColor, + PixelBitMask, PixelBltOnly }; + +typedef struct { + uint32_t Version, HorizontalResolution, VerticalResolution; + int PixelFormat; + uint32_t RedMask, GreenMask, BlueMask, ReservedMask; + uint32_t PixelsPerScanLine; +} EFI_GRAPHICS_OUTPUT_MODE_INFORMATION; + +typedef struct { + uint32_t MaxMode, Mode; + EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info; + UINTN SizeOfInfo; + uint64_t FrameBufferBase; + UINTN FrameBufferSize; +} EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE; + +typedef struct EFI_GRAPHICS_OUTPUT_PROTOCOL { + EFI_STATUS (EFIAPI *QueryMode)(struct EFI_GRAPHICS_OUTPUT_PROTOCOL *This, uint32_t Mode, + UINTN *SizeOfInfo, EFI_GRAPHICS_OUTPUT_MODE_INFORMATION **Info); + EFI_STATUS (EFIAPI *SetMode)(struct EFI_GRAPHICS_OUTPUT_PROTOCOL *This, uint32_t Mode); + /* pixels are { blue, green, red, reserved }; operation 0 = fill */ + EFI_STATUS (EFIAPI *Blt)(struct EFI_GRAPHICS_OUTPUT_PROTOCOL *This, uint32_t *Buffer, int Operation, + UINTN SrcX, UINTN SrcY, UINTN DstX, UINTN DstY, UINTN Width, + UINTN Height, UINTN Delta); + EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE *Mode; +} EFI_GRAPHICS_OUTPUT_PROTOCOL; + +/* UGA (EFI 1.1 graphics, before GOP; older Apple firmware) */ +typedef struct EFI_UGA_DRAW_PROTOCOL { + EFI_STATUS (EFIAPI *GetMode)(struct EFI_UGA_DRAW_PROTOCOL *This, uint32_t *Width, + uint32_t *Height, uint32_t *Depth, uint32_t *Refresh); + void *SetMode; + EFI_STATUS (EFIAPI *Blt)(struct EFI_UGA_DRAW_PROTOCOL *This, uint32_t *Buffer, int Operation, + UINTN SrcX, UINTN SrcY, UINTN DstX, UINTN DstY, UINTN Width, + UINTN Height, UINTN Delta); +} EFI_UGA_DRAW_PROTOCOL; + +/* Apple's console control: the firmware console starts in graphics mode */ +typedef struct EFI_CONSOLE_CONTROL_PROTOCOL { + EFI_STATUS (EFIAPI *GetMode)(struct EFI_CONSOLE_CONTROL_PROTOCOL *This, int *Mode, + uint8_t *GopExists, uint8_t *StdInLocked); + EFI_STATUS (EFIAPI *SetMode)(struct EFI_CONSOLE_CONTROL_PROTOCOL *This, int Mode); + void *LockStdIn; +} EFI_CONSOLE_CONTROL_PROTOCOL; + +#endif diff --git a/mdvmm/uefi/efi.ld b/mdvmm/uefi/efi.ld new file mode 100644 index 00000000..78f15680 --- /dev/null +++ b/mdvmm/uefi/efi.ld @@ -0,0 +1,9 @@ +/* BOOTX64.EFI: PE32+ from ELF objects (ld -m i386pep) */ +SECTIONS +{ + . = 0x10001000; + .text : { *(.text*) *(.rodata*) } + . = ALIGN(4096); + .data : { *(.data*) *(.bss*) *(COMMON) } + /DISCARD/ : { *(.comment) *(.note*) *(.eh_frame*) } +} diff --git a/mdvmm/uefi/hwinfo.c b/mdvmm/uefi/hwinfo.c new file mode 100644 index 00000000..8ce5c23b --- /dev/null +++ b/mdvmm/uefi/hwinfo.c @@ -0,0 +1,333 @@ +/* BOOTX64.EFI - hardware report + * + * Before the monitor starts, the loader writes \MDOS\HWINFO.TXT to + * the boot volume (if it is writable): the firmware, the model (SMBIOS), + * the CPU, graphics (GOP and UGA), every PCI device with its BARs, the + * EFI configuration tables and the memory map. It is how drivers for a + * real machine get written without access to it. + */ +#include "efi.h" + +#define REPORT_MAX 65536 + +static char *rep; +static UINTN len; + +static void put(const char *s) +{ + while (*s && len < REPORT_MAX - 1) + rep[len++] = *s++; +} + +static void putc_(char c) +{ + if (len < REPORT_MAX - 1) + rep[len++] = c; +} + +static void hex(uint64_t v, int digits) +{ + int i; + for (i = digits - 1; i >= 0; i--) + putc_("0123456789abcdef"[(v >> (i * 4)) & 15]); +} + +static void dec(uint64_t v) +{ + char b[24]; + int i = 0; + do + b[i++] = (char)('0' + v % 10); + while ((v /= 10) && i < 23); + while (i) + putc_(b[--i]); +} + +static void put16(const CHAR16 *s) +{ + for (; s && *s; s++) + putc_(*s < 128 ? (char)*s : '?'); +} + +static void nl(void) +{ + put("\r\n"); +} + +static void guid(const EFI_GUID *g) +{ + int i; + hex(g->d1, 8); putc_('-'); hex(g->d2, 4); putc_('-'); hex(g->d3, 4); putc_('-'); + for (i = 0; i < 8; i++) + { + if (i == 2) + putc_('-'); + hex(g->d4[i], 2); + } +} + +static int guid_eq(const EFI_GUID *a, const EFI_GUID *b) +{ + const uint8_t *x = (const uint8_t *)a, *y = (const uint8_t *)b; + int i; + for (i = 0; i < 16; i++) + if (x[i] != y[i]) + return 0; + return 1; +} + +/* ---------------------------------------------------------------- */ + +static inline void outl(uint16_t p, uint32_t v) { __asm__ volatile("outl %0,%1" :: "a"(v), "Nd"(p)); } +static inline uint32_t inl(uint16_t p) { uint32_t v; __asm__ volatile("inl %1,%0" : "=a"(v) : "Nd"(p)); return v; } + +static uint32_t pci(int bus, int dev, int fn, int reg) +{ + outl(0xcf8, 0x80000000u | (uint32_t)bus << 16 | (uint32_t)dev << 11 | (uint32_t)fn << 8 | (reg & 0xfc)); + return inl(0xcfc); +} + +static void pci_devices(void) +{ + int bus, dev, fn, i; + + put("PCI devices (bus:dev.fn vendor:device class rev subsystem)"); nl(); + for (bus = 0; bus < 256; bus++) + for (dev = 0; dev < 32; dev++) + for (fn = 0; fn < 8; fn++) + { + uint32_t id = pci(bus, dev, fn, 0), cls, hdr; + if ((id & 0xffff) == 0xffff) + { + if (fn == 0) + break; + continue; + } + cls = pci(bus, dev, fn, 8); + hdr = pci(bus, dev, fn, 0x0c); + put(" "); hex(bus, 2); putc_(':'); hex(dev, 2); putc_('.'); hex(fn, 1); + put(" "); hex(id & 0xffff, 4); putc_(':'); hex(id >> 16, 4); + put(" class "); hex(cls >> 8, 6); put(" rev "); hex(cls & 0xff, 2); + if (((hdr >> 16) & 0x7f) == 0) + { + uint32_t sub = pci(bus, dev, fn, 0x2c); + put(" sub "); hex(sub & 0xffff, 4); putc_(':'); hex(sub >> 16, 4); + nl(); + put(" BARs"); + for (i = 0; i < 6; i++) + { + putc_(' '); + hex(pci(bus, dev, fn, 0x10 + i * 4), 8); + } + put(" irq "); dec(pci(bus, dev, fn, 0x3c) & 0xff); + } + nl(); + if (fn == 0 && !(hdr & 0x00800000)) + break; + } +} + +static void cpu(void) +{ + uint32_t r[12], a, b, c, d; + int i; + + __asm__ volatile("cpuid" : "=a"(a), "=b"(b), "=c"(c), "=d"(d) : "a"(0x80000000)); + put("CPU: "); + if (a >= 0x80000004) + { + for (i = 0; i < 3; i++) + __asm__ volatile("cpuid" : "=a"(r[i * 4]), "=b"(r[i * 4 + 1]), "=c"(r[i * 4 + 2]), + "=d"(r[i * 4 + 3]) : "a"(0x80000002 + i)); + for (i = 0; i < 48; i++) + if (((char *)r)[i]) + putc_(((char *)r)[i]); + } + __asm__ volatile("cpuid" : "=a"(a), "=b"(b), "=c"(c), "=d"(d) : "a"(1)); + put(" (cpuid 1: eax "); hex(a, 8); put(" edx "); hex(d, 8); put(" ecx "); hex(c, 8); put(")"); + nl(); +} + +static UINTN slen(const char *p) +{ + UINTN n = 0; + while (p[n]) + n++; + return n; +} + +/* SMBIOS 2.x: string n of a structure */ +static const char *sm_string(const uint8_t *s, int n) +{ + const char *p = (const char *)s + s[1]; + if (!n) + return ""; + while (--n && *p) + p += slen(p) + 1; + return p; +} + +static void smbios(EFI_SYSTEM_TABLE *st) +{ + static EFI_GUID sm_guid = { 0xeb9d2d31, 0x2d88, 0x11d3, { 0x9a, 0x16, 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d } }; + const uint8_t *ep = 0, *t, *end; + UINTN i; + int n; + + for (i = 0; i < st->NumberOfTableEntries; i++) + if (guid_eq(&st->ConfigurationTable[i].VendorGuid, &sm_guid)) + ep = st->ConfigurationTable[i].VendorTable; + if (!ep || ep[0] != '_' || ep[1] != 'S' || ep[2] != 'M') + { + put("SMBIOS: none"); nl(); + return; + } + t = (const uint8_t *)(uintptr_t)*(const uint32_t *)(ep + 0x18); + end = t + *(const uint16_t *)(ep + 0x16); + for (n = 0; t + 4 <= end && n < 256; n++) + { + const uint8_t *next = t + t[1]; + if (t[0] == 0) + { + put("BIOS: "); put(sm_string(t, t[4])); put(", "); put(sm_string(t, t[5])); + put(", "); put(sm_string(t, t[8])); nl(); + } + else if (t[0] == 1) + { + put("System: "); put(sm_string(t, t[4])); put(" / "); put(sm_string(t, t[5])); + put(" / "); put(sm_string(t, t[6])); nl(); + } + else if (t[0] == 2) + { + put("Board: "); put(sm_string(t, t[4])); put(" / "); put(sm_string(t, t[5])); nl(); + } + else if (t[0] == 127) + break; + while (next + 1 < end && (next[0] || next[1])) /* skip the strings */ + next++; + t = next + 2; + } +} + +static void graphics(EFI_BOOT_SERVICES *bs) +{ + static EFI_GUID gop_guid = { 0x9042a9de, 0x23dc, 0x4a38, { 0x96, 0xfb, 0x7a, 0xde, 0xd0, 0x80, 0x51, 0x6a } }; + static EFI_GUID uga_guid = { 0x982c298b, 0xf4fa, 0x41cb, { 0xb8, 0x38, 0x77, 0xaa, 0x68, 0x8f, 0xb8, 0x39 } }; + EFI_GRAPHICS_OUTPUT_PROTOCOL *gop; + EFI_UGA_DRAW_PROTOCOL *uga; + uint32_t m; + + if (!bs->LocateProtocol(&gop_guid, 0, (void **)&gop) && gop->Mode) + { + put("GOP: mode "); dec(gop->Mode->Mode); put(" of "); dec(gop->Mode->MaxMode); + put(", framebuffer "); hex(gop->Mode->FrameBufferBase, 16); put(" size "); + hex(gop->Mode->FrameBufferSize, 8); nl(); + for (m = 0; m < gop->Mode->MaxMode && m < 32; m++) + { + EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *info; + UINTN size; + if (gop->QueryMode(gop, m, &size, &info)) + continue; + put(" mode "); dec(m); put(": "); dec(info->HorizontalResolution); putc_('x'); + dec(info->VerticalResolution); put(" format "); dec(info->PixelFormat); + put(" pitch "); dec(info->PixelsPerScanLine); nl(); + } + } + else + { + put("GOP: none"); nl(); + } + if (!bs->LocateProtocol(&uga_guid, 0, (void **)&uga)) + { + uint32_t w = 0, h = 0, d = 0, r = 0; + put("UGA: present"); + if (!uga->GetMode(uga, &w, &h, &d, &r)) + { + put(", "); dec(w); putc_('x'); dec(h); put(" depth "); dec(d); put(" refresh "); dec(r); + } + nl(); + } + else + { + put("UGA: none"); nl(); + } +} + +static void memory(EFI_BOOT_SERVICES *bs) +{ + static uint8_t map[32768]; + UINTN size = sizeof(map), key, dsize, i; + uint32_t ver; + uint64_t total = 0; + + if (bs->GetMemoryMap(&size, (EFI_MEMORY_DESCRIPTOR *)map, &key, &dsize, &ver)) + { + put("Memory map: unavailable"); nl(); + return; + } + put("Memory map (type start pages attributes)"); nl(); + for (i = 0; i + dsize <= size; i += dsize) + { + EFI_MEMORY_DESCRIPTOR *d = (EFI_MEMORY_DESCRIPTOR *)(map + i); + put(" "); dec(d->Type); put(" "); hex(d->PhysicalStart, 12); put(" "); dec(d->NumberOfPages); + put(" "); hex(d->Attribute, 16); nl(); + if (d->Type == EfiConventionalMemory || d->Type == EfiBootServicesCode || + d->Type == EfiBootServicesData || d->Type == EfiLoaderCode || d->Type == EfiLoaderData) + total += d->NumberOfPages * 4096; + } + put("Usable memory: "); dec(total >> 20); put(" MB"); nl(); +} + +/* (re)write the report so far; 0 on success */ +static int save(EFI_FILE_PROTOCOL *root) +{ + EFI_FILE_PROTOCOL *f; + UINTN n = len; + EFI_STATUS s; + + if (!root->Open(root, &f, (CHAR16 *)u"\\MDOS\\HWINFO.TXT", EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE, 0)) + f->Delete(f); + if (root->Open(root, &f, (CHAR16 *)u"\\MDOS\\HWINFO.TXT", + EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE, 0)) + return -1; + s = f->Write(f, &n, rep); + f->Close(f); + return s || n != len ? -1 : 0; +} + +/* write the report to \MDOS\HWINFO.TXT; 0 on success. It is saved + after every section, the most useful ones first: if a section hangs + on some firmware, the rest is on the disk already. */ +int hwinfo_write(EFI_HANDLE image, EFI_SYSTEM_TABLE *st, EFI_FILE_PROTOCOL *root) +{ + EFI_BOOT_SERVICES *bs = st->BootServices; + uint64_t buf = 0xffffffffull; + UINTN i; + + (void)image; + if (bs->AllocatePages(AllocateMaxAddress, EfiLoaderData, REPORT_MAX / 4096, &buf)) + return -1; + rep = (char *)(uintptr_t)buf; + len = 0; + put("modernDOS hardware report (BOOTX64.EFI)"); nl(); + put("Firmware: "); put16(st->FirmwareVendor); put(" revision "); hex(st->FirmwareRevision, 8); + put(", EFI "); dec(st->Hdr.Revision >> 16); putc_('.'); dec((st->Hdr.Revision & 0xffff) / 10); + nl(); + if (save(root)) + return -1; /* read-only medium */ + pci_devices(); + save(root); + graphics(bs); + save(root); + cpu(); + smbios(st); + save(root); + put("EFI configuration tables"); nl(); + for (i = 0; i < st->NumberOfTableEntries; i++) + { + put(" "); guid(&st->ConfigurationTable[i].VendorGuid); nl(); + } + memory(bs); + put("End of report"); nl(); + return save(root); +} diff --git a/mdvmm/uefi/install.c b/mdvmm/uefi/install.c new file mode 100644 index 00000000..6e544617 --- /dev/null +++ b/mdvmm/uefi/install.c @@ -0,0 +1,314 @@ +/* BOOTX64.EFI - installing on the internal disk, and trial boots + * + * Install: started from a stick that has \MDOS\INSTALL, the loader + * offers to copy modernDOS to a writable FAT volume of the machine (the + * EFI system partition of its disk): \EFI\BOOT\BOOTX64.EFI and the files + * of \MDOS. Nothing else on that disk is touched. The firmware's own + * file system driver does the writing. On Apple firmware the loader then + * asks the firmware to start that file by default. + * + * Trial boots (updating a machine nobody sits at): a new build is put in + * \MDOS\TRY (BOOTX64.EFI, BOOT.IMG) together with the file + * \MDOS\TRYONCE. The installed loader removes TRYONCE and starts the + * loader in TRY, once. That one boots TRY\BOOT.IMG and tells the monitor + * it is a trial: unless the trial is confirmed (MDSYS KEEP), the monitor + * restarts the machine after ten minutes, and the installed build is back. + */ +#include "efi.h" +#include "loader.h" + +static EFI_GUID loaded_image_guid = { 0x5b1b31a1, 0x9562, 0x11d2, { 0x8e, 0x3f, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }; +static EFI_GUID simple_fs_guid = { 0x964e5b22, 0x6459, 0x11d2, { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }; +static EFI_GUID device_path_guid = { 0x09576e91, 0x6d3f, 0x11d2, { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }; +static EFI_GUID apple_boot_guid = { 0x7c436110, 0xab2a, 0x4bbb, { 0xa8, 0x80, 0xfe, 0x41, 0x99, 0x5c, 0x9f, 0x82 } }; + +#define MODE_RW (EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE) +#define MODE_NEW (MODE_RW | EFI_FILE_MODE_CREATE) +#define ATTR_DIR 0x10ull + +static EFI_BOOT_SERVICES *bs; + +static EFI_FILE_PROTOCOL *volume(EFI_HANDLE dev) +{ + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *fs; + EFI_FILE_PROTOCOL *root; + + if (bs->HandleProtocol(dev, &simple_fs_guid, (void **)&fs) || fs->OpenVolume(fs, &root)) + return 0; + return root; +} + +static int exists(EFI_FILE_PROTOCOL *root, const CHAR16 *name) +{ + EFI_FILE_PROTOCOL *f; + + if (root->Open(root, &f, (CHAR16 *)name, EFI_FILE_MODE_READ, 0)) + return 0; + f->Close(f); + return 1; +} + +static void remove(EFI_FILE_PROTOCOL *root, const CHAR16 *name) +{ + EFI_FILE_PROTOCOL *f; + + if (!root->Open(root, &f, (CHAR16 *)name, MODE_RW, 0)) + f->Delete(f); +} + +/* a whole file into pages; 0 on success */ +static EFI_STATUS read_file(EFI_FILE_PROTOCOL *root, const CHAR16 *name, uint64_t *addr, UINTN *size) +{ + EFI_FILE_PROTOCOL *f; + EFI_STATUS s; + uint64_t end; + + if ((s = root->Open(root, &f, (CHAR16 *)name, EFI_FILE_MODE_READ, 0))) + return s; + f->SetPosition(f, ~0ull); + f->GetPosition(f, &end); + f->SetPosition(f, 0); + *size = end; + *addr = 0xffffffffull; + if (!(s = bs->AllocatePages(AllocateMaxAddress, EfiLoaderData, (end + 4095) / 4096 + 1, addr))) + s = f->Read(f, size, (void *)*addr); + f->Close(f); + return s ? s : *size != end; +} + +static EFI_STATUS write_file(EFI_FILE_PROTOCOL *root, const CHAR16 *name, const void *data, UINTN size) +{ + EFI_FILE_PROTOCOL *f; + EFI_STATUS s; + UINTN n = size; + + remove(root, name); + if ((s = root->Open(root, &f, (CHAR16 *)name, MODE_NEW, 0))) + return s; + s = n ? f->Write(f, &n, (void *)data) : 0; + f->Close(f); + return s ? s : n != size; +} + +static void make_dir(EFI_FILE_PROTOCOL *root, const CHAR16 *name) +{ + EFI_FILE_PROTOCOL *f; + + if (!root->Open(root, &f, (CHAR16 *)name, MODE_NEW, ATTR_DIR)) + f->Close(f); +} + +/* ---------------------------------------------------------------- */ + +/* Started by the installed loader as a trial? (its load options say so) */ +int is_trial(EFI_HANDLE image, EFI_SYSTEM_TABLE *st) +{ + EFI_LOADED_IMAGE_PROTOCOL *li; + const CHAR16 *o; + + bs = st->BootServices; + if (bs->HandleProtocol(image, &loaded_image_guid, (void **)&li) || li->LoadOptionsSize < 8) + return 0; + o = li->LoadOptions; + return o && o[0] == 'T' && o[1] == 'R' && o[2] == 'Y' && o[3] == 0; +} + +/* A trial waiting? Start it; only returns if there is none (or it failed) */ +void trial_boot(EFI_HANDLE image, EFI_SYSTEM_TABLE *st) +{ + static CHAR16 options[] = u"TRY"; + EFI_LOADED_IMAGE_PROTOCOL *li, *li2; + EFI_FILE_PROTOCOL *root; + EFI_HANDLE child; + uint64_t addr; + UINTN size; + EFI_STATUS s; + + bs = st->BootServices; + if (is_trial(image, st) || bs->HandleProtocol(image, &loaded_image_guid, (void **)&li) || + !(root = volume(li->DeviceHandle))) + return; + if (!exists(root, u"\\MDOS\\TRYONCE")) + { + root->Close(root); + return; + } + remove(root, u"\\MDOS\\TRYONCE"); /* once: the next boot is normal again */ + if (exists(root, u"\\MDOS\\TRYONCE")) + { + print(u"Trial boot: cannot remove \\MDOS\\TRYONCE (read-only volume): not started\r\n"); + root->Close(root); + return; + } + print(u"Trial boot: starting \\MDOS\\TRY\\BOOTX64.EFI\r\n"); + s = read_file(root, u"\\MDOS\\TRY\\BOOTX64.EFI", &addr, &size); + root->Close(root); + if (!s) + s = bs->LoadImage(0, image, 0, (void *)addr, size, &child); + if (!s && !(s = bs->HandleProtocol(child, &loaded_image_guid, (void **)&li2))) + { + li2->DeviceHandle = li->DeviceHandle; /* its files are on our volume */ + li2->LoadOptions = options; + li2->LoadOptionsSize = sizeof(options); + save_log(); + s = bs->StartImage(child, 0, 0); + } + print(u"Trial boot: failed (status "); + print_hex(s); + print(u"), starting the installed system\r\n"); +} + +/* ---------------------------------------------------------------- */ + +static int ask_yes(EFI_SYSTEM_TABLE *st) +{ + EFI_INPUT_KEY key; + int i; + + for (i = 0; i < 6000; i++) /* 60 seconds */ + { + if (!st->ConIn->ReadKeyStroke(st->ConIn, &key)) + return key.UnicodeChar == 'y' || key.UnicodeChar == 'Y'; + bs->Stall(10000); + } + return 0; +} + +static EFI_STATUS copy(EFI_FILE_PROTOCOL *from, EFI_FILE_PROTOCOL *to, const CHAR16 *src, const CHAR16 *dst) +{ + uint64_t addr; + UINTN size; + EFI_STATUS s = read_file(from, src, &addr, &size); + + if (!s) + { + s = write_file(to, dst, (void *)addr, size); + bs->FreePages(addr, (size + 4095) / 4096 + 1); + } + print(s ? u" FAILED " : u" copied "); + print(dst); + print(u"\r\n"); + return s; +} + +/* Apple firmware: start \EFI\BOOT\BOOTX64.EFI of that volume by default + (what "bless --setBoot" does): the variable holds its device path */ +static void apple_default(EFI_SYSTEM_TABLE *st, EFI_HANDLE dev) +{ + static const CHAR16 file[] = u"\\EFI\\BOOT\\BOOTX64.EFI"; + static uint8_t path[1024]; + EFI_DEVICE_PATH *dp, *n; + UINTN len = 0, flen = sizeof(file); + EFI_STATUS s; + + if (bs->HandleProtocol(dev, &device_path_guid, (void **)&dp)) + return; + for (n = dp; n->Type != 0x7f; n = (EFI_DEVICE_PATH *)((uint8_t *)n + (n->Length[0] | n->Length[1] << 8))) + if (!(n->Length[0] | n->Length[1] << 8)) + return; + len = (UINTN)((uint8_t *)n - (uint8_t *)dp); + if (len + 4 + flen + 4 > sizeof(path)) + return; + memcpy(path, dp, len); + path[len] = 4; /* media device path: file path */ + path[len + 1] = 4; + path[len + 2] = (uint8_t)(4 + flen); + path[len + 3] = (uint8_t)((4 + flen) >> 8); + memcpy(path + len + 4, file, flen); + len += 4 + flen; + path[len] = 0x7f; /* end of the path */ + path[len + 1] = 0xff; + path[len + 2] = 4; + path[len + 3] = 0; + len += 4; + s = st->RuntimeServices->SetVariable(u"efi-boot-device-data", &apple_boot_guid, + EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, + len, path); + print(s ? u"The firmware did not take the default start entry (hold Option at power-on, pick EFI Boot).\r\n" + : u"Set as the firmware's default start entry.\r\n"); +} + +/* \MDOS\INSTALL on the boot volume: offer to install */ +void install_offer(EFI_HANDLE image, EFI_SYSTEM_TABLE *st) +{ + EFI_LOADED_IMAGE_PROTOCOL *li; + EFI_FILE_PROTOCOL *src, *dst = 0; + EFI_HANDLE *handles, target = 0; + UINTN count, i; + int apple, bad = 0; + + bs = st->BootServices; + if (bs->HandleProtocol(image, &loaded_image_guid, (void **)&li) || !(src = volume(li->DeviceHandle))) + return; + if (!exists(src, u"\\MDOS\\INSTALL") || + bs->LocateHandleBuffer(2 /* ByProtocol */, &simple_fs_guid, 0, &count, &handles)) + { + src->Close(src); + return; + } + /* the first other volume that can be written (FAT; firmware reads + HFS+ and others only) */ + for (i = 0; i < count && !target; i++) + { + EFI_FILE_PROTOCOL *root, *f; + if (handles[i] == li->DeviceHandle || !(root = volume(handles[i]))) + continue; + if (!root->Open(root, &f, (CHAR16 *)u"\\MDTEST.TMP", MODE_NEW, 0)) + { + f->Delete(f); + target = handles[i]; + dst = root; + } + else + root->Close(root); + } + if (!target) + { + print(u"Install: no writable FAT volume (EFI system partition) found on this machine.\r\n"); + src->Close(src); + return; + } + print(u"\r\nINSTALL modernDOS on this machine's disk?\r\n" + u" It adds \\EFI\\BOOT\\BOOTX64.EFI and the folder \\MDOS to the EFI system\r\n" + u" partition"); + print(exists(dst, u"\\MDOS\\BOOT.IMG") ? u" (modernDOS is there already: it is replaced)" : u""); + print(u". Nothing else on the disk is changed.\r\n" + u" Press Y to install, any other key to just start from the stick (60 s): "); + if (!ask_yes(st)) + { + print(u"no\r\n"); + goto out; + } + print(u"yes\r\n"); + make_dir(dst, u"\\EFI"); + make_dir(dst, u"\\EFI\\BOOT"); + make_dir(dst, u"\\MDOS"); + /* another system's fallback loader: keep it */ + if (exists(dst, u"\\EFI\\BOOT\\BOOTX64.EFI") && !exists(dst, u"\\MDOS\\BOOT.IMG") && + !exists(dst, u"\\EFI\\BOOT\\BOOTX64.OLD")) + copy(dst, dst, u"\\EFI\\BOOT\\BOOTX64.EFI", u"\\EFI\\BOOT\\BOOTX64.OLD"); + bad |= copy(src, dst, u"\\MDOS\\BOOT.IMG", u"\\MDOS\\BOOT.IMG") != 0; + bad |= copy(src, dst, u"\\EFI\\BOOT\\BOOTX64.EFI", u"\\EFI\\BOOT\\BOOTX64.EFI") != 0; + if (exists(src, u"\\MDOS\\BOOTWAIT")) + copy(src, dst, u"\\MDOS\\BOOTWAIT", u"\\MDOS\\BOOTWAIT"); + /* DOS may write to the disk: C: (this partition) keeps the settings */ + bad |= write_file(dst, u"\\MDOS\\DISKRW", "modernDOS may write to the hard disks\r\n", 38) != 0; + remove(dst, u"\\MDOS\\TRYONCE"); + if (bad) + print(u"Install: FAILED, the machine's disk may hold a part of modernDOS.\r\n"); + else + { + print(u"Installed.\r\n"); + apple = st->FirmwareVendor && st->FirmwareVendor[0] == 'A' && st->FirmwareVendor[1] == 'p'; + if (apple) + apple_default(st, target); + print(u"Remove the stick and switch the machine off and on to start from its disk.\r\n" + u"Starting from the stick in 15 seconds...\r\n"); + save_log(); + bs->Stall(15000000); + } +out: + dst->Close(dst); + src->Close(src); + save_log(); +} diff --git a/mdvmm/uefi/loader.h b/mdvmm/uefi/loader.h new file mode 100644 index 00000000..1622c570 --- /dev/null +++ b/mdvmm/uefi/loader.h @@ -0,0 +1,20 @@ +/* BOOTX64.EFI: shared between its source files */ +#ifndef MDVMM_LOADER_H +#define MDVMM_LOADER_H +#include "efi.h" + +void *memcpy(void *d, const void *s, size_t n); +void *memset(void *d, int c, size_t n); + +/* main.c: console output that is also kept for \MDOS\BOOTLOG.TXT */ +void print(const CHAR16 *s); +void print_hex(uint64_t v); +void print_dec(uint64_t v); +void save_log(void); + +/* install.c */ +int is_trial(EFI_HANDLE image, EFI_SYSTEM_TABLE *st); +void trial_boot(EFI_HANDLE image, EFI_SYSTEM_TABLE *st); +void install_offer(EFI_HANDLE image, EFI_SYSTEM_TABLE *st); + +#endif diff --git a/mdvmm/uefi/main.c b/mdvmm/uefi/main.c new file mode 100644 index 00000000..6fb13052 --- /dev/null +++ b/mdvmm/uefi/main.c @@ -0,0 +1,699 @@ +/* BOOTX64.EFI - UEFI loader for the modernDOS virtual machine monitor + * + * Reads the DOS boot disk image \MDOS\BOOT.IMG from the boot volume, + * takes the GOP framebuffer and a memory pool below 4GB, copies the MDVMM + * core (embedded, start.asm) into the pool, exits boot services and starts + * the core in 32-bit protected mode (enter_core, start.asm). The core then + * provides a PC BIOS and boots DOS from the disk image in V86 mode. + * + * Built position independent (no absolute relocations): the firmware may + * load the image anywhere. + */ +#include "efi.h" +#include "loader.h" +#include "bootinfo.h" + +#define POOL_MB_MAX 32 +#define POOL_MB_MIN 8 +#define XMS_MB_MAX 64 /* DOS extended memory */ +#define XMS_MB_MIN 1 +#define BOOT_IMAGE u"\\MDOS\\BOOT.IMG" +#define TRIAL_IMAGE u"\\MDOS\\TRY\\BOOT.IMG" +#define DISK_RW_FILE u"\\MDOS\\DISKRW" /* present: disks writable */ +#define BOOTWAIT_FILE u"\\MDOS\\BOOTWAIT" /* present: the core's log stays a while */ +#define FBPROBE_FILE u"\\MDOS\\FBPROBE" /* present: probe the framebuffer (tests) */ +#define NONET_FILE u"\\MDOS\\NONET" /* present: no network card drivers */ +#define LOG_FILE u"\\MDOS\\BOOTLOG.TXT" + +extern const uint8_t core_image[], core_image_end[]; +void enter_core(uint64_t low, uint64_t bootinfo, uint64_t pool) __attribute__((noreturn)); +int hwinfo_write(EFI_HANDLE image, EFI_SYSTEM_TABLE *st, EFI_FILE_PROTOCOL *root); + +static EFI_SYSTEM_TABLE *st; +static EFI_BOOT_SERVICES *bs; +static uint8_t map_buf[32768]; + +static EFI_GUID loaded_image_guid = { 0x5b1b31a1, 0x9562, 0x11d2, { 0x8e, 0x3f, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }; +static EFI_GUID simple_fs_guid = { 0x964e5b22, 0x6459, 0x11d2, { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }; +static EFI_GUID gop_guid = { 0x9042a9de, 0x23dc, 0x4a38, { 0x96, 0xfb, 0x7a, 0xde, 0xd0, 0x80, 0x51, 0x6a } }; +static EFI_GUID uga_guid = { 0x982c298b, 0xf4fa, 0x41cb, { 0xb8, 0x38, 0x77, 0xaa, 0x68, 0x8f, 0xb8, 0x39 } }; +static EFI_GUID conctl_guid = { 0xf42f7782, 0x012e, 0x4c12, { 0x99, 0x56, 0x49, 0xf9, 0x43, 0x04, 0xf7, 0x21 } }; +static EFI_GUID acpi20_guid = { 0x8868e871, 0xe4f1, 0x11d3, { 0xbc, 0x22, 0x00, 0x80, 0xc7, 0x3c, 0x88, 0x81 } }; + +/* the compiler may emit calls to these */ +void *memcpy(void *d, const void *s, size_t n) +{ + uint8_t *dp = d; + const uint8_t *sp = s; + while (n--) + *dp++ = *sp++; + return d; +} +void *memset(void *d, int c, size_t n) +{ + uint8_t *dp = d; + while (n--) + *dp++ = (uint8_t)c; + return d; +} + +static int guid_eq(const EFI_GUID *a, const EFI_GUID *b) +{ + const uint8_t *x = (const uint8_t *)a, *y = (const uint8_t *)b; + int i; + for (i = 0; i < 16; i++) + if (x[i] != y[i]) + return 0; + return 1; +} + +/* everything printed is also kept for \MDOS\BOOTLOG.TXT: on some + machines (Apple) the firmware's text console may not be visible */ +static char logbuf[6000]; +static UINTN loglen; +static EFI_HANDLE img; + +void print(const CHAR16 *s) +{ + const CHAR16 *c; + + for (c = s; *c; c++) + if (loglen < sizeof(logbuf)) + logbuf[loglen++] = *c < 128 ? (char)*c : '?'; + st->ConOut->OutputString(st->ConOut, (CHAR16 *)s); +} + +void print_dec(uint64_t v) +{ + CHAR16 buf[24]; + int i = 23; + + buf[i] = 0; + do + buf[--i] = (CHAR16)('0' + v % 10); + while (v /= 10); + print(buf + i); +} + +/* write the log so far to the boot volume (if it is writable) */ +void save_log(void) +{ + EFI_LOADED_IMAGE_PROTOCOL *li; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *fs; + EFI_FILE_PROTOCOL *root, *f; + UINTN n = loglen; + + if (bs->HandleProtocol(img, &loaded_image_guid, (void **)&li) || + bs->HandleProtocol(li->DeviceHandle, &simple_fs_guid, (void **)&fs) || + fs->OpenVolume(fs, &root)) + return; + if (!root->Open(root, &f, (CHAR16 *)LOG_FILE, EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE, 0)) + f->Delete(f); + if (!root->Open(root, &f, (CHAR16 *)LOG_FILE, + EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE, 0)) + { + f->Write(f, &n, logbuf); + f->Close(f); + } + root->Close(root); +} + +void print_hex(uint64_t v) +{ + CHAR16 buf[19]; + int i; + buf[0] = '0'; + buf[1] = 'x'; + for (i = 0; i < 16; i++) + buf[2 + i] = (CHAR16)"0123456789ABCDEF"[(v >> (60 - 4 * i)) & 15]; + buf[18] = 0; + print(buf); +} + +static EFI_STATUS fail(const CHAR16 *what, EFI_STATUS s) +{ + print(u"MDVMM: "); + print(what); + print(u" (status "); + print_hex(s); + print(u")\r\n"); + save_log(); + return s; +} + +/* read the whole file into pages below 4GB, above the V86 address space */ +/* does the file exist on the boot volume? */ +static int file_exists(EFI_HANDLE image, const CHAR16 *name) +{ + EFI_LOADED_IMAGE_PROTOCOL *li; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *fs; + EFI_FILE_PROTOCOL *root, *file; + + if (bs->HandleProtocol(image, &loaded_image_guid, (void **)&li) || + bs->HandleProtocol(li->DeviceHandle, &simple_fs_guid, (void **)&fs) || + fs->OpenVolume(fs, &root)) + return 0; + if (root->Open(root, &file, (CHAR16 *)name, EFI_FILE_MODE_READ, 0)) + { + root->Close(root); + return 0; + } + file->Close(file); + root->Close(root); + return 1; +} + +static EFI_STATUS load_file(EFI_HANDLE image, const CHAR16 *name, uint64_t *addr, uint64_t *size) +{ + EFI_LOADED_IMAGE_PROTOCOL *li; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *fs; + EFI_FILE_PROTOCOL *root, *file; + EFI_STATUS s; + UINTN n; + + if ((s = bs->HandleProtocol(image, &loaded_image_guid, (void **)&li)) || + (s = bs->HandleProtocol(li->DeviceHandle, &simple_fs_guid, (void **)&fs)) || + (s = fs->OpenVolume(fs, &root))) + return fail(u"cannot open the boot volume", s); + if ((s = root->Open(root, &file, (CHAR16 *)name, EFI_FILE_MODE_READ, 0))) + return fail(u"cannot open \\MDOS\\BOOT.IMG", s); + file->SetPosition(file, ~0ull); + file->GetPosition(file, size); + file->SetPosition(file, 0); + *addr = 0xffffffffull; + if ((s = bs->AllocatePages(AllocateMaxAddress, EfiLoaderData, (*size + 4095) / 4096, addr))) + return fail(u"no memory for the disk image", s); + n = *size; + if ((s = file->Read(file, &n, (void *)*addr)) || n != *size) + return fail(u"cannot read the disk image", s); + file->Close(file); + root->Close(root); + return EFI_SUCCESS; +} + +/* ---------------------------------------------------------------- */ +/* the framebuffer */ + +static inline void outl(uint16_t p, uint32_t v) { __asm__ volatile("outl %0,%1" :: "a"(v), "Nd"(p)); } +static inline uint32_t inl(uint16_t p) { uint32_t v; __asm__ volatile("inl %1,%0" : "=a"(v) : "Nd"(p)); return v; } + +static uint32_t pci_rd(int bus, int dev, int fn, int reg) +{ + outl(0xcf8, 0x80000000u | (uint32_t)bus << 16 | (uint32_t)dev << 11 | (uint32_t)fn << 8 | (reg & 0xfc)); + return inl(0xcfc); +} + +static void pci_wr(int bus, int dev, int fn, int reg, uint32_t v) +{ + outl(0xcf8, 0x80000000u | (uint32_t)bus << 16 | (uint32_t)dev << 11 | (uint32_t)fn << 8 | (reg & 0xfc)); + outl(0xcfc, v); +} + +/* Where does the screen live in memory? UGA (EFI 1.1, older Apple + firmware) can draw and read pixels but does not say. Two independent + ways to find out, both through the memory BARs of the display + controllers: + scan: fill the screen with one colour and rows 1 and 3 with another, + then look for those rows in the video memory; their distance + gives the length of a scan line, their place the address of + pixel (0,0) + poke: write a marker into the video memory, page by page, and ask + the firmware to read pixel (0,0); then the same for (0,1) + Apple's firmware may only draw in its "graphics" console mode, so both + are tried there first, then in text mode. Everything is logged. */ +#define COL_A 0x00102030u /* the screen */ +#define COL_B 0x00a1b2c3u /* rows 1 and 3 */ +#define COL_M 0x005a3c96u /* poked into memory */ + +struct vbar { uint32_t base, size; }; + +static EFI_GRAPHICS_OUTPUT_PROTOCOL *p_gop; +static EFI_UGA_DRAW_PROTOCOL *p_uga; +static EFI_CONSOLE_CONTROL_PROTOCOL *conctl; + +static EFI_STATUS blt(uint32_t *buf, int op, UINTN sx, UINTN sy, UINTN dx, UINTN dy, UINTN w, UINTN h) +{ + if (p_gop) + return p_gop->Blt(p_gop, buf, op, sx, sy, dx, dy, w, h, 0); + return p_uga->Blt(p_uga, buf, op, sx, sy, dx, dy, w, h, 0); +} + +static EFI_STATUS fill(uint32_t color, UINTN x, UINTN y, UINTN w, UINTN h) +{ + return blt(&color, 0, 0, 0, x, y, w, h); +} + +/* the pixel as the firmware reads it back, FFFFFFFFh if it can not */ +static uint32_t pixel(UINTN x, UINTN y) +{ + uint32_t v = 0; + + if (blt(&v, 1, x, y, 0, 0, 1, 1)) + return 0xffffffffu; + return v & 0xffffff; +} + +/* memory BARs (1 MB and more, below 4GB) of the display controllers */ +static int display_bars(struct vbar *out, int max) +{ + int bus, dev, fn, bar, n = 0; + + for (bus = 0; bus < 256; bus++) + for (dev = 0; dev < 32; dev++) + for (fn = 0; fn < 8; fn++) + { + uint32_t id = pci_rd(bus, dev, fn, 0), hdr; + if ((id & 0xffff) == 0xffff) + { + if (fn == 0) + break; + continue; + } + hdr = pci_rd(bus, dev, fn, 0x0c); + if ((pci_rd(bus, dev, fn, 8) >> 24) == 0x03 && ((hdr >> 16) & 0x7f) == 0) + for (bar = 0; bar < 6; bar++) + { + uint32_t lo = pci_rd(bus, dev, fn, 0x10 + bar * 4), size; + int is64 = (lo & 7) == 4, reg = 0x10 + bar * 4; + if (lo & 1) + continue; /* I/O ports */ + bar += is64; + if ((is64 && pci_rd(bus, dev, fn, reg + 4)) || !(lo & ~0xfu)) + continue; /* above 4GB, or not set */ + __asm__ volatile("cli"); + pci_wr(bus, dev, fn, reg, 0xffffffffu); + size = ~(pci_rd(bus, dev, fn, reg) & ~0xfu) + 1; + pci_wr(bus, dev, fn, reg, lo); + __asm__ volatile("sti"); + if (size < 0x100000 || (size & (size - 1)) || n == max) + continue; /* registers, not video memory */ + out[n].base = lo & ~0xfu; + out[n].size = size; + n++; + } + if (fn == 0 && !(hdr & 0x00800000)) + break; + } + return n; +} + +static int probe_scan(uint32_t w, const struct vbar *b, uint64_t *base, uint32_t *pitch) +{ + const volatile uint32_t *m = (const volatile uint32_t *)(uintptr_t)b->base; + uint32_t n = b->size / 4, i, j, lo, hi, r1 = 0, r3 = 0, run, p; + + /* coarse: some pixel of the filled screen, every 64 KB */ + for (i = 0; i < n && (m[i] & 0xffffff) != COL_A; i += 0x4000) + ; + if (i >= n) + return 0; + /* the marker rows are at the start of the screen: near that hit */ + lo = i > 0x6000 ? i - 0x6000 : 0; + hi = i + 0x6000 < n ? i + 0x6000 : n; + for (j = lo; j + w <= hi && !r3; j++) + { + if ((m[j] & 0xffffff) != COL_B) + continue; + for (run = 1; run <= w && j + run < hi && (m[j + run] & 0xffffff) == COL_B; run++) + ; + if (run == w) + { + if (!r1) + r1 = j + 1; /* + 1: 0 means none */ + else + r3 = j + 1; + } + j += run; + } + if (!r1 || !r3) + return 0; + r1--; + r3--; + p = (r3 - r1) / 2; + if ((r3 - r1) % 2 || p < w || p > 4 * w || r1 < p || + (m[r1 - p] & 0xffffff) != COL_A || (m[r1 + p] & 0xffffff) != COL_A) + return 0; + *base = (uint64_t)b->base + (uint64_t)(r1 - p) * 4; + *pitch = p; + return 1; +} + +static int probe_poke(uint32_t w, const struct vbar *b, uint64_t *base, uint32_t *pitch) +{ + volatile uint32_t *m = (volatile uint32_t *)(uintptr_t)b->base; + uint32_t limit = b->size < 0x2000000 ? b->size : 0x2000000, off, p, old; + int hit = 0; + + for (off = 0; off < limit && !hit; off += 0x1000) + { + old = m[off / 4]; + m[off / 4] = COL_M; + hit = pixel(0, 0) == COL_M; + m[off / 4] = old; + } + if (!hit) + return 0; + off -= 0x1000; + for (p = w; p <= w + 2048 && off + p * 4 < b->size; p++) + { + old = m[off / 4 + p]; + m[off / 4 + p] = COL_M; + hit = pixel(0, 1) == COL_M; + m[off / 4 + p] = old; + if (hit) + { + *base = (uint64_t)b->base + off; + *pitch = p; + return 1; + } + } + return 0; +} + +static void log_fb(const CHAR16 *how, uint64_t base, uint32_t w, uint32_t h, uint32_t pitch) +{ + print(how); + print(u": "); + print_dec(w); + print(u"x"); + print_dec(h); + print(u", framebuffer at "); + print_hex(base); + print(u", "); + print_dec(pitch); + print(u" pixels per line\r\n"); +} + +/* both probes; the results in *base, *pitch (scan preferred). `both`: + log each result (tests compare them with GOP). 1 if found. */ +static int fb_probe(uint32_t w, uint32_t h, uint64_t *base, uint32_t *pitch, int both) +{ + struct vbar bars[8]; + int n = display_bars(bars, 8), i, mode, found = 0; + uint64_t b2 = 0; + uint32_t p2 = 0; + + print(u"Framebuffer probe: "); + print_dec((uint64_t)n); + print(u" video memory area(s)"); + for (i = 0; i < n; i++) + { + print(u" "); + print_hex(bars[i].base); + print(u"+"); + print_hex(bars[i].size); + } + print(u"\r\n"); + /* mode 1: graphics console, mode 0: text console (Apple) */ + for (mode = 1; mode >= 0 && !found; mode--) + { + EFI_STATUS s1, s2; + uint32_t back; + if (conctl) + conctl->SetMode(conctl, mode); + else if (mode == 0) + break; /* no console modes: one pass */ + s1 = fill(COL_A, 0, 0, w, h); + s2 = fill(COL_B, 0, 1, w, 1); + fill(COL_B, 0, 3, w, 1); + back = pixel(0, 1); + for (i = 0; i < n && !found; i++) + { + int a = probe_scan(w, &bars[i], base, pitch); + int b = (!a || both) && probe_poke(w, &bars[i], &b2, &p2); + if (both && a) + log_fb(u"Framebuffer probe (scan)", *base, w, h, *pitch); + if (both && b) + log_fb(u"Framebuffer probe (poke)", b2, w, h, p2); + if (!a && b) + { + *base = b2; + *pitch = p2; + } + found = a || b; + if (conctl) + conctl->SetMode(conctl, 0); /* text again, to say it */ + print(conctl ? (mode ? u" graphics console" : u" text console") : u" console"); + print(u", area "); + print_dec((uint64_t)i); + print(u": fill status "); + print_hex(s1); + print(u"/"); + print_hex(s2); + print(u", pixel (0,1) reads "); + print_hex(back); + print(a ? u", scan found it" : u", scan: no"); + print(b ? u", poke found it\r\n" : (!a || both) ? u", poke: no\r\n" : u"\r\n"); + if (conctl && !found) + conctl->SetMode(conctl, mode); + } + if (conctl) + conctl->SetMode(conctl, 0); + } + return found; +} + +static void find_framebuffer(struct bootinfo *bi, int probe_test) +{ + EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *info; + uint32_t pitch = 0; + uint64_t base = 0; + + if (!bs->LocateProtocol(&gop_guid, 0, (void **)&p_gop) && p_gop->Mode) + { + EFI_GRAPHICS_OUTPUT_PROTOCOL *gop = p_gop; + info = gop->Mode->Info; + log_fb(u"Graphics (GOP)", gop->Mode->FrameBufferBase, info->HorizontalResolution, + info->VerticalResolution, info->PixelsPerScanLine); + if (probe_test) /* tests: the probes must agree with GOP */ + fb_probe(info->HorizontalResolution, info->VerticalResolution, &base, &pitch, 1); + if (gop->Mode->FrameBufferBase + gop->Mode->FrameBufferSize > 0x100000000ull || + (info->PixelFormat != PixelRedGreenBlueReserved8BitPerColor && + info->PixelFormat != PixelBlueGreenRedReserved8BitPerColor)) + { + print(u"MDVMM: framebuffer above 4GB or not 32 bpp, not used\r\n"); + return; + } + bi->fb_phys = (uint32_t)gop->Mode->FrameBufferBase; + bi->fb_size = (uint32_t)gop->Mode->FrameBufferSize; + bi->fb_width = info->HorizontalResolution; + bi->fb_height = info->VerticalResolution; + bi->fb_pitch = info->PixelsPerScanLine; + bi->fb_format = info->PixelFormat == PixelRedGreenBlueReserved8BitPerColor ? FB_RGBX : FB_BGRX; + return; + } + p_gop = 0; + /* EFI 1.1 graphics (older Apple firmware) */ + if (!bs->LocateProtocol(&uga_guid, 0, (void **)&p_uga)) + { + uint32_t w = 0, h = 0, depth = 0, refresh = 0; + if (p_uga->GetMode(p_uga, &w, &h, &depth, &refresh) || !w || !h) + { + print(u"MDVMM: UGA graphics without a mode, the screen stays dark\r\n"); + return; + } + print(u"Graphics (UGA): "); + print_dec(w); + print(u"x"); + print_dec(h); + print(u", depth "); + print_dec(depth); + print(u"\r\n"); + if (depth != 32 || !fb_probe(w, h, &base, &pitch, 0)) + { + print(u"MDVMM: framebuffer not found, the screen stays dark\r\n"); + return; + } + log_fb(u"Framebuffer found", base, w, h, pitch); + bi->fb_phys = (uint32_t)base; + bi->fb_size = pitch * 4 * h; + bi->fb_width = w; + bi->fb_height = h; + bi->fb_pitch = pitch; + bi->fb_format = FB_BGRX; + return; + } + print(u"MDVMM: no graphics output (no GOP, no UGA), the screen stays dark\r\n"); +} + +/* usable conventional memory: contiguous usable pages from 0 (after + ExitBootServices everything but runtime and reserved memory is ours) */ +static uint32_t conv_kb(UINTN map_size, UINTN desc_size) +{ + uint64_t addr = 0x1000; /* page 0 is often left out */ + int found = 1; + UINTN i; + + while (found && addr < 0xa0000) + { + found = 0; + for (i = 0; i + desc_size <= map_size; i += desc_size) + { + EFI_MEMORY_DESCRIPTOR *d = (EFI_MEMORY_DESCRIPTOR *)(map_buf + i); + uint64_t end = d->PhysicalStart + d->NumberOfPages * 4096; + int usable = d->Type == EfiConventionalMemory || d->Type == EfiLoaderCode || + d->Type == EfiLoaderData || d->Type == EfiBootServicesCode || + d->Type == EfiBootServicesData; + if (usable && d->PhysicalStart <= addr && end > addr) + { + addr = end; + found = 1; + } + } + } + if (addr > 0xa0000) + addr = 0xa0000; + return (uint32_t)(addr / 1024); +} + +EFI_STATUS EFIAPI efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *systab) +{ + struct bootinfo *bi; + uint64_t rd_addr, rd_size, pool, low, core_size = (uint64_t)(core_image_end - core_image); + uint32_t pool_mb, xms_mb, conv; + uint64_t xms = 0; + UINTN map_size, map_key, desc_size, i; + uint32_t desc_ver; + EFI_STATUS s; + + st = systab; + bs = st->BootServices; + img = image; + bs->SetWatchdogTimer(0, 0, 0, 0); + { + /* Apple firmware: show the text console (it starts in graphics mode) */ + if (!bs->LocateProtocol(&conctl_guid, 0, (void **)&conctl)) + conctl->SetMode(conctl, 0); + else + conctl = 0; + } + print(u"MDVMM - modernDOS virtual machine monitor (UEFI)\r\n"); + print(u"Firmware: "); + print(st->FirmwareVendor ? st->FirmwareVendor : u"?"); + print(u", EFI "); + print_dec(st->Hdr.Revision >> 16); + print(u"."); + print_dec(st->Hdr.Revision & 0xffff); + print(u"\r\n"); + + /* a new build waiting to be tried once? (does not return if started) */ + trial_boot(image, st); + if (is_trial(image, st)) + print(u"This is a TRIAL boot of \\MDOS\\TRY: confirm it with MDSYS KEEP, or the\r\n" + u"machine restarts into the installed system after ten minutes.\r\n"); + + /* the hardware report, first: it is most useful when something fails */ + { + EFI_LOADED_IMAGE_PROTOCOL *li; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *fs; + EFI_FILE_PROTOCOL *root; + if (!bs->HandleProtocol(image, &loaded_image_guid, (void **)&li) && + !bs->HandleProtocol(li->DeviceHandle, &simple_fs_guid, (void **)&fs) && + !fs->OpenVolume(fs, &root)) + { + if (!hwinfo_write(image, st, root)) + print(u"Hardware report written to \\MDOS\\HWINFO.TXT\r\n"); + else + print(u"Hardware report not written (read-only boot medium?)\r\n"); + root->Close(root); + } + else + print(u"Hardware report not written: cannot open the boot volume\r\n"); + } + save_log(); + if (!is_trial(image, st)) + install_offer(image, st); /* a stick with \MDOS\INSTALL */ + + if (load_file(image, is_trial(image, st) ? TRIAL_IMAGE : BOOT_IMAGE, &rd_addr, &rd_size)) + return 1; + + /* memory pool for the core: below 4GB */ + for (pool_mb = POOL_MB_MAX; pool_mb >= POOL_MB_MIN; pool_mb /= 2) + { + pool = 0xffffffffull; + if (!bs->AllocatePages(AllocateMaxAddress, EfiLoaderData, pool_mb * 256, &pool)) + break; + } + if (pool_mb < POOL_MB_MIN) + return fail(u"not enough memory below 4GB", 1); + /* extended memory for DOS (XMS, HMA): contiguous, below 4GB */ + for (xms_mb = XMS_MB_MAX; xms_mb >= XMS_MB_MIN; xms_mb /= 2) + { + xms = 0xffffffffull; + if (!bs->AllocatePages(AllocateMaxAddress, EfiLoaderData, xms_mb * 256, &xms)) + break; + } + if (xms_mb < XMS_MB_MIN) + xms_mb = 0, xms = 0; + /* one page in conventional memory: hand-over code, GDT, stack, bootinfo */ + low = 0x9ffff; + if ((s = bs->AllocatePages(AllocateMaxAddress, EfiLoaderData, 1, &low))) + return fail(u"no page below 640K", s); + if (pool < 0x110000 || rd_addr < 0x110000 || (xms && xms < 0x110000)) + return fail(u"memory allocated in the DOS address space", 1); + print(u"Memory: disk image at "); + print_hex(rd_addr); + print(u", monitor pool "); + print_dec(pool_mb); + print(u" MB at "); + print_hex(pool); + print(u", DOS extended memory "); + print_dec(xms_mb); + print(u" MB at "); + print_hex(xms); + print(u"\r\n"); + + memset((void *)low, 0, 4096); + bi = (struct bootinfo *)(low + 0x800); + bi->magic = BOOTINFO_MAGIC; + bi->version = BOOTINFO_VERSION; + bi->boot_type = BOOT_UEFI; + bi->pool_phys = (uint32_t)pool; + bi->pool_size = pool_mb << 20; + bi->core_size = (uint32_t)core_size; + bi->ramdisk_phys = (uint32_t)rd_addr; + bi->ramdisk_size = (uint32_t)rd_size; + if (file_exists(image, DISK_RW_FILE)) + bi->flags |= BOOTF_DISK_WRITE; + else + print(u"Hard disks are read-only (no \\MDOS\\DISKRW).\r\n"); + bi->xms_phys = (uint32_t)xms; + bi->xms_size = xms_mb << 20; + if (is_trial(image, st)) + bi->flags |= BOOTF_TRIAL | (file_exists(image, u"\\MDOS\\TRY\\FAST") ? BOOTF_TRIAL_FAST : 0); + if (file_exists(image, NONET_FILE)) + { + bi->flags |= BOOTF_NO_NET; + print(u"Network card drivers are off (\\MDOS\\NONET).\r\n"); + } + if (file_exists(image, BOOTWAIT_FILE)) + { + bi->flags |= BOOTF_LOG_PAUSE; + print(u"The monitor's log will stay on the screen for a while (\\MDOS\\BOOTWAIT).\r\n"); + } + find_framebuffer(bi, file_exists(image, FBPROBE_FILE)); + for (i = 0; i < st->NumberOfTableEntries; i++) + if (guid_eq(&st->ConfigurationTable[i].VendorGuid, &acpi20_guid)) + bi->rsdp = (uint32_t)(uint64_t)st->ConfigurationTable[i].VendorTable; + memcpy((void *)pool, core_image, core_size); + + print(u"Starting the monitor (leaving the firmware's boot services)...\r\n"); + save_log(); + + /* exit boot services; retry once if the map changed in between */ + for (i = 0; i < 2; i++) + { + map_size = sizeof(map_buf); + if ((s = bs->GetMemoryMap(&map_size, (EFI_MEMORY_DESCRIPTOR *)map_buf, &map_key, &desc_size, &desc_ver))) + return fail(u"cannot get the memory map", s); + conv = conv_kb(map_size, desc_size); + if (!(s = bs->ExitBootServices(image, map_key))) + break; + } + if (s) + return fail(u"ExitBootServices failed", s); + + /* no firmware services from here on */ + bi->conv_kb = conv; + enter_core(low, (uint64_t)bi, pool); +} diff --git a/mdvmm/uefi/start.asm b/mdvmm/uefi/start.asm new file mode 100644 index 00000000..91d4746a --- /dev/null +++ b/mdvmm/uefi/start.asm @@ -0,0 +1,82 @@ +; MDVMM UEFI loader: the embedded core and the hand-over to it. +; +; void enter_core(uint64_t low, uint64_t bootinfo, uint64_t pool) +; low - a page below 640K (identity mapped by the firmware) +; bootinfo - struct bootinfo in that page +; pool - physical base of the pool, the core is copied there +; Copies the 32-bit hand-over code into the low page, leaves long mode +; (compatibility mode, paging off, EFER.LME off) and jumps to the core's +; _start with EAX = pool, EBX = bootinfo, as the DOS loader does. The +; core turns on its own paging through 'tramp', which must be identity +; mapped: it stays in the low page. + +bits 64 +section .text + +global enter_core +enter_core: + cli + mov rbp, rdi ; low page + mov r8, rsi ; bootinfo + mov r9, rdx ; pool + lea rsi, [rel blob] + mov rcx, blob_end - blob + cld + rep movsb ; rdi = low page + lea rax, [rbp + (gdt - blob)] + mov [rbp + (gdtr - blob) + 2], rax + lgdt [rbp + (gdtr - blob)] + lea rax, [rbp + (tramp - blob)] + mov [r8 + 20], eax ; bootinfo.trampoline + mov ebx, r8d + mov edi, r9d + push qword 08h ; 32-bit code segment + lea rax, [rbp + (pm32 - blob)] + push rax + db 48h, 0cbh ; retfq: to compatibility mode + +; ---- copied to the low page, position independent ---- +blob: +bits 32 +pm32: + mov ax, 10h + mov ds, ax + mov es, ax + mov fs, ax + mov gs, ax + mov ss, ax + mov eax, cr0 ; paging off: leaves long mode + and eax, 7ffeffffh ; (also clear WP, as from DOS) + mov cr0, eax + mov ecx, 0c0000080h ; EFER.LME off + rdmsr + and eax, ~100h + wrmsr + xor eax, eax + mov cr4, eax + lea esp, [ebp + 1000h] + mov eax, edi + jmp edi ; core _start(eax = base, ebx = bi) + +; called by the core: ESI = page directory, ECX = high entry point +tramp: + mov cr3, esi + mov eax, cr0 + or eax, 80000000h + mov cr0, eax + jmp ecx + + align 8 +gdt: dq 0 + dq 00cf9a000000ffffh ; 08h: flat 32-bit code + dq 00cf92000000ffffh ; 10h: flat 32-bit data +gdtr: dw 3 * 8 - 1 + dq 0 +blob_end: + +section .rodata +global core_image, core_image_end + align 16 +core_image: + incbin "core.bin" +core_image_end: diff --git a/mkfiles/gcc.mak b/mkfiles/gcc.mak index abc09de5..2f3ae186 100644 --- a/mkfiles/gcc.mak +++ b/mkfiles/gcc.mak @@ -20,10 +20,18 @@ ALLCFLAGS+=-DI386 endif ifeq ($(XFAT),32) -ALLCFLAGS+=-DWITHFAT32 +ALLCFLAGS+=-DWITHFAT32 -DWITHLFNAPI NASMFLAGS+=-DWITHFAT32 endif +# Windows/MDVMM enhanced mode support: INT 2Fh AX=1605h startup broadcast +# with the DOS instance data table, INT 2Ah critical section signals. +# Inert until a supervisor announces itself through the broadcast. +ifeq ($(XFAT),32) +ALLCFLAGS+=-DWIN31SUPPORT +NASMFLAGS+=-DWIN31SUPPORT +endif + NASM=$(XNASM) NASMFLAGS+=-i../hdr/ -DXCPU=$(XCPU) -felf diff --git a/mkfiles/generic.mak b/mkfiles/generic.mak index e0c0487f..9c7f87f2 100644 --- a/mkfiles/generic.mak +++ b/mkfiles/generic.mak @@ -18,6 +18,9 @@ ALLCFLAGS=$(ALLCFLAGS) -DI386 !if $(XFAT) == 32 ALLCFLAGS=$(ALLCFLAGS) -DWITHFAT32 +# The native LFN API (-DWITHLFNAPI) is only enabled in gcc.mak: with Open +# Watcom, init code shares the 64K TGROUP with resident code and the LFN +# code (~7.4K) does not fit. GCC is the reference build for modernDOS. NASMFLAGS=$(NASMFLAGS) -DWITHFAT32 !endif diff --git a/net/pkg/Makefile b/net/pkg/Makefile new file mode 100644 index 00000000..05c8451c --- /dev/null +++ b/net/pkg/Makefile @@ -0,0 +1,36 @@ +# modernDOS package manager: PKG.EXE (DJGPP + Watt-32); for the build host: +# pkg-host (the same code, tests) and pkgsign (repository keys, mkrepo.sh) + +DJ = /opt/djgpp/bin/i586-pc-msdosdjgpp- +WATT = /opt/watt32 +BEAR ?= $(firstword $(wildcard /opt/bearssl ../../_output/ext/bearssl)) +B = build +SRC = pkg.c http.c tls.c ../ssh/sha256.c ../ssh/crypto/monocypher.c ../ssh/crypto/monocypher-ed25519.c +CFLAGS = -O2 -Wall -Wextra -Wno-unused-parameter -Wno-format-truncation + +all: $(B)/pkg.exe $(B)/httpget.exe + +# HTTPGET: a test of the HTTP client +$(B)/httpget.exe: httpget.c http.c tls.c http.h tls.h | $(B) + $(DJ)gcc $(CFLAGS) -s -I$(WATT)/inc -I$(BEAR)/inc -I$(BEAR) -o $@ httpget.c http.c tls.c ../ssh/rng.c \ + ../ssh/crypto/monocypher.c -L$(WATT)/lib -lwatt $(BEAR)/lib/libbearssl.a + +$(B)/pkg.exe: $(SRC) http.h tls.h | $(B) + $(DJ)gcc $(CFLAGS) -s -I$(WATT)/inc -I$(BEAR)/inc -I$(BEAR) -o $@ $(SRC) ../ssh/rng.c \ + -L$(WATT)/lib -lwatt $(BEAR)/lib/libbearssl.a + +host: $(B)/pkg-host $(B)/pkgsign + +$(B)/pkg-host: $(SRC) http.h tls.h | $(B) + gcc $(CFLAGS) -g -I$(BEAR)/inc -I$(BEAR) -o $@ $(SRC) $(BEAR)/lib/host/libbearssl.a + +$(B)/pkgsign: pkgsign.c | $(B) + gcc $(CFLAGS) -o $@ pkgsign.c ../ssh/crypto/monocypher.c ../ssh/crypto/monocypher-ed25519.c + +$(B): + mkdir -p $@ + +clean: + rm -rf $(B) + +.PHONY: all host clean diff --git a/net/pkg/http.c b/net/pkg/http.c new file mode 100644 index 00000000..1a356063 --- /dev/null +++ b/net/pkg/http.c @@ -0,0 +1,271 @@ +/* a small HTTP/1.1 client: GET with redirects; the body by its length, in + chunks, or until the server closes; + http:// and https:// (TLS: tls.c) */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef __DJGPP__ +#include +#define CLOSE closesocket +#else +#define CLOSE close +#endif +#include "http.h" +#include "tls.h" + +int http_init(void) +{ +#ifdef __DJGPP__ + _watt_do_exit = 0; /* a failure is ours to report */ + return sock_init() == 0; +#else + return 1; +#endif +} + +static int fail(char *err, size_t errn, const char *fmt, const char *arg) +{ + snprintf(err, errn, fmt, arg); + return -1; +} + +/* "http[s]://host[:port]/path" -> host, port, path, secure; 0 if it is + not that */ +static int split(const char *url, char *host, size_t hn, int *port, char *path, size_t pn, int *secure) +{ + const char *p, *slash, *colon; + size_t n; + + *secure = !strncasecmp(url, "https://", 8); + if (!*secure && strncasecmp(url, "http://", 7)) + return 0; + p = url + (*secure ? 8 : 7); + slash = strchr(p, '/'); + if (!slash) + slash = p + strlen(p); + colon = memchr(p, ':', (size_t)(slash - p)); + n = (size_t)((colon ? colon : slash) - p); + if (!n || n >= hn) + return 0; + memcpy(host, p, n); + host[n] = 0; + *port = colon ? atoi(colon + 1) : *secure ? 443 : 80; + snprintf(path, pn, "%s", *slash ? slash : "/"); + return *port > 0 && *port < 65536; +} + +/* the body's framing: a length, chunks, or all until the close */ +struct body { + int chunked, done; + long left; /* bytes of the body / the chunk; -1: unknown */ + int state; /* chunked: 0 size line, 1 data, 2 CRLF after data */ + char num[20]; + int nnum; +}; + +/* body bytes as received -> the sink; 1 if the sink refused */ +static int body_data(struct body *b, const char *d, size_t n, http_sink sink, void *ctx) +{ + while (n && !b->done) + { + size_t k; + if (!b->chunked) + { + k = b->left >= 0 && (size_t)b->left < n ? (size_t)b->left : n; + if (k && sink(ctx, d, k)) + return 1; + if (b->left >= 0 && !(b->left -= (long)k)) + b->done = 1; + return 0; + } + if (b->state == 0) /* "hex[;ext]\r\n" */ + { + char c = *d++; + n--; + if (c == '\n') + { + b->num[b->nnum] = 0; + b->nnum = 0; + b->left = strtol(b->num, 0, 16); + if (b->left <= 0) + b->done = 1; /* the last chunk (trailers are not read) */ + else + b->state = 1; + } + else if (b->nnum < (int)sizeof(b->num) - 1 && c != '\r') + b->num[b->nnum++] = c; + } + else if (b->state == 1) + { + k = (size_t)b->left < n ? (size_t)b->left : n; + if (sink(ctx, d, k)) + return 1; + d += k; + n -= k; + if (!(b->left -= (long)k)) + b->state = 2; + } + else /* the CRLF after a chunk */ + { + if (*d == '\n') + b->state = 0; + d++; + n--; + } + } + return 0; +} + +static int get_once(const char *url, http_sink sink, void *ctx, char *type, char *next, size_t nextn, + char *err, size_t errn) +{ + char host[128], path[512], req[800], buf[2048]; + static char head[16384]; /* some sites send 8 KB of header */ + struct sockaddr_in sa; + struct hostent *h; + size_t hlen = 0; + int port, s, n = 0, status = 0, body = 0, secure; + struct tls *t = 0; + struct body bd; + char *p, *line; + + next[0] = 0; + memset(&bd, 0, sizeof(bd)); + bd.left = -1; + if (!split(url, host, sizeof(host), &port, path, sizeof(path), &secure)) + return fail(err, errn, "%s: not an http:// or https:// address", url); + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons((unsigned short)port); + sa.sin_addr.s_addr = inet_addr(host); + if (sa.sin_addr.s_addr == INADDR_NONE) + { + if (!(h = gethostbyname(host))) + return fail(err, errn, "%s: unknown host", host); + memcpy(&sa.sin_addr, h->h_addr, sizeof(sa.sin_addr)); + } + if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0 || connect(s, (struct sockaddr *)&sa, sizeof(sa)) < 0) + { + if (s >= 0) + CLOSE(s); + return fail(err, errn, "%s: cannot connect", host); + } + snprintf(req, sizeof(req), "GET %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: modernDOS/0.1\r\n" + "Accept: */*\r\nConnection: close\r\n\r\n", path, host); + if (secure && !(t = tls_open(s, host, err, errn))) + { + CLOSE(s); + return -1; + } + if (t ? tls_write(t, req, strlen(req)) : send(s, req, (int)strlen(req), 0) < 0) + { + tls_close(t); + CLOSE(s); + return fail(err, errn, "%s: cannot send the request", host); + } + while (!bd.done && (n = t ? tls_read(t, buf, sizeof(buf)) : recv(s, buf, sizeof(buf), 0)) > 0) + { + const char *data = buf; + if (!body) + { + /* collect the header (to the empty line) */ + size_t k = (size_t)n < sizeof(head) - 1 - hlen ? (size_t)n : sizeof(head) - 1 - hlen; + memcpy(head + hlen, buf, k); + hlen += k; + head[hlen] = 0; + p = strstr(head, "\r\n\r\n"); + if (!p && k == (size_t)n) + continue; + if (!p) + { + tls_close(t); + CLOSE(s); + return fail(err, errn, "%s: the answer's header is too long", host); + } + *p = 0; + body = 1; + if (sscanf(head, "HTTP/%*s %d", &status) != 1) + status = 0; + for (line = strtok(head, "\r\n"); line; line = strtok(NULL, "\r\n")) + { + if (!strncasecmp(line, "Location:", 9)) + { + const char *v = line + 9; + while (*v == ' ') + v++; + if (*v == '/') + snprintf(next, nextn, "%s://%s:%d%s", secure ? "https" : "http", host, port, v); + else + snprintf(next, nextn, "%s", v); + } + if (!strncasecmp(line, "Content-Length:", 15)) + bd.left = atol(line + 15); + if (!strncasecmp(line, "Transfer-Encoding:", 18) && strstr(line + 18, "chunked")) + bd.chunked = 1; + if (type && !strncasecmp(line, "Content-Type:", 13)) + { + const char *v = line + 13; + while (*v == ' ') + v++; + snprintf(type, 64, "%s", v); + } + } + if (status >= 300 && status < 400 && next[0]) + break; /* the caller follows */ + next[0] = 0; + if (status != 200) + { + char code[16]; + tls_close(t); + CLOSE(s); + snprintf(code, sizeof(code), "%d", status); + return fail(err, errn, status ? "the server answered %s" : "no HTTP answer%s", status ? code : ""); + } + /* body bytes that came with the header */ + data = p + 4; + n = (int)(hlen - (size_t)(data - head)); + if (bd.left == 0 && !bd.chunked) + bd.done = 1; + if (n <= 0) + continue; + } + if (body_data(&bd, data, (size_t)n, sink, ctx)) + { + tls_close(t); + CLOSE(s); + return fail(err, errn, "%s", "stopped (cannot store the data?)"); + } + } + tls_close(t); + CLOSE(s); + if (n < 0 && t) + return fail(err, errn, "%s: the secure connection broke", host); + if (!body) + return fail(err, errn, "%s: no answer", host); + return 0; +} + +int http_get(const char *url, http_sink sink, void *ctx, char *type, char *err, size_t errn) +{ + char cur[600], next[600]; + int i; + + snprintf(cur, sizeof(cur), "%s", url); + if (type) + type[0] = 0; + for (i = 0; i < 6; i++) + { + if (get_once(cur, sink, ctx, type, next, sizeof(next), err, errn)) + return -1; + if (!next[0]) + return 0; + snprintf(cur, sizeof(cur), "%s", next); + } + return fail(err, errn, "%s", "too many redirects"); +} diff --git a/net/pkg/http.h b/net/pkg/http.h new file mode 100644 index 00000000..f099a7b8 --- /dev/null +++ b/net/pkg/http.h @@ -0,0 +1,18 @@ +/* a small HTTP/1.1 client (GET; http and https), for the package manager + and the browser */ +#ifndef HTTP_H +#define HTTP_H +#include + +/* data sink: return 0 to go on */ +typedef int (*http_sink)(void *ctx, const void *data, size_t n); + +/* GET url ("http[s]://host[:port]/path"), follows redirects; 0 on success, + else -1 with a message in err. *type (if not NULL) gets the content + type (64 bytes). */ +int http_get(const char *url, http_sink sink, void *ctx, char *type, char *err, size_t errn); + +/* network up (Watt-32 on DOS); 0 on failure */ +int http_init(void); + +#endif diff --git a/net/pkg/httpget.c b/net/pkg/httpget.c new file mode 100644 index 00000000..01cc4eb0 --- /dev/null +++ b/net/pkg/httpget.c @@ -0,0 +1,33 @@ +/* HTTPGET url [file]: fetch a page (http or https) - a test of the HTTP + client; prints the content type and size, or the error */ +#include +#include "http.h" + +static unsigned long total; + +static int sink(void *ctx, const void *data, size_t n) +{ + total += n; + return ctx && fwrite(data, 1, n, ctx) != n; +} + +int main(int argc, char **argv) +{ + char err[200], type[64]; + FILE *f = argc > 2 ? fopen(argv[2], "wb") : 0; + + if (argc < 2 || !http_init()) + { + printf("HTTPGET: %s\n", argc < 2 ? "usage: HTTPGET url [file]" : "no network"); + return 2; + } + if (http_get(argv[1], sink, f, type, err, sizeof(err))) + { + printf("HTTPGET: FAILED %s\n", err); + return 1; + } + if (f) + fclose(f); + printf("HTTPGET: ok %lu bytes, type %s\n", total, type); + return 0; +} diff --git a/net/pkg/mkrepo.sh b/net/pkg/mkrepo.sh new file mode 100755 index 00000000..e3571a34 --- /dev/null +++ b/net/pkg/mkrepo.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# Make a package repository (the work of scripts/mkrepo.sh; runs where +# net/pkg/build/pkgsign exists, i.e. in the build container). +# net/pkg/mkrepo.sh +set -e +S=$1; O=$2; K=$3; P=$(dirname "$0")/build/pkgsign +mkdir -p "$O" +[ -f "$K" ] || "$P" keygen "$K" > /dev/null +: > "$O/INDEX.TXT" +for d in "$S"/*/; do + n=$(basename "$d"); f=$(echo "$n" | tr a-z A-Z | cut -c1-8).TAR + v=$(sed -n "s/^version=//p" "$d/PKGINFO"); t=$(sed -n "s/^description=//p" "$d/PKGINFO") + tar --format=ustar --owner=0 --group=0 -C "$d/root" -cf "$O/$f" . + echo "$n|$v|$f|$(stat -c %s "$O/$f")|$(sha256sum "$O/$f" | cut -d" " -f1)|$t" >> "$O/INDEX.TXT" +done +"$P" sign "$K" "$O/INDEX.TXT" > "$O/INDEX.SIG" +cat "$O/INDEX.TXT" +echo "public key (key = ... in PKG.CFG): $("$P" pub "$K")" diff --git a/net/pkg/pkg.c b/net/pkg/pkg.c new file mode 100644 index 00000000..f429492c --- /dev/null +++ b/net/pkg/pkg.c @@ -0,0 +1,494 @@ +/* + * PKG - the modernDOS package manager + * + * PKG UPDATE fetch the repository's package list + * PKG LIST packages of the repository, [*] = installed + * PKG INSTALL name download, check and unpack a package + * PKG REMOVE name delete an installed package's files + * PKG INFO repository, key, where packages go + * + * PKG.CFG (next to PKG.EXE, or in %PKGDIR%): + * repo = http://host/path/ the repository + * key = 64 hex digits its ed25519 public key + * root = C:\ where packages are unpacked + * + * A repository (made with scripts/mkrepo.sh) is a directory on a web + * server: INDEX.TXT lists the packages (name|version|file|size|sha256| + * description), INDEX.SIG is its ed25519 signature, and each package is an + * uncompressed tar archive. There is no TLS: the list is only used if the + * signature fits the key in PKG.CFG, and a package only if its SHA-256 is + * the one in the list. What a package installed is kept in + * \MDOS\PKG\.LST. + */ +#include +#include +#include +#include +#include +#include +#include +#include "../ssh/crypto/monocypher-ed25519.h" +#include "../ssh/sha256.h" +#include "http.h" + +#ifdef __DJGPP__ +#define SEP '\\' +#else +#define SEP '/' +#endif + +struct pkg { + char name[32], version[24], file[64], sha[65], desc[128]; + long size; +}; + +static char repo[256], root[128], dbdir[160], cfgdir[128]; +static uint8_t repo_key[32]; +static int have_key; +static struct pkg *pkgs; +static int npkgs; + +static void die(const char *fmt, const char *arg) +{ + fprintf(stderr, "PKG: "); + fprintf(stderr, fmt, arg); + fprintf(stderr, "\n"); + exit(1); +} + +static void join(char *out, size_t n, const char *dir, const char *name) +{ + size_t l = strlen(dir); + + snprintf(out, n, "%s%s%s", dir, l && dir[l - 1] != '/' && dir[l - 1] != '\\' ? (SEP == '/' ? "/" : "\\") : "", + name); +} + +static void make_dirs(const char *path) +{ + char tmp[300], *p; + + snprintf(tmp, sizeof(tmp), "%s", path); + for (p = tmp + 1; *p; p++) + if ((*p == '/' || *p == '\\') && p[-1] != ':') + { + char c = *p; + *p = 0; + mkdir(tmp, 0755); + *p = c; + } +} + +static int hex(const char *s, uint8_t *out, int n) +{ + int i; + unsigned v; + + for (i = 0; i < n; i++) + { + if (sscanf(s + i * 2, "%2x", &v) != 1) + return 0; + out[i] = (uint8_t)v; + } + return 1; +} + +static void config(const char *argv0) +{ + char path[200], line[400], *slash; + FILE *f; + + if (getenv("PKGDIR")) + snprintf(cfgdir, sizeof(cfgdir), "%s", getenv("PKGDIR")); + else + { + snprintf(cfgdir, sizeof(cfgdir), "%s", argv0); + slash = strrchr(cfgdir, '/'); + if (strrchr(cfgdir, '\\') > slash) + slash = strrchr(cfgdir, '\\'); + if (slash) + slash[1] = 0; + else + cfgdir[0] = 0; + } +#ifdef __DJGPP__ + strcpy(root, access("C:/", 0) == 0 ? "C:\\" : "A:\\"); +#else + strcpy(root, "./"); +#endif + join(path, sizeof(path), cfgdir, "PKG.CFG"); + f = fopen(path, "r"); + while (f && fgets(line, sizeof(line), f)) + { + char key[32], val[300]; + if (sscanf(line, " %31[a-z] = %299[^\r\n]", key, val) != 2) + continue; + if (!strcmp(key, "repo")) + snprintf(repo, sizeof(repo), "%s%s", val, val[strlen(val) - 1] == '/' ? "" : "/"); + else if (!strcmp(key, "key")) + have_key = strlen(val) >= 64 && hex(val, repo_key, 32); + else if (!strcmp(key, "root")) + snprintf(root, sizeof(root), "%s", val); + } + if (f) + fclose(f); + join(line, sizeof(line), root, "MODERNDOS"); + join(dbdir, sizeof(dbdir), line, "PKG"); +} + +/* ---------------------------------------------------------------- */ + +struct mem { + char *d; + size_t len, cap; +}; + +static int to_mem(void *ctx, const void *data, size_t n) +{ + struct mem *m = ctx; + + if (m->len + n + 1 > m->cap) + { + m->cap = (m->len + n + 1) * 2; + m->d = realloc(m->d, m->cap); + if (!m->d) + return 1; + } + memcpy(m->d + m->len, data, n); + m->len += n; + m->d[m->len] = 0; + return 0; +} + +struct dl { + FILE *f; + struct sha256 sha; + long got; +}; + +static int to_file(void *ctx, const void *data, size_t n) +{ + struct dl *d = ctx; + + sha256_update(&d->sha, data, n); + d->got += (long)n; + return fwrite(data, 1, n, d->f) != n; +} + +static void need_repo(void) +{ + if (!repo[0] || !have_key) + die("no repository: put \"repo = http://...\" and \"key = ...\" into %sPKG.CFG", cfgdir); + if (!http_init()) + die("%s", "no network (packet driver loaded?)"); +} + +static int parse_index(char *text) +{ + char *line, *save; + int n = 0; + + for (line = text; *line; line++) + n += *line == '\n'; + pkgs = calloc((size_t)n + 1, sizeof(*pkgs)); + npkgs = 0; + for (line = strtok_r(text, "\r\n", &save); line && pkgs; line = strtok_r(NULL, "\r\n", &save)) + { + struct pkg *p = &pkgs[npkgs]; + if (line[0] == '#') + continue; + if (sscanf(line, "%31[^|]|%23[^|]|%63[^|]|%ld|%64[0-9a-f]|%127[^\n]", p->name, p->version, p->file, + &p->size, p->sha, p->desc) >= 5) + npkgs++; + } + return npkgs; +} + +static void load_index(void) +{ + char path[220]; + struct mem m = { 0, 0, 0 }; + FILE *f; + char buf[1024]; + size_t n; + + join(path, sizeof(path), dbdir, "INDEX.TXT"); + f = fopen(path, "rb"); + if (!f) + die("%s", "no package list yet: run PKG UPDATE"); + while ((n = fread(buf, 1, sizeof(buf), f)) > 0) + to_mem(&m, buf, n); + fclose(f); + parse_index(m.d ? m.d : ""); +} + +static struct pkg *find(const char *name) +{ + int i; + + for (i = 0; i < npkgs; i++) + if (!strcasecmp(pkgs[i].name, name)) + return &pkgs[i]; + return 0; +} + +static void list_path(char *out, size_t n, const char *name) +{ + char file[48]; + + snprintf(file, sizeof(file), "%.8s.LST", name); + join(out, n, dbdir, file); +} + +static int installed(const char *name, char *version, size_t vn) +{ + char path[220]; + FILE *f; + + list_path(path, sizeof(path), name); + f = fopen(path, "r"); + if (!f) + return 0; + if (version && (!fgets(version, (int)vn, f))) + version[0] = 0; + if (version) + version[strcspn(version, "\r\n")] = 0; + fclose(f); + return 1; +} + +/* ---------------------------------------------------------------- */ + +static int cmd_update(void) +{ + char url[400], err[160], path[220]; + struct mem idx = { 0, 0, 0 }, sig = { 0, 0, 0 }; + uint8_t s[64]; + FILE *f; + + need_repo(); + snprintf(url, sizeof(url), "%sINDEX.TXT", repo); + if (http_get(url, to_mem, &idx, 0, err, sizeof(err))) + die("%s", err); + snprintf(url, sizeof(url), "%sINDEX.SIG", repo); + if (http_get(url, to_mem, &sig, 0, err, sizeof(err))) + die("%s", err); + if (sig.len < 128 || !hex(sig.d, s, 64) || + crypto_ed25519_check(s, repo_key, (const uint8_t *)idx.d, idx.len)) + die("%s", "the package list's signature does NOT fit the repository key: not used"); + make_dirs(dbdir); + mkdir(dbdir, 0755); + join(path, sizeof(path), dbdir, "INDEX.TXT"); + f = fopen(path, "wb"); + if (!f || fwrite(idx.d, 1, idx.len, f) != idx.len) + die("cannot write %s", path); + fclose(f); + printf("Package list updated: %d packages (signature good).\n", parse_index(idx.d)); + return 0; +} + +static int cmd_list(void) +{ + int i; + + load_index(); + for (i = 0; i < npkgs; i++) + { + char v[24]; + int inst = installed(pkgs[i].name, v, sizeof(v)); + printf("%s %-10s %-8s %6ld KB %s%s%s%s\n", inst ? "[*]" : "[ ]", pkgs[i].name, pkgs[i].version, + (pkgs[i].size + 1023) / 1024, pkgs[i].desc, inst && strcmp(v, pkgs[i].version) ? " (installed: " : "", + inst && strcmp(v, pkgs[i].version) ? v : "", inst && strcmp(v, pkgs[i].version) ? ")" : ""); + } + if (!npkgs) + printf("The repository has no packages.\n"); + return 0; +} + +/* a file name from an archive: relative, no "..", no drive */ +static int safe_name(const char *n) +{ + if (!*n || *n == '/' || *n == '\\' || strchr(n, ':') || strstr(n, "..")) + return 0; + return 1; +} + +static long octal(const char *p, int n) +{ + long v = 0; + + while (n-- > 0 && *p == ' ') + p++; + for (; *p >= '0' && *p <= '7'; p++) + v = v * 8 + (*p - '0'); + return v; +} + +/* unpack a tar archive below root; the files are listed in `lst` */ +static int untar(const char *tar, FILE *lst) +{ + FILE *f = fopen(tar, "rb"), *out; + unsigned char h[512], buf[4096]; + char name[300], path[420], *c; + long size, n; + int files = 0; + + if (!f) + return -1; + while (fread(h, 1, 512, f) == 512 && h[0]) + { + if (h[345]) + snprintf(name, sizeof(name), "%.155s/%.100s", h + 345, h); + else + snprintf(name, sizeof(name), "%.100s", h); + size = octal((char *)h + 124, 12); + c = name; + if (!strncmp(c, "./", 2)) + c += 2; + if (h[156] == '5' || (*c && c[strlen(c) - 1] == '/')) /* a directory */ + { + if (*c && safe_name(c)) + { + join(path, sizeof(path), root, c); + make_dirs(path); + mkdir(path, 0755); + } + continue; + } + if ((h[156] != '0' && h[156] != 0) || !safe_name(c)) + { + fseek(f, (size + 511) / 512 * 512, SEEK_CUR); /* links etc.: skipped */ + continue; + } + join(path, sizeof(path), root, c); + for (c = path; *c; c++) + if (*c == '/' && SEP == '\\') + *c = '\\'; + make_dirs(path); + out = fopen(path, "wb"); + if (!out) + { + fprintf(stderr, "PKG: cannot write %s\n", path); + fclose(f); + return -1; + } + for (n = size; n > 0; n -= 512) + { + if (fread(buf, 1, 512, f) != 512) + break; + fwrite(buf, 1, n > 512 ? 512 : (size_t)n, out); + } + fclose(out); + fprintf(lst, "%s\n", path); + printf(" %s\n", path); + files++; + } + fclose(f); + return files; +} + +static int cmd_install(const char *name) +{ + char url[400], err[160], tmp[220], lst[220], shahex[65]; + struct pkg *p; + struct dl d; + uint8_t sum[32]; + FILE *l; + int i, files; + + load_index(); + if (!(p = find(name))) + die("no package \"%s\" in the list (PKG LIST, PKG UPDATE)", name); + need_repo(); + make_dirs(dbdir); + mkdir(dbdir, 0755); + join(tmp, sizeof(tmp), dbdir, "DOWNLOAD.TMP"); + memset(&d, 0, sizeof(d)); + if (!(d.f = fopen(tmp, "wb"))) + die("cannot write %s", tmp); + sha256_init(&d.sha); + snprintf(url, sizeof(url), "%s%s", repo, p->file); + printf("Downloading %s %s (%ld KB)...\n", p->name, p->version, (p->size + 1023) / 1024); + i = http_get(url, to_file, &d, 0, err, sizeof(err)); + fclose(d.f); + if (i) + { + remove(tmp); + die("%s", err); + } + sha256_final(&d.sha, sum); + for (i = 0; i < 32; i++) + sprintf(shahex + i * 2, "%02x", sum[i]); + if (strcmp(shahex, p->sha) || d.got != p->size) + { + remove(tmp); + die("%s: the download does NOT match the package list (SHA-256): not installed", p->name); + } + list_path(lst, sizeof(lst), p->name); + if (!(l = fopen(lst, "w"))) + die("cannot write %s", lst); + fprintf(l, "%s\n", p->version); + files = untar(tmp, l); + fclose(l); + remove(tmp); + if (files < 0) + { + remove(lst); + die("%s: could not be unpacked", p->name); + } + printf("Installed %s %s: %d files.\n", p->name, p->version, files); + return 0; +} + +static int cmd_remove(const char *name) +{ + char lst[220], line[420]; + FILE *l; + int n = 0, first = 1; + + list_path(lst, sizeof(lst), name); + if (!(l = fopen(lst, "r"))) + die("%s is not installed", name); + while (fgets(line, sizeof(line), l)) + { + line[strcspn(line, "\r\n")] = 0; + if (first) + { + first = 0; /* the version */ + continue; + } + if (*line && !remove(line)) + n++; + } + fclose(l); + remove(lst); + printf("Removed %s: %d files.\n", name, n); + return 0; +} + +int main(int argc, char **argv) +{ + config(argv[0]); + if (argc >= 2 && !strcasecmp(argv[1], "UPDATE")) + return cmd_update(); + if (argc >= 2 && !strcasecmp(argv[1], "LIST")) + return cmd_list(); + if (argc >= 3 && !strcasecmp(argv[1], "INSTALL")) + return cmd_install(argv[2]); + if (argc >= 3 && !strcasecmp(argv[1], "REMOVE")) + return cmd_remove(argv[2]); + if (argc >= 2 && !strcasecmp(argv[1], "INFO")) + { + printf("Repository: %s\nKey: %s\nPackages go to: %s\nPackage records: %s\n", repo[0] ? repo : "(none)", + have_key ? "set" : "(none)", root, dbdir); + return 0; + } + printf("modernDOS package manager\n" + " PKG UPDATE fetch the repository's package list\n" + " PKG LIST packages, [*] = installed\n" + " PKG INSTALL name download, check and unpack\n" + " PKG REMOVE name delete an installed package\n" + " PKG INFO repository and directories\n" + "Repository and key: %sPKG.CFG\n", cfgdir); + return 2; +} diff --git a/net/pkg/pkgsign.c b/net/pkg/pkgsign.c new file mode 100644 index 00000000..19e206b3 --- /dev/null +++ b/net/pkg/pkgsign.c @@ -0,0 +1,84 @@ +/* pkgsign - repository keys and signatures for PKG (runs on the build + * host, used by scripts/mkrepo.sh) + * + * pkgsign keygen keyfile new key: the secret (hex) into keyfile, + * the public key (for PKG.CFG) to stdout + * pkgsign pub keyfile the public key + * pkgsign sign keyfile file the signature of file (hex) to stdout + */ +#include +#include +#include +#include "../ssh/crypto/monocypher-ed25519.h" + +static void puthex(const uint8_t *p, int n) +{ + while (n--) + printf("%02x", *p++); + printf("\n"); +} + +static void load(const char *file, uint8_t sk[64], uint8_t pk[32]) +{ + uint8_t seed[32]; + char hex[80]; + unsigned v; + int i; + FILE *f = fopen(file, "r"); + + if (!f || !fgets(hex, sizeof(hex), f) || strlen(hex) < 64) + { + fprintf(stderr, "pkgsign: cannot read the key %s\n", file); + exit(1); + } + fclose(f); + for (i = 0; i < 32; i++) + { + sscanf(hex + i * 2, "%2x", &v); + seed[i] = (uint8_t)v; + } + crypto_ed25519_key_pair(sk, pk, seed); +} + +int main(int argc, char **argv) +{ + uint8_t sk[64], pk[32], sig[64], seed[32]; + int i; + + if (argc == 3 && !strcmp(argv[1], "keygen")) + { + FILE *r = fopen("/dev/urandom", "rb"), *f; + if (!r || fread(seed, 1, 32, r) != 32 || !(f = fopen(argv[2], "w"))) + return 1; + fclose(r); + for (i = 0; i < 32; i++) + fprintf(f, "%02x", seed[i]); + fprintf(f, "\n"); + fclose(f); + crypto_ed25519_key_pair(sk, pk, seed); + puthex(pk, 32); + return 0; + } + if (argc == 3 && !strcmp(argv[1], "pub")) + { + load(argv[2], sk, pk); + puthex(pk, 32); + return 0; + } + if (argc == 4 && !strcmp(argv[1], "sign")) + { + FILE *f = fopen(argv[3], "rb"); + static uint8_t data[1 << 20]; + size_t n; + if (!f) + return 1; + n = fread(data, 1, sizeof(data), f); + fclose(f); + load(argv[2], sk, pk); + crypto_ed25519_sign(sig, sk, data, n); + puthex(sig, 64); + return 0; + } + fprintf(stderr, "usage: pkgsign keygen keyfile | pub keyfile | sign keyfile file\n"); + return 2; +} diff --git a/net/pkg/tls.c b/net/pkg/tls.c new file mode 100644 index 00000000..a481ea35 --- /dev/null +++ b/net/pkg/tls.c @@ -0,0 +1,146 @@ +/* + * TLS client connections with BearSSL: TLS 1.2 (and older, down to 1.0), + * server certificates checked against the certificate authorities built + * in at compile time (trust_anchors.h, Mozilla's list) and against the + * host name, with the machine's clock for the validity dates. + * + * Random numbers on DOS: the SSH programs' generator (timing jitter, seed + * file). On a build host BearSSL takes the system's. + */ +#include +#include +#include +#include +#include +#include +#include "tls.h" +#include "trust_anchors.h" +#ifdef __DJGPP__ +#include "../ssh/rng.h" +#endif + +struct tls { + br_ssl_client_context sc; + br_x509_minimal_context xc; + br_sslio_context io; + unsigned char buf[BR_SSL_BUFSIZE_BIDI]; + int fd; +}; + +static int sock_read(void *ctx, unsigned char *buf, size_t len) +{ + int n = recv(*(int *)ctx, (char *)buf, (int)len, 0); + + return n > 0 ? n : -1; +} + +static int sock_write(void *ctx, const unsigned char *buf, size_t len) +{ + int n = send(*(int *)ctx, (const char *)buf, (int)len, 0); + + return n > 0 ? n : -1; +} + +static const char *why(int e) +{ + switch (e) + { + case BR_ERR_X509_EXPIRED: + return "the server's certificate is expired or not yet valid (is this machine's clock right?)"; + case BR_ERR_X509_NOT_TRUSTED: + return "the server's certificate is not from a known authority"; + case BR_ERR_X509_BAD_SERVER_NAME: + return "the server's certificate is for another name"; + case BR_ERR_BAD_VERSION: + case BR_ERR_UNSUPPORTED_VERSION: + return "the server needs a TLS version this program does not have (TLS 1.3 only?)"; + case BR_ERR_NO_RANDOM: + return "no random numbers"; + case BR_ERR_IO: + return "the connection was closed"; + } + if (e >= BR_ERR_RECV_FATAL_ALERT && e < BR_ERR_RECV_FATAL_ALERT + 256) + return "the server refused the TLS handshake"; + return 0; +} + +static void explain(struct tls *t, char *err, size_t errn) +{ + int e = br_ssl_engine_last_error(&t->sc.eng); + + if (why(e)) + snprintf(err, errn, "secure connection failed: %s", why(e)); + else + snprintf(err, errn, "secure connection failed (TLS error %d)", e); +} + +struct tls *tls_open(int fd, const char *host, char *err, size_t errn) +{ + struct tls *t = malloc(sizeof(*t)); + time_t now = time(0); + + if (!t) + { + snprintf(err, errn, "no memory for a secure connection"); + return 0; + } + t->fd = fd; + br_ssl_client_init_full(&t->sc, &t->xc, TAs, TAs_NUM); + /* the validity dates: days since 0 AD (1970-01-01 is day 719528) */ + br_x509_minimal_set_time(&t->xc, (uint32_t)(now / 86400) + 719528, (uint32_t)(now % 86400)); +#ifdef __DJGPP__ + { + static int seeded; + unsigned char seed[32]; + if (!seeded) + { + rng_init(0); + seeded = 1; + } + rng_event((uint32_t)fd); + rng_bytes(seed, sizeof(seed)); + br_ssl_engine_inject_entropy(&t->sc.eng, seed, sizeof(seed)); + } +#endif + br_ssl_engine_set_buffer(&t->sc.eng, t->buf, sizeof(t->buf), 1); + if (!br_ssl_client_reset(&t->sc, host, 0)) + { + explain(t, err, errn); + free(t); + return 0; + } + br_sslio_init(&t->io, &t->sc.eng, sock_read, &t->fd, sock_write, &t->fd); + if (br_sslio_flush(&t->io) < 0) /* runs the handshake */ + { + explain(t, err, errn); + free(t); + return 0; + } + return t; +} + +int tls_write(struct tls *t, const void *data, size_t n) +{ + return br_sslio_write_all(&t->io, data, n) < 0 || br_sslio_flush(&t->io) < 0 ? -1 : 0; +} + +int tls_read(struct tls *t, void *buf, size_t n) +{ + int r = br_sslio_read(&t->io, buf, n); + + if (r >= 0) + return r; + /* a closed connection ends the data (HTTP/1.0 bodies end that way, and + many servers do not send TLS's own end mark) */ + return br_ssl_engine_last_error(&t->sc.eng) == BR_ERR_OK || + br_ssl_engine_last_error(&t->sc.eng) == BR_ERR_IO ? 0 : -1; +} + +void tls_close(struct tls *t) +{ + if (t) + { + br_sslio_close(&t->io); + free(t); + } +} diff --git a/net/pkg/tls.h b/net/pkg/tls.h new file mode 100644 index 00000000..bc869ad2 --- /dev/null +++ b/net/pkg/tls.h @@ -0,0 +1,16 @@ +/* TLS 1.2 client connections (BearSSL) for the HTTP client */ +#ifndef TLS_H +#define TLS_H +#include + +struct tls; + +/* TLS over the connected socket fd, to the server named host (its + certificate is checked against the built-in authorities and the name). + 0 on failure, with a message in err. */ +struct tls *tls_open(int fd, const char *host, char *err, size_t errn); +int tls_write(struct tls *t, const void *data, size_t n); /* 0 ok, -1 */ +int tls_read(struct tls *t, void *buf, size_t n); /* bytes, 0 end, -1 */ +void tls_close(struct tls *t); /* not the socket */ + +#endif diff --git a/net/ssh/Makefile b/net/ssh/Makefile new file mode 100644 index 00000000..9bd1edcc --- /dev/null +++ b/net/ssh/Makefile @@ -0,0 +1,34 @@ +# modernDOS SSH: SSHD.EXE (DJGPP + Watt-32), and a Linux build of the same +# protocol code for tests against OpenSSH (make host) + +DJ = /opt/djgpp/bin/i586-pc-msdosdjgpp- +WATT = /opt/watt32 +B = build +COMMON = ssh.c buf.c sha256.c rng.c console.c sftp.c \ + crypto/monocypher.c crypto/monocypher-ed25519.c +HDRS = $(wildcard *.h crypto/*.h) +CFLAGS = -O2 -Wall -Wextra -Wno-unused-parameter + +all: $(B)/sshd.exe $(B)/ssh.exe + +$(B)/sshd.exe: sshd.c plat_dos.c $(COMMON) $(HDRS) | $(B) + $(DJ)gcc $(CFLAGS) -s -I$(WATT)/inc -o $@ sshd.c plat_dos.c $(COMMON) -L$(WATT)/lib -lwatt + +$(B)/ssh.exe: sshc.c plat_dos.c term.c keyfile.c $(COMMON) $(HDRS) | $(B) + $(DJ)gcc $(CFLAGS) -s -I$(WATT)/inc -o $@ sshc.c plat_dos.c term.c keyfile.c $(COMMON) -L$(WATT)/lib -lwatt + +host: $(B)/sshd-host $(B)/ssh-host + +$(B)/ssh-host: sshc.c plat_host.c term.c keyfile.c $(COMMON) $(HDRS) | $(B) + gcc $(CFLAGS) -g -o $@ sshc.c plat_host.c term.c keyfile.c $(COMMON) + +$(B)/sshd-host: sshd.c plat_host.c $(COMMON) $(HDRS) | $(B) + gcc $(CFLAGS) -g -o $@ sshd.c plat_host.c $(COMMON) + +$(B): + mkdir -p $@ + +clean: + rm -rf $(B) + +.PHONY: all host clean diff --git a/net/ssh/buf.c b/net/ssh/buf.c new file mode 100644 index 00000000..7a24fe90 --- /dev/null +++ b/net/ssh/buf.c @@ -0,0 +1,261 @@ +/* growable byte buffers with SSH wire encoding */ +#include +#include +#include "buf.h" + +void buf_init(struct buf *b) +{ + memset(b, 0, sizeof(*b)); +} + +void buf_free(struct buf *b) +{ + if (b->d) + { + memset(b->d, 0, b->cap); /* may have held secrets */ + free(b->d); + } + buf_init(b); +} + +void buf_reset(struct buf *b) +{ + b->len = b->pos = 0; + b->err = 0; +} + +void buf_consume(struct buf *b, size_t n) +{ + if (n >= b->len) + { + b->len = 0; + b->pos = 0; + return; + } + memmove(b->d, b->d + n, b->len - n); + b->len -= n; + b->pos = b->pos > n ? b->pos - n : 0; +} + +void buf_reserve(struct buf *b, size_t n) +{ + size_t cap; + uint8_t *d; + + if (b->len + n <= b->cap) + return; + cap = b->cap ? b->cap : 256; + while (cap < b->len + n) + cap *= 2; + d = malloc(cap); + if (!d) + abort(); + if (b->d) + { + memcpy(d, b->d, b->len); + memset(b->d, 0, b->cap); + free(b->d); + } + b->d = d; + b->cap = cap; +} + +size_t buf_left(const struct buf *b) +{ + return b->len - b->pos; +} + +void put_bytes(struct buf *b, const void *p, size_t n) +{ + buf_reserve(b, n); + memcpy(b->d + b->len, p, n); + b->len += n; +} + +void put_u8(struct buf *b, uint8_t v) +{ + put_bytes(b, &v, 1); +} + +uint32_t peek_u32(const uint8_t *p) +{ + return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]; +} + +void poke_u32(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)(v >> 24); + p[1] = (uint8_t)(v >> 16); + p[2] = (uint8_t)(v >> 8); + p[3] = (uint8_t)v; +} + +void put_u32(struct buf *b, uint32_t v) +{ + uint8_t t[4]; + + poke_u32(t, v); + put_bytes(b, t, 4); +} + +void put_u64(struct buf *b, uint64_t v) +{ + put_u32(b, (uint32_t)(v >> 32)); + put_u32(b, (uint32_t)v); +} + +void put_str(struct buf *b, const void *p, size_t n) +{ + put_u32(b, (uint32_t)n); + put_bytes(b, p, n); +} + +void put_cstr(struct buf *b, const char *s) +{ + put_str(b, s, strlen(s)); +} + +void put_mpint(struct buf *b, const uint8_t *be, size_t n) +{ + while (n && !*be) + { + be++; + n--; + } + if (n && (*be & 0x80)) + { + put_u32(b, (uint32_t)n + 1); + put_u8(b, 0); + put_bytes(b, be, n); + } + else + put_str(b, be, n); +} + +const uint8_t *get_bytes(struct buf *b, size_t n) +{ + const uint8_t *p; + + if (b->err || n > b->len - b->pos) + { + b->err = 1; + return NULL; + } + p = b->d + b->pos; + b->pos += n; + return p; +} + +uint8_t get_u8(struct buf *b) +{ + const uint8_t *p = get_bytes(b, 1); + return p ? *p : 0; +} + +uint32_t get_u32(struct buf *b) +{ + const uint8_t *p = get_bytes(b, 4); + return p ? peek_u32(p) : 0; +} + +uint64_t get_u64(struct buf *b) +{ + uint64_t hi = get_u32(b); + return hi << 32 | get_u32(b); +} + +const uint8_t *get_str(struct buf *b, uint32_t *len) +{ + uint32_t n = get_u32(b); + const uint8_t *p = get_bytes(b, n); + + *len = p ? n : 0; + return p; +} + +int get_cstr(struct buf *b, char *out, size_t room) +{ + uint32_t n; + const uint8_t *p = get_str(b, &n); + + if (!p || n >= room || memchr(p, 0, n)) + { + if (room) + *out = 0; + return 0; + } + memcpy(out, p, n); + out[n] = 0; + return 1; +} + +static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +size_t b64_encode(const uint8_t *in, size_t n, char *out, int pad) +{ + size_t i, o = 0; + + for (i = 0; i + 2 < n; i += 3) + { + uint32_t v = (uint32_t)in[i] << 16 | (uint32_t)in[i + 1] << 8 | in[i + 2]; + out[o++] = b64[v >> 18]; + out[o++] = b64[(v >> 12) & 63]; + out[o++] = b64[(v >> 6) & 63]; + out[o++] = b64[v & 63]; + } + if (i < n) + { + uint32_t v = (uint32_t)in[i] << 16 | (i + 1 < n ? (uint32_t)in[i + 1] << 8 : 0); + out[o++] = b64[v >> 18]; + out[o++] = b64[(v >> 12) & 63]; + if (i + 1 < n) + out[o++] = b64[(v >> 6) & 63]; + else if (pad) + out[o++] = '='; + if (pad) + out[o++] = '='; + } + out[o] = 0; + return o; +} + +int b64_decode(const char *in, size_t n, uint8_t *out, size_t room) +{ + uint32_t v = 0; + int bits = 0; + size_t i, o = 0; + + for (i = 0; i < n && in[i] != '='; i++) + { + const char *c = strchr(b64, in[i]); + if (!c || !in[i]) + return -1; + v = v << 6 | (uint32_t)(c - b64); + bits += 6; + if (bits >= 8) + { + bits -= 8; + if (o >= room) + return -1; + out[o++] = (uint8_t)(v >> bits); + } + } + return (int)o; +} + +int namelist_has(const uint8_t *list, uint32_t len, const char *name) +{ + size_t n = strlen(name); + uint32_t i = 0; + + while (i <= len) + { + uint32_t j = i; + while (j < len && list[j] != ',') + j++; + if (j - i == n && !memcmp(list + i, name, n)) + return 1; + i = j + 1; + } + return 0; +} diff --git a/net/ssh/buf.h b/net/ssh/buf.h new file mode 100644 index 00000000..442cc79f --- /dev/null +++ b/net/ssh/buf.h @@ -0,0 +1,46 @@ +/* growable byte buffers with SSH wire encoding (RFC 4251 section 5) */ +#ifndef BUF_H +#define BUF_H +#include +#include + +struct buf { + uint8_t *d; + size_t len, cap; /* bytes held, allocated */ + size_t pos; /* read position */ + int err; /* a read ran past the end */ +}; + +void buf_init(struct buf *b); +void buf_free(struct buf *b); +void buf_reset(struct buf *b); +void buf_consume(struct buf *b, size_t n); /* drop n bytes at the front */ +void buf_reserve(struct buf *b, size_t n); +size_t buf_left(const struct buf *b); /* unread bytes */ + +void put_bytes(struct buf *b, const void *p, size_t n); +void put_u8(struct buf *b, uint8_t v); +void put_u32(struct buf *b, uint32_t v); +void put_u64(struct buf *b, uint64_t v); +void put_str(struct buf *b, const void *p, size_t n); +void put_cstr(struct buf *b, const char *s); +void put_mpint(struct buf *b, const uint8_t *be, size_t n); /* unsigned, big endian */ + +uint8_t get_u8(struct buf *b); +uint32_t get_u32(struct buf *b); +uint64_t get_u64(struct buf *b); +const uint8_t *get_bytes(struct buf *b, size_t n); +const uint8_t *get_str(struct buf *b, uint32_t *len); +int get_cstr(struct buf *b, char *out, size_t room); /* 0 if too long or bad */ + +uint32_t peek_u32(const uint8_t *p); +void poke_u32(uint8_t *p, uint32_t v); + +/* base64 (RFC 4648); decode returns the length or -1 */ +size_t b64_encode(const uint8_t *in, size_t n, char *out, int pad); +int b64_decode(const char *in, size_t n, uint8_t *out, size_t room); + +/* name-list helpers: is `name` in the comma separated list? */ +int namelist_has(const uint8_t *list, uint32_t len, const char *name); + +#endif diff --git a/net/ssh/console.c b/net/ssh/console.c new file mode 100644 index 00000000..d997c443 --- /dev/null +++ b/net/ssh/console.c @@ -0,0 +1,341 @@ +/* remote console: a DOS text screen (80x25, CGA attributes, code page 437) + to ANSI/UTF-8 terminal output, and terminal input to BIOS keys */ +#include +#include +#include "console.h" + +static const uint16_t cp437[256] = { + 0x0020, 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, + 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, + 0x25BA, 0x25C4, 0x2195, 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, + 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, + 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x2302, + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, + 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, + 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, + 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, + 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, + 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, + 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, + 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, + 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, + 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 +}; + +static void put(struct buf *o, const char *s) +{ + put_bytes(o, s, strlen(s)); +} + +static void put_char(struct buf *o, uint8_t c) +{ + uint16_t u = cp437[c]; + uint8_t t[3]; + + if (u < 0x80) + put_u8(o, (uint8_t)u); + else if (u < 0x800) + { + t[0] = (uint8_t)(0xc0 | u >> 6); + t[1] = (uint8_t)(0x80 | (u & 0x3f)); + put_bytes(o, t, 2); + } + else + { + t[0] = (uint8_t)(0xe0 | u >> 12); + t[1] = (uint8_t)(0x80 | ((u >> 6) & 0x3f)); + t[2] = (uint8_t)(0x80 | (u & 0x3f)); + put_bytes(o, t, 3); + } +} + +static void set_attr(struct console *c, struct buf *o, uint8_t a) +{ + static const char ansi[8] = { 0, 4, 2, 6, 1, 5, 3, 7 }; /* CGA -> ANSI order */ + char s[24]; + int fg = a & 15, bg = (a >> 4) & 7; + + if (c->attr == a) + return; + snprintf(s, sizeof(s), "\033[0;%d;%dm", fg >= 8 ? 90 + ansi[fg - 8] : 30 + ansi[fg], 40 + ansi[bg]); + put(o, s); + c->attr = a; +} + +static void goto_rc(struct buf *o, int r, int col) +{ + char s[32]; + + snprintf(s, sizeof(s), "\033[%d;%dH", r + 1, col + 1); + put(o, s); +} + +void con_init(struct console *c) +{ + memset(c, 0, sizeof(*c)); + c->attr = -1; +} + +static int row_eq(const uint8_t *a, int ra, const uint8_t *b, int rb) +{ + return !memcmp(a + ra * CON_COLS * 2, b + rb * CON_COLS * 2, CON_COLS * 2); +} + +static int row_blank(const uint8_t *a, int r) +{ + int i; + + for (i = 0; i < CON_COLS; i++) + if (a[(r * CON_COLS + i) * 2] > ' ') + return 0; + return 1; +} + +int con_render(struct console *c, const uint8_t *cells, int row, int col, int hidden, struct buf *o) +{ + size_t start = o->len; + int r, i, k; + + if (!c->have) + { + /* fresh terminal: 25 line scrolling region, clear, draw all */ + put(o, "\033[0m\033[1;25r\033[2J"); + c->attr = -1; + memset(c->last, 0, sizeof(c->last)); + for (i = 0; i < CON_COLS * CON_ROWS; i++) + c->last[i * 2 + 1] = 0x07; + c->row = c->col = -1; + c->hidden = -1; + c->have = 1; + } + else if (!memcmp(c->last, cells, sizeof(c->last)) && row == c->row && col == c->col && + hidden == c->hidden) + return 0; + + /* scrolled up by k lines? then let the terminal scroll too */ + for (k = 1; k < CON_ROWS; k++) + { + int ok = 1, nonblank = 0; + for (r = 0; r + k < CON_ROWS && ok; r++) + { + ok = row_eq(cells, r, c->last, r + k); + nonblank |= !row_blank(cells, r); + } + if (ok && nonblank) + break; + } + if (k < CON_ROWS && memcmp(c->last, cells, sizeof(c->last))) + { + goto_rc(o, CON_ROWS - 1, 0); + set_attr(c, o, 0x07); + for (i = 0; i < k; i++) + put(o, "\n"); + memmove(c->last, c->last + k * CON_COLS * 2, (size_t)(CON_ROWS - k) * CON_COLS * 2); + for (i = (CON_ROWS - k) * CON_COLS; i < CON_ROWS * CON_COLS; i++) + { + c->last[i * 2] = ' '; + c->last[i * 2 + 1] = 0x07; + } + } + + /* changed cells, row by row */ + for (r = 0; r < CON_ROWS; r++) + { + int first = -1, last = -1; + for (i = 0; i < CON_COLS; i++) + { + int p = (r * CON_COLS + i) * 2; + uint8_t ch = cells[p] ? cells[p] : ' '; + uint8_t lch = c->last[p] ? c->last[p] : ' '; + if (ch != lch || cells[p + 1] != c->last[p + 1]) + { + if (first < 0) + first = i; + last = i; + } + } + if (first < 0) + continue; + if (r == CON_ROWS - 1 && last == CON_COLS - 1) + last--; /* never the last cell: it would scroll */ + goto_rc(o, r, first); + for (i = first; i <= last; i++) + { + int p = (r * CON_COLS + i) * 2; + set_attr(c, o, cells[p + 1]); + put_char(o, cells[p]); + } + } + memcpy(c->last, cells, sizeof(c->last)); + + if (hidden != c->hidden) + { + put(o, hidden ? "\033[?25l" : "\033[?25h"); + c->hidden = hidden; + } + if (row >= 0 && row < CON_ROWS && col >= 0 && col < CON_COLS) + goto_rc(o, row, col); + c->row = row; + c->col = col; + return o->len > start; +} + +void con_reset(struct buf *o) +{ + put(o, "\033[0m\033[r\033[?25h\033[25;1H\r\n"); +} + +/* ---------------------------------------------------------------- */ +/* input */ + +/* scan codes of the US keyboard for ASCII 20h..7Eh */ +static const uint8_t scan_of[95] = { + 0x39, 0x02, 0x28, 0x04, 0x05, 0x06, 0x08, 0x28, 0x0A, 0x0B, 0x09, 0x0D, 0x33, 0x0C, 0x34, 0x35, + 0x0B, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x27, 0x27, 0x33, 0x0D, 0x34, 0x35, + 0x03, 0x1E, 0x30, 0x2E, 0x20, 0x12, 0x21, 0x22, 0x23, 0x17, 0x24, 0x25, 0x26, 0x32, 0x31, 0x18, + 0x19, 0x10, 0x13, 0x1F, 0x14, 0x16, 0x2F, 0x11, 0x2D, 0x15, 0x2C, 0x1A, 0x2B, 0x1B, 0x07, 0x0C, + 0x29, 0x1E, 0x30, 0x2E, 0x20, 0x12, 0x21, 0x22, 0x23, 0x17, 0x24, 0x25, 0x26, 0x32, 0x31, 0x18, + 0x19, 0x10, 0x13, 0x1F, 0x14, 0x16, 0x2F, 0x11, 0x2D, 0x15, 0x2C, 0x1A, 0x2B, 0x1B, 0x29 +}; + +static uint16_t key_ascii(uint8_t c) +{ + if (c == '\r') + return 0x1c0d; + if (c == 0x7f || c == 0x08) + return 0x0e08; + if (c == '\t') + return 0x0f09; + if (c == 0x1b) + return 0x011b; + if (c >= 1 && c <= 26) /* Ctrl+letter */ + return (uint16_t)(scan_of['a' - 0x20 + c - 1] << 8 | c); + if (c >= 0x20 && c <= 0x7e) + return (uint16_t)(scan_of[c - 0x20] << 8 | c); + return c; +} + +static uint16_t key_csi_num(int n) +{ + switch (n) + { + case 1: case 7: return 0x4700; /* Home */ + case 2: return 0x5200; /* Insert */ + case 3: return 0x5300; /* Delete */ + case 4: case 8: return 0x4f00; /* End */ + case 5: return 0x4900; /* Page Up */ + case 6: return 0x5100; /* Page Down */ + case 11: return 0x3b00; case 12: return 0x3c00; case 13: return 0x3d00; + case 14: return 0x3e00; case 15: return 0x3f00; + case 17: return 0x4000; case 18: return 0x4100; case 19: return 0x4200; + case 20: return 0x4300; case 21: return 0x4400; + case 23: return 0x8500; case 24: return 0x8600; + } + return 0; +} + +static uint16_t key_final(uint8_t f) +{ + switch (f) + { + case 'A': return 0x4800; /* arrows */ + case 'B': return 0x5000; + case 'C': return 0x4d00; + case 'D': return 0x4b00; + case 'H': return 0x4700; + case 'F': return 0x4f00; + case 'P': return 0x3b00; /* F1..F4 (SS3 or CSI 1;mP) */ + case 'Q': return 0x3c00; + case 'R': return 0x3d00; + case 'S': return 0x3e00; + } + return 0; +} + +/* back from Unicode to code page 437 (0 if there is no such character) */ +uint8_t cp437_from_unicode(uint32_t u) +{ + int i; + + if (u >= 0x20 && u < 0x7f) + return (uint8_t)u; + for (i = 128; i < 256; i++) + if (cp437[i] == u) + return (uint8_t)i; + return 0; +} + +uint32_t cp437_to_unicode(uint8_t c) +{ + return cp437[c]; +} + +int con_keys(struct console *c, const uint8_t *in, size_t n, uint16_t *keys, int max) +{ + size_t i = 0; + int k = 0; + + while (i < n && k < max) + { + uint8_t ch = in[i]; + if (ch == '\n' && c->last_cr) + { + c->last_cr = 0; + i++; + continue; /* CR LF: one Enter */ + } + c->last_cr = ch == '\r'; + if (ch == '\n') + ch = '\r'; + if (ch == 0x1b && i + 1 < n && (in[i + 1] == '[' || in[i + 1] == 'O')) + { + size_t j = i + 2; + int num = 0; + uint16_t key; + while (j < n && ((in[j] >= '0' && in[j] <= '9') || in[j] == ';')) + { + if (in[j] == ';') + num = num ? num : 1; /* keep the first parameter */ + else if (!memchr(in + i + 2, ';', j - i - 2)) + num = num * 10 + (in[j] - '0'); + j++; + } + if (j >= n) + break; /* incomplete: wait for the rest */ + key = in[j] == '~' ? key_csi_num(num) : key_final(in[j]); + if (key) + keys[k++] = key; + i = j + 1; + continue; + } + if (ch >= 0xc0) /* UTF-8 sequence */ + { + size_t len = ch >= 0xf0 ? 4 : ch >= 0xe0 ? 3 : 2, j; + uint32_t u = ch & (0x3f >> (len - 1)); + if (i + len > n) + break; + for (j = 1; j < len; j++) + u = u << 6 | (in[i + j] & 0x3f); + ch = cp437_from_unicode(u); + if (ch) + keys[k++] = ch; + i += len; + continue; + } + keys[k++] = key_ascii(ch); + i++; + } + c->used = i; + return k; +} diff --git a/net/ssh/console.h b/net/ssh/console.h new file mode 100644 index 00000000..bb5dfa5c --- /dev/null +++ b/net/ssh/console.h @@ -0,0 +1,28 @@ +#ifndef CONSOLE_H +#define CONSOLE_H +#include +#include "buf.h" + +#define CON_COLS 80 +#define CON_ROWS 25 + +struct console { + uint8_t last[CON_COLS * CON_ROWS * 2]; /* what the terminal shows */ + int have, row, col, hidden, attr; + int last_cr; /* input: CR seen (CR LF = 1 Enter) */ + size_t used; /* input bytes con_keys consumed */ +}; + +void con_init(struct console *c); +/* ANSI output for the changes since the last call; 1 if any */ +int con_render(struct console *c, const uint8_t *cells, int row, int col, int hidden, struct buf *o); +/* leave the terminal in a sane state */ +void con_reset(struct buf *o); +/* terminal input -> BIOS keys (scan << 8 | ASCII); c->used = bytes taken */ +int con_keys(struct console *c, const uint8_t *in, size_t n, uint16_t *keys, int max); + +/* code page 437 <-> Unicode */ +uint8_t cp437_from_unicode(uint32_t u); +uint32_t cp437_to_unicode(uint8_t c); + +#endif diff --git a/net/ssh/crypto/LICENCE.md b/net/ssh/crypto/LICENCE.md new file mode 100644 index 00000000..9c3fae95 --- /dev/null +++ b/net/ssh/crypto/LICENCE.md @@ -0,0 +1,167 @@ +Monocypher as a whole is dual-licensed. Choose whichever licence you +want from the two licences listed below. + +The first licence is a regular 2-clause BSD licence. The second licence +is the CC-0 from Creative Commons. It is intended to release Monocypher +to the public domain. The BSD licence serves as a fallback option. + +See the individual files for specific information about who contributed +to what file during which years. See below for special notes. + +Licence 1 (2-clause BSD) +------------------------ + +Copyright (c) 2017-2023, Loup Vaillant +Copyright (c) 2017-2019, Michael Savage +Copyright (c) 2017-2023, Fabio Scotoni +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Licence 2 (CC-0) +---------------- + +> CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE +> LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN +> ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS +> INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES +> REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS +> PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM +> THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED +> HEREUNDER. + +### Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work +of authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without +fear of later claims of infringement build upon, modify, incorporate in +other works, reuse and redistribute as freely as possible in any form +whatsoever and for any purposes, including without limitation commercial +purposes. These owners may contribute to the Commons to promote the +ideal of a free culture and the further production of creative, cultural +and scientific works, or to gain reputation or greater distribution for +their Work in part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or +she is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under +its terms, with knowledge of his or her Copyright and Related Rights in +the Work and the meaning and intended legal effect of CC0 on those +rights. + +1. **Copyright and Related Rights.** A Work made available under CC0 may + be protected by copyright and related or neighboring rights + ("Copyright and Related Rights"). Copyright and Related Rights + include, but are not limited to, the following: + + - the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + - moral rights retained by the original author(s) and/or + performer(s); publicity and privacy rights pertaining to a person's + image or likeness depicted in a Work; + - rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + - rights protecting the extraction, dissemination, use and reuse of + data in a Work; + - database rights (such as those arising under Directive 96/9/EC of + the European Parliament and of the Council of 11 March 1996 on the + legal protection of databases, and under any national + implementation thereof, including any amended or successor version + of such directive); and + - other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. **Waiver.** To the greatest extent permitted by, but not in + contravention of, applicable law, Affirmer hereby overtly, fully, + permanently, irrevocably and unconditionally waives, abandons, and + surrenders all of Affirmer's Copyright and Related Rights and + associated claims and causes of action, whether now known or unknown + (including existing as well as future claims and causes of action), + in the Work (i) in all territories worldwide, (ii) for the maximum + duration provided by applicable law or treaty (including future time + extensions), (iii) in any current or future medium and for any number + of copies, and (iv) for any purpose whatsoever, including without + limitation commercial, advertising or promotional purposes (the + "Waiver"). Affirmer makes the Waiver for the benefit of each member + of the public at large and to the detriment of Affirmer's heirs and + successors, fully intending that such Waiver shall not be subject to + revocation, rescission, cancellation, termination, or any other legal + or equitable action to disrupt the quiet enjoyment of the Work by the + public as contemplated by Affirmer's express Statement of Purpose. + +3. **Public License Fallback.** Should any part of the Waiver for any + reason be judged legally invalid or ineffective under applicable law, + then the Waiver shall be preserved to the maximum extent permitted + taking into account Affirmer's express Statement of Purpose. In + addition, to the extent the Waiver is so judged Affirmer hereby + grants to each affected person a royalty-free, non transferable, non + sublicensable, non exclusive, irrevocable and unconditional license + to exercise Affirmer's Copyright and Related Rights in the Work (i) + in all territories worldwide, (ii) for the maximum duration provided + by applicable law or treaty (including future time extensions), (iii) + in any current or future medium and for any number of copies, and + (iv) for any purpose whatsoever, including without limitation + commercial, advertising or promotional purposes (the "License"). The + License shall be deemed effective as of the date CC0 was applied by + Affirmer to the Work. Should any part of the License for any reason + be judged legally invalid or ineffective under applicable law, such + partial invalidity or ineffectiveness shall not invalidate the + remainder of the License, and in such case Affirmer hereby affirms + that he or she will not (i) exercise any of his or her remaining + Copyright and Related Rights in the Work or (ii) assert any + associated claims and causes of action with respect to the Work, in + either case contrary to Affirmer's express Statement of Purpose. + +4. **Limitations and Disclaimers.** + + - No trademark or patent rights held by Affirmer are waived, + abandoned, surrendered, licensed or otherwise affected by this + document. + - Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, + or the present or absence of errors, whether or not discoverable, + all to the greatest extent permissible under applicable law. + - Affirmer disclaims responsibility for clearing rights of other + persons that may apply to the Work or any use thereof, including + without limitation any person's Copyright and Related Rights in the + Work. Further, Affirmer disclaims responsibility for obtaining any + necessary consents, permissions or other rights required for any + use of the Work. + - Affirmer understands and acknowledges that Creative Commons is not + a party to this document and has no duty or obligation with respect + to this CC0 or use of the Work. diff --git a/net/ssh/crypto/README b/net/ssh/crypto/README new file mode 100644 index 00000000..b06971c4 --- /dev/null +++ b/net/ssh/crypto/README @@ -0,0 +1,3 @@ +Monocypher 4.0.2 (https://monocypher.org), unmodified. +tarball sha256 38d07179738c0c90677dba3ceb7a7b8496bcfea758ba1a53e803fed30ae0879c +(same from monocypher.org and the GitHub release). Licence: BSD-2 or CC-0, LICENCE.md. diff --git a/net/ssh/crypto/monocypher-ed25519.c b/net/ssh/crypto/monocypher-ed25519.c new file mode 100644 index 00000000..1dbcfbb3 --- /dev/null +++ b/net/ssh/crypto/monocypher-ed25519.c @@ -0,0 +1,500 @@ +// Monocypher version 4.0.2 +// +// This file is dual-licensed. Choose whichever licence you want from +// the two licences listed below. +// +// The first licence is a regular 2-clause BSD licence. The second licence +// is the CC-0 from Creative Commons. It is intended to release Monocypher +// to the public domain. The BSD licence serves as a fallback option. +// +// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0 +// +// ------------------------------------------------------------------------ +// +// Copyright (c) 2017-2019, Loup Vaillant +// All rights reserved. +// +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// ------------------------------------------------------------------------ +// +// Written in 2017-2019 by Loup Vaillant +// +// To the extent possible under law, the author(s) have dedicated all copyright +// and related neighboring rights to this software to the public domain +// worldwide. This software is distributed without any warranty. +// +// You should have received a copy of the CC0 Public Domain Dedication along +// with this software. If not, see +// + +#include "monocypher-ed25519.h" + +#ifdef MONOCYPHER_CPP_NAMESPACE +namespace MONOCYPHER_CPP_NAMESPACE { +#endif + +///////////////// +/// Utilities /// +///////////////// +#define FOR(i, min, max) for (size_t i = min; i < max; i++) +#define COPY(dst, src, size) FOR(_i_, 0, size) (dst)[_i_] = (src)[_i_] +#define ZERO(buf, size) FOR(_i_, 0, size) (buf)[_i_] = 0 +#define WIPE_CTX(ctx) crypto_wipe(ctx , sizeof(*(ctx))) +#define WIPE_BUFFER(buffer) crypto_wipe(buffer, sizeof(buffer)) +#define MIN(a, b) ((a) <= (b) ? (a) : (b)) +typedef uint8_t u8; +typedef uint64_t u64; + +// Returns the smallest positive integer y such that +// (x + y) % pow_2 == 0 +// Basically, it's how many bytes we need to add to "align" x. +// Only works when pow_2 is a power of 2. +// Note: we use ~x+1 instead of -x to avoid compiler warnings +static size_t align(size_t x, size_t pow_2) +{ + return (~x + 1) & (pow_2 - 1); +} + +static u64 load64_be(const u8 s[8]) +{ + return((u64)s[0] << 56) + | ((u64)s[1] << 48) + | ((u64)s[2] << 40) + | ((u64)s[3] << 32) + | ((u64)s[4] << 24) + | ((u64)s[5] << 16) + | ((u64)s[6] << 8) + | (u64)s[7]; +} + +static void store64_be(u8 out[8], u64 in) +{ + out[0] = (in >> 56) & 0xff; + out[1] = (in >> 48) & 0xff; + out[2] = (in >> 40) & 0xff; + out[3] = (in >> 32) & 0xff; + out[4] = (in >> 24) & 0xff; + out[5] = (in >> 16) & 0xff; + out[6] = (in >> 8) & 0xff; + out[7] = in & 0xff; +} + +static void load64_be_buf (u64 *dst, const u8 *src, size_t size) { + FOR(i, 0, size) { dst[i] = load64_be(src + i*8); } +} + +/////////////// +/// SHA 512 /// +/////////////// +static u64 rot(u64 x, int c ) { return (x >> c) | (x << (64 - c)); } +static u64 ch (u64 x, u64 y, u64 z) { return (x & y) ^ (~x & z); } +static u64 maj(u64 x, u64 y, u64 z) { return (x & y) ^ ( x & z) ^ (y & z); } +static u64 big_sigma0(u64 x) { return rot(x, 28) ^ rot(x, 34) ^ rot(x, 39); } +static u64 big_sigma1(u64 x) { return rot(x, 14) ^ rot(x, 18) ^ rot(x, 41); } +static u64 lit_sigma0(u64 x) { return rot(x, 1) ^ rot(x, 8) ^ (x >> 7); } +static u64 lit_sigma1(u64 x) { return rot(x, 19) ^ rot(x, 61) ^ (x >> 6); } + +static const u64 K[80] = { + 0x428a2f98d728ae22,0x7137449123ef65cd,0xb5c0fbcfec4d3b2f,0xe9b5dba58189dbbc, + 0x3956c25bf348b538,0x59f111f1b605d019,0x923f82a4af194f9b,0xab1c5ed5da6d8118, + 0xd807aa98a3030242,0x12835b0145706fbe,0x243185be4ee4b28c,0x550c7dc3d5ffb4e2, + 0x72be5d74f27b896f,0x80deb1fe3b1696b1,0x9bdc06a725c71235,0xc19bf174cf692694, + 0xe49b69c19ef14ad2,0xefbe4786384f25e3,0x0fc19dc68b8cd5b5,0x240ca1cc77ac9c65, + 0x2de92c6f592b0275,0x4a7484aa6ea6e483,0x5cb0a9dcbd41fbd4,0x76f988da831153b5, + 0x983e5152ee66dfab,0xa831c66d2db43210,0xb00327c898fb213f,0xbf597fc7beef0ee4, + 0xc6e00bf33da88fc2,0xd5a79147930aa725,0x06ca6351e003826f,0x142929670a0e6e70, + 0x27b70a8546d22ffc,0x2e1b21385c26c926,0x4d2c6dfc5ac42aed,0x53380d139d95b3df, + 0x650a73548baf63de,0x766a0abb3c77b2a8,0x81c2c92e47edaee6,0x92722c851482353b, + 0xa2bfe8a14cf10364,0xa81a664bbc423001,0xc24b8b70d0f89791,0xc76c51a30654be30, + 0xd192e819d6ef5218,0xd69906245565a910,0xf40e35855771202a,0x106aa07032bbd1b8, + 0x19a4c116b8d2d0c8,0x1e376c085141ab53,0x2748774cdf8eeb99,0x34b0bcb5e19b48a8, + 0x391c0cb3c5c95a63,0x4ed8aa4ae3418acb,0x5b9cca4f7763e373,0x682e6ff3d6b2b8a3, + 0x748f82ee5defb2fc,0x78a5636f43172f60,0x84c87814a1f0ab72,0x8cc702081a6439ec, + 0x90befffa23631e28,0xa4506cebde82bde9,0xbef9a3f7b2c67915,0xc67178f2e372532b, + 0xca273eceea26619c,0xd186b8c721c0c207,0xeada7dd6cde0eb1e,0xf57d4f7fee6ed178, + 0x06f067aa72176fba,0x0a637dc5a2c898a6,0x113f9804bef90dae,0x1b710b35131c471b, + 0x28db77f523047d84,0x32caab7b40c72493,0x3c9ebe0a15c9bebc,0x431d67c49c100d4c, + 0x4cc5d4becb3e42b6,0x597f299cfc657e2a,0x5fcb6fab3ad6faec,0x6c44198c4a475817 +}; + +static void sha512_compress(crypto_sha512_ctx *ctx) +{ + u64 a = ctx->hash[0]; u64 b = ctx->hash[1]; + u64 c = ctx->hash[2]; u64 d = ctx->hash[3]; + u64 e = ctx->hash[4]; u64 f = ctx->hash[5]; + u64 g = ctx->hash[6]; u64 h = ctx->hash[7]; + + FOR (j, 0, 16) { + u64 in = K[j] + ctx->input[j]; + u64 t1 = big_sigma1(e) + ch (e, f, g) + h + in; + u64 t2 = big_sigma0(a) + maj(a, b, c); + h = g; g = f; f = e; e = d + t1; + d = c; c = b; b = a; a = t1 + t2; + } + size_t i16 = 0; + FOR(i, 1, 5) { + i16 += 16; + FOR (j, 0, 16) { + ctx->input[j] += lit_sigma1(ctx->input[(j- 2) & 15]); + ctx->input[j] += lit_sigma0(ctx->input[(j-15) & 15]); + ctx->input[j] += ctx->input[(j- 7) & 15]; + u64 in = K[i16 + j] + ctx->input[j]; + u64 t1 = big_sigma1(e) + ch (e, f, g) + h + in; + u64 t2 = big_sigma0(a) + maj(a, b, c); + h = g; g = f; f = e; e = d + t1; + d = c; c = b; b = a; a = t1 + t2; + } + } + + ctx->hash[0] += a; ctx->hash[1] += b; + ctx->hash[2] += c; ctx->hash[3] += d; + ctx->hash[4] += e; ctx->hash[5] += f; + ctx->hash[6] += g; ctx->hash[7] += h; +} + +// Write 1 input byte +static void sha512_set_input(crypto_sha512_ctx *ctx, u8 input) +{ + size_t word = ctx->input_idx >> 3; + size_t byte = ctx->input_idx & 7; + ctx->input[word] |= (u64)input << (8 * (7 - byte)); +} + +// Increment a 128-bit "word". +static void sha512_incr(u64 x[2], u64 y) +{ + x[1] += y; + if (x[1] < y) { + x[0]++; + } +} + +void crypto_sha512_init(crypto_sha512_ctx *ctx) +{ + ctx->hash[0] = 0x6a09e667f3bcc908; + ctx->hash[1] = 0xbb67ae8584caa73b; + ctx->hash[2] = 0x3c6ef372fe94f82b; + ctx->hash[3] = 0xa54ff53a5f1d36f1; + ctx->hash[4] = 0x510e527fade682d1; + ctx->hash[5] = 0x9b05688c2b3e6c1f; + ctx->hash[6] = 0x1f83d9abfb41bd6b; + ctx->hash[7] = 0x5be0cd19137e2179; + ctx->input_size[0] = 0; + ctx->input_size[1] = 0; + ctx->input_idx = 0; + ZERO(ctx->input, 16); +} + +void crypto_sha512_update(crypto_sha512_ctx *ctx, + const u8 *message, size_t message_size) +{ + // Avoid undefined NULL pointer increments with empty messages + if (message_size == 0) { + return; + } + + // Align ourselves with word boundaries + if ((ctx->input_idx & 7) != 0) { + size_t nb_bytes = MIN(align(ctx->input_idx, 8), message_size); + FOR (i, 0, nb_bytes) { + sha512_set_input(ctx, message[i]); + ctx->input_idx++; + } + message += nb_bytes; + message_size -= nb_bytes; + } + + // Align ourselves with block boundaries + if ((ctx->input_idx & 127) != 0) { + size_t nb_words = MIN(align(ctx->input_idx, 128), message_size) >> 3; + load64_be_buf(ctx->input + (ctx->input_idx >> 3), message, nb_words); + ctx->input_idx += nb_words << 3; + message += nb_words << 3; + message_size -= nb_words << 3; + } + + // Compress block if needed + if (ctx->input_idx == 128) { + sha512_incr(ctx->input_size, 1024); // size is in bits + sha512_compress(ctx); + ctx->input_idx = 0; + ZERO(ctx->input, 16); + } + + // Process the message block by block + FOR (i, 0, message_size >> 7) { // number of blocks + load64_be_buf(ctx->input, message, 16); + sha512_incr(ctx->input_size, 1024); // size is in bits + sha512_compress(ctx); + ctx->input_idx = 0; + ZERO(ctx->input, 16); + message += 128; + } + message_size &= 127; + + if (message_size != 0) { + // Remaining words + size_t nb_words = message_size >> 3; + load64_be_buf(ctx->input, message, nb_words); + ctx->input_idx += nb_words << 3; + message += nb_words << 3; + message_size -= nb_words << 3; + + // Remaining bytes + FOR (i, 0, message_size) { + sha512_set_input(ctx, message[i]); + ctx->input_idx++; + } + } +} + +void crypto_sha512_final(crypto_sha512_ctx *ctx, u8 hash[64]) +{ + // Add padding bit + if (ctx->input_idx == 0) { + ZERO(ctx->input, 16); + } + sha512_set_input(ctx, 128); + + // Update size + sha512_incr(ctx->input_size, ctx->input_idx * 8); + + // Compress penultimate block (if any) + if (ctx->input_idx > 111) { + sha512_compress(ctx); + ZERO(ctx->input, 14); + } + // Compress last block + ctx->input[14] = ctx->input_size[0]; + ctx->input[15] = ctx->input_size[1]; + sha512_compress(ctx); + + // Copy hash to output (big endian) + FOR (i, 0, 8) { + store64_be(hash + i*8, ctx->hash[i]); + } + + WIPE_CTX(ctx); +} + +void crypto_sha512(u8 hash[64], const u8 *message, size_t message_size) +{ + crypto_sha512_ctx ctx; + crypto_sha512_init (&ctx); + crypto_sha512_update(&ctx, message, message_size); + crypto_sha512_final (&ctx, hash); +} + +//////////////////// +/// HMAC SHA 512 /// +//////////////////// +void crypto_sha512_hmac_init(crypto_sha512_hmac_ctx *ctx, + const u8 *key, size_t key_size) +{ + // hash key if it is too long + if (key_size > 128) { + crypto_sha512(ctx->key, key, key_size); + key = ctx->key; + key_size = 64; + } + // Compute inner key: padded key XOR 0x36 + FOR (i, 0, key_size) { ctx->key[i] = key[i] ^ 0x36; } + FOR (i, key_size, 128) { ctx->key[i] = 0x36; } + // Start computing inner hash + crypto_sha512_init (&ctx->ctx); + crypto_sha512_update(&ctx->ctx, ctx->key, 128); +} + +void crypto_sha512_hmac_update(crypto_sha512_hmac_ctx *ctx, + const u8 *message, size_t message_size) +{ + crypto_sha512_update(&ctx->ctx, message, message_size); +} + +void crypto_sha512_hmac_final(crypto_sha512_hmac_ctx *ctx, u8 hmac[64]) +{ + // Finish computing inner hash + crypto_sha512_final(&ctx->ctx, hmac); + // Compute outer key: padded key XOR 0x5c + FOR (i, 0, 128) { + ctx->key[i] ^= 0x36 ^ 0x5c; + } + // Compute outer hash + crypto_sha512_init (&ctx->ctx); + crypto_sha512_update(&ctx->ctx, ctx->key , 128); + crypto_sha512_update(&ctx->ctx, hmac, 64); + crypto_sha512_final (&ctx->ctx, hmac); // outer hash + WIPE_CTX(ctx); +} + +void crypto_sha512_hmac(u8 hmac[64], const u8 *key, size_t key_size, + const u8 *message, size_t message_size) +{ + crypto_sha512_hmac_ctx ctx; + crypto_sha512_hmac_init (&ctx, key, key_size); + crypto_sha512_hmac_update(&ctx, message, message_size); + crypto_sha512_hmac_final (&ctx, hmac); +} + +//////////////////// +/// HKDF SHA 512 /// +//////////////////// +void crypto_sha512_hkdf_expand(u8 *okm, size_t okm_size, + const u8 *prk, size_t prk_size, + const u8 *info, size_t info_size) +{ + int not_first = 0; + u8 ctr = 1; + u8 blk[64]; + + while (okm_size > 0) { + size_t out_size = MIN(okm_size, sizeof(blk)); + + crypto_sha512_hmac_ctx ctx; + crypto_sha512_hmac_init(&ctx, prk , prk_size); + if (not_first) { + // For some reason HKDF uses some kind of CBC mode. + // For some reason CTR mode alone wasn't enough. + // Like what, they didn't trust HMAC in 2010? Really?? + crypto_sha512_hmac_update(&ctx, blk , sizeof(blk)); + } + crypto_sha512_hmac_update(&ctx, info, info_size); + crypto_sha512_hmac_update(&ctx, &ctr, 1); + crypto_sha512_hmac_final(&ctx, blk); + + COPY(okm, blk, out_size); + + not_first = 1; + okm += out_size; + okm_size -= out_size; + ctr++; + } +} + +void crypto_sha512_hkdf(u8 *okm , size_t okm_size, + const u8 *ikm , size_t ikm_size, + const u8 *salt, size_t salt_size, + const u8 *info, size_t info_size) +{ + // Extract + u8 prk[64]; + crypto_sha512_hmac(prk, salt, salt_size, ikm, ikm_size); + + // Expand + crypto_sha512_hkdf_expand(okm, okm_size, prk, sizeof(prk), info, info_size); +} + +/////////////// +/// Ed25519 /// +/////////////// +void crypto_ed25519_key_pair(u8 secret_key[64], u8 public_key[32], u8 seed[32]) +{ + u8 a[64]; + COPY(a, seed, 32); // a[ 0..31] = seed + crypto_wipe(seed, 32); + COPY(secret_key, a, 32); // secret key = seed + crypto_sha512(a, a, 32); // a[ 0..31] = scalar + crypto_eddsa_trim_scalar(a, a); // a[ 0..31] = trimmed scalar + crypto_eddsa_scalarbase(public_key, a); // public key = [trimmed scalar]B + COPY(secret_key + 32, public_key, 32); // secret key includes public half + WIPE_BUFFER(a); +} + +static void hash_reduce(u8 h[32], + const u8 *a, size_t a_size, + const u8 *b, size_t b_size, + const u8 *c, size_t c_size, + const u8 *d, size_t d_size) +{ + u8 hash[64]; + crypto_sha512_ctx ctx; + crypto_sha512_init (&ctx); + crypto_sha512_update(&ctx, a, a_size); + crypto_sha512_update(&ctx, b, b_size); + crypto_sha512_update(&ctx, c, c_size); + crypto_sha512_update(&ctx, d, d_size); + crypto_sha512_final (&ctx, hash); + crypto_eddsa_reduce(h, hash); +} + +static void ed25519_dom_sign(u8 signature [64], const u8 secret_key[32], + const u8 *dom, size_t dom_size, + const u8 *message, size_t message_size) +{ + u8 a[64]; // secret scalar and prefix + u8 r[32]; // secret deterministic "random" nonce + u8 h[32]; // publically verifiable hash of the message (not wiped) + u8 R[32]; // first half of the signature (allows overlapping inputs) + const u8 *pk = secret_key + 32; + + crypto_sha512(a, secret_key, 32); + crypto_eddsa_trim_scalar(a, a); + hash_reduce(r, dom, dom_size, a + 32, 32, message, message_size, 0, 0); + crypto_eddsa_scalarbase(R, r); + hash_reduce(h, dom, dom_size, R, 32, pk, 32, message, message_size); + COPY(signature, R, 32); + crypto_eddsa_mul_add(signature + 32, h, a, r); + + WIPE_BUFFER(a); + WIPE_BUFFER(r); +} + +void crypto_ed25519_sign(u8 signature [64], const u8 secret_key[64], + const u8 *message, size_t message_size) +{ + ed25519_dom_sign(signature, secret_key, 0, 0, message, message_size); +} + +int crypto_ed25519_check(const u8 signature[64], const u8 public_key[32], + const u8 *msg, size_t msg_size) +{ + u8 h_ram[32]; + hash_reduce(h_ram, signature, 32, public_key, 32, msg, msg_size, 0, 0); + return crypto_eddsa_check_equation(signature, public_key, h_ram); +} + +static const u8 domain[34] = "SigEd25519 no Ed25519 collisions\1"; + +void crypto_ed25519_ph_sign(uint8_t signature[64], const uint8_t secret_key[64], + const uint8_t message_hash[64]) +{ + ed25519_dom_sign(signature, secret_key, domain, sizeof(domain), + message_hash, 64); +} + +int crypto_ed25519_ph_check(const uint8_t sig[64], const uint8_t pk[32], + const uint8_t msg_hash[64]) +{ + u8 h_ram[32]; + hash_reduce(h_ram, domain, sizeof(domain), sig, 32, pk, 32, msg_hash, 64); + return crypto_eddsa_check_equation(sig, pk, h_ram); +} + + +#ifdef MONOCYPHER_CPP_NAMESPACE +} +#endif diff --git a/net/ssh/crypto/monocypher-ed25519.h b/net/ssh/crypto/monocypher-ed25519.h new file mode 100644 index 00000000..1e6d705d --- /dev/null +++ b/net/ssh/crypto/monocypher-ed25519.h @@ -0,0 +1,140 @@ +// Monocypher version 4.0.2 +// +// This file is dual-licensed. Choose whichever licence you want from +// the two licences listed below. +// +// The first licence is a regular 2-clause BSD licence. The second licence +// is the CC-0 from Creative Commons. It is intended to release Monocypher +// to the public domain. The BSD licence serves as a fallback option. +// +// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0 +// +// ------------------------------------------------------------------------ +// +// Copyright (c) 2017-2019, Loup Vaillant +// All rights reserved. +// +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// ------------------------------------------------------------------------ +// +// Written in 2017-2019 by Loup Vaillant +// +// To the extent possible under law, the author(s) have dedicated all copyright +// and related neighboring rights to this software to the public domain +// worldwide. This software is distributed without any warranty. +// +// You should have received a copy of the CC0 Public Domain Dedication along +// with this software. If not, see +// + +#ifndef ED25519_H +#define ED25519_H + +#include "monocypher.h" + +#ifdef MONOCYPHER_CPP_NAMESPACE +namespace MONOCYPHER_CPP_NAMESPACE { +#elif defined(__cplusplus) +extern "C" { +#endif + +//////////////////////// +/// Type definitions /// +//////////////////////// + +// Do not rely on the size or content on any of those types, +// they may change without notice. +typedef struct { + uint64_t hash[8]; + uint64_t input[16]; + uint64_t input_size[2]; + size_t input_idx; +} crypto_sha512_ctx; + +typedef struct { + uint8_t key[128]; + crypto_sha512_ctx ctx; +} crypto_sha512_hmac_ctx; + + +// SHA 512 +// ------- +void crypto_sha512_init (crypto_sha512_ctx *ctx); +void crypto_sha512_update(crypto_sha512_ctx *ctx, + const uint8_t *message, size_t message_size); +void crypto_sha512_final (crypto_sha512_ctx *ctx, uint8_t hash[64]); +void crypto_sha512(uint8_t hash[64], + const uint8_t *message, size_t message_size); + +// SHA 512 HMAC +// ------------ +void crypto_sha512_hmac_init(crypto_sha512_hmac_ctx *ctx, + const uint8_t *key, size_t key_size); +void crypto_sha512_hmac_update(crypto_sha512_hmac_ctx *ctx, + const uint8_t *message, size_t message_size); +void crypto_sha512_hmac_final(crypto_sha512_hmac_ctx *ctx, uint8_t hmac[64]); +void crypto_sha512_hmac(uint8_t hmac[64], + const uint8_t *key , size_t key_size, + const uint8_t *message, size_t message_size); + +// SHA 512 HKDF +// ------------ +void crypto_sha512_hkdf_expand(uint8_t *okm, size_t okm_size, + const uint8_t *prk, size_t prk_size, + const uint8_t *info, size_t info_size); +void crypto_sha512_hkdf(uint8_t *okm , size_t okm_size, + const uint8_t *ikm , size_t ikm_size, + const uint8_t *salt, size_t salt_size, + const uint8_t *info, size_t info_size); + +// Ed25519 +// ------- +// Signatures (EdDSA with curve25519 + SHA-512) +// -------------------------------------------- +void crypto_ed25519_key_pair(uint8_t secret_key[64], + uint8_t public_key[32], + uint8_t seed[32]); +void crypto_ed25519_sign(uint8_t signature [64], + const uint8_t secret_key[64], + const uint8_t *message, size_t message_size); +int crypto_ed25519_check(const uint8_t signature [64], + const uint8_t public_key[32], + const uint8_t *message, size_t message_size); + +// Pre-hash variants +void crypto_ed25519_ph_sign(uint8_t signature [64], + const uint8_t secret_key [64], + const uint8_t message_hash[64]); +int crypto_ed25519_ph_check(const uint8_t signature [64], + const uint8_t public_key [32], + const uint8_t message_hash[64]); + +#ifdef __cplusplus +} +#endif + +#endif // ED25519_H diff --git a/net/ssh/crypto/monocypher.c b/net/ssh/crypto/monocypher.c new file mode 100644 index 00000000..d3930fb8 --- /dev/null +++ b/net/ssh/crypto/monocypher.c @@ -0,0 +1,2956 @@ +// Monocypher version 4.0.2 +// +// This file is dual-licensed. Choose whichever licence you want from +// the two licences listed below. +// +// The first licence is a regular 2-clause BSD licence. The second licence +// is the CC-0 from Creative Commons. It is intended to release Monocypher +// to the public domain. The BSD licence serves as a fallback option. +// +// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0 +// +// ------------------------------------------------------------------------ +// +// Copyright (c) 2017-2020, Loup Vaillant +// All rights reserved. +// +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// ------------------------------------------------------------------------ +// +// Written in 2017-2020 by Loup Vaillant +// +// To the extent possible under law, the author(s) have dedicated all copyright +// and related neighboring rights to this software to the public domain +// worldwide. This software is distributed without any warranty. +// +// You should have received a copy of the CC0 Public Domain Dedication along +// with this software. If not, see +// + +#include "monocypher.h" + +#ifdef MONOCYPHER_CPP_NAMESPACE +namespace MONOCYPHER_CPP_NAMESPACE { +#endif + +///////////////// +/// Utilities /// +///////////////// +#define FOR_T(type, i, start, end) for (type i = (start); i < (end); i++) +#define FOR(i, start, end) FOR_T(size_t, i, start, end) +#define COPY(dst, src, size) FOR(_i_, 0, size) (dst)[_i_] = (src)[_i_] +#define ZERO(buf, size) FOR(_i_, 0, size) (buf)[_i_] = 0 +#define WIPE_CTX(ctx) crypto_wipe(ctx , sizeof(*(ctx))) +#define WIPE_BUFFER(buffer) crypto_wipe(buffer, sizeof(buffer)) +#define MIN(a, b) ((a) <= (b) ? (a) : (b)) +#define MAX(a, b) ((a) >= (b) ? (a) : (b)) + +typedef int8_t i8; +typedef uint8_t u8; +typedef int16_t i16; +typedef uint32_t u32; +typedef int32_t i32; +typedef int64_t i64; +typedef uint64_t u64; + +static const u8 zero[128] = {0}; + +// returns the smallest positive integer y such that +// (x + y) % pow_2 == 0 +// Basically, y is the "gap" missing to align x. +// Only works when pow_2 is a power of 2. +// Note: we use ~x+1 instead of -x to avoid compiler warnings +static size_t gap(size_t x, size_t pow_2) +{ + return (~x + 1) & (pow_2 - 1); +} + +static u32 load24_le(const u8 s[3]) +{ + return + ((u32)s[0] << 0) | + ((u32)s[1] << 8) | + ((u32)s[2] << 16); +} + +static u32 load32_le(const u8 s[4]) +{ + return + ((u32)s[0] << 0) | + ((u32)s[1] << 8) | + ((u32)s[2] << 16) | + ((u32)s[3] << 24); +} + +static u64 load64_le(const u8 s[8]) +{ + return load32_le(s) | ((u64)load32_le(s+4) << 32); +} + +static void store32_le(u8 out[4], u32 in) +{ + out[0] = in & 0xff; + out[1] = (in >> 8) & 0xff; + out[2] = (in >> 16) & 0xff; + out[3] = (in >> 24) & 0xff; +} + +static void store64_le(u8 out[8], u64 in) +{ + store32_le(out , (u32)in ); + store32_le(out + 4, in >> 32); +} + +static void load32_le_buf (u32 *dst, const u8 *src, size_t size) { + FOR(i, 0, size) { dst[i] = load32_le(src + i*4); } +} +static void load64_le_buf (u64 *dst, const u8 *src, size_t size) { + FOR(i, 0, size) { dst[i] = load64_le(src + i*8); } +} +static void store32_le_buf(u8 *dst, const u32 *src, size_t size) { + FOR(i, 0, size) { store32_le(dst + i*4, src[i]); } +} +static void store64_le_buf(u8 *dst, const u64 *src, size_t size) { + FOR(i, 0, size) { store64_le(dst + i*8, src[i]); } +} + +static u64 rotr64(u64 x, u64 n) { return (x >> n) ^ (x << (64 - n)); } +static u32 rotl32(u32 x, u32 n) { return (x << n) ^ (x >> (32 - n)); } + +static int neq0(u64 diff) +{ + // constant time comparison to zero + // return diff != 0 ? -1 : 0 + u64 half = (diff >> 32) | ((u32)diff); + return (1 & ((half - 1) >> 32)) - 1; +} + +static u64 x16(const u8 a[16], const u8 b[16]) +{ + return (load64_le(a + 0) ^ load64_le(b + 0)) + | (load64_le(a + 8) ^ load64_le(b + 8)); +} +static u64 x32(const u8 a[32],const u8 b[32]){return x16(a,b)| x16(a+16, b+16);} +static u64 x64(const u8 a[64],const u8 b[64]){return x32(a,b)| x32(a+32, b+32);} +int crypto_verify16(const u8 a[16], const u8 b[16]){ return neq0(x16(a, b)); } +int crypto_verify32(const u8 a[32], const u8 b[32]){ return neq0(x32(a, b)); } +int crypto_verify64(const u8 a[64], const u8 b[64]){ return neq0(x64(a, b)); } + +void crypto_wipe(void *secret, size_t size) +{ + volatile u8 *v_secret = (u8*)secret; + ZERO(v_secret, size); +} + +///////////////// +/// Chacha 20 /// +///////////////// +#define QUARTERROUND(a, b, c, d) \ + a += b; d = rotl32(d ^ a, 16); \ + c += d; b = rotl32(b ^ c, 12); \ + a += b; d = rotl32(d ^ a, 8); \ + c += d; b = rotl32(b ^ c, 7) + +static void chacha20_rounds(u32 out[16], const u32 in[16]) +{ + // The temporary variables make Chacha20 10% faster. + u32 t0 = in[ 0]; u32 t1 = in[ 1]; u32 t2 = in[ 2]; u32 t3 = in[ 3]; + u32 t4 = in[ 4]; u32 t5 = in[ 5]; u32 t6 = in[ 6]; u32 t7 = in[ 7]; + u32 t8 = in[ 8]; u32 t9 = in[ 9]; u32 t10 = in[10]; u32 t11 = in[11]; + u32 t12 = in[12]; u32 t13 = in[13]; u32 t14 = in[14]; u32 t15 = in[15]; + + FOR (i, 0, 10) { // 20 rounds, 2 rounds per loop. + QUARTERROUND(t0, t4, t8 , t12); // column 0 + QUARTERROUND(t1, t5, t9 , t13); // column 1 + QUARTERROUND(t2, t6, t10, t14); // column 2 + QUARTERROUND(t3, t7, t11, t15); // column 3 + QUARTERROUND(t0, t5, t10, t15); // diagonal 0 + QUARTERROUND(t1, t6, t11, t12); // diagonal 1 + QUARTERROUND(t2, t7, t8 , t13); // diagonal 2 + QUARTERROUND(t3, t4, t9 , t14); // diagonal 3 + } + out[ 0] = t0; out[ 1] = t1; out[ 2] = t2; out[ 3] = t3; + out[ 4] = t4; out[ 5] = t5; out[ 6] = t6; out[ 7] = t7; + out[ 8] = t8; out[ 9] = t9; out[10] = t10; out[11] = t11; + out[12] = t12; out[13] = t13; out[14] = t14; out[15] = t15; +} + +static const u8 *chacha20_constant = (const u8*)"expand 32-byte k"; // 16 bytes + +void crypto_chacha20_h(u8 out[32], const u8 key[32], const u8 in [16]) +{ + u32 block[16]; + load32_le_buf(block , chacha20_constant, 4); + load32_le_buf(block + 4, key , 8); + load32_le_buf(block + 12, in , 4); + + chacha20_rounds(block, block); + + // prevent reversal of the rounds by revealing only half of the buffer. + store32_le_buf(out , block , 4); // constant + store32_le_buf(out+16, block+12, 4); // counter and nonce + WIPE_BUFFER(block); +} + +u64 crypto_chacha20_djb(u8 *cipher_text, const u8 *plain_text, + size_t text_size, const u8 key[32], const u8 nonce[8], + u64 ctr) +{ + u32 input[16]; + load32_le_buf(input , chacha20_constant, 4); + load32_le_buf(input + 4, key , 8); + load32_le_buf(input + 14, nonce , 2); + input[12] = (u32) ctr; + input[13] = (u32)(ctr >> 32); + + // Whole blocks + u32 pool[16]; + size_t nb_blocks = text_size >> 6; + FOR (i, 0, nb_blocks) { + chacha20_rounds(pool, input); + if (plain_text != 0) { + FOR (j, 0, 16) { + u32 p = pool[j] + input[j]; + store32_le(cipher_text, p ^ load32_le(plain_text)); + cipher_text += 4; + plain_text += 4; + } + } else { + FOR (j, 0, 16) { + u32 p = pool[j] + input[j]; + store32_le(cipher_text, p); + cipher_text += 4; + } + } + input[12]++; + if (input[12] == 0) { + input[13]++; + } + } + text_size &= 63; + + // Last (incomplete) block + if (text_size > 0) { + if (plain_text == 0) { + plain_text = zero; + } + chacha20_rounds(pool, input); + u8 tmp[64]; + FOR (i, 0, 16) { + store32_le(tmp + i*4, pool[i] + input[i]); + } + FOR (i, 0, text_size) { + cipher_text[i] = tmp[i] ^ plain_text[i]; + } + WIPE_BUFFER(tmp); + } + ctr = input[12] + ((u64)input[13] << 32) + (text_size > 0); + + WIPE_BUFFER(pool); + WIPE_BUFFER(input); + return ctr; +} + +u32 crypto_chacha20_ietf(u8 *cipher_text, const u8 *plain_text, + size_t text_size, + const u8 key[32], const u8 nonce[12], u32 ctr) +{ + u64 big_ctr = ctr + ((u64)load32_le(nonce) << 32); + return (u32)crypto_chacha20_djb(cipher_text, plain_text, text_size, + key, nonce + 4, big_ctr); +} + +u64 crypto_chacha20_x(u8 *cipher_text, const u8 *plain_text, + size_t text_size, + const u8 key[32], const u8 nonce[24], u64 ctr) +{ + u8 sub_key[32]; + crypto_chacha20_h(sub_key, key, nonce); + ctr = crypto_chacha20_djb(cipher_text, plain_text, text_size, + sub_key, nonce + 16, ctr); + WIPE_BUFFER(sub_key); + return ctr; +} + +///////////////// +/// Poly 1305 /// +///////////////// + +// h = (h + c) * r +// preconditions: +// ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff +// ctx->r <= 0ffffffc_0ffffffc_0ffffffc_0fffffff +// end <= 1 +// Postcondition: +// ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff +static void poly_blocks(crypto_poly1305_ctx *ctx, const u8 *in, + size_t nb_blocks, unsigned end) +{ + // Local all the things! + const u32 r0 = ctx->r[0]; + const u32 r1 = ctx->r[1]; + const u32 r2 = ctx->r[2]; + const u32 r3 = ctx->r[3]; + const u32 rr0 = (r0 >> 2) * 5; // lose 2 bits... + const u32 rr1 = (r1 >> 2) + r1; // rr1 == (r1 >> 2) * 5 + const u32 rr2 = (r2 >> 2) + r2; // rr1 == (r2 >> 2) * 5 + const u32 rr3 = (r3 >> 2) + r3; // rr1 == (r3 >> 2) * 5 + const u32 rr4 = r0 & 3; // ...recover 2 bits + u32 h0 = ctx->h[0]; + u32 h1 = ctx->h[1]; + u32 h2 = ctx->h[2]; + u32 h3 = ctx->h[3]; + u32 h4 = ctx->h[4]; + + FOR (i, 0, nb_blocks) { + // h + c, without carry propagation + const u64 s0 = (u64)h0 + load32_le(in); in += 4; + const u64 s1 = (u64)h1 + load32_le(in); in += 4; + const u64 s2 = (u64)h2 + load32_le(in); in += 4; + const u64 s3 = (u64)h3 + load32_le(in); in += 4; + const u32 s4 = h4 + end; + + // (h + c) * r, without carry propagation + const u64 x0 = s0*r0+ s1*rr3+ s2*rr2+ s3*rr1+ s4*rr0; + const u64 x1 = s0*r1+ s1*r0 + s2*rr3+ s3*rr2+ s4*rr1; + const u64 x2 = s0*r2+ s1*r1 + s2*r0 + s3*rr3+ s4*rr2; + const u64 x3 = s0*r3+ s1*r2 + s2*r1 + s3*r0 + s4*rr3; + const u32 x4 = s4*rr4; + + // partial reduction modulo 2^130 - 5 + const u32 u5 = x4 + (x3 >> 32); // u5 <= 7ffffff5 + const u64 u0 = (u5 >> 2) * 5 + (x0 & 0xffffffff); + const u64 u1 = (u0 >> 32) + (x1 & 0xffffffff) + (x0 >> 32); + const u64 u2 = (u1 >> 32) + (x2 & 0xffffffff) + (x1 >> 32); + const u64 u3 = (u2 >> 32) + (x3 & 0xffffffff) + (x2 >> 32); + const u32 u4 = (u3 >> 32) + (u5 & 3); // u4 <= 4 + + // Update the hash + h0 = u0 & 0xffffffff; + h1 = u1 & 0xffffffff; + h2 = u2 & 0xffffffff; + h3 = u3 & 0xffffffff; + h4 = u4; + } + ctx->h[0] = h0; + ctx->h[1] = h1; + ctx->h[2] = h2; + ctx->h[3] = h3; + ctx->h[4] = h4; +} + +void crypto_poly1305_init(crypto_poly1305_ctx *ctx, const u8 key[32]) +{ + ZERO(ctx->h, 5); // Initial hash is zero + ctx->c_idx = 0; + // load r and pad (r has some of its bits cleared) + load32_le_buf(ctx->r , key , 4); + load32_le_buf(ctx->pad, key+16, 4); + FOR (i, 0, 1) { ctx->r[i] &= 0x0fffffff; } + FOR (i, 1, 4) { ctx->r[i] &= 0x0ffffffc; } +} + +void crypto_poly1305_update(crypto_poly1305_ctx *ctx, + const u8 *message, size_t message_size) +{ + // Avoid undefined NULL pointer increments with empty messages + if (message_size == 0) { + return; + } + + // Align ourselves with block boundaries + size_t aligned = MIN(gap(ctx->c_idx, 16), message_size); + FOR (i, 0, aligned) { + ctx->c[ctx->c_idx] = *message; + ctx->c_idx++; + message++; + message_size--; + } + + // If block is complete, process it + if (ctx->c_idx == 16) { + poly_blocks(ctx, ctx->c, 1, 1); + ctx->c_idx = 0; + } + + // Process the message block by block + size_t nb_blocks = message_size >> 4; + poly_blocks(ctx, message, nb_blocks, 1); + message += nb_blocks << 4; + message_size &= 15; + + // remaining bytes (we never complete a block here) + FOR (i, 0, message_size) { + ctx->c[ctx->c_idx] = message[i]; + ctx->c_idx++; + } +} + +void crypto_poly1305_final(crypto_poly1305_ctx *ctx, u8 mac[16]) +{ + // Process the last block (if any) + // We move the final 1 according to remaining input length + // (this will add less than 2^130 to the last input block) + if (ctx->c_idx != 0) { + ZERO(ctx->c + ctx->c_idx, 16 - ctx->c_idx); + ctx->c[ctx->c_idx] = 1; + poly_blocks(ctx, ctx->c, 1, 0); + } + + // check if we should subtract 2^130-5 by performing the + // corresponding carry propagation. + u64 c = 5; + FOR (i, 0, 4) { + c += ctx->h[i]; + c >>= 32; + } + c += ctx->h[4]; + c = (c >> 2) * 5; // shift the carry back to the beginning + // c now indicates how many times we should subtract 2^130-5 (0 or 1) + FOR (i, 0, 4) { + c += (u64)ctx->h[i] + ctx->pad[i]; + store32_le(mac + i*4, (u32)c); + c = c >> 32; + } + WIPE_CTX(ctx); +} + +void crypto_poly1305(u8 mac[16], const u8 *message, + size_t message_size, const u8 key[32]) +{ + crypto_poly1305_ctx ctx; + crypto_poly1305_init (&ctx, key); + crypto_poly1305_update(&ctx, message, message_size); + crypto_poly1305_final (&ctx, mac); +} + +//////////////// +/// BLAKE2 b /// +//////////////// +static const u64 iv[8] = { + 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, + 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, + 0x510e527fade682d1, 0x9b05688c2b3e6c1f, + 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179, +}; + +static void blake2b_compress(crypto_blake2b_ctx *ctx, int is_last_block) +{ + static const u8 sigma[12][16] = { + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, + { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, + { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, + { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, + { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, + { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, + { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, + { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + }; + + // increment input offset + u64 *x = ctx->input_offset; + size_t y = ctx->input_idx; + x[0] += y; + if (x[0] < y) { + x[1]++; + } + + // init work vector + u64 v0 = ctx->hash[0]; u64 v8 = iv[0]; + u64 v1 = ctx->hash[1]; u64 v9 = iv[1]; + u64 v2 = ctx->hash[2]; u64 v10 = iv[2]; + u64 v3 = ctx->hash[3]; u64 v11 = iv[3]; + u64 v4 = ctx->hash[4]; u64 v12 = iv[4] ^ ctx->input_offset[0]; + u64 v5 = ctx->hash[5]; u64 v13 = iv[5] ^ ctx->input_offset[1]; + u64 v6 = ctx->hash[6]; u64 v14 = iv[6] ^ (u64)~(is_last_block - 1); + u64 v7 = ctx->hash[7]; u64 v15 = iv[7]; + + // mangle work vector + u64 *input = ctx->input; +#define BLAKE2_G(a, b, c, d, x, y) \ + a += b + x; d = rotr64(d ^ a, 32); \ + c += d; b = rotr64(b ^ c, 24); \ + a += b + y; d = rotr64(d ^ a, 16); \ + c += d; b = rotr64(b ^ c, 63) +#define BLAKE2_ROUND(i) \ + BLAKE2_G(v0, v4, v8 , v12, input[sigma[i][ 0]], input[sigma[i][ 1]]); \ + BLAKE2_G(v1, v5, v9 , v13, input[sigma[i][ 2]], input[sigma[i][ 3]]); \ + BLAKE2_G(v2, v6, v10, v14, input[sigma[i][ 4]], input[sigma[i][ 5]]); \ + BLAKE2_G(v3, v7, v11, v15, input[sigma[i][ 6]], input[sigma[i][ 7]]); \ + BLAKE2_G(v0, v5, v10, v15, input[sigma[i][ 8]], input[sigma[i][ 9]]); \ + BLAKE2_G(v1, v6, v11, v12, input[sigma[i][10]], input[sigma[i][11]]); \ + BLAKE2_G(v2, v7, v8 , v13, input[sigma[i][12]], input[sigma[i][13]]); \ + BLAKE2_G(v3, v4, v9 , v14, input[sigma[i][14]], input[sigma[i][15]]) + +#ifdef BLAKE2_NO_UNROLLING + FOR (i, 0, 12) { + BLAKE2_ROUND(i); + } +#else + BLAKE2_ROUND(0); BLAKE2_ROUND(1); BLAKE2_ROUND(2); BLAKE2_ROUND(3); + BLAKE2_ROUND(4); BLAKE2_ROUND(5); BLAKE2_ROUND(6); BLAKE2_ROUND(7); + BLAKE2_ROUND(8); BLAKE2_ROUND(9); BLAKE2_ROUND(10); BLAKE2_ROUND(11); +#endif + + // update hash + ctx->hash[0] ^= v0 ^ v8; ctx->hash[1] ^= v1 ^ v9; + ctx->hash[2] ^= v2 ^ v10; ctx->hash[3] ^= v3 ^ v11; + ctx->hash[4] ^= v4 ^ v12; ctx->hash[5] ^= v5 ^ v13; + ctx->hash[6] ^= v6 ^ v14; ctx->hash[7] ^= v7 ^ v15; +} + +void crypto_blake2b_keyed_init(crypto_blake2b_ctx *ctx, size_t hash_size, + const u8 *key, size_t key_size) +{ + // initial hash + COPY(ctx->hash, iv, 8); + ctx->hash[0] ^= 0x01010000 ^ (key_size << 8) ^ hash_size; + + ctx->input_offset[0] = 0; // beginning of the input, no offset + ctx->input_offset[1] = 0; // beginning of the input, no offset + ctx->hash_size = hash_size; + ctx->input_idx = 0; + ZERO(ctx->input, 16); + + // if there is a key, the first block is that key (padded with zeroes) + if (key_size > 0) { + u8 key_block[128] = {0}; + COPY(key_block, key, key_size); + // same as calling crypto_blake2b_update(ctx, key_block , 128) + load64_le_buf(ctx->input, key_block, 16); + ctx->input_idx = 128; + } +} + +void crypto_blake2b_init(crypto_blake2b_ctx *ctx, size_t hash_size) +{ + crypto_blake2b_keyed_init(ctx, hash_size, 0, 0); +} + +void crypto_blake2b_update(crypto_blake2b_ctx *ctx, + const u8 *message, size_t message_size) +{ + // Avoid undefined NULL pointer increments with empty messages + if (message_size == 0) { + return; + } + + // Align with word boundaries + if ((ctx->input_idx & 7) != 0) { + size_t nb_bytes = MIN(gap(ctx->input_idx, 8), message_size); + size_t word = ctx->input_idx >> 3; + size_t byte = ctx->input_idx & 7; + FOR (i, 0, nb_bytes) { + ctx->input[word] |= (u64)message[i] << ((byte + i) << 3); + } + ctx->input_idx += nb_bytes; + message += nb_bytes; + message_size -= nb_bytes; + } + + // Align with block boundaries (faster than byte by byte) + if ((ctx->input_idx & 127) != 0) { + size_t nb_words = MIN(gap(ctx->input_idx, 128), message_size) >> 3; + load64_le_buf(ctx->input + (ctx->input_idx >> 3), message, nb_words); + ctx->input_idx += nb_words << 3; + message += nb_words << 3; + message_size -= nb_words << 3; + } + + // Process block by block + size_t nb_blocks = message_size >> 7; + FOR (i, 0, nb_blocks) { + if (ctx->input_idx == 128) { + blake2b_compress(ctx, 0); + } + load64_le_buf(ctx->input, message, 16); + message += 128; + ctx->input_idx = 128; + } + message_size &= 127; + + if (message_size != 0) { + // Compress block & flush input buffer as needed + if (ctx->input_idx == 128) { + blake2b_compress(ctx, 0); + ctx->input_idx = 0; + } + if (ctx->input_idx == 0) { + ZERO(ctx->input, 16); + } + // Fill remaining words (faster than byte by byte) + size_t nb_words = message_size >> 3; + load64_le_buf(ctx->input, message, nb_words); + ctx->input_idx += nb_words << 3; + message += nb_words << 3; + message_size -= nb_words << 3; + + // Fill remaining bytes + FOR (i, 0, message_size) { + size_t word = ctx->input_idx >> 3; + size_t byte = ctx->input_idx & 7; + ctx->input[word] |= (u64)message[i] << (byte << 3); + ctx->input_idx++; + } + } +} + +void crypto_blake2b_final(crypto_blake2b_ctx *ctx, u8 *hash) +{ + blake2b_compress(ctx, 1); // compress the last block + size_t hash_size = MIN(ctx->hash_size, 64); + size_t nb_words = hash_size >> 3; + store64_le_buf(hash, ctx->hash, nb_words); + FOR (i, nb_words << 3, hash_size) { + hash[i] = (ctx->hash[i >> 3] >> (8 * (i & 7))) & 0xff; + } + WIPE_CTX(ctx); +} + +void crypto_blake2b_keyed(u8 *hash, size_t hash_size, + const u8 *key, size_t key_size, + const u8 *message, size_t message_size) +{ + crypto_blake2b_ctx ctx; + crypto_blake2b_keyed_init(&ctx, hash_size, key, key_size); + crypto_blake2b_update (&ctx, message, message_size); + crypto_blake2b_final (&ctx, hash); +} + +void crypto_blake2b(u8 *hash, size_t hash_size, const u8 *msg, size_t msg_size) +{ + crypto_blake2b_keyed(hash, hash_size, 0, 0, msg, msg_size); +} + +////////////// +/// Argon2 /// +////////////// +// references to R, Z, Q etc. come from the spec + +// Argon2 operates on 1024 byte blocks. +typedef struct { u64 a[128]; } blk; + +// updates a BLAKE2 hash with a 32 bit word, little endian. +static void blake_update_32(crypto_blake2b_ctx *ctx, u32 input) +{ + u8 buf[4]; + store32_le(buf, input); + crypto_blake2b_update(ctx, buf, 4); + WIPE_BUFFER(buf); +} + +static void blake_update_32_buf(crypto_blake2b_ctx *ctx, + const u8 *buf, u32 size) +{ + blake_update_32(ctx, size); + crypto_blake2b_update(ctx, buf, size); +} + + +static void copy_block(blk *o,const blk*in){FOR(i, 0, 128) o->a[i] = in->a[i];} +static void xor_block(blk *o,const blk*in){FOR(i, 0, 128) o->a[i] ^= in->a[i];} + +// Hash with a virtually unlimited digest size. +// Doesn't extract more entropy than the base hash function. +// Mainly used for filling a whole kilobyte block with pseudo-random bytes. +// (One could use a stream cipher with a seed hash as the key, but +// this would introduce another dependency —and point of failure.) +static void extended_hash(u8 *digest, u32 digest_size, + const u8 *input , u32 input_size) +{ + crypto_blake2b_ctx ctx; + crypto_blake2b_init (&ctx, MIN(digest_size, 64)); + blake_update_32 (&ctx, digest_size); + crypto_blake2b_update(&ctx, input, input_size); + crypto_blake2b_final (&ctx, digest); + + if (digest_size > 64) { + // the conversion to u64 avoids integer overflow on + // ludicrously big hash sizes. + u32 r = (u32)(((u64)digest_size + 31) >> 5) - 2; + u32 i = 1; + u32 in = 0; + u32 out = 32; + while (i < r) { + // Input and output overlap. This is intentional + crypto_blake2b(digest + out, 64, digest + in, 64); + i += 1; + in += 32; + out += 32; + } + crypto_blake2b(digest + out, digest_size - (32 * r), digest + in , 64); + } +} + +#define LSB(x) ((u64)(u32)x) +#define G(a, b, c, d) \ + a += b + ((LSB(a) * LSB(b)) << 1); d ^= a; d = rotr64(d, 32); \ + c += d + ((LSB(c) * LSB(d)) << 1); b ^= c; b = rotr64(b, 24); \ + a += b + ((LSB(a) * LSB(b)) << 1); d ^= a; d = rotr64(d, 16); \ + c += d + ((LSB(c) * LSB(d)) << 1); b ^= c; b = rotr64(b, 63) +#define ROUND(v0, v1, v2, v3, v4, v5, v6, v7, \ + v8, v9, v10, v11, v12, v13, v14, v15) \ + G(v0, v4, v8, v12); G(v1, v5, v9, v13); \ + G(v2, v6, v10, v14); G(v3, v7, v11, v15); \ + G(v0, v5, v10, v15); G(v1, v6, v11, v12); \ + G(v2, v7, v8, v13); G(v3, v4, v9, v14) + +// Core of the compression function G. Computes Z from R in place. +static void g_rounds(blk *b) +{ + // column rounds (work_block = Q) + for (int i = 0; i < 128; i += 16) { + ROUND(b->a[i ], b->a[i+ 1], b->a[i+ 2], b->a[i+ 3], + b->a[i+ 4], b->a[i+ 5], b->a[i+ 6], b->a[i+ 7], + b->a[i+ 8], b->a[i+ 9], b->a[i+10], b->a[i+11], + b->a[i+12], b->a[i+13], b->a[i+14], b->a[i+15]); + } + // row rounds (b = Z) + for (int i = 0; i < 16; i += 2) { + ROUND(b->a[i ], b->a[i+ 1], b->a[i+ 16], b->a[i+ 17], + b->a[i+32], b->a[i+33], b->a[i+ 48], b->a[i+ 49], + b->a[i+64], b->a[i+65], b->a[i+ 80], b->a[i+ 81], + b->a[i+96], b->a[i+97], b->a[i+112], b->a[i+113]); + } +} + +const crypto_argon2_extras crypto_argon2_no_extras = { 0, 0, 0, 0 }; + +void crypto_argon2(u8 *hash, u32 hash_size, void *work_area, + crypto_argon2_config config, + crypto_argon2_inputs inputs, + crypto_argon2_extras extras) +{ + const u32 segment_size = config.nb_blocks / config.nb_lanes / 4; + const u32 lane_size = segment_size * 4; + const u32 nb_blocks = lane_size * config.nb_lanes; // rounding down + + // work area seen as blocks (must be suitably aligned) + blk *blocks = (blk*)work_area; + { + u8 initial_hash[72]; // 64 bytes plus 2 words for future hashes + crypto_blake2b_ctx ctx; + crypto_blake2b_init (&ctx, 64); + blake_update_32 (&ctx, config.nb_lanes ); // p: number of "threads" + blake_update_32 (&ctx, hash_size); + blake_update_32 (&ctx, config.nb_blocks); + blake_update_32 (&ctx, config.nb_passes); + blake_update_32 (&ctx, 0x13); // v: version number + blake_update_32 (&ctx, config.algorithm); // y: Argon2i, Argon2d... + blake_update_32_buf (&ctx, inputs.pass, inputs.pass_size); + blake_update_32_buf (&ctx, inputs.salt, inputs.salt_size); + blake_update_32_buf (&ctx, extras.key, extras.key_size); + blake_update_32_buf (&ctx, extras.ad, extras.ad_size); + crypto_blake2b_final(&ctx, initial_hash); // fill 64 first bytes only + + // fill first 2 blocks of each lane + u8 hash_area[1024]; + FOR_T(u32, l, 0, config.nb_lanes) { + FOR_T(u32, i, 0, 2) { + store32_le(initial_hash + 64, i); // first additional word + store32_le(initial_hash + 68, l); // second additional word + extended_hash(hash_area, 1024, initial_hash, 72); + load64_le_buf(blocks[l * lane_size + i].a, hash_area, 128); + } + } + + WIPE_BUFFER(initial_hash); + WIPE_BUFFER(hash_area); + } + + // Argon2i and Argon2id start with constant time indexing + int constant_time = config.algorithm != CRYPTO_ARGON2_D; + + // Fill (and re-fill) the rest of the blocks + // + // Note: even though each segment within the same slice can be + // computed in parallel, (one thread per lane), we are computing + // them sequentially, because Monocypher doesn't support threads. + // + // Yet optimal performance (and therefore security) requires one + // thread per lane. The only reason Monocypher supports multiple + // lanes is compatibility. + blk tmp; + FOR_T(u32, pass, 0, config.nb_passes) { + FOR_T(u32, slice, 0, 4) { + // On the first slice of the first pass, + // blocks 0 and 1 are already filled, hence pass_offset. + u32 pass_offset = pass == 0 && slice == 0 ? 2 : 0; + u32 slice_offset = slice * segment_size; + + // Argon2id switches back to non-constant time indexing + // after the first two slices of the first pass + if (slice == 2 && config.algorithm == CRYPTO_ARGON2_ID) { + constant_time = 0; + } + + // Each iteration of the following loop may be performed in + // a separate thread. All segments must be fully completed + // before we start filling the next slice. + FOR_T(u32, segment, 0, config.nb_lanes) { + blk index_block; + u32 index_ctr = 1; + FOR_T (u32, block, pass_offset, segment_size) { + // Current and previous blocks + u32 lane_offset = segment * lane_size; + blk *segment_start = blocks + lane_offset + slice_offset; + blk *current = segment_start + block; + blk *previous = + block == 0 && slice_offset == 0 + ? segment_start + lane_size - 1 + : segment_start + block - 1; + + u64 index_seed; + if (constant_time) { + if (block == pass_offset || (block % 128) == 0) { + // Fill or refresh deterministic indices block + + // seed the beginning of the block... + ZERO(index_block.a, 128); + index_block.a[0] = pass; + index_block.a[1] = segment; + index_block.a[2] = slice; + index_block.a[3] = nb_blocks; + index_block.a[4] = config.nb_passes; + index_block.a[5] = config.algorithm; + index_block.a[6] = index_ctr; + index_ctr++; + + // ... then shuffle it + copy_block(&tmp, &index_block); + g_rounds (&index_block); + xor_block (&index_block, &tmp); + copy_block(&tmp, &index_block); + g_rounds (&index_block); + xor_block (&index_block, &tmp); + } + index_seed = index_block.a[block % 128]; + } else { + index_seed = previous->a[0]; + } + + // Establish the reference set. *Approximately* comprises: + // - The last 3 slices (if they exist yet) + // - The already constructed blocks in the current segment + u32 next_slice = ((slice + 1) % 4) * segment_size; + u32 window_start = pass == 0 ? 0 : next_slice; + u32 nb_segments = pass == 0 ? slice : 3; + u64 lane = + pass == 0 && slice == 0 + ? segment + : (index_seed >> 32) % config.nb_lanes; + u32 window_size = + nb_segments * segment_size + + (lane == segment ? block-1 : + block == 0 ? (u32)-1 : 0); + + // Find reference block + u64 j1 = index_seed & 0xffffffff; // block selector + u64 x = (j1 * j1) >> 32; + u64 y = (window_size * x) >> 32; + u64 z = (window_size - 1) - y; + u64 ref = (window_start + z) % lane_size; + u32 index = lane * lane_size + (u32)ref; + blk *reference = blocks + index; + + // Shuffle the previous & reference block + // into the current block + copy_block(&tmp, previous); + xor_block (&tmp, reference); + if (pass == 0) { copy_block(current, &tmp); } + else { xor_block (current, &tmp); } + g_rounds (&tmp); + xor_block (current, &tmp); + } + } + } + } + + // Wipe temporary block + volatile u64* p = tmp.a; + ZERO(p, 128); + + // XOR last blocks of each lane + blk *last_block = blocks + lane_size - 1; + FOR_T (u32, lane, 1, config.nb_lanes) { + blk *next_block = last_block + lane_size; + xor_block(next_block, last_block); + last_block = next_block; + } + + // Serialize last block + u8 final_block[1024]; + store64_le_buf(final_block, last_block->a, 128); + + // Wipe work area + p = (u64*)work_area; + ZERO(p, 128 * nb_blocks); + + // Hash the very last block with H' into the output hash + extended_hash(hash, hash_size, final_block, 1024); + WIPE_BUFFER(final_block); +} + +//////////////////////////////////// +/// Arithmetic modulo 2^255 - 19 /// +//////////////////////////////////// +// Originally taken from SUPERCOP's ref10 implementation. +// A bit bigger than TweetNaCl, over 4 times faster. + +// field element +typedef i32 fe[10]; + +// field constants +// +// fe_one : 1 +// sqrtm1 : sqrt(-1) +// d : -121665 / 121666 +// D2 : 2 * -121665 / 121666 +// lop_x, lop_y: low order point in Edwards coordinates +// ufactor : -sqrt(-1) * 2 +// A2 : 486662^2 (A squared) +static const fe fe_one = {1}; +static const fe sqrtm1 = { + -32595792, -7943725, 9377950, 3500415, 12389472, + -272473, -25146209, -2005654, 326686, 11406482, +}; +static const fe d = { + -10913610, 13857413, -15372611, 6949391, 114729, + -8787816, -6275908, -3247719, -18696448, -12055116, +}; +static const fe D2 = { + -21827239, -5839606, -30745221, 13898782, 229458, + 15978800, -12551817, -6495438, 29715968, 9444199, +}; +static const fe lop_x = { + 21352778, 5345713, 4660180, -8347857, 24143090, + 14568123, 30185756, -12247770, -33528939, 8345319, +}; +static const fe lop_y = { + -6952922, -1265500, 6862341, -7057498, -4037696, + -5447722, 31680899, -15325402, -19365852, 1569102, +}; +static const fe ufactor = { + -1917299, 15887451, -18755900, -7000830, -24778944, + 544946, -16816446, 4011309, -653372, 10741468, +}; +static const fe A2 = { + 12721188, 3529, 0, 0, 0, 0, 0, 0, 0, 0, +}; + +static void fe_0(fe h) { ZERO(h , 10); } +static void fe_1(fe h) { h[0] = 1; ZERO(h+1, 9); } + +static void fe_copy(fe h,const fe f ){FOR(i,0,10) h[i] = f[i]; } +static void fe_neg (fe h,const fe f ){FOR(i,0,10) h[i] = -f[i]; } +static void fe_add (fe h,const fe f,const fe g){FOR(i,0,10) h[i] = f[i] + g[i];} +static void fe_sub (fe h,const fe f,const fe g){FOR(i,0,10) h[i] = f[i] - g[i];} + +static void fe_cswap(fe f, fe g, int b) +{ + i32 mask = -b; // -1 = 0xffffffff + FOR (i, 0, 10) { + i32 x = (f[i] ^ g[i]) & mask; + f[i] = f[i] ^ x; + g[i] = g[i] ^ x; + } +} + +static void fe_ccopy(fe f, const fe g, int b) +{ + i32 mask = -b; // -1 = 0xffffffff + FOR (i, 0, 10) { + i32 x = (f[i] ^ g[i]) & mask; + f[i] = f[i] ^ x; + } +} + + +// Signed carry propagation +// ------------------------ +// +// Let t be a number. It can be uniquely decomposed thus: +// +// t = h*2^26 + l +// such that -2^25 <= l < 2^25 +// +// Let c = (t + 2^25) / 2^26 (rounded down) +// c = (h*2^26 + l + 2^25) / 2^26 (rounded down) +// c = h + (l + 2^25) / 2^26 (rounded down) +// c = h (exactly) +// Because 0 <= l + 2^25 < 2^26 +// +// Let u = t - c*2^26 +// u = h*2^26 + l - h*2^26 +// u = l +// Therefore, -2^25 <= u < 2^25 +// +// Additionally, if |t| < x, then |h| < x/2^26 (rounded down) +// +// Notations: +// - In C, 1<<25 means 2^25. +// - In C, x>>25 means floor(x / (2^25)). +// - All of the above applies with 25 & 24 as well as 26 & 25. +// +// +// Note on negative right shifts +// ----------------------------- +// +// In C, x >> n, where x is a negative integer, is implementation +// defined. In practice, all platforms do arithmetic shift, which is +// equivalent to division by 2^26, rounded down. Some compilers, like +// GCC, even guarantee it. +// +// If we ever stumble upon a platform that does not propagate the sign +// bit (we won't), visible failures will show at the slightest test, and +// the signed shifts can be replaced by the following: +// +// typedef struct { i64 x:39; } s25; +// typedef struct { i64 x:38; } s26; +// i64 shift25(i64 x) { s25 s; s.x = ((u64)x)>>25; return s.x; } +// i64 shift26(i64 x) { s26 s; s.x = ((u64)x)>>26; return s.x; } +// +// Current compilers cannot optimise this, causing a 30% drop in +// performance. Fairly expensive for something that never happens. +// +// +// Precondition +// ------------ +// +// |t0| < 2^63 +// |t1|..|t9| < 2^62 +// +// Algorithm +// --------- +// c = t0 + 2^25 / 2^26 -- |c| <= 2^36 +// t0 -= c * 2^26 -- |t0| <= 2^25 +// t1 += c -- |t1| <= 2^63 +// +// c = t4 + 2^25 / 2^26 -- |c| <= 2^36 +// t4 -= c * 2^26 -- |t4| <= 2^25 +// t5 += c -- |t5| <= 2^63 +// +// c = t1 + 2^24 / 2^25 -- |c| <= 2^38 +// t1 -= c * 2^25 -- |t1| <= 2^24 +// t2 += c -- |t2| <= 2^63 +// +// c = t5 + 2^24 / 2^25 -- |c| <= 2^38 +// t5 -= c * 2^25 -- |t5| <= 2^24 +// t6 += c -- |t6| <= 2^63 +// +// c = t2 + 2^25 / 2^26 -- |c| <= 2^37 +// t2 -= c * 2^26 -- |t2| <= 2^25 < 1.1 * 2^25 (final t2) +// t3 += c -- |t3| <= 2^63 +// +// c = t6 + 2^25 / 2^26 -- |c| <= 2^37 +// t6 -= c * 2^26 -- |t6| <= 2^25 < 1.1 * 2^25 (final t6) +// t7 += c -- |t7| <= 2^63 +// +// c = t3 + 2^24 / 2^25 -- |c| <= 2^38 +// t3 -= c * 2^25 -- |t3| <= 2^24 < 1.1 * 2^24 (final t3) +// t4 += c -- |t4| <= 2^25 + 2^38 < 2^39 +// +// c = t7 + 2^24 / 2^25 -- |c| <= 2^38 +// t7 -= c * 2^25 -- |t7| <= 2^24 < 1.1 * 2^24 (final t7) +// t8 += c -- |t8| <= 2^63 +// +// c = t4 + 2^25 / 2^26 -- |c| <= 2^13 +// t4 -= c * 2^26 -- |t4| <= 2^25 < 1.1 * 2^25 (final t4) +// t5 += c -- |t5| <= 2^24 + 2^13 < 1.1 * 2^24 (final t5) +// +// c = t8 + 2^25 / 2^26 -- |c| <= 2^37 +// t8 -= c * 2^26 -- |t8| <= 2^25 < 1.1 * 2^25 (final t8) +// t9 += c -- |t9| <= 2^63 +// +// c = t9 + 2^24 / 2^25 -- |c| <= 2^38 +// t9 -= c * 2^25 -- |t9| <= 2^24 < 1.1 * 2^24 (final t9) +// t0 += c * 19 -- |t0| <= 2^25 + 2^38*19 < 2^44 +// +// c = t0 + 2^25 / 2^26 -- |c| <= 2^18 +// t0 -= c * 2^26 -- |t0| <= 2^25 < 1.1 * 2^25 (final t0) +// t1 += c -- |t1| <= 2^24 + 2^18 < 1.1 * 2^24 (final t1) +// +// Postcondition +// ------------- +// |t0|, |t2|, |t4|, |t6|, |t8| < 1.1 * 2^25 +// |t1|, |t3|, |t5|, |t7|, |t9| < 1.1 * 2^24 +#define FE_CARRY \ + i64 c; \ + c = (t0 + ((i64)1<<25)) >> 26; t0 -= c * ((i64)1 << 26); t1 += c; \ + c = (t4 + ((i64)1<<25)) >> 26; t4 -= c * ((i64)1 << 26); t5 += c; \ + c = (t1 + ((i64)1<<24)) >> 25; t1 -= c * ((i64)1 << 25); t2 += c; \ + c = (t5 + ((i64)1<<24)) >> 25; t5 -= c * ((i64)1 << 25); t6 += c; \ + c = (t2 + ((i64)1<<25)) >> 26; t2 -= c * ((i64)1 << 26); t3 += c; \ + c = (t6 + ((i64)1<<25)) >> 26; t6 -= c * ((i64)1 << 26); t7 += c; \ + c = (t3 + ((i64)1<<24)) >> 25; t3 -= c * ((i64)1 << 25); t4 += c; \ + c = (t7 + ((i64)1<<24)) >> 25; t7 -= c * ((i64)1 << 25); t8 += c; \ + c = (t4 + ((i64)1<<25)) >> 26; t4 -= c * ((i64)1 << 26); t5 += c; \ + c = (t8 + ((i64)1<<25)) >> 26; t8 -= c * ((i64)1 << 26); t9 += c; \ + c = (t9 + ((i64)1<<24)) >> 25; t9 -= c * ((i64)1 << 25); t0 += c * 19; \ + c = (t0 + ((i64)1<<25)) >> 26; t0 -= c * ((i64)1 << 26); t1 += c; \ + h[0]=(i32)t0; h[1]=(i32)t1; h[2]=(i32)t2; h[3]=(i32)t3; h[4]=(i32)t4; \ + h[5]=(i32)t5; h[6]=(i32)t6; h[7]=(i32)t7; h[8]=(i32)t8; h[9]=(i32)t9 + +// Decodes a field element from a byte buffer. +// mask specifies how many bits we ignore. +// Traditionally we ignore 1. It's useful for EdDSA, +// which uses that bit to denote the sign of x. +// Elligator however uses positive representatives, +// which means ignoring 2 bits instead. +static void fe_frombytes_mask(fe h, const u8 s[32], unsigned nb_mask) +{ + u32 mask = 0xffffff >> nb_mask; + i64 t0 = load32_le(s); // t0 < 2^32 + i64 t1 = load24_le(s + 4) << 6; // t1 < 2^30 + i64 t2 = load24_le(s + 7) << 5; // t2 < 2^29 + i64 t3 = load24_le(s + 10) << 3; // t3 < 2^27 + i64 t4 = load24_le(s + 13) << 2; // t4 < 2^26 + i64 t5 = load32_le(s + 16); // t5 < 2^32 + i64 t6 = load24_le(s + 20) << 7; // t6 < 2^31 + i64 t7 = load24_le(s + 23) << 5; // t7 < 2^29 + i64 t8 = load24_le(s + 26) << 4; // t8 < 2^28 + i64 t9 = (load24_le(s + 29) & mask) << 2; // t9 < 2^25 + FE_CARRY; // Carry precondition OK +} + +static void fe_frombytes(fe h, const u8 s[32]) +{ + fe_frombytes_mask(h, s, 1); +} + + +// Precondition +// |h[0]|, |h[2]|, |h[4]|, |h[6]|, |h[8]| < 1.1 * 2^25 +// |h[1]|, |h[3]|, |h[5]|, |h[7]|, |h[9]| < 1.1 * 2^24 +// +// Therefore, |h| < 2^255-19 +// There are two possibilities: +// +// - If h is positive, all we need to do is reduce its individual +// limbs down to their tight positive range. +// - If h is negative, we also need to add 2^255-19 to it. +// Or just remove 19 and chop off any excess bit. +static void fe_tobytes(u8 s[32], const fe h) +{ + i32 t[10]; + COPY(t, h, 10); + i32 q = (19 * t[9] + (((i32) 1) << 24)) >> 25; + // |t9| < 1.1 * 2^24 + // -1.1 * 2^24 < t9 < 1.1 * 2^24 + // -21 * 2^24 < 19 * t9 < 21 * 2^24 + // -2^29 < 19 * t9 + 2^24 < 2^29 + // -2^29 / 2^25 < (19 * t9 + 2^24) / 2^25 < 2^29 / 2^25 + // -16 < (19 * t9 + 2^24) / 2^25 < 16 + FOR (i, 0, 5) { + q += t[2*i ]; q >>= 26; // q = 0 or -1 + q += t[2*i+1]; q >>= 25; // q = 0 or -1 + } + // q = 0 iff h >= 0 + // q = -1 iff h < 0 + // Adding q * 19 to h reduces h to its proper range. + q *= 19; // Shift carry back to the beginning + FOR (i, 0, 5) { + t[i*2 ] += q; q = t[i*2 ] >> 26; t[i*2 ] -= q * ((i32)1 << 26); + t[i*2+1] += q; q = t[i*2+1] >> 25; t[i*2+1] -= q * ((i32)1 << 25); + } + // h is now fully reduced, and q represents the excess bit. + + store32_le(s + 0, ((u32)t[0] >> 0) | ((u32)t[1] << 26)); + store32_le(s + 4, ((u32)t[1] >> 6) | ((u32)t[2] << 19)); + store32_le(s + 8, ((u32)t[2] >> 13) | ((u32)t[3] << 13)); + store32_le(s + 12, ((u32)t[3] >> 19) | ((u32)t[4] << 6)); + store32_le(s + 16, ((u32)t[5] >> 0) | ((u32)t[6] << 25)); + store32_le(s + 20, ((u32)t[6] >> 7) | ((u32)t[7] << 19)); + store32_le(s + 24, ((u32)t[7] >> 13) | ((u32)t[8] << 12)); + store32_le(s + 28, ((u32)t[8] >> 20) | ((u32)t[9] << 6)); + + WIPE_BUFFER(t); +} + +// Precondition +// ------------- +// |f0|, |f2|, |f4|, |f6|, |f8| < 1.65 * 2^26 +// |f1|, |f3|, |f5|, |f7|, |f9| < 1.65 * 2^25 +// +// |g0|, |g2|, |g4|, |g6|, |g8| < 1.65 * 2^26 +// |g1|, |g3|, |g5|, |g7|, |g9| < 1.65 * 2^25 +static void fe_mul_small(fe h, const fe f, i32 g) +{ + i64 t0 = f[0] * (i64) g; i64 t1 = f[1] * (i64) g; + i64 t2 = f[2] * (i64) g; i64 t3 = f[3] * (i64) g; + i64 t4 = f[4] * (i64) g; i64 t5 = f[5] * (i64) g; + i64 t6 = f[6] * (i64) g; i64 t7 = f[7] * (i64) g; + i64 t8 = f[8] * (i64) g; i64 t9 = f[9] * (i64) g; + // |t0|, |t2|, |t4|, |t6|, |t8| < 1.65 * 2^26 * 2^31 < 2^58 + // |t1|, |t3|, |t5|, |t7|, |t9| < 1.65 * 2^25 * 2^31 < 2^57 + + FE_CARRY; // Carry precondition OK +} + +// Precondition +// ------------- +// |f0|, |f2|, |f4|, |f6|, |f8| < 1.65 * 2^26 +// |f1|, |f3|, |f5|, |f7|, |f9| < 1.65 * 2^25 +// +// |g0|, |g2|, |g4|, |g6|, |g8| < 1.65 * 2^26 +// |g1|, |g3|, |g5|, |g7|, |g9| < 1.65 * 2^25 +static void fe_mul(fe h, const fe f, const fe g) +{ + // Everything is unrolled and put in temporary variables. + // We could roll the loop, but that would make curve25519 twice as slow. + i32 f0 = f[0]; i32 f1 = f[1]; i32 f2 = f[2]; i32 f3 = f[3]; i32 f4 = f[4]; + i32 f5 = f[5]; i32 f6 = f[6]; i32 f7 = f[7]; i32 f8 = f[8]; i32 f9 = f[9]; + i32 g0 = g[0]; i32 g1 = g[1]; i32 g2 = g[2]; i32 g3 = g[3]; i32 g4 = g[4]; + i32 g5 = g[5]; i32 g6 = g[6]; i32 g7 = g[7]; i32 g8 = g[8]; i32 g9 = g[9]; + i32 F1 = f1*2; i32 F3 = f3*2; i32 F5 = f5*2; i32 F7 = f7*2; i32 F9 = f9*2; + i32 G1 = g1*19; i32 G2 = g2*19; i32 G3 = g3*19; + i32 G4 = g4*19; i32 G5 = g5*19; i32 G6 = g6*19; + i32 G7 = g7*19; i32 G8 = g8*19; i32 G9 = g9*19; + // |F1|, |F3|, |F5|, |F7|, |F9| < 1.65 * 2^26 + // |G0|, |G2|, |G4|, |G6|, |G8| < 2^31 + // |G1|, |G3|, |G5|, |G7|, |G9| < 2^30 + + i64 t0 = f0*(i64)g0 + F1*(i64)G9 + f2*(i64)G8 + F3*(i64)G7 + f4*(i64)G6 + + F5*(i64)G5 + f6*(i64)G4 + F7*(i64)G3 + f8*(i64)G2 + F9*(i64)G1; + i64 t1 = f0*(i64)g1 + f1*(i64)g0 + f2*(i64)G9 + f3*(i64)G8 + f4*(i64)G7 + + f5*(i64)G6 + f6*(i64)G5 + f7*(i64)G4 + f8*(i64)G3 + f9*(i64)G2; + i64 t2 = f0*(i64)g2 + F1*(i64)g1 + f2*(i64)g0 + F3*(i64)G9 + f4*(i64)G8 + + F5*(i64)G7 + f6*(i64)G6 + F7*(i64)G5 + f8*(i64)G4 + F9*(i64)G3; + i64 t3 = f0*(i64)g3 + f1*(i64)g2 + f2*(i64)g1 + f3*(i64)g0 + f4*(i64)G9 + + f5*(i64)G8 + f6*(i64)G7 + f7*(i64)G6 + f8*(i64)G5 + f9*(i64)G4; + i64 t4 = f0*(i64)g4 + F1*(i64)g3 + f2*(i64)g2 + F3*(i64)g1 + f4*(i64)g0 + + F5*(i64)G9 + f6*(i64)G8 + F7*(i64)G7 + f8*(i64)G6 + F9*(i64)G5; + i64 t5 = f0*(i64)g5 + f1*(i64)g4 + f2*(i64)g3 + f3*(i64)g2 + f4*(i64)g1 + + f5*(i64)g0 + f6*(i64)G9 + f7*(i64)G8 + f8*(i64)G7 + f9*(i64)G6; + i64 t6 = f0*(i64)g6 + F1*(i64)g5 + f2*(i64)g4 + F3*(i64)g3 + f4*(i64)g2 + + F5*(i64)g1 + f6*(i64)g0 + F7*(i64)G9 + f8*(i64)G8 + F9*(i64)G7; + i64 t7 = f0*(i64)g7 + f1*(i64)g6 + f2*(i64)g5 + f3*(i64)g4 + f4*(i64)g3 + + f5*(i64)g2 + f6*(i64)g1 + f7*(i64)g0 + f8*(i64)G9 + f9*(i64)G8; + i64 t8 = f0*(i64)g8 + F1*(i64)g7 + f2*(i64)g6 + F3*(i64)g5 + f4*(i64)g4 + + F5*(i64)g3 + f6*(i64)g2 + F7*(i64)g1 + f8*(i64)g0 + F9*(i64)G9; + i64 t9 = f0*(i64)g9 + f1*(i64)g8 + f2*(i64)g7 + f3*(i64)g6 + f4*(i64)g5 + + f5*(i64)g4 + f6*(i64)g3 + f7*(i64)g2 + f8*(i64)g1 + f9*(i64)g0; + // t0 < 0.67 * 2^61 + // t1 < 0.41 * 2^61 + // t2 < 0.52 * 2^61 + // t3 < 0.32 * 2^61 + // t4 < 0.38 * 2^61 + // t5 < 0.22 * 2^61 + // t6 < 0.23 * 2^61 + // t7 < 0.13 * 2^61 + // t8 < 0.09 * 2^61 + // t9 < 0.03 * 2^61 + + FE_CARRY; // Everything below 2^62, Carry precondition OK +} + +// Precondition +// ------------- +// |f0|, |f2|, |f4|, |f6|, |f8| < 1.65 * 2^26 +// |f1|, |f3|, |f5|, |f7|, |f9| < 1.65 * 2^25 +// +// Note: we could use fe_mul() for this, but this is significantly faster +static void fe_sq(fe h, const fe f) +{ + i32 f0 = f[0]; i32 f1 = f[1]; i32 f2 = f[2]; i32 f3 = f[3]; i32 f4 = f[4]; + i32 f5 = f[5]; i32 f6 = f[6]; i32 f7 = f[7]; i32 f8 = f[8]; i32 f9 = f[9]; + i32 f0_2 = f0*2; i32 f1_2 = f1*2; i32 f2_2 = f2*2; i32 f3_2 = f3*2; + i32 f4_2 = f4*2; i32 f5_2 = f5*2; i32 f6_2 = f6*2; i32 f7_2 = f7*2; + i32 f5_38 = f5*38; i32 f6_19 = f6*19; i32 f7_38 = f7*38; + i32 f8_19 = f8*19; i32 f9_38 = f9*38; + // |f0_2| , |f2_2| , |f4_2| , |f6_2| , |f8_2| < 1.65 * 2^27 + // |f1_2| , |f3_2| , |f5_2| , |f7_2| , |f9_2| < 1.65 * 2^26 + // |f5_38|, |f6_19|, |f7_38|, |f8_19|, |f9_38| < 2^31 + + i64 t0 = f0 *(i64)f0 + f1_2*(i64)f9_38 + f2_2*(i64)f8_19 + + f3_2*(i64)f7_38 + f4_2*(i64)f6_19 + f5 *(i64)f5_38; + i64 t1 = f0_2*(i64)f1 + f2 *(i64)f9_38 + f3_2*(i64)f8_19 + + f4 *(i64)f7_38 + f5_2*(i64)f6_19; + i64 t2 = f0_2*(i64)f2 + f1_2*(i64)f1 + f3_2*(i64)f9_38 + + f4_2*(i64)f8_19 + f5_2*(i64)f7_38 + f6 *(i64)f6_19; + i64 t3 = f0_2*(i64)f3 + f1_2*(i64)f2 + f4 *(i64)f9_38 + + f5_2*(i64)f8_19 + f6 *(i64)f7_38; + i64 t4 = f0_2*(i64)f4 + f1_2*(i64)f3_2 + f2 *(i64)f2 + + f5_2*(i64)f9_38 + f6_2*(i64)f8_19 + f7 *(i64)f7_38; + i64 t5 = f0_2*(i64)f5 + f1_2*(i64)f4 + f2_2*(i64)f3 + + f6 *(i64)f9_38 + f7_2*(i64)f8_19; + i64 t6 = f0_2*(i64)f6 + f1_2*(i64)f5_2 + f2_2*(i64)f4 + + f3_2*(i64)f3 + f7_2*(i64)f9_38 + f8 *(i64)f8_19; + i64 t7 = f0_2*(i64)f7 + f1_2*(i64)f6 + f2_2*(i64)f5 + + f3_2*(i64)f4 + f8 *(i64)f9_38; + i64 t8 = f0_2*(i64)f8 + f1_2*(i64)f7_2 + f2_2*(i64)f6 + + f3_2*(i64)f5_2 + f4 *(i64)f4 + f9 *(i64)f9_38; + i64 t9 = f0_2*(i64)f9 + f1_2*(i64)f8 + f2_2*(i64)f7 + + f3_2*(i64)f6 + f4 *(i64)f5_2; + // t0 < 0.67 * 2^61 + // t1 < 0.41 * 2^61 + // t2 < 0.52 * 2^61 + // t3 < 0.32 * 2^61 + // t4 < 0.38 * 2^61 + // t5 < 0.22 * 2^61 + // t6 < 0.23 * 2^61 + // t7 < 0.13 * 2^61 + // t8 < 0.09 * 2^61 + // t9 < 0.03 * 2^61 + + FE_CARRY; +} + +// Parity check. Returns 0 if even, 1 if odd +static int fe_isodd(const fe f) +{ + u8 s[32]; + fe_tobytes(s, f); + u8 isodd = s[0] & 1; + WIPE_BUFFER(s); + return isodd; +} + +// Returns 1 if equal, 0 if not equal +static int fe_isequal(const fe f, const fe g) +{ + u8 fs[32]; + u8 gs[32]; + fe_tobytes(fs, f); + fe_tobytes(gs, g); + int isdifferent = crypto_verify32(fs, gs); + WIPE_BUFFER(fs); + WIPE_BUFFER(gs); + return 1 + isdifferent; +} + +// Inverse square root. +// Returns true if x is a square, false otherwise. +// After the call: +// isr = sqrt(1/x) if x is a non-zero square. +// isr = sqrt(sqrt(-1)/x) if x is not a square. +// isr = 0 if x is zero. +// We do not guarantee the sign of the square root. +// +// Notes: +// Let quartic = x^((p-1)/4) +// +// x^((p-1)/2) = chi(x) +// quartic^2 = chi(x) +// quartic = sqrt(chi(x)) +// quartic = 1 or -1 or sqrt(-1) or -sqrt(-1) +// +// Note that x is a square if quartic is 1 or -1 +// There are 4 cases to consider: +// +// if quartic = 1 (x is a square) +// then x^((p-1)/4) = 1 +// x^((p-5)/4) * x = 1 +// x^((p-5)/4) = 1/x +// x^((p-5)/8) = sqrt(1/x) or -sqrt(1/x) +// +// if quartic = -1 (x is a square) +// then x^((p-1)/4) = -1 +// x^((p-5)/4) * x = -1 +// x^((p-5)/4) = -1/x +// x^((p-5)/8) = sqrt(-1) / sqrt(x) +// x^((p-5)/8) * sqrt(-1) = sqrt(-1)^2 / sqrt(x) +// x^((p-5)/8) * sqrt(-1) = -1/sqrt(x) +// x^((p-5)/8) * sqrt(-1) = -sqrt(1/x) or sqrt(1/x) +// +// if quartic = sqrt(-1) (x is not a square) +// then x^((p-1)/4) = sqrt(-1) +// x^((p-5)/4) * x = sqrt(-1) +// x^((p-5)/4) = sqrt(-1)/x +// x^((p-5)/8) = sqrt(sqrt(-1)/x) or -sqrt(sqrt(-1)/x) +// +// Note that the product of two non-squares is always a square: +// For any non-squares a and b, chi(a) = -1 and chi(b) = -1. +// Since chi(x) = x^((p-1)/2), chi(a)*chi(b) = chi(a*b) = 1. +// Therefore a*b is a square. +// +// Since sqrt(-1) and x are both non-squares, their product is a +// square, and we can compute their square root. +// +// if quartic = -sqrt(-1) (x is not a square) +// then x^((p-1)/4) = -sqrt(-1) +// x^((p-5)/4) * x = -sqrt(-1) +// x^((p-5)/4) = -sqrt(-1)/x +// x^((p-5)/8) = sqrt(-sqrt(-1)/x) +// x^((p-5)/8) = sqrt( sqrt(-1)/x) * sqrt(-1) +// x^((p-5)/8) * sqrt(-1) = sqrt( sqrt(-1)/x) * sqrt(-1)^2 +// x^((p-5)/8) * sqrt(-1) = sqrt( sqrt(-1)/x) * -1 +// x^((p-5)/8) * sqrt(-1) = -sqrt(sqrt(-1)/x) or sqrt(sqrt(-1)/x) +static int invsqrt(fe isr, const fe x) +{ + fe t0, t1, t2; + + // t0 = x^((p-5)/8) + // Can be achieved with a simple double & add ladder, + // but it would be slower. + fe_sq(t0, x); + fe_sq(t1,t0); fe_sq(t1, t1); fe_mul(t1, x, t1); + fe_mul(t0, t0, t1); + fe_sq(t0, t0); fe_mul(t0, t1, t0); + fe_sq(t1, t0); FOR (i, 1, 5) { fe_sq(t1, t1); } fe_mul(t0, t1, t0); + fe_sq(t1, t0); FOR (i, 1, 10) { fe_sq(t1, t1); } fe_mul(t1, t1, t0); + fe_sq(t2, t1); FOR (i, 1, 20) { fe_sq(t2, t2); } fe_mul(t1, t2, t1); + fe_sq(t1, t1); FOR (i, 1, 10) { fe_sq(t1, t1); } fe_mul(t0, t1, t0); + fe_sq(t1, t0); FOR (i, 1, 50) { fe_sq(t1, t1); } fe_mul(t1, t1, t0); + fe_sq(t2, t1); FOR (i, 1, 100) { fe_sq(t2, t2); } fe_mul(t1, t2, t1); + fe_sq(t1, t1); FOR (i, 1, 50) { fe_sq(t1, t1); } fe_mul(t0, t1, t0); + fe_sq(t0, t0); FOR (i, 1, 2) { fe_sq(t0, t0); } fe_mul(t0, t0, x); + + // quartic = x^((p-1)/4) + i32 *quartic = t1; + fe_sq (quartic, t0); + fe_mul(quartic, quartic, x); + + i32 *check = t2; + fe_0 (check); int z0 = fe_isequal(x , check); + fe_1 (check); int p1 = fe_isequal(quartic, check); + fe_neg(check, check ); int m1 = fe_isequal(quartic, check); + fe_neg(check, sqrtm1); int ms = fe_isequal(quartic, check); + + // if quartic == -1 or sqrt(-1) + // then isr = x^((p-1)/4) * sqrt(-1) + // else isr = x^((p-1)/4) + fe_mul(isr, t0, sqrtm1); + fe_ccopy(isr, t0, 1 - (m1 | ms)); + + WIPE_BUFFER(t0); + WIPE_BUFFER(t1); + WIPE_BUFFER(t2); + return p1 | m1 | z0; +} + +// Inverse in terms of inverse square root. +// Requires two additional squarings to get rid of the sign. +// +// 1/x = x * (+invsqrt(x^2))^2 +// = x * (-invsqrt(x^2))^2 +// +// A fully optimised exponentiation by p-1 would save 6 field +// multiplications, but it would require more code. +static void fe_invert(fe out, const fe x) +{ + fe tmp; + fe_sq(tmp, x); + invsqrt(tmp, tmp); + fe_sq(tmp, tmp); + fe_mul(out, tmp, x); + WIPE_BUFFER(tmp); +} + +// trim a scalar for scalar multiplication +void crypto_eddsa_trim_scalar(u8 out[32], const u8 in[32]) +{ + COPY(out, in, 32); + out[ 0] &= 248; + out[31] &= 127; + out[31] |= 64; +} + +// get bit from scalar at position i +static int scalar_bit(const u8 s[32], int i) +{ + if (i < 0) { return 0; } // handle -1 for sliding windows + return (s[i>>3] >> (i&7)) & 1; +} + +/////////////// +/// X-25519 /// Taken from SUPERCOP's ref10 implementation. +/////////////// +static void scalarmult(u8 q[32], const u8 scalar[32], const u8 p[32], + int nb_bits) +{ + // computes the scalar product + fe x1; + fe_frombytes(x1, p); + + // computes the actual scalar product (the result is in x2 and z2) + fe x2, z2, x3, z3, t0, t1; + // Montgomery ladder + // In projective coordinates, to avoid divisions: x = X / Z + // We don't care about the y coordinate, it's only 1 bit of information + fe_1(x2); fe_0(z2); // "zero" point + fe_copy(x3, x1); fe_1(z3); // "one" point + int swap = 0; + for (int pos = nb_bits-1; pos >= 0; --pos) { + // constant time conditional swap before ladder step + int b = scalar_bit(scalar, pos); + swap ^= b; // xor trick avoids swapping at the end of the loop + fe_cswap(x2, x3, swap); + fe_cswap(z2, z3, swap); + swap = b; // anticipates one last swap after the loop + + // Montgomery ladder step: replaces (P2, P3) by (P2*2, P2+P3) + // with differential addition + fe_sub(t0, x3, z3); + fe_sub(t1, x2, z2); + fe_add(x2, x2, z2); + fe_add(z2, x3, z3); + fe_mul(z3, t0, x2); + fe_mul(z2, z2, t1); + fe_sq (t0, t1 ); + fe_sq (t1, x2 ); + fe_add(x3, z3, z2); + fe_sub(z2, z3, z2); + fe_mul(x2, t1, t0); + fe_sub(t1, t1, t0); + fe_sq (z2, z2 ); + fe_mul_small(z3, t1, 121666); + fe_sq (x3, x3 ); + fe_add(t0, t0, z3); + fe_mul(z3, x1, z2); + fe_mul(z2, t1, t0); + } + // last swap is necessary to compensate for the xor trick + // Note: after this swap, P3 == P2 + P1. + fe_cswap(x2, x3, swap); + fe_cswap(z2, z3, swap); + + // normalises the coordinates: x == X / Z + fe_invert(z2, z2); + fe_mul(x2, x2, z2); + fe_tobytes(q, x2); + + WIPE_BUFFER(x1); + WIPE_BUFFER(x2); WIPE_BUFFER(z2); WIPE_BUFFER(t0); + WIPE_BUFFER(x3); WIPE_BUFFER(z3); WIPE_BUFFER(t1); +} + +void crypto_x25519(u8 raw_shared_secret[32], + const u8 your_secret_key [32], + const u8 their_public_key [32]) +{ + // restrict the possible scalar values + u8 e[32]; + crypto_eddsa_trim_scalar(e, your_secret_key); + scalarmult(raw_shared_secret, e, their_public_key, 255); + WIPE_BUFFER(e); +} + +void crypto_x25519_public_key(u8 public_key[32], + const u8 secret_key[32]) +{ + static const u8 base_point[32] = {9}; + crypto_x25519(public_key, secret_key, base_point); +} + +/////////////////////////// +/// Arithmetic modulo L /// +/////////////////////////// +static const u32 L[8] = { + 0x5cf5d3ed, 0x5812631a, 0xa2f79cd6, 0x14def9de, + 0x00000000, 0x00000000, 0x00000000, 0x10000000, +}; + +// p = a*b + p +static void multiply(u32 p[16], const u32 a[8], const u32 b[8]) +{ + FOR (i, 0, 8) { + u64 carry = 0; + FOR (j, 0, 8) { + carry += p[i+j] + (u64)a[i] * b[j]; + p[i+j] = (u32)carry; + carry >>= 32; + } + p[i+8] = (u32)carry; + } +} + +static int is_above_l(const u32 x[8]) +{ + // We work with L directly, in a 2's complement encoding + // (-L == ~L + 1) + u64 carry = 1; + FOR (i, 0, 8) { + carry += (u64)x[i] + (~L[i] & 0xffffffff); + carry >>= 32; + } + return (int)carry; // carry is either 0 or 1 +} + +// Final reduction modulo L, by conditionally removing L. +// if x < l , then r = x +// if l <= x 2*l, then r = x-l +// otherwise the result will be wrong +static void remove_l(u32 r[8], const u32 x[8]) +{ + u64 carry = (u64)is_above_l(x); + u32 mask = ~(u32)carry + 1; // carry == 0 or 1 + FOR (i, 0, 8) { + carry += (u64)x[i] + (~L[i] & mask); + r[i] = (u32)carry; + carry >>= 32; + } +} + +// Full reduction modulo L (Barrett reduction) +static void mod_l(u8 reduced[32], const u32 x[16]) +{ + static const u32 r[9] = { + 0x0a2c131b,0xed9ce5a3,0x086329a7,0x2106215d, + 0xffffffeb,0xffffffff,0xffffffff,0xffffffff,0xf, + }; + // xr = x * r + u32 xr[25] = {0}; + FOR (i, 0, 9) { + u64 carry = 0; + FOR (j, 0, 16) { + carry += xr[i+j] + (u64)r[i] * x[j]; + xr[i+j] = (u32)carry; + carry >>= 32; + } + xr[i+16] = (u32)carry; + } + // xr = floor(xr / 2^512) * L + // Since the result is guaranteed to be below 2*L, + // it is enough to only compute the first 256 bits. + // The division is performed by saying xr[i+16]. (16 * 32 = 512) + ZERO(xr, 8); + FOR (i, 0, 8) { + u64 carry = 0; + FOR (j, 0, 8-i) { + carry += xr[i+j] + (u64)xr[i+16] * L[j]; + xr[i+j] = (u32)carry; + carry >>= 32; + } + } + // xr = x - xr + u64 carry = 1; + FOR (i, 0, 8) { + carry += (u64)x[i] + (~xr[i] & 0xffffffff); + xr[i] = (u32)carry; + carry >>= 32; + } + // Final reduction modulo L (conditional subtraction) + remove_l(xr, xr); + store32_le_buf(reduced, xr, 8); + + WIPE_BUFFER(xr); +} + +void crypto_eddsa_reduce(u8 reduced[32], const u8 expanded[64]) +{ + u32 x[16]; + load32_le_buf(x, expanded, 16); + mod_l(reduced, x); + WIPE_BUFFER(x); +} + +// r = (a * b) + c +void crypto_eddsa_mul_add(u8 r[32], + const u8 a[32], const u8 b[32], const u8 c[32]) +{ + u32 A[8]; load32_le_buf(A, a, 8); + u32 B[8]; load32_le_buf(B, b, 8); + u32 p[16]; load32_le_buf(p, c, 8); ZERO(p + 8, 8); + multiply(p, A, B); + mod_l(r, p); + WIPE_BUFFER(p); + WIPE_BUFFER(A); + WIPE_BUFFER(B); +} + +/////////////// +/// Ed25519 /// +/////////////// + +// Point (group element, ge) in a twisted Edwards curve, +// in extended projective coordinates. +// ge : x = X/Z, y = Y/Z, T = XY/Z +// ge_cached : Yp = X+Y, Ym = X-Y, T2 = T*D2 +// ge_precomp: Z = 1 +typedef struct { fe X; fe Y; fe Z; fe T; } ge; +typedef struct { fe Yp; fe Ym; fe Z; fe T2; } ge_cached; +typedef struct { fe Yp; fe Ym; fe T2; } ge_precomp; + +static void ge_zero(ge *p) +{ + fe_0(p->X); + fe_1(p->Y); + fe_1(p->Z); + fe_0(p->T); +} + +static void ge_tobytes(u8 s[32], const ge *h) +{ + fe recip, x, y; + fe_invert(recip, h->Z); + fe_mul(x, h->X, recip); + fe_mul(y, h->Y, recip); + fe_tobytes(s, y); + s[31] ^= fe_isodd(x) << 7; + + WIPE_BUFFER(recip); + WIPE_BUFFER(x); + WIPE_BUFFER(y); +} + +// h = -s, where s is a point encoded in 32 bytes +// +// Variable time! Inputs must not be secret! +// => Use only to *check* signatures. +// +// From the specifications: +// The encoding of s contains y and the sign of x +// x = sqrt((y^2 - 1) / (d*y^2 + 1)) +// In extended coordinates: +// X = x, Y = y, Z = 1, T = x*y +// +// Note that num * den is a square iff num / den is a square +// If num * den is not a square, the point was not on the curve. +// From the above: +// Let num = y^2 - 1 +// Let den = d*y^2 + 1 +// x = sqrt((y^2 - 1) / (d*y^2 + 1)) +// x = sqrt(num / den) +// x = sqrt(num^2 / (num * den)) +// x = num * sqrt(1 / (num * den)) +// +// Therefore, we can just compute: +// num = y^2 - 1 +// den = d*y^2 + 1 +// isr = invsqrt(num * den) // abort if not square +// x = num * isr +// Finally, negate x if its sign is not as specified. +static int ge_frombytes_neg_vartime(ge *h, const u8 s[32]) +{ + fe_frombytes(h->Y, s); + fe_1(h->Z); + fe_sq (h->T, h->Y); // t = y^2 + fe_mul(h->X, h->T, d ); // x = d*y^2 + fe_sub(h->T, h->T, h->Z); // t = y^2 - 1 + fe_add(h->X, h->X, h->Z); // x = d*y^2 + 1 + fe_mul(h->X, h->T, h->X); // x = (y^2 - 1) * (d*y^2 + 1) + int is_square = invsqrt(h->X, h->X); + if (!is_square) { + return -1; // Not on the curve, abort + } + fe_mul(h->X, h->T, h->X); // x = sqrt((y^2 - 1) / (d*y^2 + 1)) + if (fe_isodd(h->X) == (s[31] >> 7)) { + fe_neg(h->X, h->X); + } + fe_mul(h->T, h->X, h->Y); + return 0; +} + +static void ge_cache(ge_cached *c, const ge *p) +{ + fe_add (c->Yp, p->Y, p->X); + fe_sub (c->Ym, p->Y, p->X); + fe_copy(c->Z , p->Z ); + fe_mul (c->T2, p->T, D2 ); +} + +// Internal buffers are not wiped! Inputs must not be secret! +// => Use only to *check* signatures. +static void ge_add(ge *s, const ge *p, const ge_cached *q) +{ + fe a, b; + fe_add(a , p->Y, p->X ); + fe_sub(b , p->Y, p->X ); + fe_mul(a , a , q->Yp); + fe_mul(b , b , q->Ym); + fe_add(s->Y, a , b ); + fe_sub(s->X, a , b ); + + fe_add(s->Z, p->Z, p->Z ); + fe_mul(s->Z, s->Z, q->Z ); + fe_mul(s->T, p->T, q->T2); + fe_add(a , s->Z, s->T ); + fe_sub(b , s->Z, s->T ); + + fe_mul(s->T, s->X, s->Y); + fe_mul(s->X, s->X, b ); + fe_mul(s->Y, s->Y, a ); + fe_mul(s->Z, a , b ); +} + +// Internal buffers are not wiped! Inputs must not be secret! +// => Use only to *check* signatures. +static void ge_sub(ge *s, const ge *p, const ge_cached *q) +{ + ge_cached neg; + fe_copy(neg.Ym, q->Yp); + fe_copy(neg.Yp, q->Ym); + fe_copy(neg.Z , q->Z ); + fe_neg (neg.T2, q->T2); + ge_add(s, p, &neg); +} + +static void ge_madd(ge *s, const ge *p, const ge_precomp *q, fe a, fe b) +{ + fe_add(a , p->Y, p->X ); + fe_sub(b , p->Y, p->X ); + fe_mul(a , a , q->Yp); + fe_mul(b , b , q->Ym); + fe_add(s->Y, a , b ); + fe_sub(s->X, a , b ); + + fe_add(s->Z, p->Z, p->Z ); + fe_mul(s->T, p->T, q->T2); + fe_add(a , s->Z, s->T ); + fe_sub(b , s->Z, s->T ); + + fe_mul(s->T, s->X, s->Y); + fe_mul(s->X, s->X, b ); + fe_mul(s->Y, s->Y, a ); + fe_mul(s->Z, a , b ); +} + +// Internal buffers are not wiped! Inputs must not be secret! +// => Use only to *check* signatures. +static void ge_msub(ge *s, const ge *p, const ge_precomp *q, fe a, fe b) +{ + ge_precomp neg; + fe_copy(neg.Ym, q->Yp); + fe_copy(neg.Yp, q->Ym); + fe_neg (neg.T2, q->T2); + ge_madd(s, p, &neg, a, b); +} + +static void ge_double(ge *s, const ge *p, ge *q) +{ + fe_sq (q->X, p->X); + fe_sq (q->Y, p->Y); + fe_sq (q->Z, p->Z); // qZ = pZ^2 + fe_mul_small(q->Z, q->Z, 2); // qZ = pZ^2 * 2 + fe_add(q->T, p->X, p->Y); + fe_sq (s->T, q->T); + fe_add(q->T, q->Y, q->X); + fe_sub(q->Y, q->Y, q->X); + fe_sub(q->X, s->T, q->T); + fe_sub(q->Z, q->Z, q->Y); + + fe_mul(s->X, q->X , q->Z); + fe_mul(s->Y, q->T , q->Y); + fe_mul(s->Z, q->Y , q->Z); + fe_mul(s->T, q->X , q->T); +} + +// 5-bit signed window in cached format (Niels coordinates, Z=1) +static const ge_precomp b_window[8] = { + {{25967493,-14356035,29566456,3660896,-12694345, + 4014787,27544626,-11754271,-6079156,2047605,}, + {-12545711,934262,-2722910,3049990,-727428, + 9406986,12720692,5043384,19500929,-15469378,}, + {-8738181,4489570,9688441,-14785194,10184609, + -12363380,29287919,11864899,-24514362,-4438546,},}, + {{15636291,-9688557,24204773,-7912398,616977, + -16685262,27787600,-14772189,28944400,-1550024,}, + {16568933,4717097,-11556148,-1102322,15682896, + -11807043,16354577,-11775962,7689662,11199574,}, + {30464156,-5976125,-11779434,-15670865,23220365, + 15915852,7512774,10017326,-17749093,-9920357,},}, + {{10861363,11473154,27284546,1981175,-30064349, + 12577861,32867885,14515107,-15438304,10819380,}, + {4708026,6336745,20377586,9066809,-11272109, + 6594696,-25653668,12483688,-12668491,5581306,}, + {19563160,16186464,-29386857,4097519,10237984, + -4348115,28542350,13850243,-23678021,-15815942,},}, + {{5153746,9909285,1723747,-2777874,30523605, + 5516873,19480852,5230134,-23952439,-15175766,}, + {-30269007,-3463509,7665486,10083793,28475525, + 1649722,20654025,16520125,30598449,7715701,}, + {28881845,14381568,9657904,3680757,-20181635, + 7843316,-31400660,1370708,29794553,-1409300,},}, + {{-22518993,-6692182,14201702,-8745502,-23510406, + 8844726,18474211,-1361450,-13062696,13821877,}, + {-6455177,-7839871,3374702,-4740862,-27098617, + -10571707,31655028,-7212327,18853322,-14220951,}, + {4566830,-12963868,-28974889,-12240689,-7602672, + -2830569,-8514358,-10431137,2207753,-3209784,},}, + {{-25154831,-4185821,29681144,7868801,-6854661, + -9423865,-12437364,-663000,-31111463,-16132436,}, + {25576264,-2703214,7349804,-11814844,16472782, + 9300885,3844789,15725684,171356,6466918,}, + {23103977,13316479,9739013,-16149481,817875, + -15038942,8965339,-14088058,-30714912,16193877,},}, + {{-33521811,3180713,-2394130,14003687,-16903474, + -16270840,17238398,4729455,-18074513,9256800,}, + {-25182317,-4174131,32336398,5036987,-21236817, + 11360617,22616405,9761698,-19827198,630305,}, + {-13720693,2639453,-24237460,-7406481,9494427, + -5774029,-6554551,-15960994,-2449256,-14291300,},}, + {{-3151181,-5046075,9282714,6866145,-31907062, + -863023,-18940575,15033784,25105118,-7894876,}, + {-24326370,15950226,-31801215,-14592823,-11662737, + -5090925,1573892,-2625887,2198790,-15804619,}, + {-3099351,10324967,-2241613,7453183,-5446979, + -2735503,-13812022,-16236442,-32461234,-12290683,},}, +}; + +// Incremental sliding windows (left to right) +// Based on Roberto Maria Avanzi[2005] +typedef struct { + i16 next_index; // position of the next signed digit + i8 next_digit; // next signed digit (odd number below 2^window_width) + u8 next_check; // point at which we must check for a new window +} slide_ctx; + +static void slide_init(slide_ctx *ctx, const u8 scalar[32]) +{ + // scalar is guaranteed to be below L, either because we checked (s), + // or because we reduced it modulo L (h_ram). L is under 2^253, so + // so bits 253 to 255 are guaranteed to be zero. No need to test them. + // + // Note however that L is very close to 2^252, so bit 252 is almost + // always zero. If we were to start at bit 251, the tests wouldn't + // catch the off-by-one error (constructing one that does would be + // prohibitively expensive). + // + // We should still check bit 252, though. + int i = 252; + while (i > 0 && scalar_bit(scalar, i) == 0) { + i--; + } + ctx->next_check = (u8)(i + 1); + ctx->next_index = -1; + ctx->next_digit = -1; +} + +static int slide_step(slide_ctx *ctx, int width, int i, const u8 scalar[32]) +{ + if (i == ctx->next_check) { + if (scalar_bit(scalar, i) == scalar_bit(scalar, i - 1)) { + ctx->next_check--; + } else { + // compute digit of next window + int w = MIN(width, i + 1); + int v = -(scalar_bit(scalar, i) << (w-1)); + FOR_T (int, j, 0, w-1) { + v += scalar_bit(scalar, i-(w-1)+j) << j; + } + v += scalar_bit(scalar, i-w); + int lsb = v & (~v + 1); // smallest bit of v + int s = // log2(lsb) + (((lsb & 0xAA) != 0) << 0) | + (((lsb & 0xCC) != 0) << 1) | + (((lsb & 0xF0) != 0) << 2); + ctx->next_index = (i16)(i-(w-1)+s); + ctx->next_digit = (i8) (v >> s ); + ctx->next_check -= (u8) w; + } + } + return i == ctx->next_index ? ctx->next_digit: 0; +} + +#define P_W_WIDTH 3 // Affects the size of the stack +#define B_W_WIDTH 5 // Affects the size of the binary +#define P_W_SIZE (1<<(P_W_WIDTH-2)) + +int crypto_eddsa_check_equation(const u8 signature[64], const u8 public_key[32], + const u8 h[32]) +{ + ge minus_A; // -public_key + ge minus_R; // -first_half_of_signature + const u8 *s = signature + 32; + + // Check that A and R are on the curve + // Check that 0 <= S < L (prevents malleability) + // *Allow* non-cannonical encoding for A and R + { + u32 s32[8]; + load32_le_buf(s32, s, 8); + if (ge_frombytes_neg_vartime(&minus_A, public_key) || + ge_frombytes_neg_vartime(&minus_R, signature) || + is_above_l(s32)) { + return -1; + } + } + + // look-up table for minus_A + ge_cached lutA[P_W_SIZE]; + { + ge minus_A2, tmp; + ge_double(&minus_A2, &minus_A, &tmp); + ge_cache(&lutA[0], &minus_A); + FOR (i, 1, P_W_SIZE) { + ge_add(&tmp, &minus_A2, &lutA[i-1]); + ge_cache(&lutA[i], &tmp); + } + } + + // sum = [s]B - [h]A + // Merged double and add ladder, fused with sliding + slide_ctx h_slide; slide_init(&h_slide, h); + slide_ctx s_slide; slide_init(&s_slide, s); + int i = MAX(h_slide.next_check, s_slide.next_check); + ge *sum = &minus_A; // reuse minus_A for the sum + ge_zero(sum); + while (i >= 0) { + ge tmp; + ge_double(sum, sum, &tmp); + int h_digit = slide_step(&h_slide, P_W_WIDTH, i, h); + int s_digit = slide_step(&s_slide, B_W_WIDTH, i, s); + if (h_digit > 0) { ge_add(sum, sum, &lutA[ h_digit / 2]); } + if (h_digit < 0) { ge_sub(sum, sum, &lutA[-h_digit / 2]); } + fe t1, t2; + if (s_digit > 0) { ge_madd(sum, sum, b_window + s_digit/2, t1, t2); } + if (s_digit < 0) { ge_msub(sum, sum, b_window + -s_digit/2, t1, t2); } + i--; + } + + // Compare [8](sum-R) and the zero point + // The multiplication by 8 eliminates any low-order component + // and ensures consistency with batched verification. + ge_cached cached; + u8 check[32]; + static const u8 zero_point[32] = {1}; // Point of order 1 + ge_cache(&cached, &minus_R); + ge_add(sum, sum, &cached); + ge_double(sum, sum, &minus_R); // reuse minus_R as temporary + ge_double(sum, sum, &minus_R); // reuse minus_R as temporary + ge_double(sum, sum, &minus_R); // reuse minus_R as temporary + ge_tobytes(check, sum); + return crypto_verify32(check, zero_point); +} + +// 5-bit signed comb in cached format (Niels coordinates, Z=1) +static const ge_precomp b_comb_low[8] = { + {{-6816601,-2324159,-22559413,124364,18015490, + 8373481,19993724,1979872,-18549925,9085059,}, + {10306321,403248,14839893,9633706,8463310, + -8354981,-14305673,14668847,26301366,2818560,}, + {-22701500,-3210264,-13831292,-2927732,-16326337, + -14016360,12940910,177905,12165515,-2397893,},}, + {{-12282262,-7022066,9920413,-3064358,-32147467, + 2927790,22392436,-14852487,2719975,16402117,}, + {-7236961,-4729776,2685954,-6525055,-24242706, + -15940211,-6238521,14082855,10047669,12228189,}, + {-30495588,-12893761,-11161261,3539405,-11502464, + 16491580,-27286798,-15030530,-7272871,-15934455,},}, + {{17650926,582297,-860412,-187745,-12072900, + -10683391,-20352381,15557840,-31072141,-5019061,}, + {-6283632,-2259834,-4674247,-4598977,-4089240, + 12435688,-31278303,1060251,6256175,10480726,}, + {-13871026,2026300,-21928428,-2741605,-2406664, + -8034988,7355518,15733500,-23379862,7489131,},}, + {{6883359,695140,23196907,9644202,-33430614, + 11354760,-20134606,6388313,-8263585,-8491918,}, + {-7716174,-13605463,-13646110,14757414,-19430591, + -14967316,10359532,-11059670,-21935259,12082603,}, + {-11253345,-15943946,10046784,5414629,24840771, + 8086951,-6694742,9868723,15842692,-16224787,},}, + {{9639399,11810955,-24007778,-9320054,3912937, + -9856959,996125,-8727907,-8919186,-14097242,}, + {7248867,14468564,25228636,-8795035,14346339, + 8224790,6388427,-7181107,6468218,-8720783,}, + {15513115,15439095,7342322,-10157390,18005294, + -7265713,2186239,4884640,10826567,7135781,},}, + {{-14204238,5297536,-5862318,-6004934,28095835, + 4236101,-14203318,1958636,-16816875,3837147,}, + {-5511166,-13176782,-29588215,12339465,15325758, + -15945770,-8813185,11075932,-19608050,-3776283,}, + {11728032,9603156,-4637821,-5304487,-7827751, + 2724948,31236191,-16760175,-7268616,14799772,},}, + {{-28842672,4840636,-12047946,-9101456,-1445464, + 381905,-30977094,-16523389,1290540,12798615,}, + {27246947,-10320914,14792098,-14518944,5302070, + -8746152,-3403974,-4149637,-27061213,10749585,}, + {25572375,-6270368,-15353037,16037944,1146292, + 32198,23487090,9585613,24714571,-1418265,},}, + {{19844825,282124,-17583147,11004019,-32004269, + -2716035,6105106,-1711007,-21010044,14338445,}, + {8027505,8191102,-18504907,-12335737,25173494, + -5923905,15446145,7483684,-30440441,10009108,}, + {-14134701,-4174411,10246585,-14677495,33553567, + -14012935,23366126,15080531,-7969992,7663473,},}, +}; + +static const ge_precomp b_comb_high[8] = { + {{33055887,-4431773,-521787,6654165,951411, + -6266464,-5158124,6995613,-5397442,-6985227,}, + {4014062,6967095,-11977872,3960002,8001989, + 5130302,-2154812,-1899602,-31954493,-16173976,}, + {16271757,-9212948,23792794,731486,-25808309, + -3546396,6964344,-4767590,10976593,10050757,},}, + {{2533007,-4288439,-24467768,-12387405,-13450051, + 14542280,12876301,13893535,15067764,8594792,}, + {20073501,-11623621,3165391,-13119866,13188608, + -11540496,-10751437,-13482671,29588810,2197295,}, + {-1084082,11831693,6031797,14062724,14748428, + -8159962,-20721760,11742548,31368706,13161200,},}, + {{2050412,-6457589,15321215,5273360,25484180, + 124590,-18187548,-7097255,-6691621,-14604792,}, + {9938196,2162889,-6158074,-1711248,4278932, + -2598531,-22865792,-7168500,-24323168,11746309,}, + {-22691768,-14268164,5965485,9383325,20443693, + 5854192,28250679,-1381811,-10837134,13717818,},}, + {{-8495530,16382250,9548884,-4971523,-4491811, + -3902147,6182256,-12832479,26628081,10395408,}, + {27329048,-15853735,7715764,8717446,-9215518, + -14633480,28982250,-5668414,4227628,242148,}, + {-13279943,-7986904,-7100016,8764468,-27276630, + 3096719,29678419,-9141299,3906709,11265498,},}, + {{11918285,15686328,-17757323,-11217300,-27548967, + 4853165,-27168827,6807359,6871949,-1075745,}, + {-29002610,13984323,-27111812,-2713442,28107359, + -13266203,6155126,15104658,3538727,-7513788,}, + {14103158,11233913,-33165269,9279850,31014152, + 4335090,-1827936,4590951,13960841,12787712,},}, + {{1469134,-16738009,33411928,13942824,8092558, + -8778224,-11165065,1437842,22521552,-2792954,}, + {31352705,-4807352,-25327300,3962447,12541566, + -9399651,-27425693,7964818,-23829869,5541287,}, + {-25732021,-6864887,23848984,3039395,-9147354, + 6022816,-27421653,10590137,25309915,-1584678,},}, + {{-22951376,5048948,31139401,-190316,-19542447, + -626310,-17486305,-16511925,-18851313,-12985140,}, + {-9684890,14681754,30487568,7717771,-10829709, + 9630497,30290549,-10531496,-27798994,-13812825,}, + {5827835,16097107,-24501327,12094619,7413972, + 11447087,28057551,-1793987,-14056981,4359312,},}, + {{26323183,2342588,-21887793,-1623758,-6062284, + 2107090,-28724907,9036464,-19618351,-13055189,}, + {-29697200,14829398,-4596333,14220089,-30022969, + 2955645,12094100,-13693652,-5941445,7047569,}, + {-3201977,14413268,-12058324,-16417589,-9035655, + -7224648,9258160,1399236,30397584,-5684634,},}, +}; + +static void lookup_add(ge *p, ge_precomp *tmp_c, fe tmp_a, fe tmp_b, + const ge_precomp comb[8], const u8 scalar[32], int i) +{ + u8 teeth = (u8)((scalar_bit(scalar, i) ) + + (scalar_bit(scalar, i + 32) << 1) + + (scalar_bit(scalar, i + 64) << 2) + + (scalar_bit(scalar, i + 96) << 3)); + u8 high = teeth >> 3; + u8 index = (teeth ^ (high - 1)) & 7; + FOR (j, 0, 8) { + i32 select = 1 & (((j ^ index) - 1) >> 8); + fe_ccopy(tmp_c->Yp, comb[j].Yp, select); + fe_ccopy(tmp_c->Ym, comb[j].Ym, select); + fe_ccopy(tmp_c->T2, comb[j].T2, select); + } + fe_neg(tmp_a, tmp_c->T2); + fe_cswap(tmp_c->T2, tmp_a , high ^ 1); + fe_cswap(tmp_c->Yp, tmp_c->Ym, high ^ 1); + ge_madd(p, p, tmp_c, tmp_a, tmp_b); +} + +// p = [scalar]B, where B is the base point +static void ge_scalarmult_base(ge *p, const u8 scalar[32]) +{ + // twin 4-bits signed combs, from Mike Hamburg's + // Fast and compact elliptic-curve cryptography (2012) + // 1 / 2 modulo L + static const u8 half_mod_L[32] = { + 247,233,122,46,141,49,9,44,107,206,123,81,239,124,111,10, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8, + }; + // (2^256 - 1) / 2 modulo L + static const u8 half_ones[32] = { + 142,74,204,70,186,24,118,107,184,231,190,57,250,173,119,99, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,7, + }; + + // All bits set form: 1 means 1, 0 means -1 + u8 s_scalar[32]; + crypto_eddsa_mul_add(s_scalar, scalar, half_mod_L, half_ones); + + // Double and add ladder + fe tmp_a, tmp_b; // temporaries for addition + ge_precomp tmp_c; // temporary for comb lookup + ge tmp_d; // temporary for doubling + fe_1(tmp_c.Yp); + fe_1(tmp_c.Ym); + fe_0(tmp_c.T2); + + // Save a double on the first iteration + ge_zero(p); + lookup_add(p, &tmp_c, tmp_a, tmp_b, b_comb_low , s_scalar, 31); + lookup_add(p, &tmp_c, tmp_a, tmp_b, b_comb_high, s_scalar, 31+128); + // Regular double & add for the rest + for (int i = 30; i >= 0; i--) { + ge_double(p, p, &tmp_d); + lookup_add(p, &tmp_c, tmp_a, tmp_b, b_comb_low , s_scalar, i); + lookup_add(p, &tmp_c, tmp_a, tmp_b, b_comb_high, s_scalar, i+128); + } + // Note: we could save one addition at the end if we assumed the + // scalar fit in 252 bits. Which it does in practice if it is + // selected at random. However, non-random, non-hashed scalars + // *can* overflow 252 bits in practice. Better account for that + // than leaving that kind of subtle corner case. + + WIPE_BUFFER(tmp_a); WIPE_CTX(&tmp_d); + WIPE_BUFFER(tmp_b); WIPE_CTX(&tmp_c); + WIPE_BUFFER(s_scalar); +} + +void crypto_eddsa_scalarbase(u8 point[32], const u8 scalar[32]) +{ + ge P; + ge_scalarmult_base(&P, scalar); + ge_tobytes(point, &P); + WIPE_CTX(&P); +} + +void crypto_eddsa_key_pair(u8 secret_key[64], u8 public_key[32], u8 seed[32]) +{ + // To allow overlaps, observable writes happen in this order: + // 1. seed + // 2. secret_key + // 3. public_key + u8 a[64]; + COPY(a, seed, 32); + crypto_wipe(seed, 32); + COPY(secret_key, a, 32); + crypto_blake2b(a, 64, a, 32); + crypto_eddsa_trim_scalar(a, a); + crypto_eddsa_scalarbase(secret_key + 32, a); + COPY(public_key, secret_key + 32, 32); + WIPE_BUFFER(a); +} + +static void hash_reduce(u8 h[32], + const u8 *a, size_t a_size, + const u8 *b, size_t b_size, + const u8 *c, size_t c_size) +{ + u8 hash[64]; + crypto_blake2b_ctx ctx; + crypto_blake2b_init (&ctx, 64); + crypto_blake2b_update(&ctx, a, a_size); + crypto_blake2b_update(&ctx, b, b_size); + crypto_blake2b_update(&ctx, c, c_size); + crypto_blake2b_final (&ctx, hash); + crypto_eddsa_reduce(h, hash); +} + +// Digital signature of a message with from a secret key. +// +// The secret key comprises two parts: +// - The seed that generates the key (secret_key[ 0..31]) +// - The public key (secret_key[32..63]) +// +// The seed and the public key are bundled together to make sure users +// don't use mismatched seeds and public keys, which would instantly +// leak the secret scalar and allow forgeries (allowing this to happen +// has resulted in critical vulnerabilities in the wild). +// +// The seed is hashed to derive the secret scalar and a secret prefix. +// The sole purpose of the prefix is to generate a secret random nonce. +// The properties of that nonce must be as follows: +// - Unique: we need a different one for each message. +// - Secret: third parties must not be able to predict it. +// - Random: any detectable bias would break all security. +// +// There are two ways to achieve these properties. The obvious one is +// to simply generate a random number. Here that would be a parameter +// (Monocypher doesn't have an RNG). It works, but then users may reuse +// the nonce by accident, which _also_ leaks the secret scalar and +// allows forgeries. This has happened in the wild too. +// +// This is no good, so instead we generate that nonce deterministically +// by reducing modulo L a hash of the secret prefix and the message. +// The secret prefix makes the nonce unpredictable, the message makes it +// unique, and the hash/reduce removes all bias. +// +// The cost of that safety is hashing the message twice. If that cost +// is unacceptable, there are two alternatives: +// +// - Signing a hash of the message instead of the message itself. This +// is fine as long as the hash is collision resistant. It is not +// compatible with existing "pure" signatures, but at least it's safe. +// +// - Using a random nonce. Please exercise **EXTREME CAUTION** if you +// ever do that. It is absolutely **critical** that the nonce is +// really an unbiased random number between 0 and L-1, never reused, +// and wiped immediately. +// +// To lower the likelihood of complete catastrophe if the RNG is +// either flawed or misused, you can hash the RNG output together with +// the secret prefix and the beginning of the message, and use the +// reduction of that hash instead of the RNG output itself. It's not +// foolproof (you'd need to hash the whole message) but it helps. +// +// Signing a message involves the following operations: +// +// scalar, prefix = HASH(secret_key) +// r = HASH(prefix || message) % L +// R = [r]B +// h = HASH(R || public_key || message) % L +// S = ((h * a) + r) % L +// signature = R || S +void crypto_eddsa_sign(u8 signature [64], const u8 secret_key[64], + const u8 *message, size_t message_size) +{ + u8 a[64]; // secret scalar and prefix + u8 r[32]; // secret deterministic "random" nonce + u8 h[32]; // publically verifiable hash of the message (not wiped) + u8 R[32]; // first half of the signature (allows overlapping inputs) + + crypto_blake2b(a, 64, secret_key, 32); + crypto_eddsa_trim_scalar(a, a); + hash_reduce(r, a + 32, 32, message, message_size, 0, 0); + crypto_eddsa_scalarbase(R, r); + hash_reduce(h, R, 32, secret_key + 32, 32, message, message_size); + COPY(signature, R, 32); + crypto_eddsa_mul_add(signature + 32, h, a, r); + + WIPE_BUFFER(a); + WIPE_BUFFER(r); +} + +// To check the signature R, S of the message M with the public key A, +// there are 3 steps: +// +// compute h = HASH(R || A || message) % L +// check that A is on the curve. +// check that R == [s]B - [h]A +// +// The last two steps are done in crypto_eddsa_check_equation() +int crypto_eddsa_check(const u8 signature[64], const u8 public_key[32], + const u8 *message, size_t message_size) +{ + u8 h[32]; + hash_reduce(h, signature, 32, public_key, 32, message, message_size); + return crypto_eddsa_check_equation(signature, public_key, h); +} + +///////////////////////// +/// EdDSA <--> X25519 /// +///////////////////////// +void crypto_eddsa_to_x25519(u8 x25519[32], const u8 eddsa[32]) +{ + // (u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x) + // Only converting y to u, the sign of x is ignored. + fe t1, t2; + fe_frombytes(t2, eddsa); + fe_add(t1, fe_one, t2); + fe_sub(t2, fe_one, t2); + fe_invert(t2, t2); + fe_mul(t1, t1, t2); + fe_tobytes(x25519, t1); + WIPE_BUFFER(t1); + WIPE_BUFFER(t2); +} + +void crypto_x25519_to_eddsa(u8 eddsa[32], const u8 x25519[32]) +{ + // (x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1)) + // Only converting u to y, x is assumed positive. + fe t1, t2; + fe_frombytes(t2, x25519); + fe_sub(t1, t2, fe_one); + fe_add(t2, t2, fe_one); + fe_invert(t2, t2); + fe_mul(t1, t1, t2); + fe_tobytes(eddsa, t1); + WIPE_BUFFER(t1); + WIPE_BUFFER(t2); +} + +///////////////////////////////////////////// +/// Dirty ephemeral public key generation /// +///////////////////////////////////////////// + +// Those functions generates a public key, *without* clearing the +// cofactor. Sending that key over the network leaks 3 bits of the +// private key. Use only to generate ephemeral keys that will be hidden +// with crypto_curve_to_hidden(). +// +// The public key is otherwise compatible with crypto_x25519(), which +// properly clears the cofactor. +// +// Note that the distribution of the resulting public keys is almost +// uniform. Flipping the sign of the v coordinate (not provided by this +// function), covers the entire key space almost perfectly, where +// "almost" means a 2^-128 bias (undetectable). This uniformity is +// needed to ensure the proper randomness of the resulting +// representatives (once we apply crypto_curve_to_hidden()). +// +// Recall that Curve25519 has order C = 2^255 + e, with e < 2^128 (not +// to be confused with the prime order of the main subgroup, L, which is +// 8 times less than that). +// +// Generating all points would require us to multiply a point of order C +// (the base point plus any point of order 8) by all scalars from 0 to +// C-1. Clamping limits us to scalars between 2^254 and 2^255 - 1. But +// by negating the resulting point at random, we also cover scalars from +// -2^255 + 1 to -2^254 (which modulo C is congruent to e+1 to 2^254 + e). +// +// In practice: +// - Scalars from 0 to e + 1 are never generated +// - Scalars from 2^255 to 2^255 + e are never generated +// - Scalars from 2^254 + 1 to 2^254 + e are generated twice +// +// Since e < 2^128, detecting this bias requires observing over 2^100 +// representatives from a given source (this will never happen), *and* +// recovering enough of the private key to determine that they do, or do +// not, belong to the biased set (this practically requires solving +// discrete logarithm, which is conjecturally intractable). +// +// In practice, this means the bias is impossible to detect. + +// s + (x*L) % 8*L +// Guaranteed to fit in 256 bits iff s fits in 255 bits. +// L < 2^253 +// x%8 < 2^3 +// L * (x%8) < 2^255 +// s < 2^255 +// s + L * (x%8) < 2^256 +static void add_xl(u8 s[32], u8 x) +{ + u64 mod8 = x & 7; + u64 carry = 0; + FOR (i , 0, 8) { + carry = carry + load32_le(s + 4*i) + L[i] * mod8; + store32_le(s + 4*i, (u32)carry); + carry >>= 32; + } +} + +// "Small" dirty ephemeral key. +// Use if you need to shrink the size of the binary, and can afford to +// slow down by a factor of two (compared to the fast version) +// +// This version works by decoupling the cofactor from the main factor. +// +// - The trimmed scalar determines the main factor +// - The clamped bits of the scalar determine the cofactor. +// +// Cofactor and main factor are combined into a single scalar, which is +// then multiplied by a point of order 8*L (unlike the base point, which +// has prime order). That "dirty" base point is the addition of the +// regular base point (9), and a point of order 8. +void crypto_x25519_dirty_small(u8 public_key[32], const u8 secret_key[32]) +{ + // Base point of order 8*L + // Raw scalar multiplication with it does not clear the cofactor, + // and the resulting public key will reveal 3 bits of the scalar. + // + // The low order component of this base point has been chosen + // to yield the same results as crypto_x25519_dirty_fast(). + static const u8 dirty_base_point[32] = { + 0xd8, 0x86, 0x1a, 0xa2, 0x78, 0x7a, 0xd9, 0x26, + 0x8b, 0x74, 0x74, 0xb6, 0x82, 0xe3, 0xbe, 0xc3, + 0xce, 0x36, 0x9a, 0x1e, 0x5e, 0x31, 0x47, 0xa2, + 0x6d, 0x37, 0x7c, 0xfd, 0x20, 0xb5, 0xdf, 0x75, + }; + // separate the main factor & the cofactor of the scalar + u8 scalar[32]; + crypto_eddsa_trim_scalar(scalar, secret_key); + + // Separate the main factor and the cofactor + // + // The scalar is trimmed, so its cofactor is cleared. The three + // least significant bits however still have a main factor. We must + // remove it for X25519 compatibility. + // + // cofactor = lsb * L (modulo 8*L) + // combined = scalar + cofactor (modulo 8*L) + add_xl(scalar, secret_key[0]); + scalarmult(public_key, scalar, dirty_base_point, 256); + WIPE_BUFFER(scalar); +} + +// Select low order point +// We're computing the [cofactor]lop scalar multiplication, where: +// +// cofactor = tweak & 7. +// lop = (lop_x, lop_y) +// lop_x = sqrt((sqrt(d + 1) + 1) / d) +// lop_y = -lop_x * sqrtm1 +// +// The low order point has order 8. There are 4 such points. We've +// chosen the one whose both coordinates are positive (below p/2). +// The 8 low order points are as follows: +// +// [0]lop = ( 0 , 1 ) +// [1]lop = ( lop_x , lop_y) +// [2]lop = ( sqrt(-1), -0 ) +// [3]lop = ( lop_x , -lop_y) +// [4]lop = (-0 , -1 ) +// [5]lop = (-lop_x , -lop_y) +// [6]lop = (-sqrt(-1), 0 ) +// [7]lop = (-lop_x , lop_y) +// +// The x coordinate is either 0, sqrt(-1), lop_x, or their opposite. +// The y coordinate is either 0, -1 , lop_y, or their opposite. +// The pattern for both is the same, except for a rotation of 2 (modulo 8) +// +// This helper function captures the pattern, and we can use it thus: +// +// select_lop(x, lop_x, sqrtm1, cofactor); +// select_lop(y, lop_y, fe_one, cofactor + 2); +// +// This is faster than an actual scalar multiplication, +// and requires less code than naive constant time look up. +static void select_lop(fe out, const fe x, const fe k, u8 cofactor) +{ + fe tmp; + fe_0(out); + fe_ccopy(out, k , (cofactor >> 1) & 1); // bit 1 + fe_ccopy(out, x , (cofactor >> 0) & 1); // bit 0 + fe_neg (tmp, out); + fe_ccopy(out, tmp, (cofactor >> 2) & 1); // bit 2 + WIPE_BUFFER(tmp); +} + +// "Fast" dirty ephemeral key +// We use this one by default. +// +// This version works by performing a regular scalar multiplication, +// then add a low order point. The scalar multiplication is done in +// Edwards space for more speed (*2 compared to the "small" version). +// The cost is a bigger binary for programs that don't also sign messages. +void crypto_x25519_dirty_fast(u8 public_key[32], const u8 secret_key[32]) +{ + // Compute clean scalar multiplication + u8 scalar[32]; + ge pk; + crypto_eddsa_trim_scalar(scalar, secret_key); + ge_scalarmult_base(&pk, scalar); + + // Compute low order point + fe t1, t2; + select_lop(t1, lop_x, sqrtm1, secret_key[0]); + select_lop(t2, lop_y, fe_one, secret_key[0] + 2); + ge_precomp low_order_point; + fe_add(low_order_point.Yp, t2, t1); + fe_sub(low_order_point.Ym, t2, t1); + fe_mul(low_order_point.T2, t2, t1); + fe_mul(low_order_point.T2, low_order_point.T2, D2); + + // Add low order point to the public key + ge_madd(&pk, &pk, &low_order_point, t1, t2); + + // Convert to Montgomery u coordinate (we ignore the sign) + fe_add(t1, pk.Z, pk.Y); + fe_sub(t2, pk.Z, pk.Y); + fe_invert(t2, t2); + fe_mul(t1, t1, t2); + + fe_tobytes(public_key, t1); + + WIPE_BUFFER(t1); WIPE_CTX(&pk); + WIPE_BUFFER(t2); WIPE_CTX(&low_order_point); + WIPE_BUFFER(scalar); +} + +/////////////////// +/// Elligator 2 /// +/////////////////// +static const fe A = {486662}; + +// Elligator direct map +// +// Computes the point corresponding to a representative, encoded in 32 +// bytes (little Endian). Since positive representatives fits in 254 +// bits, The two most significant bits are ignored. +// +// From the paper: +// w = -A / (fe(1) + non_square * r^2) +// e = chi(w^3 + A*w^2 + w) +// u = e*w - (fe(1)-e)*(A//2) +// v = -e * sqrt(u^3 + A*u^2 + u) +// +// We ignore v because we don't need it for X25519 (the Montgomery +// ladder only uses u). +// +// Note that e is either 0, 1 or -1 +// if e = 0 u = 0 and v = 0 +// if e = 1 u = w +// if e = -1 u = -w - A = w * non_square * r^2 +// +// Let r1 = non_square * r^2 +// Let r2 = 1 + r1 +// Note that r2 cannot be zero, -1/non_square is not a square. +// We can (tediously) verify that: +// w^3 + A*w^2 + w = (A^2*r1 - r2^2) * A / r2^3 +// Therefore: +// chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * (A / r2^3)) +// chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * (A / r2^3)) * 1 +// chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * (A / r2^3)) * chi(r2^6) +// chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * (A / r2^3) * r2^6) +// chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * A * r2^3) +// Corollary: +// e = 1 if (A^2*r1 - r2^2) * A * r2^3) is a non-zero square +// e = -1 if (A^2*r1 - r2^2) * A * r2^3) is not a square +// Note that w^3 + A*w^2 + w (and therefore e) can never be zero: +// w^3 + A*w^2 + w = w * (w^2 + A*w + 1) +// w^3 + A*w^2 + w = w * (w^2 + A*w + A^2/4 - A^2/4 + 1) +// w^3 + A*w^2 + w = w * (w + A/2)^2 - A^2/4 + 1) +// which is zero only if: +// w = 0 (impossible) +// (w + A/2)^2 = A^2/4 - 1 (impossible, because A^2/4-1 is not a square) +// +// Let isr = invsqrt((A^2*r1 - r2^2) * A * r2^3) +// isr = sqrt(1 / ((A^2*r1 - r2^2) * A * r2^3)) if e = 1 +// isr = sqrt(sqrt(-1) / ((A^2*r1 - r2^2) * A * r2^3)) if e = -1 +// +// if e = 1 +// let u1 = -A * (A^2*r1 - r2^2) * A * r2^2 * isr^2 +// u1 = w +// u1 = u +// +// if e = -1 +// let ufactor = -non_square * sqrt(-1) * r^2 +// let vfactor = sqrt(ufactor) +// let u2 = -A * (A^2*r1 - r2^2) * A * r2^2 * isr^2 * ufactor +// u2 = w * -1 * -non_square * r^2 +// u2 = w * non_square * r^2 +// u2 = u +void crypto_elligator_map(u8 curve[32], const u8 hidden[32]) +{ + fe r, u, t1, t2, t3; + fe_frombytes_mask(r, hidden, 2); // r is encoded in 254 bits. + fe_sq(r, r); + fe_add(t1, r, r); + fe_add(u, t1, fe_one); + fe_sq (t2, u); + fe_mul(t3, A2, t1); + fe_sub(t3, t3, t2); + fe_mul(t3, t3, A); + fe_mul(t1, t2, u); + fe_mul(t1, t3, t1); + int is_square = invsqrt(t1, t1); + fe_mul(u, r, ufactor); + fe_ccopy(u, fe_one, is_square); + fe_sq (t1, t1); + fe_mul(u, u, A); + fe_mul(u, u, t3); + fe_mul(u, u, t2); + fe_mul(u, u, t1); + fe_neg(u, u); + fe_tobytes(curve, u); + + WIPE_BUFFER(t1); WIPE_BUFFER(r); + WIPE_BUFFER(t2); WIPE_BUFFER(u); + WIPE_BUFFER(t3); +} + +// Elligator inverse map +// +// Computes the representative of a point, if possible. If not, it does +// nothing and returns -1. Note that the success of the operation +// depends only on the point (more precisely its u coordinate). The +// tweak parameter is used only upon success +// +// The tweak should be a random byte. Beyond that, its contents are an +// implementation detail. Currently, the tweak comprises: +// - Bit 1 : sign of the v coordinate (0 if positive, 1 if negative) +// - Bit 2-5: not used +// - Bits 6-7: random padding +// +// From the paper: +// Let sq = -non_square * u * (u+A) +// if sq is not a square, or u = -A, there is no mapping +// Assuming there is a mapping: +// if v is positive: r = sqrt(-u / (non_square * (u+A))) +// if v is negative: r = sqrt(-(u+A) / (non_square * u )) +// +// We compute isr = invsqrt(-non_square * u * (u+A)) +// if it wasn't a square, abort. +// else, isr = sqrt(-1 / (non_square * u * (u+A)) +// +// If v is positive, we return isr * u: +// isr * u = sqrt(-1 / (non_square * u * (u+A)) * u +// isr * u = sqrt(-u / (non_square * (u+A)) +// +// If v is negative, we return isr * (u+A): +// isr * (u+A) = sqrt(-1 / (non_square * u * (u+A)) * (u+A) +// isr * (u+A) = sqrt(-(u+A) / (non_square * u) +int crypto_elligator_rev(u8 hidden[32], const u8 public_key[32], u8 tweak) +{ + fe t1, t2, t3; + fe_frombytes(t1, public_key); // t1 = u + + fe_add(t2, t1, A); // t2 = u + A + fe_mul(t3, t1, t2); + fe_mul_small(t3, t3, -2); + int is_square = invsqrt(t3, t3); // t3 = sqrt(-1 / non_square * u * (u+A)) + if (is_square) { + // The only variable time bit. This ultimately reveals how many + // tries it took us to find a representable key. + // This does not affect security as long as we try keys at random. + + fe_ccopy (t1, t2, tweak & 1); // multiply by u if v is positive, + fe_mul (t3, t1, t3); // multiply by u+A otherwise + fe_mul_small(t1, t3, 2); + fe_neg (t2, t3); + fe_ccopy (t3, t2, fe_isodd(t1)); + fe_tobytes(hidden, t3); + + // Pad with two random bits + hidden[31] |= tweak & 0xc0; + } + + WIPE_BUFFER(t1); + WIPE_BUFFER(t2); + WIPE_BUFFER(t3); + return is_square - 1; +} + +void crypto_elligator_key_pair(u8 hidden[32], u8 secret_key[32], u8 seed[32]) +{ + u8 pk [32]; // public key + u8 buf[64]; // seed + representative + COPY(buf + 32, seed, 32); + do { + crypto_chacha20_djb(buf, 0, 64, buf+32, zero, 0); + crypto_x25519_dirty_fast(pk, buf); // or the "small" version + } while(crypto_elligator_rev(buf+32, pk, buf[32])); + // Note that the return value of crypto_elligator_rev() is + // independent from its tweak parameter. + // Therefore, buf[32] is not actually reused. Either we loop one + // more time and buf[32] is used for the new seed, or we succeeded, + // and buf[32] becomes the tweak parameter. + + crypto_wipe(seed, 32); + COPY(hidden , buf + 32, 32); + COPY(secret_key, buf , 32); + WIPE_BUFFER(buf); + WIPE_BUFFER(pk); +} + +/////////////////////// +/// Scalar division /// +/////////////////////// + +// Montgomery reduction. +// Divides x by (2^256), and reduces the result modulo L +// +// Precondition: +// x < L * 2^256 +// Constants: +// r = 2^256 (makes division by r trivial) +// k = (r * (1/r) - 1) // L (1/r is computed modulo L ) +// Algorithm: +// s = (x * k) % r +// t = x + s*L (t is always a multiple of r) +// u = (t/r) % L (u is always below 2*L, conditional subtraction is enough) +static void redc(u32 u[8], u32 x[16]) +{ + static const u32 k[8] = { + 0x12547e1b, 0xd2b51da3, 0xfdba84ff, 0xb1a206f2, + 0xffa36bea, 0x14e75438, 0x6fe91836, 0x9db6c6f2, + }; + + // s = x * k (modulo 2^256) + // This is cheaper than the full multiplication. + u32 s[8] = {0}; + FOR (i, 0, 8) { + u64 carry = 0; + FOR (j, 0, 8-i) { + carry += s[i+j] + (u64)x[i] * k[j]; + s[i+j] = (u32)carry; + carry >>= 32; + } + } + u32 t[16] = {0}; + multiply(t, s, L); + + // t = t + x + u64 carry = 0; + FOR (i, 0, 16) { + carry += (u64)t[i] + x[i]; + t[i] = (u32)carry; + carry >>= 32; + } + + // u = (t / 2^256) % L + // Note that t / 2^256 is always below 2*L, + // So a constant time conditional subtraction is enough + remove_l(u, t+8); + + WIPE_BUFFER(s); + WIPE_BUFFER(t); +} + +void crypto_x25519_inverse(u8 blind_salt [32], const u8 private_key[32], + const u8 curve_point[32]) +{ + static const u8 Lm2[32] = { // L - 2 + 0xeb, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, + 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, + }; + // 1 in Montgomery form + u32 m_inv [8] = { + 0x8d98951d, 0xd6ec3174, 0x737dcf70, 0xc6ef5bf4, + 0xfffffffe, 0xffffffff, 0xffffffff, 0x0fffffff, + }; + + u8 scalar[32]; + crypto_eddsa_trim_scalar(scalar, private_key); + + // Convert the scalar in Montgomery form + // m_scl = scalar * 2^256 (modulo L) + u32 m_scl[8]; + { + u32 tmp[16]; + ZERO(tmp, 8); + load32_le_buf(tmp+8, scalar, 8); + mod_l(scalar, tmp); + load32_le_buf(m_scl, scalar, 8); + WIPE_BUFFER(tmp); // Wipe ASAP to save stack space + } + + // Compute the inverse + u32 product[16]; + for (int i = 252; i >= 0; i--) { + ZERO(product, 16); + multiply(product, m_inv, m_inv); + redc(m_inv, product); + if (scalar_bit(Lm2, i)) { + ZERO(product, 16); + multiply(product, m_inv, m_scl); + redc(m_inv, product); + } + } + // Convert the inverse *out* of Montgomery form + // scalar = m_inv / 2^256 (modulo L) + COPY(product, m_inv, 8); + ZERO(product + 8, 8); + redc(m_inv, product); + store32_le_buf(scalar, m_inv, 8); // the *inverse* of the scalar + + // Clear the cofactor of scalar: + // cleared = scalar * (3*L + 1) (modulo 8*L) + // cleared = scalar + scalar * 3 * L (modulo 8*L) + // Note that (scalar * 3) is reduced modulo 8, so we only need the + // first byte. + add_xl(scalar, scalar[0] * 3); + + // Recall that 8*L < 2^256. However it is also very close to + // 2^255. If we spanned the ladder over 255 bits, random tests + // wouldn't catch the off-by-one error. + scalarmult(blind_salt, scalar, curve_point, 256); + + WIPE_BUFFER(scalar); WIPE_BUFFER(m_scl); + WIPE_BUFFER(product); WIPE_BUFFER(m_inv); +} + +//////////////////////////////// +/// Authenticated encryption /// +//////////////////////////////// +static void lock_auth(u8 mac[16], const u8 auth_key[32], + const u8 *ad , size_t ad_size, + const u8 *cipher_text, size_t text_size) +{ + u8 sizes[16]; // Not secret, not wiped + store64_le(sizes + 0, ad_size); + store64_le(sizes + 8, text_size); + crypto_poly1305_ctx poly_ctx; // auto wiped... + crypto_poly1305_init (&poly_ctx, auth_key); + crypto_poly1305_update(&poly_ctx, ad , ad_size); + crypto_poly1305_update(&poly_ctx, zero , gap(ad_size, 16)); + crypto_poly1305_update(&poly_ctx, cipher_text, text_size); + crypto_poly1305_update(&poly_ctx, zero , gap(text_size, 16)); + crypto_poly1305_update(&poly_ctx, sizes , 16); + crypto_poly1305_final (&poly_ctx, mac); // ...here +} + +void crypto_aead_init_x(crypto_aead_ctx *ctx, + u8 const key[32], const u8 nonce[24]) +{ + crypto_chacha20_h(ctx->key, key, nonce); + COPY(ctx->nonce, nonce + 16, 8); + ctx->counter = 0; +} + +void crypto_aead_init_djb(crypto_aead_ctx *ctx, + const u8 key[32], const u8 nonce[8]) +{ + COPY(ctx->key , key , 32); + COPY(ctx->nonce, nonce, 8); + ctx->counter = 0; +} + +void crypto_aead_init_ietf(crypto_aead_ctx *ctx, + const u8 key[32], const u8 nonce[12]) +{ + COPY(ctx->key , key , 32); + COPY(ctx->nonce, nonce + 4, 8); + ctx->counter = (u64)load32_le(nonce) << 32; +} + +void crypto_aead_write(crypto_aead_ctx *ctx, u8 *cipher_text, u8 mac[16], + const u8 *ad, size_t ad_size, + const u8 *plain_text, size_t text_size) +{ + u8 auth_key[64]; // the last 32 bytes are used for rekeying. + crypto_chacha20_djb(auth_key, 0, 64, ctx->key, ctx->nonce, ctx->counter); + crypto_chacha20_djb(cipher_text, plain_text, text_size, + ctx->key, ctx->nonce, ctx->counter + 1); + lock_auth(mac, auth_key, ad, ad_size, cipher_text, text_size); + COPY(ctx->key, auth_key + 32, 32); + WIPE_BUFFER(auth_key); +} + +int crypto_aead_read(crypto_aead_ctx *ctx, u8 *plain_text, const u8 mac[16], + const u8 *ad, size_t ad_size, + const u8 *cipher_text, size_t text_size) +{ + u8 auth_key[64]; // the last 32 bytes are used for rekeying. + u8 real_mac[16]; + crypto_chacha20_djb(auth_key, 0, 64, ctx->key, ctx->nonce, ctx->counter); + lock_auth(real_mac, auth_key, ad, ad_size, cipher_text, text_size); + int mismatch = crypto_verify16(mac, real_mac); + if (!mismatch) { + crypto_chacha20_djb(plain_text, cipher_text, text_size, + ctx->key, ctx->nonce, ctx->counter + 1); + COPY(ctx->key, auth_key + 32, 32); + } + WIPE_BUFFER(auth_key); + WIPE_BUFFER(real_mac); + return mismatch; +} + +void crypto_aead_lock(u8 *cipher_text, u8 mac[16], const u8 key[32], + const u8 nonce[24], const u8 *ad, size_t ad_size, + const u8 *plain_text, size_t text_size) +{ + crypto_aead_ctx ctx; + crypto_aead_init_x(&ctx, key, nonce); + crypto_aead_write(&ctx, cipher_text, mac, ad, ad_size, + plain_text, text_size); + crypto_wipe(&ctx, sizeof(ctx)); +} + +int crypto_aead_unlock(u8 *plain_text, const u8 mac[16], const u8 key[32], + const u8 nonce[24], const u8 *ad, size_t ad_size, + const u8 *cipher_text, size_t text_size) +{ + crypto_aead_ctx ctx; + crypto_aead_init_x(&ctx, key, nonce); + int mismatch = crypto_aead_read(&ctx, plain_text, mac, ad, ad_size, + cipher_text, text_size); + crypto_wipe(&ctx, sizeof(ctx)); + return mismatch; +} + +#ifdef MONOCYPHER_CPP_NAMESPACE +} +#endif diff --git a/net/ssh/crypto/monocypher.h b/net/ssh/crypto/monocypher.h new file mode 100644 index 00000000..765a07ff --- /dev/null +++ b/net/ssh/crypto/monocypher.h @@ -0,0 +1,321 @@ +// Monocypher version 4.0.2 +// +// This file is dual-licensed. Choose whichever licence you want from +// the two licences listed below. +// +// The first licence is a regular 2-clause BSD licence. The second licence +// is the CC-0 from Creative Commons. It is intended to release Monocypher +// to the public domain. The BSD licence serves as a fallback option. +// +// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0 +// +// ------------------------------------------------------------------------ +// +// Copyright (c) 2017-2019, Loup Vaillant +// All rights reserved. +// +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// ------------------------------------------------------------------------ +// +// Written in 2017-2019 by Loup Vaillant +// +// To the extent possible under law, the author(s) have dedicated all copyright +// and related neighboring rights to this software to the public domain +// worldwide. This software is distributed without any warranty. +// +// You should have received a copy of the CC0 Public Domain Dedication along +// with this software. If not, see +// + +#ifndef MONOCYPHER_H +#define MONOCYPHER_H + +#include +#include + +#ifdef MONOCYPHER_CPP_NAMESPACE +namespace MONOCYPHER_CPP_NAMESPACE { +#elif defined(__cplusplus) +extern "C" { +#endif + +// Constant time comparisons +// ------------------------- + +// Return 0 if a and b are equal, -1 otherwise +int crypto_verify16(const uint8_t a[16], const uint8_t b[16]); +int crypto_verify32(const uint8_t a[32], const uint8_t b[32]); +int crypto_verify64(const uint8_t a[64], const uint8_t b[64]); + + +// Erase sensitive data +// -------------------- +void crypto_wipe(void *secret, size_t size); + + +// Authenticated encryption +// ------------------------ +void crypto_aead_lock(uint8_t *cipher_text, + uint8_t mac [16], + const uint8_t key [32], + const uint8_t nonce[24], + const uint8_t *ad, size_t ad_size, + const uint8_t *plain_text, size_t text_size); +int crypto_aead_unlock(uint8_t *plain_text, + const uint8_t mac [16], + const uint8_t key [32], + const uint8_t nonce[24], + const uint8_t *ad, size_t ad_size, + const uint8_t *cipher_text, size_t text_size); + +// Authenticated stream +// -------------------- +typedef struct { + uint64_t counter; + uint8_t key[32]; + uint8_t nonce[8]; +} crypto_aead_ctx; + +void crypto_aead_init_x(crypto_aead_ctx *ctx, + const uint8_t key[32], const uint8_t nonce[24]); +void crypto_aead_init_djb(crypto_aead_ctx *ctx, + const uint8_t key[32], const uint8_t nonce[8]); +void crypto_aead_init_ietf(crypto_aead_ctx *ctx, + const uint8_t key[32], const uint8_t nonce[12]); + +void crypto_aead_write(crypto_aead_ctx *ctx, + uint8_t *cipher_text, + uint8_t mac[16], + const uint8_t *ad , size_t ad_size, + const uint8_t *plain_text, size_t text_size); +int crypto_aead_read(crypto_aead_ctx *ctx, + uint8_t *plain_text, + const uint8_t mac[16], + const uint8_t *ad , size_t ad_size, + const uint8_t *cipher_text, size_t text_size); + + +// General purpose hash (BLAKE2b) +// ------------------------------ + +// Direct interface +void crypto_blake2b(uint8_t *hash, size_t hash_size, + const uint8_t *message, size_t message_size); + +void crypto_blake2b_keyed(uint8_t *hash, size_t hash_size, + const uint8_t *key, size_t key_size, + const uint8_t *message, size_t message_size); + +// Incremental interface +typedef struct { + // Do not rely on the size or contents of this type, + // for they may change without notice. + uint64_t hash[8]; + uint64_t input_offset[2]; + uint64_t input[16]; + size_t input_idx; + size_t hash_size; +} crypto_blake2b_ctx; + +void crypto_blake2b_init(crypto_blake2b_ctx *ctx, size_t hash_size); +void crypto_blake2b_keyed_init(crypto_blake2b_ctx *ctx, size_t hash_size, + const uint8_t *key, size_t key_size); +void crypto_blake2b_update(crypto_blake2b_ctx *ctx, + const uint8_t *message, size_t message_size); +void crypto_blake2b_final(crypto_blake2b_ctx *ctx, uint8_t *hash); + + +// Password key derivation (Argon2) +// -------------------------------- +#define CRYPTO_ARGON2_D 0 +#define CRYPTO_ARGON2_I 1 +#define CRYPTO_ARGON2_ID 2 + +typedef struct { + uint32_t algorithm; // Argon2d, Argon2i, Argon2id + uint32_t nb_blocks; // memory hardness, >= 8 * nb_lanes + uint32_t nb_passes; // CPU hardness, >= 1 (>= 3 recommended for Argon2i) + uint32_t nb_lanes; // parallelism level (single threaded anyway) +} crypto_argon2_config; + +typedef struct { + const uint8_t *pass; + const uint8_t *salt; + uint32_t pass_size; + uint32_t salt_size; // 16 bytes recommended +} crypto_argon2_inputs; + +typedef struct { + const uint8_t *key; // may be NULL if no key + const uint8_t *ad; // may be NULL if no additional data + uint32_t key_size; // 0 if no key (32 bytes recommended otherwise) + uint32_t ad_size; // 0 if no additional data +} crypto_argon2_extras; + +extern const crypto_argon2_extras crypto_argon2_no_extras; + +void crypto_argon2(uint8_t *hash, uint32_t hash_size, void *work_area, + crypto_argon2_config config, + crypto_argon2_inputs inputs, + crypto_argon2_extras extras); + + +// Key exchange (X-25519) +// ---------------------- + +// Shared secrets are not quite random. +// Hash them to derive an actual shared key. +void crypto_x25519_public_key(uint8_t public_key[32], + const uint8_t secret_key[32]); +void crypto_x25519(uint8_t raw_shared_secret[32], + const uint8_t your_secret_key [32], + const uint8_t their_public_key [32]); + +// Conversion to EdDSA +void crypto_x25519_to_eddsa(uint8_t eddsa[32], const uint8_t x25519[32]); + +// scalar "division" +// Used for OPRF. Be aware that exponential blinding is less secure +// than Diffie-Hellman key exchange. +void crypto_x25519_inverse(uint8_t blind_salt [32], + const uint8_t private_key[32], + const uint8_t curve_point[32]); + +// "Dirty" versions of x25519_public_key(). +// Use with crypto_elligator_rev(). +// Leaks 3 bits of the private key. +void crypto_x25519_dirty_small(uint8_t pk[32], const uint8_t sk[32]); +void crypto_x25519_dirty_fast (uint8_t pk[32], const uint8_t sk[32]); + + +// Signatures +// ---------- + +// EdDSA with curve25519 + BLAKE2b +void crypto_eddsa_key_pair(uint8_t secret_key[64], + uint8_t public_key[32], + uint8_t seed[32]); +void crypto_eddsa_sign(uint8_t signature [64], + const uint8_t secret_key[64], + const uint8_t *message, size_t message_size); +int crypto_eddsa_check(const uint8_t signature [64], + const uint8_t public_key[32], + const uint8_t *message, size_t message_size); + +// Conversion to X25519 +void crypto_eddsa_to_x25519(uint8_t x25519[32], const uint8_t eddsa[32]); + +// EdDSA building blocks +void crypto_eddsa_trim_scalar(uint8_t out[32], const uint8_t in[32]); +void crypto_eddsa_reduce(uint8_t reduced[32], const uint8_t expanded[64]); +void crypto_eddsa_mul_add(uint8_t r[32], + const uint8_t a[32], + const uint8_t b[32], + const uint8_t c[32]); +void crypto_eddsa_scalarbase(uint8_t point[32], const uint8_t scalar[32]); +int crypto_eddsa_check_equation(const uint8_t signature[64], + const uint8_t public_key[32], + const uint8_t h_ram[32]); + + +// Chacha20 +// -------- + +// Specialised hash. +// Used to hash X25519 shared secrets. +void crypto_chacha20_h(uint8_t out[32], + const uint8_t key[32], + const uint8_t in [16]); + +// Unauthenticated stream cipher. +// Don't forget to add authentication. +uint64_t crypto_chacha20_djb(uint8_t *cipher_text, + const uint8_t *plain_text, + size_t text_size, + const uint8_t key[32], + const uint8_t nonce[8], + uint64_t ctr); +uint32_t crypto_chacha20_ietf(uint8_t *cipher_text, + const uint8_t *plain_text, + size_t text_size, + const uint8_t key[32], + const uint8_t nonce[12], + uint32_t ctr); +uint64_t crypto_chacha20_x(uint8_t *cipher_text, + const uint8_t *plain_text, + size_t text_size, + const uint8_t key[32], + const uint8_t nonce[24], + uint64_t ctr); + + +// Poly 1305 +// --------- + +// This is a *one time* authenticator. +// Disclosing the mac reveals the key. +// See crypto_lock() on how to use it properly. + +// Direct interface +void crypto_poly1305(uint8_t mac[16], + const uint8_t *message, size_t message_size, + const uint8_t key[32]); + +// Incremental interface +typedef struct { + // Do not rely on the size or contents of this type, + // for they may change without notice. + uint8_t c[16]; // chunk of the message + size_t c_idx; // How many bytes are there in the chunk. + uint32_t r [4]; // constant multiplier (from the secret key) + uint32_t pad[4]; // random number added at the end (from the secret key) + uint32_t h [5]; // accumulated hash +} crypto_poly1305_ctx; + +void crypto_poly1305_init (crypto_poly1305_ctx *ctx, const uint8_t key[32]); +void crypto_poly1305_update(crypto_poly1305_ctx *ctx, + const uint8_t *message, size_t message_size); +void crypto_poly1305_final (crypto_poly1305_ctx *ctx, uint8_t mac[16]); + + +// Elligator 2 +// ----------- + +// Elligator mappings proper +void crypto_elligator_map(uint8_t curve [32], const uint8_t hidden[32]); +int crypto_elligator_rev(uint8_t hidden[32], const uint8_t curve [32], + uint8_t tweak); + +// Easy to use key pair generation +void crypto_elligator_key_pair(uint8_t hidden[32], uint8_t secret_key[32], + uint8_t seed[32]); + +#ifdef __cplusplus +} +#endif + +#endif // MONOCYPHER_H diff --git a/net/ssh/keyfile.c b/net/ssh/keyfile.c new file mode 100644 index 00000000..07528afb --- /dev/null +++ b/net/ssh/keyfile.c @@ -0,0 +1,168 @@ +/* OpenSSH private key files ("openssh-key-v1", PROTOCOL.key), ed25519, + without a passphrase: read and write */ +#include +#include +#include +#include "crypto/monocypher.h" +#include "rng.h" +#include "keyfile.h" + +#define BEGIN "-----BEGIN OPENSSH PRIVATE KEY-----" +#define END "-----END OPENSSH PRIVATE KEY-----" +#define MAGIC "openssh-key-v1" + +int key_read(const char *path, uint8_t sk[64], uint8_t pk[32], char *err, size_t errn) +{ + FILE *f = fopen(path, "r"); + char line[256], *b64; + size_t len = 0, cap = 8192; + uint8_t *raw; + int n, in = 0, ok = 0; + struct buf b, priv; + uint32_t l1, l2, kn, pn, sn, i; + const uint8_t *cipher, *kdf, *p, *kpk, *ksk; + + if (!f) + { + snprintf(err, errn, "cannot open %s", path); + return 0; + } + b64 = malloc(cap); + raw = malloc(cap); + if (!b64 || !raw) + abort(); + while (fgets(line, sizeof(line), f)) + { + char *c; + if (!strncmp(line, BEGIN, strlen(BEGIN))) + { + in = 1; + continue; + } + if (!strncmp(line, END, strlen(END))) + break; + if (!in) + continue; + for (c = line; *c; c++) + if (*c > ' ' && len + 1 < cap) + b64[len++] = *c; + } + fclose(f); + n = b64_decode(b64, len, raw, cap); + free(b64); + if (n <= (int)sizeof(MAGIC) || memcmp(raw, MAGIC, sizeof(MAGIC))) + { + snprintf(err, errn, "%s is not an OpenSSH private key", path); + free(raw); + return 0; + } + b.d = raw; b.len = (size_t)n; b.cap = 0; b.pos = sizeof(MAGIC); b.err = 0; + cipher = get_str(&b, &l1); + kdf = get_str(&b, &l2); + get_str(&b, &kn); /* kdf options */ + if (b.err || l1 != 4 || memcmp(cipher, "none", 4) || l2 != 4 || memcmp(kdf, "none", 4)) + { + snprintf(err, errn, "%s has a passphrase (not supported: make one without)", path); + goto out; + } + if (get_u32(&b) != 1) + { + snprintf(err, errn, "%s: one key per file please", path); + goto out; + } + get_str(&b, &pn); /* public key blob */ + p = get_str(&b, &sn); + if (b.err) + goto bad; + priv.d = (uint8_t *)p; priv.len = sn; priv.cap = 0; priv.pos = 0; priv.err = 0; + if (get_u32(&priv) != get_u32(&priv)) + goto bad; /* check integers */ + p = get_str(&priv, &l1); + if (priv.err || l1 != 11 || memcmp(p, "ssh-ed25519", 11)) + { + snprintf(err, errn, "%s: only ed25519 keys are supported", path); + goto out; + } + kpk = get_str(&priv, &l1); + ksk = get_str(&priv, &l2); + if (priv.err || l1 != 32 || l2 != 64) + goto bad; + memcpy(pk, kpk, 32); + memcpy(sk, ksk, 64); + for (i = 0; i < 32 && sk[32 + i] == pk[i]; i++) + ; + if (i != 32) + goto bad; + ok = 1; + goto out; +bad: + snprintf(err, errn, "%s is damaged", path); +out: + crypto_wipe(raw, cap); + free(raw); + return ok; +} + +int key_write(const char *path, const uint8_t sk[64], const uint8_t pk[32], const char *comment) +{ + struct buf b, priv, pub; + uint8_t check[4]; + char *b64; + size_t n, i; + FILE *f; + int pad; + + buf_init(&b); + buf_init(&priv); + buf_init(&pub); + put_cstr(&pub, "ssh-ed25519"); + put_str(&pub, pk, 32); + rng_bytes(check, 4); + put_bytes(&priv, check, 4); + put_bytes(&priv, check, 4); + put_cstr(&priv, "ssh-ed25519"); + put_str(&priv, pk, 32); + put_str(&priv, sk, 64); + put_cstr(&priv, comment); + for (pad = 1; priv.len % 8; pad++) + put_u8(&priv, (uint8_t)pad); + put_bytes(&b, MAGIC, sizeof(MAGIC)); + put_cstr(&b, "none"); + put_cstr(&b, "none"); + put_cstr(&b, ""); + put_u32(&b, 1); + put_str(&b, pub.d, pub.len); + put_str(&b, priv.d, priv.len); + b64 = malloc(b.len * 2 + 4); + if (!b64) + abort(); + n = b64_encode(b.d, b.len, b64, 1); + f = fopen(path, "w"); + if (f) + { + fprintf(f, "%s\n", BEGIN); + for (i = 0; i < n; i += 70) + fprintf(f, "%.70s\n", b64 + i); + fprintf(f, "%s\n", END); + fclose(f); + } + crypto_wipe(b64, b.len * 2 + 4); + free(b64); + buf_free(&b); + buf_free(&priv); + buf_free(&pub); + return f != NULL; +} + +void key_public_line(const uint8_t pk[32], const char *comment, char *out, size_t n) +{ + struct buf b; + char b64[128]; + + buf_init(&b); + put_cstr(&b, "ssh-ed25519"); + put_str(&b, pk, 32); + b64_encode(b.d, b.len, b64, 1); + buf_free(&b); + snprintf(out, n, "ssh-ed25519 %s %s", b64, comment); +} diff --git a/net/ssh/keyfile.h b/net/ssh/keyfile.h new file mode 100644 index 00000000..d7239a05 --- /dev/null +++ b/net/ssh/keyfile.h @@ -0,0 +1,13 @@ +#ifndef KEYFILE_H +#define KEYFILE_H +#include +#include +#include "buf.h" + +/* an unencrypted OpenSSH ed25519 private key; 0 + message on failure */ +int key_read(const char *path, uint8_t sk[64], uint8_t pk[32], char *err, size_t errn); +int key_write(const char *path, const uint8_t sk[64], const uint8_t pk[32], const char *comment); +/* "ssh-ed25519 AAAA... comment" for authorized_keys */ +void key_public_line(const uint8_t pk[32], const char *comment, char *out, size_t n); + +#endif diff --git a/net/ssh/plat.h b/net/ssh/plat.h new file mode 100644 index 00000000..5747687f --- /dev/null +++ b/net/ssh/plat.h @@ -0,0 +1,38 @@ +/* platform services for the SSH programs: plat_dos.c (DJGPP + Watt-32 + + the MDVMM monitor) and plat_host.c (Linux, for protocol tests) */ +#ifndef PLAT_H +#define PLAT_H +#include +#include + +extern const char *plat_prog; /* name for the log lines */ +int plat_init(void); /* network up; 0 on failure */ +void plat_log(const char *fmt, ...); /* screen + monitor log */ +uint32_t plat_ms(void); /* milliseconds, wraps */ +void plat_idle(void); /* nothing to do: let others run */ +int plat_key(void); /* a key pressed on this console, or -1 */ +int plat_bioskey(void); /* BIOS key (scan << 8 | ASCII), or -1 */ +/* show an 80x25 screen of cells (attribute << 8 | char) and the cursor */ +void plat_screen_show(const uint16_t *cells, int row, int col, int cursor_on); + +int plat_listen(int port); /* non-blocking listening socket */ +int plat_accept(int lfd, char *peer, size_t n); /* -1: none waiting */ +int plat_connect(const char *host, int port); /* blocking; -1 on failure */ +void plat_nonblock(int fd); +void plat_close(int fd); + +/* job slots (MDVMM sessions running COMMAND.COM, see SSHSLOT.COM) */ +enum { JOB_NONE, JOB_ASSIGNED, JOB_RUNNING, JOB_DONE }; +int plat_job_start(const char *cmd); /* "" = interactive shell; slot or -1 */ +int plat_job_state(int slot, int *code); /* JOB_*, -1 if not a slot */ +/* text screen: cells (char, attribute) 80x25, cursor; 0 on failure */ +int plat_screen(int slot, uint8_t cells[4000], int *row, int *col, int *hidden); +int plat_keys(int slot, const uint16_t *keys, int n); /* keys taken */ + +/* file names: "/C/DIR/FILE" style SFTP paths <-> the native ones */ +int plat_native_path(const char *sftp, char *out, size_t n); /* 0: bad */ +int plat_drive_ok(char letter); /* drive to list under "/" */ +const char *plat_home(void); /* initial SFTP directory */ +const char *plat_tempdir(void); /* for exec output, ends in a separator */ + +#endif diff --git a/net/ssh/plat_dos.c b/net/ssh/plat_dos.c new file mode 100644 index 00000000..4ac5be6f --- /dev/null +++ b/net/ssh/plat_dos.c @@ -0,0 +1,374 @@ +/* platform services on modernDOS: DJGPP, Watt-32, MDVMM monitor calls */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "plat.h" +#include "ssh.h" + +const char *plat_prog = "sshd"; +static int have_mdvmm; +static char home[16], tmpdir[80]; + +static int mdvmm(__dpmi_regs *r, int al) +{ + r->h.ah = 0xde; + r->h.al = (unsigned char)al; + __dpmi_int(0x2f, r); + return !(r->x.flags & 1); +} + +int plat_init(void) +{ + __dpmi_regs r; + const char *t; + char cwd[80]; + + memset(&r, 0, sizeof(r)); + r.x.ax = 0xde00; + __dpmi_int(0x2f, &r); + have_mdvmm = r.h.al == 0xff; + if (!getcwd(cwd, sizeof(cwd))) + strcpy(cwd, "."); + if (isalpha((unsigned char)cwd[0]) && cwd[1] == ':') + snprintf(home, sizeof(home), "/%c", toupper((unsigned char)cwd[0])); + else + strcpy(home, "/C"); + /* exec output files: absolute, DOS separators (COMMAND.COM redirects) */ + t = getenv("TEMP"); + if (!t) + t = getenv("TMP"); + snprintf(tmpdir, sizeof(tmpdir), "%s", t ? t : cwd); + { + char *p; + size_t n; + for (p = tmpdir; *p; p++) + if (*p == '/') + *p = '\\'; + n = strlen(tmpdir); + if (n && tmpdir[n - 1] != '\\' && n + 1 < sizeof(tmpdir)) + strcat(tmpdir, "\\"); + } + if (sock_init()) + { + plat_log("network setup failed (packet driver loaded? WATTCP.CFG?)\n"); + return 0; + } + { + char ip[20]; + if (!strcmp(plat_prog, "sshd")) /* the client stays quiet */ + plat_log("network up, address %s\n", _inet_ntoa(ip, my_ip_addr)); + } + return 1; +} + +void plat_log(const char *fmt, ...) +{ + char buf[300]; + va_list ap; + size_t n; + + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + fputs(buf, stderr); /* stdout is a command's output */ + if (have_mdvmm) /* the monitor's log (and port E9h) */ + { + __dpmi_regs r; + char line[320]; + char *p; + snprintf(line, sizeof(line), "%s: %s", plat_prog, buf); + for (p = line; *p; p++) + if (*p == '\n') + *p = '\r'; /* the log wants CR LF */ + n = strlen(line); + if (n && line[n - 1] == '\r') + { + line[n - 1] = 0; + strcat(line, "\r\n"); + } + dosmemput(line, strlen(line) + 1, __tb); + memset(&r, 0, sizeof(r)); + r.x.ds = __tb >> 4; + r.x.dx = __tb & 15; + mdvmm(&r, 0x01); + } +} + +/* milliseconds from the BIOS tick count (55 ms steps). Not uclock(): it + reprograms the timer, and this session's tick count jumps when MDVMM + catches up the ticks it missed while other sessions ran. Never goes + backwards (midnight wrap included). */ +uint32_t plat_ms(void) +{ + static uint32_t last, base; + uint32_t t = _farpeekl(_dos_ds, 0x46c); + + if (t < last) + base += 0x1800b0; /* past midnight */ + last = t; + return (uint32_t)(((uint64_t)(base + t) * 54925) / 1000); +} + +void plat_idle(void) +{ + __dpmi_yield(); +} + +int plat_key(void) +{ + if (!kbhit()) + return -1; + return getch(); +} + +int plat_bioskey(void) +{ + if (!_bios_keybrd(_KEYBRD_READY)) + return -1; + return (int)(_bios_keybrd(_KEYBRD_READ) & 0xffff); +} + +void plat_screen_show(const uint16_t *cells, int row, int col, int cursor_on) +{ + __dpmi_regs r; + + dosmemput(cells, 80 * 25 * 2, 0xb8000); + memset(&r, 0, sizeof(r)); + r.h.ah = 0x02; /* cursor position, page 0 */ + r.h.dh = (unsigned char)row; + r.h.dl = (unsigned char)col; + __dpmi_int(0x10, &r); + memset(&r, 0, sizeof(r)); + r.h.ah = 0x01; /* cursor shape */ + r.x.cx = cursor_on ? 0x0607 : 0x2000; + __dpmi_int(0x10, &r); +} + +void plat_nonblock(int fd) +{ + int on = 1; + ioctlsocket(fd, FIONBIO, (char *)&on); +} + +int plat_listen(int port) +{ + struct sockaddr_in sa; + int fd = socket(AF_INET, SOCK_STREAM, 0), on = 1; + + if (fd < 0) + return -1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)); + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons((unsigned short)port); + sa.sin_addr.s_addr = INADDR_ANY; + if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0 || listen(fd, 4) < 0) + { + closesocket(fd); + return -1; + } + plat_nonblock(fd); + return fd; +} + +int plat_accept(int lfd, char *peer, size_t n) +{ + struct sockaddr_in sa; + int len = sizeof(sa), fd; + + fd = accept(lfd, (struct sockaddr *)&sa, &len); + if (fd < 0) + return -1; + plat_nonblock(fd); + snprintf(peer, n, "%s:%u", inet_ntoa(sa.sin_addr), ntohs(sa.sin_port)); + return fd; +} + +int plat_connect(const char *host, int port) +{ + struct sockaddr_in sa; + struct hostent *h; + int fd; + + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons((unsigned short)port); + sa.sin_addr.s_addr = inet_addr(host); + if (sa.sin_addr.s_addr == INADDR_NONE) + { + h = gethostbyname(host); + if (!h) + return -1; + memcpy(&sa.sin_addr, h->h_addr, sizeof(sa.sin_addr)); + } + fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) + return -1; + if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) + { + closesocket(fd); + return -1; + } + plat_nonblock(fd); + return fd; +} + +void plat_close(int fd) +{ + closesocket(fd); +} + +int net_recv(int fd, void *p, int n) +{ + int r = recv(fd, p, n, 0); + + if (r > 0) + return r; + if (r == 0) + return -1; + if (errno == EWOULDBLOCK || errno == EAGAIN) + return 0; + return -1; +} + +int net_send(int fd, const void *p, int n) +{ + int r = send(fd, (void *)p, n, 0); + + if (r >= 0) + return r; + if (errno == EWOULDBLOCK || errno == EAGAIN) + return 0; + return -1; +} + +/* ---------------------------------------------------------------- */ +/* job slots */ + +int plat_job_start(const char *cmd) +{ + __dpmi_regs r; + + if (!have_mdvmm) + return -1; + memset(&r, 0, sizeof(r)); + dosmemput(cmd, strlen(cmd) + 1, __tb); + r.x.ds = __tb >> 4; + r.x.si = __tb & 15; + return mdvmm(&r, 0x0c) ? r.x.ax : -1; +} + +int plat_job_state(int slot, int *code) +{ + __dpmi_regs r; + + memset(&r, 0, sizeof(r)); + r.h.bl = (unsigned char)slot; + if (!mdvmm(&r, 0x0d)) + return -1; + *code = r.x.bx; + return r.x.ax; +} + +int plat_screen(int slot, uint8_t cells[4000], int *row, int *col, int *hidden) +{ + __dpmi_regs r; + + memset(&r, 0, sizeof(r)); + r.h.bl = (unsigned char)slot; + r.x.es = __tb >> 4; + r.x.di = __tb & 15; + r.x.cx = 4000; + if (!mdvmm(&r, 0x08)) + return 0; + if (r.x.si < 4000) + memset(cells, 0, 4000); + dosmemget(__tb, r.x.si, cells); + *row = r.h.ah; + *col = r.h.al; + *hidden = (r.x.bx & 0x2000) != 0 || (r.h.cl > 3 && r.h.cl != 7); + return 1; +} + +int plat_keys(int slot, const uint16_t *keys, int n) +{ + __dpmi_regs r; + + if (n > 64) + n = 64; + memset(&r, 0, sizeof(r)); + dosmemput(keys, (size_t)n * 2, __tb); + r.h.bl = (unsigned char)slot; + r.x.ds = __tb >> 4; + r.x.si = __tb & 15; + r.x.cx = (unsigned short)n; + if (!mdvmm(&r, 0x09)) + return 0; + return r.x.cx; +} + +/* ---------------------------------------------------------------- */ +/* files */ + +/* "/C/DIR/FILE" -> "C:/DIR/FILE"; "/C" -> "C:/" */ +int plat_native_path(const char *sftp, char *out, size_t n) +{ + if (sftp[0] != '/' || !isalpha((unsigned char)sftp[1]) || (sftp[2] && sftp[2] != '/')) + return 0; + if (snprintf(out, n, "%c:%s", toupper((unsigned char)sftp[1]), sftp[2] ? sftp + 2 : "/") >= (int)n) + return 0; + return 1; +} + +int plat_drive_ok(char letter) +{ + unsigned int cur, total; + int d = toupper((unsigned char)letter) - 'A' + 1; + + if (d < 1 || d > 26) + return 0; + if (d <= 2) /* floppies: only the current one */ + { + _dos_getdrive(&cur); + return (int)cur == d; + } + { + __dpmi_regs r; /* INT 21h AX=4409h: drive exists? */ + memset(&r, 0, sizeof(r)); + r.x.ax = 0x4409; + r.h.bl = (unsigned char)d; + __dpmi_int(0x21, &r); + (void)total; + return !(r.x.flags & 1); + } +} + +const char *plat_home(void) +{ + return home; +} + +const char *plat_tempdir(void) +{ + return tmpdir; +} diff --git a/net/ssh/plat_host.c b/net/ssh/plat_host.c new file mode 100644 index 00000000..ca90f8bc --- /dev/null +++ b/net/ssh/plat_host.c @@ -0,0 +1,255 @@ +/* platform services on Linux, for testing the SSH protocol code against + OpenSSH without DOS: exec jobs run with /bin/sh, the SFTP root "/C" is + the directory $SSHD_ROOT (default: the current one); no shells. */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "plat.h" +#include "ssh.h" + +#define MAX_JOBS 3 + +static struct { pid_t pid; int state, code; } jobs[MAX_JOBS + 1]; +const char *plat_prog = "sshd"; +static char root[512]; + +int plat_init(void) +{ + const char *r = getenv("SSHD_ROOT"); + + snprintf(root, sizeof(root), "%s", r ? r : "."); + return 1; +} + +void plat_log(const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); +} + +uint32_t plat_ms(void) +{ + struct timespec t; + + clock_gettime(CLOCK_MONOTONIC, &t); + return (uint32_t)(t.tv_sec * 1000 + t.tv_nsec / 1000000); +} + +void plat_idle(void) +{ + usleep(2000); +} + +/* stdin without blocking (tests pipe the password in) */ +int plat_key(void) +{ + static int eof; + struct pollfd pf = { 0, POLLIN, 0 }; + unsigned char c; + + if (eof || poll(&pf, 1, 0) <= 0) + return -1; + if (read(0, &c, 1) != 1) + { + eof = 1; + return -1; + } + return c; +} + +int plat_bioskey(void) +{ + int c = plat_key(); + + if (c == '\n') + c = '\r'; + return c < 0 ? -1 : c; +} + +void plat_screen_show(const uint16_t *cells, int row, int col, int cursor_on) +{ + (void)cells; (void)row; (void)col; (void)cursor_on; +} + +void plat_nonblock(int fd) +{ + fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK); +} + +int plat_listen(int port) +{ + struct sockaddr_in sa; + int fd = socket(AF_INET, SOCK_STREAM, 0), on = 1; + + if (fd < 0) + return -1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons((unsigned short)port); + sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0 || listen(fd, 4) < 0) + { + close(fd); + return -1; + } + plat_nonblock(fd); + return fd; +} + +int plat_accept(int lfd, char *peer, size_t n) +{ + struct sockaddr_in sa; + socklen_t len = sizeof(sa); + int fd = accept(lfd, (struct sockaddr *)&sa, &len); + + if (fd < 0) + return -1; + plat_nonblock(fd); + snprintf(peer, n, "%s:%u", inet_ntoa(sa.sin_addr), ntohs(sa.sin_port)); + return fd; +} + +int plat_connect(const char *host, int port) +{ + struct addrinfo hints, *ai; + char ps[8]; + int fd; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + snprintf(ps, sizeof(ps), "%d", port); + if (getaddrinfo(host, ps, &hints, &ai)) + return -1; + fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0 || connect(fd, ai->ai_addr, ai->ai_addrlen) < 0) + { + freeaddrinfo(ai); + if (fd >= 0) + close(fd); + return -1; + } + freeaddrinfo(ai); + plat_nonblock(fd); + return fd; +} + +void plat_close(int fd) +{ + close(fd); +} + +int net_recv(int fd, void *p, int n) +{ + ssize_t r = recv(fd, p, (size_t)n, 0); + + if (r > 0) + return (int)r; + if (r == 0) + return -1; + return errno == EAGAIN || errno == EWOULDBLOCK ? 0 : -1; +} + +int net_send(int fd, const void *p, int n) +{ + ssize_t r = send(fd, p, (size_t)n, MSG_NOSIGNAL); + + if (r >= 0) + return (int)r; + return errno == EAGAIN || errno == EWOULDBLOCK ? 0 : -1; +} + +int plat_job_start(const char *cmd) +{ + int i; + + if (!*cmd) + return -1; /* no interactive shells here */ + for (i = 1; i <= MAX_JOBS; i++) + if (jobs[i].state == JOB_NONE) + { + pid_t pid = fork(); + if (pid < 0) + return -1; + if (!pid) + { + execl("/bin/sh", "sh", "-c", cmd, (char *)NULL); + _exit(127); + } + jobs[i].pid = pid; + jobs[i].state = JOB_RUNNING; + return i; + } + return -1; +} + +int plat_job_state(int slot, int *code) +{ + int st; + + if (slot < 1 || slot > MAX_JOBS) + return -1; + if (jobs[slot].state == JOB_RUNNING && waitpid(jobs[slot].pid, &st, WNOHANG) == jobs[slot].pid) + { + jobs[slot].state = JOB_DONE; + jobs[slot].code = WIFEXITED(st) ? WEXITSTATUS(st) : 255; + } + *code = jobs[slot].code; + st = jobs[slot].state; + if (st == JOB_DONE) + jobs[slot].state = JOB_NONE; + return st; +} + +int plat_screen(int slot, uint8_t cells[4000], int *row, int *col, int *hidden) +{ + (void)slot; + memset(cells, 0, 4000); + *row = *col = *hidden = 0; + return 1; +} + +int plat_keys(int slot, const uint16_t *keys, int n) +{ + (void)slot; + (void)keys; + return n; +} + +int plat_native_path(const char *sftp, char *out, size_t n) +{ + if (strncmp(sftp, "/C", 2) || (sftp[2] && sftp[2] != '/')) + return 0; + return snprintf(out, n, "%s%s", root, sftp[2] ? sftp + 2 : "/") < (int)n; +} + +int plat_drive_ok(char letter) +{ + return letter == 'C'; +} + +const char *plat_home(void) +{ + return "/C"; +} + +const char *plat_tempdir(void) +{ + return "/tmp/"; +} diff --git a/net/ssh/rng.c b/net/ssh/rng.c new file mode 100644 index 00000000..d68e9c47 --- /dev/null +++ b/net/ssh/rng.c @@ -0,0 +1,147 @@ +/* random numbers for SSH + * + * DOS has no entropy source and the target CPUs (Core 2) have no RDRAND, + * so: timing jitter between the CPU's time stamp counter and the 8254 + * timer (sampled many times at start), the time of day, a seed file kept + * between runs, and the timing of later events (packets, keys) are hashed + * into a BLAKE2b pool. Output: ChaCha20 keyed from the pool, with a new + * key after every request (old output can not be recomputed). + * On a host build (tests) /dev/urandom is used as well. + */ +#include +#include +#include +#include "crypto/monocypher.h" +#include "rng.h" +#ifdef __DJGPP__ +#include +#endif + +static crypto_blake2b_ctx pool; +static uint8_t key[32]; +static uint64_t nonce; +static int ready; + +static uint64_t tsc(void) +{ +#if defined(__i386__) || defined(__x86_64__) + uint32_t lo, hi; + __asm__ volatile("rdtsc" : "=a"(lo), "=d"(hi)); + return (uint64_t)hi << 32 | lo; +#else + return (uint64_t)clock(); +#endif +} + +void rng_event(uint32_t what) +{ + uint64_t t = tsc(); + + if (!ready) + return; + crypto_blake2b_update(&pool, (const uint8_t *)&t, sizeof(t)); + crypto_blake2b_update(&pool, (const uint8_t *)&what, sizeof(what)); +} + +/* fold the pool into the output key */ +static void reseed(void) +{ + uint8_t h[64]; + + crypto_blake2b_update(&pool, key, sizeof(key)); + crypto_blake2b_final(&pool, h); + memcpy(key, h, 32); + crypto_blake2b_init(&pool, 64); + crypto_blake2b_update(&pool, h + 32, 32); /* carry the rest along */ + crypto_wipe(h, sizeof(h)); +} + +static void jitter(int samples) +{ + int i; + + for (i = 0; i < samples; i++) + { + uint64_t t0 = tsc(), t1; +#ifdef __DJGPP__ + uint8_t a, b; + int spin = 0; + outportb(0x43, 0x00); /* latch counter 0 */ + a = inportb(0x40); + (void)inportb(0x40); + do + { + outportb(0x43, 0x00); + b = inportb(0x40); + (void)inportb(0x40); + } while (b == a && ++spin < 100000); /* no 8254: TSC alone */ +#endif + t1 = tsc(); + t1 -= t0; + crypto_blake2b_update(&pool, (const uint8_t *)&t1, sizeof(t1)); + } +} + +void rng_init(const char *seedfile) +{ + uint8_t buf[64]; + time_t now = time(NULL); + FILE *f; + + crypto_blake2b_init(&pool, 64); + ready = 1; + rng_event(1); + crypto_blake2b_update(&pool, (const uint8_t *)&now, sizeof(now)); + if (seedfile && (f = fopen(seedfile, "rb"))) + { + size_t n = fread(buf, 1, sizeof(buf), f); + crypto_blake2b_update(&pool, buf, n); + fclose(f); + } + f = fopen("/dev/urandom", "rb"); + if (f) + { + size_t n = fread(buf, 1, sizeof(buf), f); + crypto_blake2b_update(&pool, buf, n); + fclose(f); + } + jitter(4096); + reseed(); + rng_save(seedfile); + crypto_wipe(buf, sizeof(buf)); +} + +void rng_bytes(void *out, size_t n) +{ + uint8_t next[32], nb[8]; + int i; + + rng_event(2); + reseed(); + for (i = 0; i < 8; i++) + nb[i] = (uint8_t)(nonce >> (i * 8)); + nonce++; + memset(out, 0, n); + crypto_chacha20_djb(out, out, n, key, nb, 1); + memset(next, 0, sizeof(next)); + crypto_chacha20_djb(next, next, sizeof(next), key, nb, 0); + memcpy(key, next, sizeof(key)); /* fast key erasure */ + crypto_wipe(next, sizeof(next)); +} + +void rng_save(const char *seedfile) +{ + uint8_t s[32]; + FILE *f; + + if (!seedfile) + return; + rng_bytes(s, sizeof(s)); + f = fopen(seedfile, "wb"); + if (f) + { + fwrite(s, 1, sizeof(s), f); + fclose(f); + } + crypto_wipe(s, sizeof(s)); +} diff --git a/net/ssh/rng.h b/net/ssh/rng.h new file mode 100644 index 00000000..e3378df6 --- /dev/null +++ b/net/ssh/rng.h @@ -0,0 +1,11 @@ +#ifndef RNG_H +#define RNG_H +#include +#include + +void rng_init(const char *seedfile); /* seedfile may be NULL */ +void rng_event(uint32_t what); /* mix in the time of an event */ +void rng_bytes(void *out, size_t n); +void rng_save(const char *seedfile); /* new seed for the next run */ + +#endif diff --git a/net/ssh/sftp.c b/net/ssh/sftp.c new file mode 100644 index 00000000..24cdbd4e --- /dev/null +++ b/net/ssh/sftp.c @@ -0,0 +1,667 @@ +/* SFTP server, protocol version 3 (draft-ietf-secsh-filexfer-02), as used + * by OpenSSH's sftp and scp. DOS drives appear as top level directories: + * "/C/DOS/FILE.TXT" is C:\DOS\FILE.TXT, "/" lists the drives. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "plat.h" +#include "sftp.h" + +#ifndef O_BINARY +#define O_BINARY 0 +#endif + +enum { + FXP_INIT = 1, FXP_VERSION, FXP_OPEN, FXP_CLOSE, FXP_READ, FXP_WRITE, FXP_LSTAT, + FXP_FSTAT, FXP_SETSTAT, FXP_FSETSTAT, FXP_OPENDIR, FXP_READDIR, FXP_REMOVE, + FXP_MKDIR, FXP_RMDIR, FXP_REALPATH, FXP_STAT, FXP_RENAME, FXP_READLINK, FXP_SYMLINK, + FXP_STATUS = 101, FXP_HANDLE, FXP_DATA, FXP_NAME, FXP_ATTRS, FXP_EXTENDED = 200 +}; +enum { FX_OK, FX_EOF, FX_NO_SUCH_FILE, FX_PERMISSION_DENIED, FX_FAILURE, FX_BAD_MESSAGE, + FX_NO_CONNECTION, FX_CONNECTION_LOST, FX_OP_UNSUPPORTED }; +#define ATTR_SIZE 1 +#define ATTR_PERMISSIONS 4 +#define ATTR_ACMODTIME 8 +#define PF_READ 1 +#define PF_WRITE 2 +#define PF_APPEND 4 +#define PF_CREAT 8 +#define PF_TRUNC 16 +#define PF_EXCL 32 + +#define MAX_HANDLES 16 +#define MAX_PATH_LEN 260 + +struct handle { + int used; + int fd; /* file, or -1 */ + DIR *dir; /* directory */ + int drives; /* "/": next drive letter to list */ + char path[MAX_PATH_LEN]; /* SFTP path of the directory */ +}; + +struct sftp { + struct handle h[MAX_HANDLES]; + int ready; +}; + +struct sftp *sftp_new(void) +{ + return calloc(1, sizeof(struct sftp)); +} + +void sftp_free(struct sftp *s) +{ + int i; + + if (!s) + return; + for (i = 0; i < MAX_HANDLES; i++) + if (s->h[i].used) + { + if (s->h[i].fd >= 0) + close(s->h[i].fd); + if (s->h[i].dir) + closedir(s->h[i].dir); + } + free(s); +} + +/* ---------------------------------------------------------------- */ + +/* resolve an SFTP path (absolute, or relative to the home) into a clean + absolute one: "/", "/C", "/C/DIR" ... */ +static int clean_path(const char *in, char *out, size_t n) +{ + char tmp[MAX_PATH_LEN * 2], *seg, *save; + size_t len = 0; + + if (in[0] == '/') + snprintf(tmp, sizeof(tmp), "%s", in); + else + snprintf(tmp, sizeof(tmp), "%s/%s", plat_home(), in); + out[0] = 0; + for (seg = strtok_r(tmp, "/\\", &save); seg; seg = strtok_r(NULL, "/\\", &save)) + { + if (!strcmp(seg, ".") || !*seg) + continue; + if (!strcmp(seg, "..")) + { + char *slash = strrchr(out, '/'); + if (slash) + *slash = 0; + len = strlen(out); + continue; + } + if (len + 1 + strlen(seg) + 1 > n) + return 0; + out[len++] = '/'; + strcpy(out + len, seg); + len += strlen(seg); + } + if (!len) + strcpy(out, "/"); + else if (len == 2 && out[1] >= 'a' && out[1] <= 'z') + out[1] -= 32; /* "/c" -> "/C" */ + else if (len > 2 && out[1] >= 'a' && out[1] <= 'z') + out[1] -= 32; + return 1; +} + +static int native(const char *sftp, char *out, size_t n) +{ + char clean[MAX_PATH_LEN]; + + return clean_path(sftp, clean, sizeof(clean)) && plat_native_path(clean, out, n); +} + +static void status(struct buf *o, uint32_t id, uint32_t code, const char *msg) +{ + size_t at = o->len; + + put_u32(o, 0); + put_u8(o, FXP_STATUS); + put_u32(o, id); + put_u32(o, code); + put_cstr(o, msg); + put_cstr(o, "en"); + poke_u32(o->d + at, (uint32_t)(o->len - at - 4)); +} + +static uint32_t errno_status(void) +{ + switch (errno) + { + case ENOENT: case ENOTDIR: return FX_NO_SUCH_FILE; + case EACCES: case EPERM: case EROFS: return FX_PERMISSION_DENIED; + } + return FX_FAILURE; +} + +static void status_errno(struct buf *o, uint32_t id) +{ + uint32_t code = errno_status(); + + status(o, id, code, code == FX_NO_SUCH_FILE ? "No such file" : + code == FX_PERMISSION_DENIED ? "Permission denied" : strerror(errno)); +} + +static void put_attrs(struct buf *o, const struct stat *st) +{ + uint32_t perm = S_ISDIR(st->st_mode) ? 040755 : (st->st_mode & S_IWUSR) ? 0100644 : 0100444; + + put_u32(o, ATTR_SIZE | ATTR_PERMISSIONS | ATTR_ACMODTIME); + put_u64(o, S_ISDIR(st->st_mode) ? 0 : (uint64_t)st->st_size); + put_u32(o, perm); + put_u32(o, (uint32_t)st->st_atime); + put_u32(o, (uint32_t)st->st_mtime); +} + +static void put_dir_attrs(struct buf *o) +{ + put_u32(o, ATTR_PERMISSIONS); + put_u32(o, 040755); +} + +/* "ls -l" style line for sftp's ls -l */ +static void longname(char *out, size_t n, const char *name, const struct stat *st) +{ + char when[16]; + struct tm *t = localtime(&st->st_mtime); + int dir = S_ISDIR(st->st_mode); + + if (t) + strftime(when, sizeof(when), "%b %d %H:%M", t); + else + strcpy(when, "Jan 01 00:00"); + snprintf(out, n, "%s 1 dos dos %10lu %s %s", dir ? "drwxr-xr-x" : + (st->st_mode & S_IWUSR) ? "-rw-r--r--" : "-r--r--r--", + dir ? 0ul : (unsigned long)st->st_size, when, name); +} + +static int new_handle(struct sftp *s) +{ + int i; + + for (i = 0; i < MAX_HANDLES; i++) + if (!s->h[i].used) + { + memset(&s->h[i], 0, sizeof(s->h[i])); + s->h[i].used = 1; + s->h[i].fd = -1; + return i; + } + return -1; +} + +static void put_handle(struct buf *o, uint32_t id, int h) +{ + size_t at = o->len; + char hs[8]; + + snprintf(hs, sizeof(hs), "%d", h); + put_u32(o, 0); + put_u8(o, FXP_HANDLE); + put_u32(o, id); + put_cstr(o, hs); + poke_u32(o->d + at, (uint32_t)(o->len - at - 4)); +} + +static struct handle *get_handle(struct sftp *s, struct buf *p) +{ + uint32_t n; + const uint8_t *hs = get_str(p, &n); + int h = 0; + uint32_t i; + + if (!hs || !n || n > 3) + return NULL; + for (i = 0; i < n; i++) + { + if (hs[i] < '0' || hs[i] > '9') + return NULL; + h = h * 10 + hs[i] - '0'; + } + if (h >= MAX_HANDLES || !s->h[h].used) + return NULL; + return &s->h[h]; +} + +/* skip an ATTRS structure in a request; returns the flags (and mtime) */ +static uint32_t skip_attrs(struct buf *p, uint32_t *atime, uint32_t *mtime) +{ + uint32_t flags = get_u32(p), i, count; + + if (flags & ATTR_SIZE) + get_u64(p); + if (flags & 2) /* uid, gid */ + { + get_u32(p); + get_u32(p); + } + if (flags & ATTR_PERMISSIONS) + get_u32(p); + if (flags & ATTR_ACMODTIME) + { + *atime = get_u32(p); + *mtime = get_u32(p); + } + if (flags & 0x80000000u) /* extended */ + { + count = get_u32(p); + for (i = 0; i < count && !p->err; i++) + { + get_str(p, &flags); + get_str(p, &flags); + } + } + return flags; +} + +/* "/" : the drives */ +static int is_root(const char *clean) +{ + return !strcmp(clean, "/"); +} + +static void do_stat(struct sftp *s, struct buf *p, struct buf *o, uint32_t id) +{ + char path[MAX_PATH_LEN], clean[MAX_PATH_LEN], nat[MAX_PATH_LEN]; + struct stat st; + size_t at = o->len; + + (void)s; + if (!get_cstr(p, path, sizeof(path)) || !clean_path(path, clean, sizeof(clean))) + { + status(o, id, FX_BAD_MESSAGE, "bad path"); + return; + } + put_u32(o, 0); + put_u8(o, FXP_ATTRS); + put_u32(o, id); + if (is_root(clean) || (strlen(clean) == 2 && plat_drive_ok(clean[1]))) + put_dir_attrs(o); + else if (plat_native_path(clean, nat, sizeof(nat)) && !stat(nat, &st)) + put_attrs(o, &st); + else + { + o->len = at; + status_errno(o, id); + return; + } + poke_u32(o->d + at, (uint32_t)(o->len - at - 4)); +} + +static void do_realpath(struct buf *p, struct buf *o, uint32_t id) +{ + char path[MAX_PATH_LEN], clean[MAX_PATH_LEN]; + size_t at = o->len; + + if (!get_cstr(p, path, sizeof(path)) || !clean_path(*path ? path : ".", clean, sizeof(clean))) + { + status(o, id, FX_BAD_MESSAGE, "bad path"); + return; + } + put_u32(o, 0); + put_u8(o, FXP_NAME); + put_u32(o, id); + put_u32(o, 1); + put_cstr(o, clean); + put_cstr(o, clean); + put_u32(o, 0); + poke_u32(o->d + at, (uint32_t)(o->len - at - 4)); +} + +static void do_open(struct sftp *s, struct buf *p, struct buf *o, uint32_t id) +{ + char path[MAX_PATH_LEN], nat[MAX_PATH_LEN]; + uint32_t pf, at = 0, mt = 0; + int flags = O_BINARY, h, fd; + + get_cstr(p, path, sizeof(path)); + pf = get_u32(p); + skip_attrs(p, &at, &mt); + if (p->err || !native(path, nat, sizeof(nat))) + { + status(o, id, FX_NO_SUCH_FILE, "bad path"); + return; + } + if ((pf & PF_READ) && (pf & PF_WRITE)) + flags |= O_RDWR; + else if (pf & PF_WRITE) + flags |= O_WRONLY; + else + flags |= O_RDONLY; + if (pf & PF_APPEND) + flags |= O_APPEND; + if (pf & PF_CREAT) + flags |= O_CREAT; + if (pf & PF_TRUNC) + flags |= O_TRUNC; + if (pf & PF_EXCL) + flags |= O_EXCL; + h = new_handle(s); + if (h < 0) + { + status(o, id, FX_FAILURE, "too many open files"); + return; + } + fd = open(nat, flags, 0644); + if (fd < 0) + { + s->h[h].used = 0; + status_errno(o, id); + return; + } + s->h[h].fd = fd; + put_handle(o, id, h); +} + +static void do_read(struct sftp *s, struct buf *p, struct buf *o, uint32_t id) +{ + struct handle *h = get_handle(s, p); + uint64_t off = get_u64(p); + uint32_t len = get_u32(p); + size_t at = o->len; + int n; + + if (!h || h->fd < 0 || p->err) + { + status(o, id, FX_FAILURE, "bad handle"); + return; + } + if (len > 32768) + len = 32768; + if (lseek(h->fd, (off_t)off, SEEK_SET) < 0) + { + status_errno(o, id); + return; + } + put_u32(o, 0); + put_u8(o, FXP_DATA); + put_u32(o, id); + put_u32(o, 0); + buf_reserve(o, len); + n = read(h->fd, o->d + o->len, len); + if (n <= 0) + { + o->len = at; + if (n == 0) + status(o, id, FX_EOF, "end of file"); + else + status_errno(o, id); + return; + } + o->len += (size_t)n; + poke_u32(o->d + at + 9, (uint32_t)n); + poke_u32(o->d + at, (uint32_t)(o->len - at - 4)); +} + +static void do_write(struct sftp *s, struct buf *p, struct buf *o, uint32_t id) +{ + struct handle *h = get_handle(s, p); + uint64_t off = get_u64(p); + uint32_t len; + const uint8_t *data = get_str(p, &len); + + if (!h || h->fd < 0 || !data) + { + status(o, id, FX_FAILURE, "bad handle"); + return; + } + if (lseek(h->fd, (off_t)off, SEEK_SET) < 0 || write(h->fd, data, len) != (int)len) + { + if (errno == 0) + errno = ENOSPC; + status_errno(o, id); + return; + } + status(o, id, FX_OK, ""); +} + +static void do_fstat(struct sftp *s, struct buf *p, struct buf *o, uint32_t id) +{ + struct handle *h = get_handle(s, p); + struct stat st; + size_t at = o->len; + + if (!h || h->fd < 0 || fstat(h->fd, &st)) + { + status(o, id, FX_FAILURE, "bad handle"); + return; + } + put_u32(o, 0); + put_u8(o, FXP_ATTRS); + put_u32(o, id); + put_attrs(o, &st); + poke_u32(o->d + at, (uint32_t)(o->len - at - 4)); +} + +static void do_opendir(struct sftp *s, struct buf *p, struct buf *o, uint32_t id) +{ + char path[MAX_PATH_LEN], clean[MAX_PATH_LEN], nat[MAX_PATH_LEN]; + int h; + + if (!get_cstr(p, path, sizeof(path)) || !clean_path(path, clean, sizeof(clean))) + { + status(o, id, FX_BAD_MESSAGE, "bad path"); + return; + } + h = new_handle(s); + if (h < 0) + { + status(o, id, FX_FAILURE, "too many open directories"); + return; + } + strcpy(s->h[h].path, clean); + if (is_root(clean)) + { + s->h[h].drives = 'A'; + put_handle(o, id, h); + return; + } + if (!plat_native_path(clean, nat, sizeof(nat)) || !(s->h[h].dir = opendir(nat))) + { + s->h[h].used = 0; + status_errno(o, id); + return; + } + put_handle(o, id, h); +} + +static void do_readdir(struct sftp *s, struct buf *p, struct buf *o, uint32_t id) +{ + struct handle *h = get_handle(s, p); + size_t at = o->len; + uint32_t count = 0; + char line[MAX_PATH_LEN + 64]; + + if (!h || (!h->dir && !h->drives)) + { + status(o, id, FX_FAILURE, "bad handle"); + return; + } + put_u32(o, 0); + put_u8(o, FXP_NAME); + put_u32(o, id); + put_u32(o, 0); + if (h->drives) + { + while (h->drives <= 'Z' && count < 26) + { + char name[2] = { (char)h->drives++, 0 }; + if (!plat_drive_ok(name[0])) + continue; + snprintf(line, sizeof(line), "drwxr-xr-x 1 dos dos %10u Jan 01 00:00 %s", 0u, name); + put_cstr(o, name); + put_cstr(o, line); + put_dir_attrs(o); + count++; + } + } + else + { + struct dirent *e; + while (count < 64 && (e = readdir(h->dir))) + { + char nat[MAX_PATH_LEN], sp[MAX_PATH_LEN * 2]; + struct stat st; + snprintf(sp, sizeof(sp), "%s/%s", h->path, e->d_name); + if (!plat_native_path(sp, nat, sizeof(nat)) || stat(nat, &st)) + memset(&st, 0, sizeof(st)); + longname(line, sizeof(line), e->d_name, &st); + put_cstr(o, e->d_name); + put_cstr(o, line); + put_attrs(o, &st); + count++; + } + } + if (!count) + { + o->len = at; + status(o, id, FX_EOF, "end of directory"); + return; + } + poke_u32(o->d + at + 9, count); + poke_u32(o->d + at, (uint32_t)(o->len - at - 4)); +} + +static void do_close(struct sftp *s, struct buf *p, struct buf *o, uint32_t id) +{ + struct handle *h = get_handle(s, p); + int r = 0; + + if (!h) + { + status(o, id, FX_FAILURE, "bad handle"); + return; + } + if (h->fd >= 0) + r = close(h->fd); + if (h->dir) + closedir(h->dir); + h->used = 0; + if (r) + status_errno(o, id); + else + status(o, id, FX_OK, ""); +} + +/* REMOVE, RMDIR, MKDIR, RENAME, SETSTAT */ +static void do_path_op(int type, struct buf *p, struct buf *o, uint32_t id) +{ + char path[MAX_PATH_LEN], nat[MAX_PATH_LEN], path2[MAX_PATH_LEN], nat2[MAX_PATH_LEN]; + uint32_t at = 0, mt = 0, flags = 0; + int r = -1; + + get_cstr(p, path, sizeof(path)); + if (type == FXP_RENAME) + get_cstr(p, path2, sizeof(path2)); + if (type == FXP_MKDIR || type == FXP_SETSTAT) + flags = skip_attrs(p, &at, &mt); + if (p->err || !native(path, nat, sizeof(nat)) || + (type == FXP_RENAME && !native(path2, nat2, sizeof(nat2)))) + { + status(o, id, FX_NO_SUCH_FILE, "bad path"); + return; + } + errno = 0; + switch (type) + { + case FXP_REMOVE: r = unlink(nat); break; + case FXP_RMDIR: r = rmdir(nat); break; + case FXP_MKDIR: r = mkdir(nat, 0755); break; + case FXP_RENAME: r = rename(nat, nat2); break; + case FXP_SETSTAT: + r = 0; + if (flags & ATTR_ACMODTIME) + { + struct utimbuf u; + u.actime = (time_t)at; + u.modtime = (time_t)mt; + r = utime(nat, &u); + } + break; + } + if (r) + status_errno(o, id); + else + status(o, id, FX_OK, ""); +} + +static void do_fsetstat(struct sftp *s, struct buf *p, struct buf *o, uint32_t id) +{ + struct handle *h = get_handle(s, p); + uint32_t at = 0, mt = 0; + + skip_attrs(p, &at, &mt); + /* times are set by the client with SETSTAT after the close as well */ + status(o, id, h ? FX_OK : FX_FAILURE, h ? "" : "bad handle"); +} + +int sftp_input(struct sftp *s, struct buf *in, struct buf *o) +{ + int done = 0; + + while (in->len - in->pos >= 4) + { + uint32_t len = peek_u32(in->d + in->pos), id = 0; + struct buf p; + uint8_t type; + + if (len < 1 || len > 300000) + return -1; + if (in->len - in->pos < 4 + len) + break; + p.d = in->d + in->pos + 4; + p.len = len; + p.cap = 0; + p.pos = 0; + p.err = 0; + in->pos += 4 + len; + type = get_u8(&p); + if (type == FXP_INIT) + { + size_t at = o->len; + put_u32(o, 0); + put_u8(o, FXP_VERSION); + put_u32(o, 3); + poke_u32(o->d + at, (uint32_t)(o->len - at - 4)); + s->ready = 1; + done++; + continue; + } + id = get_u32(&p); + switch (type) + { + case FXP_OPEN: do_open(s, &p, o, id); break; + case FXP_CLOSE: do_close(s, &p, o, id); break; + case FXP_READ: do_read(s, &p, o, id); break; + case FXP_WRITE: do_write(s, &p, o, id); break; + case FXP_LSTAT: + case FXP_STAT: do_stat(s, &p, o, id); break; + case FXP_FSTAT: do_fstat(s, &p, o, id); break; + case FXP_SETSTAT: + case FXP_REMOVE: + case FXP_MKDIR: + case FXP_RMDIR: + case FXP_RENAME: do_path_op(type, &p, o, id); break; + case FXP_FSETSTAT: do_fsetstat(s, &p, o, id); break; + case FXP_OPENDIR: do_opendir(s, &p, o, id); break; + case FXP_READDIR: do_readdir(s, &p, o, id); break; + case FXP_REALPATH: do_realpath(&p, o, id); break; + default: status(o, id, FX_OP_UNSUPPORTED, "not supported"); break; + } + done++; + } + buf_consume(in, in->pos); + return done; +} diff --git a/net/ssh/sftp.h b/net/ssh/sftp.h new file mode 100644 index 00000000..d27240da --- /dev/null +++ b/net/ssh/sftp.h @@ -0,0 +1,12 @@ +#ifndef SFTP_H +#define SFTP_H +#include "buf.h" + +struct sftp; +struct sftp *sftp_new(void); +void sftp_free(struct sftp *s); +/* handle the complete requests in `in` (consumed), replies appended to + `out`; returns the number handled, -1 on a broken stream */ +int sftp_input(struct sftp *s, struct buf *in, struct buf *out); + +#endif diff --git a/net/ssh/sha256.c b/net/ssh/sha256.c new file mode 100644 index 00000000..e4bda691 --- /dev/null +++ b/net/ssh/sha256.c @@ -0,0 +1,102 @@ +/* SHA-256 (FIPS 180-4) */ +#include +#include "sha256.h" + +static const uint32_t K[64] = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +}; + +#define ROR(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) + +static void block(struct sha256 *c, const uint8_t *p) +{ + uint32_t w[64], a, b, cc, d, e, f, g, h, t1, t2; + int i; + + for (i = 0; i < 16; i++) + w[i] = (uint32_t)p[i * 4] << 24 | (uint32_t)p[i * 4 + 1] << 16 | (uint32_t)p[i * 4 + 2] << 8 | p[i * 4 + 3]; + for (; i < 64; i++) + w[i] = (ROR(w[i - 2], 17) ^ ROR(w[i - 2], 19) ^ (w[i - 2] >> 10)) + w[i - 7] + + (ROR(w[i - 15], 7) ^ ROR(w[i - 15], 18) ^ (w[i - 15] >> 3)) + w[i - 16]; + a = c->h[0]; b = c->h[1]; cc = c->h[2]; d = c->h[3]; + e = c->h[4]; f = c->h[5]; g = c->h[6]; h = c->h[7]; + for (i = 0; i < 64; i++) + { + t1 = h + (ROR(e, 6) ^ ROR(e, 11) ^ ROR(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]; + t2 = (ROR(a, 2) ^ ROR(a, 13) ^ ROR(a, 22)) + ((a & b) ^ (a & cc) ^ (b & cc)); + h = g; g = f; f = e; e = d + t1; + d = cc; cc = b; b = a; a = t1 + t2; + } + c->h[0] += a; c->h[1] += b; c->h[2] += cc; c->h[3] += d; + c->h[4] += e; c->h[5] += f; c->h[6] += g; c->h[7] += h; +} + +void sha256_init(struct sha256 *c) +{ + static const uint32_t iv[8] = { + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + }; + memcpy(c->h, iv, sizeof(iv)); + c->len = 0; + c->n = 0; +} + +void sha256_update(struct sha256 *c, const void *data, size_t len) +{ + const uint8_t *p = data; + + c->len += len; + while (len) + { + size_t k = 64 - c->n; + if (k > len) + k = len; + memcpy(c->buf + c->n, p, k); + c->n += k; + p += k; + len -= k; + if (c->n == 64) + { + block(c, c->buf); + c->n = 0; + } + } +} + +void sha256_final(struct sha256 *c, uint8_t out[32]) +{ + uint64_t bits = c->len * 8; + uint8_t pad = 0x80, z = 0, l[8]; + int i; + + sha256_update(c, &pad, 1); + while (c->n != 56) + sha256_update(c, &z, 1); + for (i = 0; i < 8; i++) + l[i] = (uint8_t)(bits >> (56 - i * 8)); + sha256_update(c, l, 8); + for (i = 0; i < 8; i++) + { + out[i * 4] = (uint8_t)(c->h[i] >> 24); + out[i * 4 + 1] = (uint8_t)(c->h[i] >> 16); + out[i * 4 + 2] = (uint8_t)(c->h[i] >> 8); + out[i * 4 + 3] = (uint8_t)c->h[i]; + } + memset(c, 0, sizeof(*c)); +} + +void sha256(const void *data, size_t len, uint8_t out[32]) +{ + struct sha256 c; + + sha256_init(&c); + sha256_update(&c, data, len); + sha256_final(&c, out); +} diff --git a/net/ssh/sha256.h b/net/ssh/sha256.h new file mode 100644 index 00000000..687283b2 --- /dev/null +++ b/net/ssh/sha256.h @@ -0,0 +1,18 @@ +#ifndef SHA256_H +#define SHA256_H +#include +#include + +struct sha256 { + uint32_t h[8]; + uint64_t len; + uint8_t buf[64]; + size_t n; +}; + +void sha256_init(struct sha256 *c); +void sha256_update(struct sha256 *c, const void *data, size_t len); +void sha256_final(struct sha256 *c, uint8_t out[32]); +void sha256(const void *data, size_t len, uint8_t out[32]); + +#endif diff --git a/net/ssh/ssh.c b/net/ssh/ssh.c new file mode 100644 index 00000000..088276ae --- /dev/null +++ b/net/ssh/ssh.c @@ -0,0 +1,695 @@ +/* SSH transport layer: packets, encryption, key exchange (see ssh.h) */ +#include +#include +#include +#include "crypto/monocypher.h" +#include "crypto/monocypher-ed25519.h" +#include "sha256.h" +#include "rng.h" +#include "ssh.h" + +#define VERSION "SSH-2.0-modernDOS_0.1" + +#define KEX_ALGS_S "curve25519-sha256,curve25519-sha256@libssh.org,kex-strict-s-v00@openssh.com" +#define KEX_ALGS_C "curve25519-sha256,curve25519-sha256@libssh.org,kex-strict-c-v00@openssh.com" +#define HOSTKEY_ALG "ssh-ed25519" +#define CIPHER "chacha20-poly1305@openssh.com" +#define MAC "hmac-sha2-256" /* unused with an AEAD cipher */ +#define COMP "none" + +static void fail(struct ssh *s, uint32_t code, const char *fmt, ...) +{ + va_list ap; + + if (s->dead) + return; + va_start(ap, fmt); + vsnprintf(s->why, sizeof(s->why), fmt, ap); + va_end(ap); + ssh_disconnect(s, code, s->why); +} + +void ssh_start(struct ssh *s, int fd, int server) +{ + const uint8_t *hsk = s->host_sk, *hpk = s->host_pk; + int (*check)(struct ssh *, const uint8_t *) = s->check_hostkey; + void *user = s->user; + + memset(s, 0, sizeof(*s)); + s->host_sk = hsk; + s->host_pk = hpk; + s->check_hostkey = check; + s->user = user; + s->fd = fd; + s->server = server; + buf_init(&s->in); + buf_init(&s->out); + buf_init(&s->deferred); + buf_init(&s->i_c); + buf_init(&s->i_s); + strcpy(server ? s->vs : s->vc, VERSION); + put_bytes(&s->out, VERSION "\r\n", strlen(VERSION) + 2); +} + +void ssh_free(struct ssh *s) +{ + buf_free(&s->in); + buf_free(&s->out); + buf_free(&s->deferred); + buf_free(&s->i_c); + buf_free(&s->i_s); + crypto_wipe(&s->rx, sizeof(s->rx)); + crypto_wipe(&s->tx, sizeof(s->tx)); + crypto_wipe(&s->nrx, sizeof(s->nrx)); + crypto_wipe(&s->ntx, sizeof(s->ntx)); + crypto_wipe(s->x_sk, sizeof(s->x_sk)); +} + +int ssh_ready(const struct ssh *s) +{ + return !s->dead && s->kex_done && !s->sent_kexinit && !s->got_kexinit; +} + +size_t ssh_pending(const struct ssh *s) +{ + return s->out.len + s->deferred.len; +} + +int ssh_io(struct ssh *s) +{ + uint8_t tmp[4096]; + int n, moved = 0; + + if (s->dead && !s->out.len) + return 0; + while (s->out.len) + { + n = net_send(s->fd, s->out.d, (int)s->out.len); + if (n < 0) + { + s->dead = 1; + if (!s->why[0]) + strcpy(s->why, "connection lost"); + buf_reset(&s->out); + return 1; + } + if (n == 0) + break; + buf_consume(&s->out, (size_t)n); + moved = 1; + } + while (!s->dead && s->in.len < 2 * SSH_MAX_PACKET) + { + n = net_recv(s->fd, tmp, sizeof(tmp)); + if (n < 0) + { + s->dead = 1; + if (!s->why[0]) + strcpy(s->why, "connection closed by peer"); + return 1; + } + if (n == 0) + break; + put_bytes(&s->in, tmp, (size_t)n); + rng_event((uint32_t)n); + moved = 1; + } + return moved; +} + +/* ---------------------------------------------------------------- */ +/* packets */ + +static void nonce_of(uint32_t seq, uint8_t n[8]) +{ + memset(n, 0, 4); + poke_u32(n + 4, seq); +} + +static void send_now(struct ssh *s, const uint8_t *payload, size_t plen) +{ + size_t start = s->out.len, len; + uint8_t pad[32], *pkt; + int padlen; + + if (s->tx_on) + padlen = 8 - (int)((1 + plen) % 8); + else + padlen = 8 - (int)((5 + plen) % 8); + if (padlen < 4) + padlen += 8; + rng_bytes(pad, (size_t)padlen); + len = 1 + plen + (size_t)padlen; + put_u32(&s->out, (uint32_t)len); + put_u8(&s->out, (uint8_t)padlen); + put_bytes(&s->out, payload, plen); + put_bytes(&s->out, pad, (size_t)padlen); + if (s->tx_on) + { + uint8_t nonce[8], polykey[32], tag[16]; + buf_reserve(&s->out, 16); + pkt = s->out.d + start; + nonce_of(s->seq_out, nonce); + crypto_chacha20_djb(pkt, pkt, 4, s->tx.hdr, nonce, 0); + crypto_chacha20_djb(pkt + 4, pkt + 4, len, s->tx.main, nonce, 1); + memset(polykey, 0, sizeof(polykey)); + crypto_chacha20_djb(polykey, polykey, sizeof(polykey), s->tx.main, nonce, 0); + crypto_poly1305(tag, pkt, 4 + len, polykey); + put_bytes(&s->out, tag, 16); + crypto_wipe(polykey, sizeof(polykey)); + } + s->seq_out++; +} + +static int kex_msg(uint8_t t) +{ + return (t >= 1 && t <= 4) || (t >= 20 && t <= 49); +} + +void ssh_send(struct ssh *s, struct buf *payload) +{ + if (s->dead || !payload->len) + { + buf_reset(payload); + return; + } + /* during a key exchange only transport messages go out */ + if ((s->sent_kexinit || s->got_kexinit || !s->kex_done) && !kex_msg(payload->d[0])) + { + put_u32(&s->deferred, (uint32_t)payload->len); + put_bytes(&s->deferred, payload->d, payload->len); + } + else + send_now(s, payload->d, payload->len); + buf_reset(payload); +} + +void ssh_disconnect(struct ssh *s, uint32_t code, const char *msg) +{ + struct buf b; + + if (s->dead) + return; + buf_init(&b); + put_u8(&b, SSH_MSG_DISCONNECT); + put_u32(&b, code); + put_cstr(&b, msg); + put_cstr(&b, ""); + if (s->version_done) + send_now(s, b.d, b.len); + buf_free(&b); + if (!s->why[0]) + snprintf(s->why, sizeof(s->why), "%s", msg); + s->dead = 1; +} + +/* one packet from s->in into `payload` (type byte first): 1 yes, 0 not + complete yet, -1 broken */ +static int read_packet(struct ssh *s, struct buf *payload) +{ + uint8_t lenbytes[4], nonce[8]; + uint32_t len, total, padlen; + + if (s->in.len < 4) + return 0; + nonce_of(s->seq_in, nonce); + memcpy(lenbytes, s->in.d, 4); + if (s->rx_on) + crypto_chacha20_djb(lenbytes, lenbytes, 4, s->rx.hdr, nonce, 0); + len = peek_u32(lenbytes); + if (len < 8 || len > SSH_MAX_PACKET || (s->rx_on ? len : len + 4) % 8) + { + fail(s, SSH_DISCONNECT_PROTOCOL_ERROR, "bad packet length %lu", (unsigned long)len); + return -1; + } + total = 4 + len + (s->rx_on ? 16 : 0); + if (s->in.len < total) + return 0; + if (s->rx_on) + { + uint8_t polykey[32], tag[16]; + memset(polykey, 0, sizeof(polykey)); + crypto_chacha20_djb(polykey, polykey, sizeof(polykey), s->rx.main, nonce, 0); + crypto_poly1305(tag, s->in.d, 4 + len, polykey); + crypto_wipe(polykey, sizeof(polykey)); + if (crypto_verify16(tag, s->in.d + 4 + len)) + { + fail(s, SSH_DISCONNECT_MAC_ERROR, "packet authentication failed"); + return -1; + } + crypto_chacha20_djb(s->in.d + 4, s->in.d + 4, len, s->rx.main, nonce, 1); + } + padlen = s->in.d[4]; + if (padlen < 4 || padlen + 1 >= len) + { + fail(s, SSH_DISCONNECT_PROTOCOL_ERROR, "bad padding"); + return -1; + } + buf_reset(payload); + put_bytes(payload, s->in.d + 5, len - padlen - 1); + buf_consume(&s->in, total); + s->seq_in++; + return 1; +} + +/* ---------------------------------------------------------------- */ +/* key exchange */ + +static void send_kexinit(struct ssh *s) +{ + struct buf b, *mine = s->server ? &s->i_s : &s->i_c; + uint8_t cookie[16]; + + buf_init(&b); + put_u8(&b, SSH_MSG_KEXINIT); + rng_bytes(cookie, sizeof(cookie)); + put_bytes(&b, cookie, sizeof(cookie)); + /* the strict-KEX marker only in the first KEXINIT */ + put_cstr(&b, s->kex_done ? "curve25519-sha256,curve25519-sha256@libssh.org" + : s->server ? KEX_ALGS_S : KEX_ALGS_C); + put_cstr(&b, HOSTKEY_ALG); + put_cstr(&b, CIPHER); + put_cstr(&b, CIPHER); + put_cstr(&b, MAC); + put_cstr(&b, MAC); + put_cstr(&b, COMP); + put_cstr(&b, COMP); + put_cstr(&b, ""); + put_cstr(&b, ""); + put_u8(&b, 0); /* first_kex_packet_follows */ + put_u32(&b, 0); + buf_reset(mine); + put_bytes(mine, b.d, b.len); + send_now(s, b.d, b.len); + buf_free(&b); + s->sent_kexinit = 1; +} + +/* the peer's KEXINIT: check that our algorithms are acceptable */ +static int got_kexinit(struct ssh *s, struct buf *p) +{ + const uint8_t *l[10]; + uint32_t n[10]; + int i, follows; + struct buf *theirs = s->server ? &s->i_c : &s->i_s; + + buf_reset(theirs); + put_bytes(theirs, p->d, p->len); + p->pos = 1; + get_bytes(p, 16); + for (i = 0; i < 10; i++) + l[i] = get_str(p, &n[i]); + follows = get_u8(p); + if (p->err) + { + fail(s, SSH_DISCONNECT_PROTOCOL_ERROR, "bad KEXINIT"); + return 0; + } + if (!namelist_has(l[0], n[0], "curve25519-sha256") && + !namelist_has(l[0], n[0], "curve25519-sha256@libssh.org")) + { + fail(s, SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "no common key exchange (need curve25519-sha256)"); + return 0; + } + if (!namelist_has(l[1], n[1], HOSTKEY_ALG)) + { + fail(s, SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "no common host key type (need ssh-ed25519)"); + return 0; + } + if (!namelist_has(l[2], n[2], CIPHER) || !namelist_has(l[3], n[3], CIPHER)) + { + fail(s, SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "no common cipher (need " CIPHER ")"); + return 0; + } + if (!namelist_has(l[6], n[6], COMP) || !namelist_has(l[7], n[7], COMP)) + { + fail(s, SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "no common compression"); + return 0; + } + if (!s->kex_done) + s->strict = namelist_has(l[0], n[0], s->server ? "kex-strict-c-v00@openssh.com" + : "kex-strict-s-v00@openssh.com"); + /* a guessed first kex packet is only right if both lists start alike */ + if (follows) + { + const char *first = "curve25519-sha256,"; + s->ignore_next = n[0] < strlen(first) || memcmp(l[0], first, strlen(first)) || + n[1] < strlen(HOSTKEY_ALG) || memcmp(l[1], HOSTKEY_ALG, strlen(HOSTKEY_ALG)); + } + s->got_kexinit = 1; + return 1; +} + +/* exchange hash and the four keys */ +static void kex_finish(struct ssh *s, const uint8_t *ks, size_t ks_len, const uint8_t qc[32], + const uint8_t qs[32], const uint8_t k[32], uint8_t h[32]) +{ + struct buf b, kmp; + struct sha256 c; + uint8_t k1[32], k2[32]; + int i; + const char letters[4] = { 'C', 'D', 0, 0 }; + + buf_init(&b); + buf_init(&kmp); + put_cstr(&b, s->vc); + put_cstr(&b, s->vs); + put_str(&b, s->i_c.d, s->i_c.len); + put_str(&b, s->i_s.d, s->i_s.len); + put_str(&b, ks, ks_len); + put_str(&b, qc, 32); + put_str(&b, qs, 32); + put_mpint(&kmp, k, 32); + put_bytes(&b, kmp.d, kmp.len); + sha256(b.d, b.len, h); + if (!s->have_sid) + { + memcpy(s->sid, h, 32); + s->have_sid = 1; + } + /* C: client to server key, D: server to client (64 bytes each) */ + for (i = 0; i < 2; i++) + { + struct ssh_keys *dst = (i == 0) == s->server ? &s->nrx : &s->ntx; + sha256_init(&c); + sha256_update(&c, kmp.d, kmp.len); + sha256_update(&c, h, 32); + sha256_update(&c, &letters[i], 1); + sha256_update(&c, s->sid, 32); + sha256_final(&c, k1); + sha256_init(&c); + sha256_update(&c, kmp.d, kmp.len); + sha256_update(&c, h, 32); + sha256_update(&c, k1, 32); + sha256_final(&c, k2); + memcpy(dst->main, k1, 32); /* K_2: first half of the 64 bytes */ + memcpy(dst->hdr, k2, 32); /* K_1: second half */ + } + crypto_wipe(k1, sizeof(k1)); + crypto_wipe(k2, sizeof(k2)); + buf_free(&kmp); + buf_free(&b); +} + +static void send_newkeys(struct ssh *s) +{ + uint8_t m = SSH_MSG_NEWKEYS; + + send_now(s, &m, 1); + s->tx = s->ntx; + s->tx_on = 1; + crypto_wipe(&s->ntx, sizeof(s->ntx)); + if (s->strict) + s->seq_out = 0; + s->sent_newkeys = 1; +} + +static int all_zero(const uint8_t *p, int n) +{ + uint8_t acc = 0; + while (n--) + acc |= *p++; + return !acc; +} + +/* server: the client's ephemeral key */ +static void ecdh_init(struct ssh *s, struct buf *p) +{ + uint32_t n; + const uint8_t *qc = get_str(p, &n); + uint8_t k[32], h[32], sig[64]; + struct buf ks, r, sigb; + + if (!qc || n != 32) + { + fail(s, SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "bad ECDH_INIT"); + return; + } + rng_bytes(s->x_sk, 32); + crypto_x25519_public_key(s->x_pk, s->x_sk); + crypto_x25519(k, s->x_sk, qc); + crypto_wipe(s->x_sk, 32); + if (all_zero(k, 32)) + { + fail(s, SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "bad client key"); + return; + } + buf_init(&ks); + buf_init(&r); + buf_init(&sigb); + ssh_ed25519_blob(&ks, s->host_pk); + kex_finish(s, ks.d, ks.len, qc, s->x_pk, k, h); + crypto_ed25519_sign(sig, s->host_sk, h, 32); + put_cstr(&sigb, HOSTKEY_ALG); + put_str(&sigb, sig, 64); + put_u8(&r, SSH_MSG_KEX_ECDH_REPLY); + put_str(&r, ks.d, ks.len); + put_str(&r, s->x_pk, 32); + put_str(&r, sigb.d, sigb.len); + send_now(s, r.d, r.len); + send_newkeys(s); + crypto_wipe(k, sizeof(k)); + buf_free(&ks); + buf_free(&r); + buf_free(&sigb); +} + +static void send_ecdh_init(struct ssh *s) +{ + struct buf b; + + rng_bytes(s->x_sk, 32); + crypto_x25519_public_key(s->x_pk, s->x_sk); + buf_init(&b); + put_u8(&b, SSH_MSG_KEX_ECDH_INIT); + put_str(&b, s->x_pk, 32); + send_now(s, b.d, b.len); + buf_free(&b); +} + +/* client: the server's reply */ +static void ecdh_reply(struct ssh *s, struct buf *p) +{ + uint32_t ksn, qsn, sn, an, pkn, sgn; + const uint8_t *ks = get_str(p, &ksn), *qs = get_str(p, &qsn), *sig = get_str(p, &sn); + const uint8_t *alg, *pk, *sg; + struct buf kb, sb; + uint8_t k[32], h[32]; + + if (p->err || qsn != 32) + { + fail(s, SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "bad ECDH_REPLY"); + return; + } + kb.d = (uint8_t *)ks; kb.len = ksn; kb.pos = 0; kb.err = 0; kb.cap = 0; + alg = get_str(&kb, &an); + pk = get_str(&kb, &pkn); + sb.d = (uint8_t *)sig; sb.len = sn; sb.pos = 0; sb.err = 0; sb.cap = 0; + get_str(&sb, &an); + sg = get_str(&sb, &sgn); + if (kb.err || sb.err || an != strlen(HOSTKEY_ALG) || memcmp(alg, HOSTKEY_ALG, an) || + pkn != 32 || sgn != 64) + { + fail(s, SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "unsupported host key"); + return; + } + crypto_x25519(k, s->x_sk, qs); + crypto_wipe(s->x_sk, 32); + if (all_zero(k, 32)) + { + fail(s, SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "bad server key"); + return; + } + kex_finish(s, ks, ksn, s->x_pk, qs, k, h); + crypto_wipe(k, sizeof(k)); + if (crypto_ed25519_check(sg, pk, h, 32)) + { + fail(s, SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "host key signature is wrong"); + return; + } + if (s->kex_done && memcmp(pk, s->peer_hostkey, 32)) + { + fail(s, SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE, "host key changed during re-key"); + return; + } + memcpy(s->peer_hostkey, pk, 32); + if (!s->kex_done && s->check_hostkey && !s->check_hostkey(s, pk)) + { + fail(s, SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE, "host key not accepted"); + return; + } + send_newkeys(s); +} + +static void got_newkeys(struct ssh *s) +{ + size_t i = 0; + + s->rx = s->nrx; + s->rx_on = 1; + crypto_wipe(&s->nrx, sizeof(s->nrx)); + if (s->strict) + s->seq_in = 0; + s->kex_done = 1; + s->sent_kexinit = s->got_kexinit = s->sent_newkeys = 0; + /* what the caller sent meanwhile */ + while (i + 4 <= s->deferred.len) + { + uint32_t n = peek_u32(s->deferred.d + i); + send_now(s, s->deferred.d + i + 4, n); + i += 4 + n; + } + buf_reset(&s->deferred); +} + +/* identification line of the peer */ +static int read_version(struct ssh *s) +{ + for (;;) + { + uint8_t *nl = memchr(s->in.d, '\n', s->in.len); + size_t n; + char *dst = s->server ? s->vc : s->vs; + if (!nl) + { + if (s->in.len > 255) + { + fail(s, SSH_DISCONNECT_PROTOCOL_ERROR, "no SSH identification"); + return -1; + } + return 0; + } + n = (size_t)(nl - s->in.d); + if (n && nl[-1] == '\r') + n--; + if (n >= 8 && !memcmp(s->in.d, "SSH-", 4)) + { + if (memcmp(s->in.d, "SSH-2.0-", 8) && memcmp(s->in.d, "SSH-1.99-", 9)) + { + fail(s, SSH_DISCONNECT_PROTOCOL_ERROR, "SSH protocol 2 only"); + return -1; + } + if (n > 250) + n = 250; + memcpy(dst, s->in.d, n); + dst[n] = 0; + buf_consume(&s->in, (size_t)(nl - s->in.d) + 1); + s->version_done = 1; + return 1; + } + if (s->server) /* clients send nothing before it */ + { + fail(s, SSH_DISCONNECT_PROTOCOL_ERROR, "no SSH identification"); + return -1; + } + buf_consume(&s->in, (size_t)(nl - s->in.d) + 1); /* server banner line */ + } +} + +int ssh_packet(struct ssh *s, struct buf *payload) +{ + for (;;) + { + int r; + uint8_t t; + + if (s->dead) + return -1; + if (!s->version_done) + { + r = read_version(s); + if (r <= 0) + return r; + if (!s->sent_kexinit) + send_kexinit(s); + } + r = read_packet(s, payload); + if (r <= 0) + return r; + t = payload->d[0]; + payload->pos = 1; + if (s->ignore_next && t >= 30 && t <= 49) + { + s->ignore_next = 0; + continue; + } + /* strict KEX: nothing else during the first key exchange */ + if (s->strict && !s->kex_done && t != SSH_MSG_KEXINIT && t != SSH_MSG_NEWKEYS && + t != SSH_MSG_KEX_ECDH_INIT && t != SSH_MSG_KEX_ECDH_REPLY && t != SSH_MSG_DISCONNECT) + { + fail(s, SSH_DISCONNECT_PROTOCOL_ERROR, "unexpected message %u during key exchange", t); + return -1; + } + switch (t) + { + case SSH_MSG_DISCONNECT: + { + char msg[120]; + get_u32(payload); + get_cstr(payload, msg, sizeof(msg)); + snprintf(s->why, sizeof(s->why), "peer disconnected: %s", msg); + s->dead = 1; + return -1; + } + case SSH_MSG_IGNORE: + case SSH_MSG_DEBUG: + case SSH_MSG_UNIMPLEMENTED: + continue; + case SSH_MSG_KEXINIT: + if (s->got_kexinit) + { + fail(s, SSH_DISCONNECT_PROTOCOL_ERROR, "second KEXINIT"); + return -1; + } + if (!got_kexinit(s, payload)) + return -1; + if (!s->sent_kexinit) + send_kexinit(s); + if (!s->server) + send_ecdh_init(s); + continue; + case SSH_MSG_KEX_ECDH_INIT: + if (!s->server || !s->got_kexinit || s->sent_newkeys) + break; + ecdh_init(s, payload); + continue; + case SSH_MSG_KEX_ECDH_REPLY: + if (s->server || !s->got_kexinit || s->sent_newkeys) + break; + ecdh_reply(s, payload); + continue; + case SSH_MSG_NEWKEYS: + if (!s->sent_newkeys) + break; + got_newkeys(s); + continue; + default: + if (!s->kex_done || (t >= 20 && t <= 49)) + break; /* not allowed before / during kex */ + return 1; + } + fail(s, SSH_DISCONNECT_PROTOCOL_ERROR, "unexpected message %u", t); + return -1; + } +} + +/* ---------------------------------------------------------------- */ + +void ssh_ed25519_blob(struct buf *b, const uint8_t pk[32]) +{ + put_cstr(b, HOSTKEY_ALG); + put_str(b, pk, 32); +} + +void ssh_fingerprint(const uint8_t pk[32], char out[64]) +{ + struct buf b; + uint8_t h[32]; + + buf_init(&b); + ssh_ed25519_blob(&b, pk); + sha256(b.d, b.len, h); + buf_free(&b); + strcpy(out, "SHA256:"); + b64_encode(h, 32, out + 7, 0); +} diff --git a/net/ssh/ssh.h b/net/ssh/ssh.h new file mode 100644 index 00000000..339e4a42 --- /dev/null +++ b/net/ssh/ssh.h @@ -0,0 +1,98 @@ +/* SSH transport layer (RFC 4253) for the modernDOS SSH server and client + * + * One fixed algorithm set, chosen for small code and good security: + * key exchange curve25519-sha256 (RFC 8731), with OpenSSH's "strict KEX" + * (kex-strict-*-v00@openssh.com, against the Terrapin attack) + * host key ssh-ed25519 + * cipher chacha20-poly1305@openssh.com (no separate MAC) + * compression none + */ +#ifndef SSH_H +#define SSH_H +#include +#include "buf.h" + +enum { + SSH_MSG_DISCONNECT = 1, SSH_MSG_IGNORE = 2, SSH_MSG_UNIMPLEMENTED = 3, + SSH_MSG_DEBUG = 4, SSH_MSG_SERVICE_REQUEST = 5, SSH_MSG_SERVICE_ACCEPT = 6, + SSH_MSG_KEXINIT = 20, SSH_MSG_NEWKEYS = 21, + SSH_MSG_KEX_ECDH_INIT = 30, SSH_MSG_KEX_ECDH_REPLY = 31, + SSH_MSG_USERAUTH_REQUEST = 50, SSH_MSG_USERAUTH_FAILURE = 51, + SSH_MSG_USERAUTH_SUCCESS = 52, SSH_MSG_USERAUTH_BANNER = 53, + SSH_MSG_USERAUTH_PK_OK = 60, + SSH_MSG_GLOBAL_REQUEST = 80, SSH_MSG_REQUEST_SUCCESS = 81, SSH_MSG_REQUEST_FAILURE = 82, + SSH_MSG_CHANNEL_OPEN = 90, SSH_MSG_CHANNEL_OPEN_CONFIRMATION = 91, + SSH_MSG_CHANNEL_OPEN_FAILURE = 92, SSH_MSG_CHANNEL_WINDOW_ADJUST = 93, + SSH_MSG_CHANNEL_DATA = 94, SSH_MSG_CHANNEL_EXTENDED_DATA = 95, + SSH_MSG_CHANNEL_EOF = 96, SSH_MSG_CHANNEL_CLOSE = 97, + SSH_MSG_CHANNEL_REQUEST = 98, SSH_MSG_CHANNEL_SUCCESS = 99, SSH_MSG_CHANNEL_FAILURE = 100 +}; + +enum { + SSH_DISCONNECT_PROTOCOL_ERROR = 2, SSH_DISCONNECT_KEY_EXCHANGE_FAILED = 3, + SSH_DISCONNECT_MAC_ERROR = 5, SSH_DISCONNECT_SERVICE_NOT_AVAILABLE = 7, + SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE = 9, SSH_DISCONNECT_BY_APPLICATION = 11, + SSH_DISCONNECT_TOO_MANY_CONNECTIONS = 12, SSH_DISCONNECT_AUTH_CANCELLED = 13, + SSH_DISCONNECT_NO_MORE_AUTH_METHODS = 14 +}; + +#define SSH_MAX_PACKET 35000 /* RFC 4253: at least 35000 */ + +struct ssh_keys { + uint8_t main[32]; /* payload (K_2) */ + uint8_t hdr[32]; /* length field (K_1) */ +}; + +struct ssh { + int fd; + int server; + char vc[256], vs[256]; /* identification strings, no CR LF */ + int version_done; + struct buf in, out; /* raw bytes from / to the peer */ + struct buf deferred; /* payloads held back during a re-kex */ + struct buf i_c, i_s; /* the two KEXINIT payloads */ + uint32_t seq_in, seq_out; + int rx_on, tx_on; + struct ssh_keys rx, tx, nrx, ntx; /* current and next keys */ + uint8_t sid[32]; /* session identifier */ + int have_sid; + int sent_kexinit, got_kexinit, sent_newkeys; + int kex_done; /* the first key exchange finished */ + int strict; /* strict KEX negotiated */ + int ignore_next; /* wrong first_kex_packet_follows guess */ + uint8_t x_sk[32], x_pk[32]; /* our ephemeral X25519 key */ + const uint8_t *host_sk; /* server: ed25519 secret key (64) */ + const uint8_t *host_pk; /* server: ed25519 public key (32) */ + /* client: accept the server's host key? (ed25519 public key) */ + int (*check_hostkey)(struct ssh *s, const uint8_t pk[32]); + uint8_t peer_hostkey[32]; + void *user; /* for the caller */ + int dead; /* connection unusable */ + char why[160]; /* reason, for the log */ +}; + +/* start a connection on a connected, non-blocking socket */ +void ssh_start(struct ssh *s, int fd, int server); +void ssh_free(struct ssh *s); +/* move bytes between the socket and the buffers; 0 if nothing moved */ +int ssh_io(struct ssh *s); +/* next payload for the caller (kex and transport messages are handled + here): 1 = `payload` holds one (type first), 0 = none yet, -1 = dead */ +int ssh_packet(struct ssh *s, struct buf *payload); +/* send a payload (first byte = message type); consumes it */ +void ssh_send(struct ssh *s, struct buf *payload); +void ssh_disconnect(struct ssh *s, uint32_t code, const char *msg); +/* keys are up and no key exchange runs: channel traffic may be sent */ +int ssh_ready(const struct ssh *s); +/* bytes waiting to go out (for flow control) */ +size_t ssh_pending(const struct ssh *s); + +/* ed25519 public key blob and its OpenSSH fingerprint "SHA256:..." */ +void ssh_ed25519_blob(struct buf *b, const uint8_t pk[32]); +void ssh_fingerprint(const uint8_t pk[32], char out[64]); + +/* platform: non-blocking socket I/O (net_*.c) */ +int net_recv(int fd, void *p, int n); /* >0 bytes, 0 nothing yet, -1 closed */ +int net_send(int fd, const void *p, int n); + +#endif diff --git a/net/ssh/sshc.c b/net/ssh/sshc.c new file mode 100644 index 00000000..0a352d76 --- /dev/null +++ b/net/ssh/sshc.c @@ -0,0 +1,732 @@ +/* + * SSH - SSH client for modernDOS + * + * SSH [options] [user@]host [command] + * /P port port (default 22) + * /I keyfile private key (default ID.KEY next to SSH.EXE) + * /L user user name (default: the one before @, else "dos") + * /Y accept an unknown host key without asking (saved) + * /T a terminal even when a command is given + * SSH /KEYGEN make ID.KEY (ed25519) and print the public key line + * to add to the server's ~/.ssh/authorized_keys + * + * Without a command: an interactive session in an xterm-like terminal on + * the DOS screen (type ~. at the start of a line to disconnect). With a + * command: its output goes to standard output; the exit code is the + * command's. + * Known host keys are kept in KNOWNHST.TXT next to SSH.EXE; a changed host + * key is refused. ID.KEY is an OpenSSH private key file without + * passphrase, so an existing ed25519 key can be copied from another + * machine too. + */ +#include +#include +#include +#include +#include +#include +#include "crypto/monocypher.h" +#include "crypto/monocypher-ed25519.h" +#include "buf.h" +#include "rng.h" +#include "ssh.h" +#include "plat.h" +#include "term.h" +#include "keyfile.h" + +#define WINDOW (1024 * 1024) +#define MAX_PKT 32768 + +static char dir[96], host[128], user[64], cmd[512], keypath[128]; +static int port = 22, accept_new, want_tty, have_key; +static uint8_t key_sk[64], key_pk[32]; +static struct ssh s; +static struct term term; +static struct buf replies; + +enum { A_SERVICE, A_KEY, A_NONE, A_PASSWORD, A_KBDINT, A_DONE }; +static int auth_state, pw_tries, service_sent; +static uint32_t peer_chan, peer_window, peer_max; +static int chan_open, chan_closed, exit_code = 255, got_exit; + +#ifdef __DJGPP__ +/* remote commands are not for local wildcard expansion */ +char **__crt0_glob_function(char *arg) +{ + (void)arg; + return 0; +} +#endif + +static void path_of(char *out, size_t n, const char *file) +{ + snprintf(out, n, "%s%s", dir, file); +} + +static void say(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +static void say(const char *fmt, ...) +{ + char b[400]; + va_list ap; + + va_start(ap, fmt); + vsnprintf(b, sizeof(b), fmt, ap); + va_end(ap); + fputs(b, stderr); +} + +static void read_line(const char *prompt, char *out, size_t n, int echo) +{ + size_t len = 0; + int c; + + fputs(prompt, stderr); + fflush(stderr); + for (;;) + { + while ((c = plat_key()) < 0) + { + ssh_io(&s); /* keep the connection alive */ + plat_idle(); + } + if (c == '\r' || c == '\n') + break; + if ((c == 8 || c == 127) && len) + { + len--; + if (echo) + fputs("\b \b", stderr); + } + else if (c >= 32 && len + 1 < n) + { + out[len++] = (char)c; + if (echo) + fputc(c, stderr); + } + } + out[len] = 0; + fputs("\n", stderr); +} + +/* ---------------------------------------------------------------- */ +/* known hosts: "host port ssh-ed25519 BASE64" lines */ + +static int check_hostkey(struct ssh *ss, const uint8_t pk[32]) +{ + char path[128], line[512], fp[64], want[128], answer[8]; + struct buf b; + FILE *f; + int found = 0, same = 0; + + (void)ss; + buf_init(&b); + ssh_ed25519_blob(&b, pk); + b64_encode(b.d, b.len, want, 1); + buf_free(&b); + ssh_fingerprint(pk, fp); + path_of(path, sizeof(path), "KNOWNHST.TXT"); + f = fopen(path, "r"); + if (f) + { + while (fgets(line, sizeof(line), f)) + { + char h[128], alg[32], key[128]; + int p; + if (sscanf(line, "%127s %d %31s %127s", h, &p, alg, key) != 4) + continue; + if (strcasecmp(h, host) || p != port) + continue; + found = 1; + if (!strcmp(alg, "ssh-ed25519") && !strcmp(key, want)) + same = 1; + } + fclose(f); + } + if (same) + return 1; + if (found) + { + say("\n@@@ WARNING: THE HOST KEY OF %s HAS CHANGED! @@@\n" + "Someone could be intercepting the connection, or the host was\n" + "reinstalled. New key: %s\n" + "If that is expected, remove the line for %s from %s.\n", host, fp, host, path); + return 0; + } + say("The host key of %s (port %d) is not known yet:\n ED25519 %s\n", host, port, fp); + if (!accept_new) + { + read_line("Connect and remember it (yes/no)? ", answer, sizeof(answer), 1); + if (strcasecmp(answer, "yes") && strcasecmp(answer, "y")) + return 0; + } + f = fopen(path, "a"); + if (f) + { + fprintf(f, "%s %d ssh-ed25519 %s\n", host, port, want); + fclose(f); + say("Added to %s.\n", path); + } + return 1; +} + +/* ---------------------------------------------------------------- */ +/* authentication */ + +static void send_auth_key(void) +{ + struct buf b, data, sig; + uint8_t sg[64]; + + buf_init(&b); + buf_init(&data); + buf_init(&sig); + put_u8(&b, SSH_MSG_USERAUTH_REQUEST); + put_cstr(&b, user); + put_cstr(&b, "ssh-connection"); + put_cstr(&b, "publickey"); + put_u8(&b, 1); + put_cstr(&b, "ssh-ed25519"); + { + struct buf blob; + buf_init(&blob); + ssh_ed25519_blob(&blob, key_pk); + put_str(&b, blob.d, blob.len); + put_str(&data, s.sid, 32); + put_bytes(&data, b.d, b.len); /* the request so far */ + buf_free(&blob); + } + crypto_ed25519_sign(sg, key_sk, data.d, data.len); + put_cstr(&sig, "ssh-ed25519"); + put_str(&sig, sg, 64); + put_str(&b, sig.d, sig.len); + ssh_send(&s, &b); + buf_free(&b); + buf_free(&data); + buf_free(&sig); +} + +static void send_auth(const char *method) +{ + struct buf b; + + buf_init(&b); + put_u8(&b, SSH_MSG_USERAUTH_REQUEST); + put_cstr(&b, user); + put_cstr(&b, "ssh-connection"); + put_cstr(&b, method); + if (!strcmp(method, "password")) + { + char pw[128]; + char prompt[300]; + snprintf(prompt, sizeof(prompt), "%s@%s's password: ", user, host); + read_line(prompt, pw, sizeof(pw), 0); + put_u8(&b, 0); + put_cstr(&b, pw); + crypto_wipe(pw, sizeof(pw)); + } + else if (!strcmp(method, "keyboard-interactive")) + { + put_cstr(&b, ""); /* language */ + put_cstr(&b, ""); /* submethods */ + } + ssh_send(&s, &b); + buf_free(&b); +} + +/* the server's list of methods that can continue: pick the next one */ +static void auth_next(struct buf *p) +{ + uint32_t n; + const uint8_t *list = get_str(p, &n); + + if (auth_state == A_KEY) + say("The server did not accept the key %s.\n", keypath); + if (list && namelist_has(list, n, "password") && pw_tries < 3) + { + pw_tries++; + auth_state = A_PASSWORD; + send_auth("password"); + } + else if (list && namelist_has(list, n, "keyboard-interactive") && pw_tries < 3) + { + pw_tries++; + auth_state = A_KBDINT; + send_auth("keyboard-interactive"); + } + else + { + say("Permission denied (%.*s).\n", (int)n, list ? (const char *)list : ""); + ssh_disconnect(&s, SSH_DISCONNECT_NO_MORE_AUTH_METHODS, "no more methods"); + } +} + +/* keyboard-interactive: the server's questions */ +static void kbd_info(struct buf *p) +{ + char name[128], instr[256], prompt[256], ans[128]; + uint32_t i, num; + struct buf b; + + get_cstr(p, name, sizeof(name)); + get_cstr(p, instr, sizeof(instr)); + get_str(p, &i); /* language */ + num = get_u32(p); + if (name[0]) + say("%s\n", name); + if (instr[0]) + say("%s\n", instr); + buf_init(&b); + put_u8(&b, 61); /* SSH_MSG_USERAUTH_INFO_RESPONSE */ + put_u32(&b, num); + for (i = 0; i < num && i < 8; i++) + { + int echo; + get_cstr(p, prompt, sizeof(prompt)); + echo = get_u8(p); + read_line(prompt, ans, sizeof(ans), echo); + put_cstr(&b, ans); + crypto_wipe(ans, sizeof(ans)); + } + ssh_send(&s, &b); + buf_free(&b); +} + +/* ---------------------------------------------------------------- */ +/* the session channel */ + +static void open_session(void) +{ + struct buf b; + + buf_init(&b); + put_u8(&b, SSH_MSG_CHANNEL_OPEN); + put_cstr(&b, "session"); + put_u32(&b, 0); + put_u32(&b, WINDOW); + put_u32(&b, MAX_PKT); + ssh_send(&s, &b); + buf_free(&b); +} + +static void start_session(void) +{ + struct buf b; + + buf_init(&b); + if (want_tty) + { + put_u8(&b, SSH_MSG_CHANNEL_REQUEST); + put_u32(&b, peer_chan); + put_cstr(&b, "pty-req"); + put_u8(&b, 0); + put_cstr(&b, "xterm"); + put_u32(&b, TERM_COLS); + put_u32(&b, TERM_ROWS); + put_u32(&b, 0); + put_u32(&b, 0); + put_cstr(&b, ""); /* terminal modes: none */ + ssh_send(&s, &b); + } + put_u8(&b, SSH_MSG_CHANNEL_REQUEST); + put_u32(&b, peer_chan); + put_cstr(&b, cmd[0] ? "exec" : "shell"); + put_u8(&b, 1); + if (cmd[0]) + put_cstr(&b, cmd); + ssh_send(&s, &b); + buf_free(&b); +} + +static void send_data(const uint8_t *d, size_t n) +{ + struct buf b; + + buf_init(&b); + while (n && chan_open && !chan_closed) + { + size_t k = n > 16384 ? 16384 : n; + if (k > peer_window) + break; /* rare with interactive input */ + put_u8(&b, SSH_MSG_CHANNEL_DATA); + put_u32(&b, peer_chan); + put_str(&b, d, k); + ssh_send(&s, &b); + peer_window -= (uint32_t)k; + d += k; + n -= k; + } + buf_free(&b); +} + +static uint32_t window_used; + +static void got_data(const uint8_t *d, uint32_t n, int err) +{ + if (want_tty) + term_write(&term, d, n); + else + { + fwrite(d, 1, n, err ? stderr : stdout); + fflush(err ? stderr : stdout); + } + window_used += n; + if (window_used > WINDOW / 2) + { + struct buf b; + buf_init(&b); + put_u8(&b, SSH_MSG_CHANNEL_WINDOW_ADJUST); + put_u32(&b, peer_chan); + put_u32(&b, window_used); + ssh_send(&s, &b); + buf_free(&b); + window_used = 0; + } +} + +static void handle(struct buf *p) +{ + uint8_t t = p->d[0]; + struct buf b; + uint32_t n; + const uint8_t *d; + + buf_init(&b); + switch (t) + { + case SSH_MSG_SERVICE_ACCEPT: + if (have_key) + { + auth_state = A_KEY; + send_auth_key(); + } + else + { + auth_state = A_NONE; + send_auth("none"); + } + break; + case SSH_MSG_USERAUTH_FAILURE: + auth_next(p); + break; + case SSH_MSG_USERAUTH_BANNER: + { + char msg[1024]; + if (get_cstr(p, msg, sizeof(msg))) + say("%s", msg); + break; + } + case 60: /* PK_OK / INFO_REQUEST */ + if (auth_state == A_KBDINT) + kbd_info(p); + break; + case SSH_MSG_USERAUTH_SUCCESS: + auth_state = A_DONE; + open_session(); + break; + case SSH_MSG_GLOBAL_REQUEST: + { + char name[64]; + get_cstr(p, name, sizeof(name)); + if (get_u8(p)) + { + put_u8(&b, SSH_MSG_REQUEST_FAILURE); + ssh_send(&s, &b); + } + break; + } + case SSH_MSG_CHANNEL_OPEN_CONFIRMATION: + get_u32(p); + peer_chan = get_u32(p); + peer_window = get_u32(p); + peer_max = get_u32(p); + chan_open = 1; + start_session(); + break; + case SSH_MSG_CHANNEL_OPEN_FAILURE: + { + char msg[128]; + get_u32(p); + get_u32(p); + get_cstr(p, msg, sizeof(msg)); + say("The server refused the session: %s\n", msg); + ssh_disconnect(&s, SSH_DISCONNECT_BY_APPLICATION, "no session"); + break; + } + case SSH_MSG_CHANNEL_WINDOW_ADJUST: + get_u32(p); + peer_window += get_u32(p); + break; + case SSH_MSG_CHANNEL_DATA: + get_u32(p); + d = get_str(p, &n); + if (d) + got_data(d, n, 0); + break; + case SSH_MSG_CHANNEL_EXTENDED_DATA: + get_u32(p); + get_u32(p); + d = get_str(p, &n); + if (d) + got_data(d, n, 1); + break; + case SSH_MSG_CHANNEL_REQUEST: + { + char req[32]; + int want; + get_u32(p); + get_cstr(p, req, sizeof(req)); + want = get_u8(p); + if (!strcmp(req, "exit-status")) + { + exit_code = (int)get_u32(p); + got_exit = 1; + } + if (want) + { + put_u8(&b, SSH_MSG_CHANNEL_FAILURE); + put_u32(&b, peer_chan); + ssh_send(&s, &b); + } + break; + } + case SSH_MSG_CHANNEL_FAILURE: + say("The server refused the %s request.\n", cmd[0] ? "exec" : "shell"); + break; + case SSH_MSG_CHANNEL_SUCCESS: + case SSH_MSG_CHANNEL_EOF: + case SSH_MSG_REQUEST_FAILURE: + case SSH_MSG_REQUEST_SUCCESS: + break; + case SSH_MSG_CHANNEL_CLOSE: + if (!chan_closed) + { + put_u8(&b, SSH_MSG_CHANNEL_CLOSE); + put_u32(&b, peer_chan); + ssh_send(&s, &b); + } + chan_closed = 1; + break; + default: + put_u8(&b, SSH_MSG_UNIMPLEMENTED); + put_u32(&b, s.seq_in - 1); + ssh_send(&s, &b); + } + buf_free(&b); +} + +/* ---------------------------------------------------------------- */ + +static int keygen(void) +{ + uint8_t seed[32], sk[64], pk[32]; + char line[200]; + + rng_bytes(seed, 32); + crypto_ed25519_key_pair(sk, pk, seed); + if (!key_write(keypath, sk, pk, "dos@modernDOS")) + { + say("Cannot write %s\n", keypath); + return 1; + } + crypto_wipe(sk, sizeof(sk)); + key_public_line(pk, "dos@modernDOS", line, sizeof(line)); + say("Made %s. Add this line to ~/.ssh/authorized_keys on the server:\n", keypath); + printf("%s\n", line); + return 0; +} + +static void usage(void) +{ + say("Usage: SSH [/P port] [/I keyfile] [/L user] [/Y] [/T] [user@]host [command]\n" + " SSH /KEYGEN\n"); + exit(2); +} + +int main(int argc, char **argv) +{ + char seed[128], *slash, err[160]; + int i, keygen_only = 0, escape_state = 1; + uint32_t last_draw = 0; + struct buf p, keys; + + snprintf(dir, sizeof(dir), "%s", argv[0]); + for (i = 0; dir[i]; i++) + if (dir[i] == '\\') + dir[i] = '/'; + slash = strrchr(dir, '/'); + if (slash) + slash[1] = 0; + else + dir[0] = 0; + /* SSHDIR: keys and settings elsewhere (a disk that keeps them) */ + if (getenv("SSHDIR") && strlen(getenv("SSHDIR")) < sizeof(dir) - 2) + { + snprintf(dir, sizeof(dir), "%s", getenv("SSHDIR")); + for (i = 0; dir[i]; i++) + if (dir[i] == '\\') + dir[i] = '/'; + if (i && dir[i - 1] != '/') + strcat(dir, "/"); + } + plat_prog = "ssh"; + path_of(seed, sizeof(seed), "SEED.BIN"); + path_of(keypath, sizeof(keypath), "ID.KEY"); + + for (i = 1; i < argc; i++) + { + const char *a = argv[i]; + if (!host[0] && (a[0] == '/' || a[0] == '-') && a[1]) + { + char o = (char)toupper((unsigned char)a[1]); + if (!strcasecmp(a + 1, "KEYGEN")) + keygen_only = 1; + else if (o == 'P' && i + 1 < argc) + port = atoi(argv[++i]); + else if (o == 'I' && i + 1 < argc) + snprintf(keypath, sizeof(keypath), "%s", argv[++i]); + else if (o == 'L' && i + 1 < argc) + snprintf(user, sizeof(user), "%s", argv[++i]); + else if (o == 'Y') + accept_new = 1; + else if (o == 'T') + want_tty = 1; + else + usage(); + } + else if (!host[0]) + { + const char *at = strchr(a, '@'); + if (at) + { + snprintf(user, sizeof(user), "%.*s", (int)(at - a), a); + snprintf(host, sizeof(host), "%s", at + 1); + } + else + snprintf(host, sizeof(host), "%s", a); + } + else + { + size_t n = strlen(cmd); + snprintf(cmd + n, sizeof(cmd) - n, "%s%s", n ? " " : "", a); + } + } + rng_init(seed); + if (keygen_only) + return keygen(); + if (!host[0]) + usage(); + if (!user[0]) + strcpy(user, "dos"); + if (!cmd[0]) + want_tty = 1; + have_key = key_read(keypath, key_sk, key_pk, err, sizeof(err)); + if (!have_key && strstr(err, "cannot open") == NULL) + say("%s\n", err); + + if (!plat_init()) + return 255; + say("Connecting to %s port %d...\n", host, port); + { + int fd = plat_connect(host, port); + if (fd < 0) + { + say("Cannot connect to %s port %d.\n", host, port); + return 255; + } + s.check_hostkey = check_hostkey; + ssh_start(&s, fd, 0); + } + buf_init(&p); + buf_init(&keys); + buf_init(&replies); + term_init(&term, &replies); + + while (!s.dead && !chan_closed) + { + int busy = ssh_io(&s), r, k; + while ((r = ssh_packet(&s, &p)) > 0) + { + handle(&p); + busy = 1; + } + if (ssh_ready(&s) && !service_sent) + { + struct buf b; + buf_init(&b); + put_u8(&b, SSH_MSG_SERVICE_REQUEST); + put_cstr(&b, "ssh-userauth"); + ssh_send(&s, &b); + buf_free(&b); + service_sent = 1; /* SERVICE_ACCEPT starts the login */ + } + if (chan_open && want_tty) + { + /* keys: ~. at the start of a line disconnects */ + while ((k = plat_bioskey()) >= 0) + { + uint8_t ascii = (uint8_t)k; + if (escape_state == 2 && ascii == '.') + { + say("\r\nDisconnected.\r\n"); + ssh_disconnect(&s, SSH_DISCONNECT_BY_APPLICATION, "disconnected by user"); + break; + } + if (escape_state == 1 && ascii == '~') + { + escape_state = 2; + continue; + } + if (escape_state == 2) + term_key(&term, '~', &keys); + escape_state = ascii == '\r'; + term_key(&term, (uint16_t)k, &keys); + } + if (replies.len) + { + put_bytes(&keys, replies.d, replies.len); + buf_reset(&replies); + } + if (keys.len) + { + send_data(keys.d, keys.len); + buf_reset(&keys); + busy = 1; + } + if (term.dirty && plat_ms() - last_draw >= 30) + { + plat_screen_show(&term.cell[0][0], term.row, term.col, term.cursor_on); + term.dirty = 0; + last_draw = plat_ms(); + } + } + busy |= ssh_io(&s); + if (!busy) + plat_idle(); + } + if (want_tty && chan_open) + { + plat_screen_show(&term.cell[0][0], term.row, term.col, 1); + if (getenv("SSHDUMP")) /* tests: the final screen to the log */ + for (i = 0; i < TERM_ROWS; i++) + { + char line[TERM_COLS + 1]; + int c; + for (c = 0; c < TERM_COLS; c++) + line[c] = (char)(term.cell[i][c] & 0xff); + while (c > 0 && line[c - 1] == ' ') + c--; + line[c] = 0; + if (c) + plat_log("screen: %s\n", line); + } + printf("\n"); + } + ssh_io(&s); + if (s.dead && !chan_closed && s.why[0]) + say("Connection to %s closed: %s\n", host, s.why); + plat_close(s.fd); + ssh_free(&s); + rng_save(seed); + crypto_wipe(key_sk, sizeof(key_sk)); + return got_exit ? exit_code : (chan_closed ? 0 : 255); +} diff --git a/net/ssh/sshd.c b/net/ssh/sshd.c new file mode 100644 index 00000000..766653fd --- /dev/null +++ b/net/ssh/sshd.c @@ -0,0 +1,1066 @@ +/* + * SSHD - SSH server for modernDOS + * + * SSHD [/P port] run the server (default port 22) + * SSHD /PASSWD set the login password (stored hashed) + * SSHD /NOPASSWD remove it (public keys only) + * + * Files, in the directory of SSHD.EXE (or in %SSHDIR%): + * HOSTKEY.ED the host's ed25519 key (made on the first start) + * AUTHKEYS.TXT public keys allowed to log in, OpenSSH authorized_keys + * format ("ssh-ed25519 AAAA... comment"), one per line + * PASSWD.TXT password hash (Argon2i), if a password is set + * SEED.BIN random seed kept between runs + * Without AUTHKEYS.TXT and PASSWD.TXT nobody can log in. + * + * Sessions: "shell" runs COMMAND.COM in an MDVMM job slot (SSHSLOT.COM) + * whose screen is sent to the client as ANSI text; "exec" runs one command + * in a slot, its output redirected to a file that is sent back; the "sftp" + * subsystem serves files (scp and sftp). Press Esc on the DOS console to + * stop the server. + */ +#include +#include +#include +#include +#include +#include "crypto/monocypher.h" +#include "crypto/monocypher-ed25519.h" +#include "buf.h" +#include "rng.h" +#include "ssh.h" +#include "plat.h" +#include "console.h" +#include "sftp.h" + +#define MAX_CONN 4 +#define MAX_CHAN 2 +#define MAX_KEYS 32 +#define WINDOW (256 * 1024) +#define MAX_PKT 32768 +#define AUTH_TRIES 6 +#define AUTH_TIMEOUT 120000 /* ms to log in */ +#define SCREEN_MS 40 /* screen polling interval */ + +enum { CH_FREE, CH_OPEN, CH_SHELL, CH_EXEC, CH_SFTP }; + +struct chan { + int type; + uint32_t peer, peer_window, peer_max; + uint32_t window; /* what the client may still send */ + int pty; + int slot; /* job slot, or -1 */ + struct buf inq, outq; + int got_eof, sent_eof, sent_close, got_close; + int done; /* the job ended */ + int code; + struct console con; + uint32_t last_screen; + char outfile[96]; + struct sftp *sftp; +}; + +struct conn { + int used; + struct ssh s; + char peer[32]; + int authed; + char user[64]; + int tries; + uint32_t start; + struct chan ch[MAX_CHAN]; +}; + +static struct conn conns[MAX_CONN]; +static uint8_t host_sk[64], host_pk[32]; +static uint8_t auth_keys[MAX_KEYS][32]; +static int nkeys; +static char pw_line[256]; /* "argon2i$blocks$passes$salt$hash" */ +static char dir[96]; /* where SSHD.EXE and its files are */ +static int orphan[8]; /* slots of closed sessions to recover */ + +static void path_of(char *out, size_t n, const char *file) +{ + snprintf(out, n, "%s%s", dir, file); +} + +/* ---------------------------------------------------------------- */ +/* keys and passwords */ + +static int load_hostkey(void) +{ + char path[128], fp[64]; + uint8_t seed[32]; + FILE *f; + + path_of(path, sizeof(path), "HOSTKEY.ED"); + f = fopen(path, "rb"); + if (f) + { + size_t n = fread(seed, 1, 32, f); + fclose(f); + if (n != 32) + { + plat_log("%s is damaged\n", path); + return 0; + } + } + else + { + plat_log("making a new host key %s\n", path); + rng_bytes(seed, 32); + f = fopen(path, "wb"); + if (!f || fwrite(seed, 1, 32, f) != 32) + { + plat_log("cannot write %s\n", path); + if (f) + fclose(f); + return 0; + } + fclose(f); + } + crypto_ed25519_key_pair(host_sk, host_pk, seed); /* wipes seed */ + ssh_fingerprint(host_pk, fp); + plat_log("host key ED25519 %s\n", fp); + return 1; +} + +static void load_authkeys(void) +{ + char path[128], line[1024]; + FILE *f; + + nkeys = 0; + path_of(path, sizeof(path), "AUTHKEYS.TXT"); + f = fopen(path, "r"); + if (!f) + return; + while (fgets(line, sizeof(line), f) && nkeys < MAX_KEYS) + { + char *p = line, *b64, *end; + uint8_t blob[128]; + int n; + struct buf b; + uint32_t an, kn; + const uint8_t *alg, *pk; + + while (*p == ' ' || *p == '\t') + p++; + if (strncmp(p, "ssh-ed25519 ", 12)) + continue; /* comments, other key types */ + b64 = p + 12; + while (*b64 == ' ') + b64++; + end = b64; + while (*end && !isspace((unsigned char)*end)) + end++; + n = b64_decode(b64, (size_t)(end - b64), blob, sizeof(blob)); + if (n <= 0) + continue; + b.d = blob; b.len = (size_t)n; b.cap = 0; b.pos = 0; b.err = 0; + alg = get_str(&b, &an); + pk = get_str(&b, &kn); + if (b.err || an != 11 || memcmp(alg, "ssh-ed25519", 11) || kn != 32) + continue; + memcpy(auth_keys[nkeys++], pk, 32); + } + fclose(f); +} + +static void load_password(void) +{ + char path[128]; + FILE *f; + + pw_line[0] = 0; + path_of(path, sizeof(path), "PASSWD.TXT"); + f = fopen(path, "r"); + if (!f) + return; + if (!fgets(pw_line, sizeof(pw_line), f)) + pw_line[0] = 0; + pw_line[strcspn(pw_line, "\r\n")] = 0; + fclose(f); + if (strncmp(pw_line, "argon2i$", 8)) + pw_line[0] = 0; +} + +static int hexval(const char *s, uint8_t *out, int n) +{ + int i; + + for (i = 0; i < n; i++) + { + unsigned v; + if (sscanf(s + i * 2, "%2x", &v) != 1) + return 0; + out[i] = (uint8_t)v; + } + return 1; +} + +static void argon(uint8_t hash[32], const char *pw, size_t pwlen, const uint8_t salt[16], + uint32_t blocks, uint32_t passes) +{ + crypto_argon2_config cfg; + crypto_argon2_inputs in; + void *work = malloc((size_t)blocks * 1024); + + if (!work) + { + memset(hash, 0, 32); + return; + } + cfg.algorithm = CRYPTO_ARGON2_I; + cfg.nb_blocks = blocks; + cfg.nb_passes = passes; + cfg.nb_lanes = 1; + in.pass = (const uint8_t *)pw; + in.pass_size = (uint32_t)pwlen; + in.salt = salt; + in.salt_size = 16; + crypto_argon2(hash, 32, work, cfg, in, crypto_argon2_no_extras); + free(work); +} + +static int check_password(const char *pw, size_t len) +{ + uint8_t salt[16], want[32], got[32]; + unsigned blocks, passes; + char saltx[40], hashx[80]; + + if (!pw_line[0] || sscanf(pw_line, "argon2i$%u$%u$%32[0-9a-f]$%64[0-9a-f]", &blocks, &passes, + saltx, hashx) != 4 || + blocks < 8 || blocks > 65536 || passes < 1 || passes > 16 || + !hexval(saltx, salt, 16) || !hexval(hashx, want, 32)) + return 0; + argon(got, pw, len, salt, blocks, passes); + return !crypto_verify32(got, want); +} + +static void read_secret(const char *prompt, char *out, size_t n) +{ + size_t len = 0; + int c; + + fputs(prompt, stdout); + fflush(stdout); + for (;;) + { + while ((c = plat_key()) < 0) + plat_idle(); + if (c == '\r' || c == '\n') + break; + if ((c == 8 || c == 127) && len) + len--; + else if (c >= 32 && len + 1 < n) + out[len++] = (char)c; + } + out[len] = 0; + fputs("\n", stdout); +} + +static int set_password(void) +{ + char a[128], b[128], path[128]; + uint8_t salt[16], hash[32]; + FILE *f; + int i; + + read_secret("New password: ", a, sizeof(a)); + read_secret("Again: ", b, sizeof(b)); + if (strcmp(a, b) || strlen(a) < 8) + { + printf(strcmp(a, b) ? "The passwords differ.\n" : "Use at least 8 characters.\n"); + return 1; + } + rng_bytes(salt, sizeof(salt)); + argon(hash, a, strlen(a), salt, 4096, 3); + crypto_wipe(a, sizeof(a)); + crypto_wipe(b, sizeof(b)); + path_of(path, sizeof(path), "PASSWD.TXT"); + f = fopen(path, "w"); + if (!f) + { + printf("Cannot write %s\n", path); + return 1; + } + fprintf(f, "argon2i$4096$3$"); + for (i = 0; i < 16; i++) + fprintf(f, "%02x", salt[i]); + fprintf(f, "$"); + for (i = 0; i < 32; i++) + fprintf(f, "%02x", hash[i]); + fprintf(f, "\n"); + fclose(f); + printf("Password set (%s).\n", path); + return 0; +} + +/* ---------------------------------------------------------------- */ +/* authentication */ + +static void auth_failure(struct conn *c) +{ + struct buf b; + + buf_init(&b); + put_u8(&b, SSH_MSG_USERAUTH_FAILURE); + put_cstr(&b, pw_line[0] ? "publickey,password" : "publickey"); + put_u8(&b, 0); + ssh_send(&c->s, &b); + buf_free(&b); +} + +static int key_allowed(const uint8_t pk[32]) +{ + int i; + + load_authkeys(); /* edits apply without a restart */ + for (i = 0; i < nkeys; i++) + if (!crypto_verify32(auth_keys[i], pk)) + return 1; + return 0; +} + +static void userauth(struct conn *c, struct buf *p) +{ + char user[64], service[32], method[32]; + struct buf b; + + buf_init(&b); + get_cstr(p, user, sizeof(user)); + get_cstr(p, service, sizeof(service)); + get_cstr(p, method, sizeof(method)); + if (p->err || strcmp(service, "ssh-connection")) + { + ssh_disconnect(&c->s, SSH_DISCONNECT_SERVICE_NOT_AVAILABLE, "bad service"); + return; + } + if (!strcmp(method, "publickey")) + { + int hassig = get_u8(p); + uint32_t an, bn, sn, n2, kn; + const uint8_t *alg = get_str(p, &an), *blob = get_str(p, &bn), *sig = NULL; + struct buf kb; + const uint8_t *pk; + if (hassig) + sig = get_str(p, &sn); + kb.d = (uint8_t *)blob; kb.len = bn; kb.cap = 0; kb.pos = 0; kb.err = 0; + get_str(&kb, &n2); + pk = get_str(&kb, &kn); + if (p->err || kb.err || an != 11 || memcmp(alg, "ssh-ed25519", 11) || kn != 32 || + !key_allowed(pk)) + { + if (hassig) + c->tries++; + auth_failure(c); + } + else if (!hassig) + { + put_u8(&b, SSH_MSG_USERAUTH_PK_OK); + put_str(&b, alg, an); + put_str(&b, blob, bn); + ssh_send(&c->s, &b); + } + else + { + struct buf sb, data; + uint32_t sa, sl; + const uint8_t *s64; + sb.d = (uint8_t *)sig; sb.len = sn; sb.cap = 0; sb.pos = 0; sb.err = 0; + get_str(&sb, &sa); + s64 = get_str(&sb, &sl); + buf_init(&data); + put_str(&data, c->s.sid, 32); + put_u8(&data, SSH_MSG_USERAUTH_REQUEST); + put_cstr(&data, user); + put_cstr(&data, service); + put_cstr(&data, "publickey"); + put_u8(&data, 1); + put_str(&data, alg, an); + put_str(&data, blob, bn); + if (!sb.err && sl == 64 && !crypto_ed25519_check(s64, pk, data.d, data.len)) + { + char fp[64]; + ssh_fingerprint(pk, fp); + plat_log("%s: user %s logged in with key %s\n", c->peer, user, fp); + c->authed = 1; + strcpy(c->user, user); + put_u8(&b, SSH_MSG_USERAUTH_SUCCESS); + ssh_send(&c->s, &b); + } + else + { + c->tries++; + auth_failure(c); + } + buf_free(&data); + } + } + else if (!strcmp(method, "password") && pw_line[0]) + { + uint32_t n; + const uint8_t *pw; + get_u8(p); + pw = get_str(p, &n); + if (pw && n < 128 && check_password((const char *)pw, n)) + { + plat_log("%s: user %s logged in with the password\n", c->peer, user); + c->authed = 1; + strcpy(c->user, user); + put_u8(&b, SSH_MSG_USERAUTH_SUCCESS); + ssh_send(&c->s, &b); + } + else + { + plat_log("%s: wrong password for %s\n", c->peer, user); + c->tries++; + auth_failure(c); + } + } + else + auth_failure(c); + buf_free(&b); + if (c->tries >= AUTH_TRIES) + ssh_disconnect(&c->s, SSH_DISCONNECT_NO_MORE_AUTH_METHODS, "too many failed logins"); +} + +/* ---------------------------------------------------------------- */ +/* channels */ + +static struct chan *chan_get(struct conn *c, struct buf *p) +{ + uint32_t n = get_u32(p); + + if (p->err || n >= MAX_CHAN || c->ch[n].type == CH_FREE) + { + ssh_disconnect(&c->s, SSH_DISCONNECT_PROTOCOL_ERROR, "bad channel"); + return NULL; + } + return &c->ch[n]; +} + +static void chan_reply(struct conn *c, struct chan *ch, int ok) +{ + struct buf b; + + buf_init(&b); + put_u8(&b, ok ? SSH_MSG_CHANNEL_SUCCESS : SSH_MSG_CHANNEL_FAILURE); + put_u32(&b, ch->peer); + ssh_send(&c->s, &b); + buf_free(&b); +} + +static void chan_free(struct chan *ch) +{ + if (ch->slot >= 0 && !ch->done) + { + int i; + for (i = 0; i < 8; i++) + if (!orphan[i]) + { + orphan[i] = ch->slot; /* end it in the background */ + break; + } + } + if (ch->outfile[0]) + remove(ch->outfile); + buf_free(&ch->inq); + buf_free(&ch->outq); + sftp_free(ch->sftp); + memset(ch, 0, sizeof(*ch)); + ch->slot = -1; +} + +static void chan_open(struct conn *c, struct buf *p) +{ + char type[32]; + uint32_t peer, win, max; + struct buf b; + int i; + + get_cstr(p, type, sizeof(type)); + peer = get_u32(p); + win = get_u32(p); + max = get_u32(p); + buf_init(&b); + for (i = 0; i < MAX_CHAN && c->ch[i].type != CH_FREE; i++) + ; + if (p->err || strcmp(type, "session") || i == MAX_CHAN) + { + put_u8(&b, SSH_MSG_CHANNEL_OPEN_FAILURE); + put_u32(&b, peer); + put_u32(&b, strcmp(type, "session") ? 3 : 4); /* unknown type / no resources */ + put_cstr(&b, strcmp(type, "session") ? "only sessions" : "too many sessions"); + put_cstr(&b, ""); + ssh_send(&c->s, &b); + buf_free(&b); + return; + } + memset(&c->ch[i], 0, sizeof(c->ch[i])); + c->ch[i].type = CH_OPEN; + c->ch[i].peer = peer; + c->ch[i].peer_window = win; + c->ch[i].peer_max = max < 1024 ? 1024 : max; + c->ch[i].window = WINDOW; + c->ch[i].slot = -1; + buf_init(&c->ch[i].inq); + buf_init(&c->ch[i].outq); + put_u8(&b, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); + put_u32(&b, peer); + put_u32(&b, (uint32_t)i); + put_u32(&b, WINDOW); + put_u32(&b, MAX_PKT); + ssh_send(&c->s, &b); + buf_free(&b); +} + +static int start_job(struct conn *c, struct chan *ch, const char *cmd) +{ + ch->slot = plat_job_start(cmd); + if (ch->slot < 0) + { + plat_log("%s: no free job slot (SSHSLOT loaded? sessions busy?)\n", c->peer); + return 0; + } + return 1; +} + +static void chan_request(struct conn *c, struct buf *p) +{ + struct chan *ch = chan_get(c, p); + char req[32]; + int want, ok = 0; + + if (!ch) + return; + get_cstr(p, req, sizeof(req)); + want = get_u8(p); + if (!strcmp(req, "pty-req")) + { + ch->pty = 1; + ok = 1; + } + else if (!strcmp(req, "shell") && ch->type == CH_OPEN) + { + if (start_job(c, ch, "")) + { + ch->type = CH_SHELL; + con_init(&ch->con); + plat_log("%s: shell in session %d\n", c->peer, ch->slot); + ok = 1; + } + } + else if (!strcmp(req, "exec") && ch->type == CH_OPEN) + { + char cmd[200], line[400]; + static int seq; + if (get_cstr(p, cmd, sizeof(cmd)) && cmd[0]) + { + snprintf(ch->outfile, sizeof(ch->outfile), "%sSSH%05d.OUT", plat_tempdir(), + (seq++ + (int)plat_ms()) % 100000); +#ifdef __DJGPP__ + /* through a second shell: its output handle is inherited by all it + runs, also the commands of a batch file (a redirected batch file + alone does not pass it on). No space before ">": ECHO would + write it. */ + snprintf(line, sizeof(line), "%%COMSPEC%% /F /C %s>%s", cmd, ch->outfile); +#else + snprintf(line, sizeof(line), "%s > %s", cmd, ch->outfile); /* sh: "3>" is fd 3 */ +#endif + if (strlen(line) < 118 && start_job(c, ch, line)) + { + ch->type = CH_EXEC; + plat_log("%s: exec \"%s\" in session %d\n", c->peer, cmd, ch->slot); + ok = 1; + } + else + ch->outfile[0] = 0; + } + } + else if (!strcmp(req, "subsystem") && ch->type == CH_OPEN) + { + char name[32]; + if (get_cstr(p, name, sizeof(name)) && !strcmp(name, "sftp")) + { + ch->sftp = sftp_new(); + ch->type = CH_SFTP; + plat_log("%s: sftp\n", c->peer); + ok = 1; + } + } + else if (!strcmp(req, "window-change")) + ok = 1; + else if ((!strcmp(req, "signal") || !strcmp(req, "break")) && ch->type == CH_SHELL) + { + uint16_t k = 0x2e03; /* Ctrl+C */ + plat_keys(ch->slot, &k, 1); + ok = 1; + } + if (want) + chan_reply(c, ch, ok); +} + +static void chan_data(struct conn *c, struct buf *p) +{ + struct chan *ch = chan_get(c, p); + uint32_t n; + const uint8_t *d; + + if (!ch) + return; + d = get_str(p, &n); + if (!d || n > ch->window) + { + ssh_disconnect(&c->s, SSH_DISCONNECT_PROTOCOL_ERROR, "window exceeded"); + return; + } + ch->window -= n; + if (ch->type == CH_SHELL || ch->type == CH_SFTP) + put_bytes(&ch->inq, d, n); +} + +static void handle(struct conn *c, struct buf *p) +{ + uint8_t t = p->d[0]; + struct buf b; + struct chan *ch; + + buf_init(&b); + if (t == SSH_MSG_SERVICE_REQUEST) + { + char svc[32]; + get_cstr(p, svc, sizeof(svc)); + if (strcmp(svc, "ssh-userauth")) + ssh_disconnect(&c->s, SSH_DISCONNECT_SERVICE_NOT_AVAILABLE, "unknown service"); + else + { + put_u8(&b, SSH_MSG_SERVICE_ACCEPT); + put_cstr(&b, svc); + ssh_send(&c->s, &b); + } + } + else if (t == SSH_MSG_USERAUTH_REQUEST) + { + if (c->authed) + ; /* ignore after success (RFC 4252) */ + else + userauth(c, p); + } + else if (!c->authed) + ssh_disconnect(&c->s, SSH_DISCONNECT_PROTOCOL_ERROR, "not logged in"); + else + switch (t) + { + case SSH_MSG_GLOBAL_REQUEST: + { + char name[64]; + get_cstr(p, name, sizeof(name)); + if (get_u8(p)) + { + put_u8(&b, SSH_MSG_REQUEST_FAILURE); + ssh_send(&c->s, &b); + } + break; + } + case SSH_MSG_CHANNEL_OPEN: chan_open(c, p); break; + case SSH_MSG_CHANNEL_REQUEST: chan_request(c, p); break; + case SSH_MSG_CHANNEL_DATA: chan_data(c, p); break; + case SSH_MSG_CHANNEL_EXTENDED_DATA: break; + case SSH_MSG_CHANNEL_WINDOW_ADJUST: + if ((ch = chan_get(c, p))) + ch->peer_window += get_u32(p); + break; + case SSH_MSG_CHANNEL_EOF: + if ((ch = chan_get(c, p))) + ch->got_eof = 1; + break; + case SSH_MSG_CHANNEL_CLOSE: + if ((ch = chan_get(c, p))) + ch->got_close = 1; + break; + case SSH_MSG_CHANNEL_SUCCESS: + case SSH_MSG_CHANNEL_FAILURE: + case SSH_MSG_REQUEST_SUCCESS: + case SSH_MSG_REQUEST_FAILURE: + break; + default: + { + put_u8(&b, SSH_MSG_UNIMPLEMENTED); + put_u32(&b, c->s.seq_in - 1); + ssh_send(&c->s, &b); + } + } + buf_free(&b); +} + +/* ---------------------------------------------------------------- */ +/* channel work */ + +static void send_exit(struct conn *c, struct chan *ch) +{ + struct buf b; + + buf_init(&b); + put_u8(&b, SSH_MSG_CHANNEL_REQUEST); + put_u32(&b, ch->peer); + put_cstr(&b, "exit-status"); + put_u8(&b, 0); + put_u32(&b, (uint32_t)ch->code); + ssh_send(&c->s, &b); + buf_free(&b); +} + +static void send_close(struct conn *c, struct chan *ch) +{ + struct buf b; + + buf_init(&b); + if (!ch->sent_eof) + { + put_u8(&b, SSH_MSG_CHANNEL_EOF); + put_u32(&b, ch->peer); + ssh_send(&c->s, &b); + ch->sent_eof = 1; + } + put_u8(&b, SSH_MSG_CHANNEL_CLOSE); + put_u32(&b, ch->peer); + ssh_send(&c->s, &b); + ch->sent_close = 1; + buf_free(&b); +} + +/* outq -> CHANNEL_DATA within the client's window */ +static int pump_out(struct conn *c, struct chan *ch) +{ + struct buf b; + int moved = 0; + + buf_init(&b); + while (ch->outq.len && ch->peer_window && ssh_pending(&c->s) < 64 * 1024) + { + uint32_t n = (uint32_t)ch->outq.len; + if (n > ch->peer_window) + n = ch->peer_window; + if (n > ch->peer_max) + n = ch->peer_max; + if (n > 16384) + n = 16384; + put_u8(&b, SSH_MSG_CHANNEL_DATA); + put_u32(&b, ch->peer); + put_str(&b, ch->outq.d, n); + ssh_send(&c->s, &b); + buf_consume(&ch->outq, n); + ch->peer_window -= n; + moved = 1; + } + buf_free(&b); + /* let the client send more */ + if (ch->window < WINDOW / 2 && ch->inq.len < WINDOW / 2) + { + buf_init(&b); + put_u8(&b, SSH_MSG_CHANNEL_WINDOW_ADJUST); + put_u32(&b, ch->peer); + put_u32(&b, WINDOW - ch->window); + ssh_send(&c->s, &b); + buf_free(&b); + ch->window = WINDOW; + } + return moved; +} + +static void shell_work(struct conn *c, struct chan *ch) +{ + uint8_t cells[4000]; + int row, col, hidden, state; + + (void)c; + /* keys from the client */ + if (ch->inq.len && !ch->done) + { + uint16_t keys[64]; + int n = con_keys(&ch->con, ch->inq.d, ch->inq.len, keys, 15), taken; + taken = n ? plat_keys(ch->slot, keys, n) : 0; + if (taken == n) + buf_consume(&ch->inq, ch->con.used); + else if (taken > 0) + { + /* the BIOS buffer took only some: parse again next time */ + struct console tmp = ch->con; + con_keys(&tmp, ch->inq.d, ch->inq.len, keys, taken); + buf_consume(&ch->inq, tmp.used); + ch->con.last_cr = tmp.last_cr; + } + } + /* the screen */ + if (!ch->done && !ch->outq.len && plat_ms() - ch->last_screen >= SCREEN_MS && + ch->peer_window >= 32768) + { + ch->last_screen = plat_ms(); + if (plat_screen(ch->slot, cells, &row, &col, &hidden)) + con_render(&ch->con, cells, row, col, hidden, &ch->outq); + } + if (!ch->done) + { + state = plat_job_state(ch->slot, &ch->code); + if (state == JOB_DONE || state < 0) + { + ch->done = 1; + ch->slot = -1; + con_reset(&ch->outq); + } + } +} + +static void exec_work(struct conn *c, struct chan *ch) +{ + int state; + + if (ch->done) + return; + state = plat_job_state(ch->slot, &ch->code); + if (state == JOB_DONE || state < 0) + { + FILE *f = fopen(ch->outfile, "rb"); + ch->done = 1; + ch->slot = -1; + if (f) + { + char tmp[4096]; + size_t n; + while ((n = fread(tmp, 1, sizeof(tmp), f)) > 0) + put_bytes(&ch->outq, tmp, n); + fclose(f); + } + remove(ch->outfile); + ch->outfile[0] = 0; + plat_log("%s: exec finished, exit code %d\n", c->peer, ch->code); + } +} + +static int conn_work(struct conn *c) +{ + int i, busy = 0; + + for (i = 0; i < MAX_CHAN; i++) + { + struct chan *ch = &c->ch[i]; + if (ch->type == CH_FREE) + continue; + if (ch->got_close) + { + if (!ch->sent_close) + send_close(c, ch); + chan_free(ch); + continue; + } + if (!ssh_ready(&c->s)) + continue; + if (ch->type == CH_SHELL) + shell_work(c, ch); + else if (ch->type == CH_EXEC) + exec_work(c, ch); + else if (ch->type == CH_SFTP && ch->outq.len < 128 * 1024 && ch->inq.len) + { + if (sftp_input(ch->sftp, &ch->inq, &ch->outq) < 0) + ssh_disconnect(&c->s, SSH_DISCONNECT_PROTOCOL_ERROR, "bad sftp packet"); + busy = 1; + } + if (ch->type == CH_SFTP && ch->got_eof && !ch->inq.len && !ch->outq.len && !ch->sent_close) + { + ch->code = 0; + send_exit(c, ch); /* scp checks it */ + send_close(c, ch); + } + busy |= pump_out(c, ch); + if ((ch->type == CH_SHELL || ch->type == CH_EXEC) && ch->done && !ch->outq.len && + !ch->sent_close) + { + send_exit(c, ch); + send_close(c, ch); + } + } + return busy; +} + +static void conn_close(struct conn *c) +{ + int i; + + plat_log("%s: closed (%s)\n", c->peer, c->s.why[0] ? c->s.why : "done"); + ssh_io(&c->s); /* a last DISCONNECT */ + plat_close(c->s.fd); + for (i = 0; i < MAX_CHAN; i++) + if (c->ch[i].type != CH_FREE) + chan_free(&c->ch[i]); + ssh_free(&c->s); + c->used = 0; +} + +/* sessions of closed connections: Ctrl+C and EXIT until the shell ends */ +static void orphans(void) +{ + static uint32_t last; + int i, code; + + if (plat_ms() - last < 2000) + return; + last = plat_ms(); + for (i = 0; i < 8; i++) + if (orphan[i]) + { + int st = plat_job_state(orphan[i], &code); + if (st == JOB_DONE || st == JOB_NONE || st < 0) + orphan[i] = 0; + else + { + static const uint16_t keys[] = { 0x2e03, 0x1c0d, 0x1265, 0x2d78, 0x1769, 0x1474, 0x1c0d }; + plat_keys(orphan[i], keys, 7); /* ^C Enter "exit" Enter */ + } + } +} + +/* ---------------------------------------------------------------- */ + +int main(int argc, char **argv) +{ + int port = 22, lfd, i; + char seed[128], *slash; + + snprintf(dir, sizeof(dir), "%s", argv[0]); + for (i = 0; dir[i]; i++) + if (dir[i] == '\\') + dir[i] = '/'; + slash = strrchr(dir, '/'); + if (slash) + slash[1] = 0; + else + dir[0] = 0; + /* SSHDIR: keys and settings elsewhere (a disk that keeps them) */ + if (getenv("SSHDIR") && strlen(getenv("SSHDIR")) < sizeof(dir) - 2) + { + snprintf(dir, sizeof(dir), "%s", getenv("SSHDIR")); + for (i = 0; dir[i]; i++) + if (dir[i] == '\\') + dir[i] = '/'; + if (i && dir[i - 1] != '/') + strcat(dir, "/"); + } + path_of(seed, sizeof(seed), "SEED.BIN"); + + for (i = 1; i < argc; i++) + { + if (!strcmp(argv[i], "/P") || !strcmp(argv[i], "/p") || !strcmp(argv[i], "-p")) + { + if (++i < argc) + port = atoi(argv[i]); + } + else if (!strcasecmp(argv[i], "/PASSWD")) + { + rng_init(seed); + return set_password(); + } + else if (!strcasecmp(argv[i], "/NOPASSWD")) + { + char path[128]; + path_of(path, sizeof(path), "PASSWD.TXT"); + remove(path); + printf("Password removed: public keys only.\n"); + return 0; + } + else + { + printf("Usage: SSHD [/P port] | /PASSWD | /NOPASSWD\n"); + return 2; + } + } + + plat_log("modernDOS SSH server\n"); + rng_init(seed); + if (!plat_init() || !load_hostkey()) + return 1; + load_authkeys(); + load_password(); + if (!nkeys && !pw_line[0]) + plat_log("warning: no AUTHKEYS.TXT and no password: nobody can log in\n"); + lfd = plat_listen(port); + if (lfd < 0) + { + plat_log("cannot listen on port %d\n", port); + return 1; + } + plat_log("listening on port %d (%d keys%s); Esc stops\n", port, nkeys, + pw_line[0] ? ", password" : ""); + + for (;;) + { + int busy = 0, fd; + char peer[32]; + struct buf p; + + if (plat_key() == 27) + break; + fd = plat_accept(lfd, peer, sizeof(peer)); + if (fd >= 0) + { + for (i = 0; i < MAX_CONN && conns[i].used; i++) + ; + if (i == MAX_CONN) + { + plat_log("%s: refused, too many connections\n", peer); + plat_close(fd); + } + else + { + struct conn *c = &conns[i]; + memset(c, 0, sizeof(*c)); + c->used = 1; + strcpy(c->peer, peer); + c->start = plat_ms(); + c->s.host_sk = host_sk; + c->s.host_pk = host_pk; + ssh_start(&c->s, fd, 1); + for (fd = 0; fd < MAX_CHAN; fd++) + c->ch[fd].slot = -1; + plat_log("%s: connected\n", peer); + } + busy = 1; + } + buf_init(&p); + for (i = 0; i < MAX_CONN; i++) + { + struct conn *c = &conns[i]; + int r; + if (!c->used) + continue; + busy |= ssh_io(&c->s); + while ((r = ssh_packet(&c->s, &p)) > 0) + { + handle(c, &p); + busy = 1; + } + if (!c->authed && plat_ms() - c->start > AUTH_TIMEOUT) + ssh_disconnect(&c->s, SSH_DISCONNECT_AUTH_CANCELLED, "login timeout"); + if (!c->s.dead) + busy |= conn_work(c); + busy |= ssh_io(&c->s); + if (c->s.dead) + conn_close(c); + } + buf_free(&p); + orphans(); + if (!busy) + plat_idle(); + } + for (i = 0; i < MAX_CONN; i++) + if (conns[i].used) + { + ssh_disconnect(&conns[i].s, SSH_DISCONNECT_BY_APPLICATION, "server stopped"); + conn_close(&conns[i]); + } + plat_close(lfd); + rng_save(seed); + plat_log("stopped\n"); + return 0; +} diff --git a/net/ssh/term.c b/net/ssh/term.c new file mode 100644 index 00000000..ba6495f3 --- /dev/null +++ b/net/ssh/term.c @@ -0,0 +1,557 @@ +/* terminal emulator for the SSH client (see term.h) */ +#include +#include +#include "console.h" +#include "term.h" + +enum { S_GROUND, S_ESC, S_CSI, S_OSC, S_OSC_ESC, S_CHARSET }; + +static const uint8_t cga_of_ansi[8] = { 0, 4, 2, 6, 1, 5, 3, 7 }; + +static uint8_t attr(const struct term *t) +{ + int fg = t->fg, bg = t->bg & 7; + + if (t->bold && fg < 8) + fg += 8; + if (t->reverse) + { + int tmp = fg & 7; + fg = bg | (fg & 8); + bg = tmp; + } + return (uint8_t)(cga_of_ansi[bg] << 4 | (fg & 8) | cga_of_ansi[fg & 7]); +} + +static uint16_t blank(const struct term *t) +{ + return (uint16_t)(attr(t) << 8 | ' '); +} + +static void clear_cells(struct term *t, int row, int c0, int c1) +{ + int c; + + for (c = c0; c < c1 && c < TERM_COLS; c++) + t->cell[row][c] = blank(t); + t->dirty = 1; +} + +/* scroll rows top..bottom up by n (down if n < 0) */ +static void scroll(struct term *t, int top, int bottom, int n) +{ + int r, h = bottom - top + 1; + + if (n > h) + n = h; + if (n < -h) + n = -h; + if (n > 0) + { + memmove(t->cell[top], t->cell[top + n], (size_t)(h - n) * sizeof(t->cell[0])); + for (r = bottom - n + 1; r <= bottom; r++) + clear_cells(t, r, 0, TERM_COLS); + } + else if (n < 0) + { + n = -n; + memmove(t->cell[top + n], t->cell[top], (size_t)(h - n) * sizeof(t->cell[0])); + for (r = top; r < top + n; r++) + clear_cells(t, r, 0, TERM_COLS); + } + t->dirty = 1; +} + +static void line_feed(struct term *t) +{ + if (t->row == t->bottom) + scroll(t, t->top, t->bottom, 1); + else if (t->row < TERM_ROWS - 1) + t->row++; +} + +static void reset(struct term *t) +{ + struct buf *reply = t->reply; + int r; + + memset(t, 0, sizeof(*t)); + t->reply = reply; + t->fg = 7; + t->bottom = TERM_ROWS - 1; + t->cursor_on = 1; + t->autowrap = 1; + for (r = 0; r < TERM_ROWS; r++) + clear_cells(t, r, 0, TERM_COLS); +} + +void term_init(struct term *t, struct buf *reply) +{ + t->reply = reply; + reset(t); +} + +static void put_glyph(struct term *t, uint8_t ch) +{ + if (t->wrap_pending) + { + t->col = 0; + line_feed(t); + t->wrap_pending = 0; + } + t->cell[t->row][t->col] = (uint16_t)(attr(t) << 8 | ch); + t->dirty = 1; + if (t->col == TERM_COLS - 1) + t->wrap_pending = t->autowrap; + else + t->col++; +} + +/* DEC special graphics (ESC ( 0) to code page 437 */ +static uint8_t dec_graphics(uint8_t c) +{ + switch (c) + { + case 'j': return 0xd9; case 'k': return 0xbf; case 'l': return 0xda; case 'm': return 0xc0; + case 'n': return 0xc5; case 'q': return 0xc4; case 't': return 0xc3; case 'u': return 0xb4; + case 'v': return 0xc1; case 'w': return 0xc2; case 'x': return 0xb3; case 'a': return 0xb1; + case '`': return 0x04; case 'f': return 0xf8; case 'g': return 0xf1; case '~': return 0xfa; + case 'y': return 0xf3; case 'z': return 0xf2; case '0': return 0xdb; + } + return c; +} + +static int par(const struct term *t, int i, int def) +{ + return i < t->nparams && t->params[i] > 0 ? t->params[i] : def; +} + +static void clamp(struct term *t) +{ + if (t->row < 0) t->row = 0; + if (t->row >= TERM_ROWS) t->row = TERM_ROWS - 1; + if (t->col < 0) t->col = 0; + if (t->col >= TERM_COLS) t->col = TERM_COLS - 1; + t->wrap_pending = 0; + t->dirty = 1; +} + +/* 256-colour / RGB to the nearest of the 16 ANSI colours */ +static int nearest16(int r, int g, int b) +{ + static const uint8_t pal[16][3] = { + {0,0,0},{170,0,0},{0,170,0},{170,85,0},{0,0,170},{170,0,170},{0,170,170},{170,170,170}, + {85,85,85},{255,85,85},{85,255,85},{255,255,85},{85,85,255},{255,85,255},{85,255,255},{255,255,255} + }; + int i, best = 0; + long bd = 1L << 30; + + for (i = 0; i < 16; i++) + { + long d = (long)(r - pal[i][0]) * (r - pal[i][0]) + (long)(g - pal[i][1]) * (g - pal[i][1]) + + (long)(b - pal[i][2]) * (b - pal[i][2]); + if (d < bd) + { + bd = d; + best = i; + } + } + return best; +} + +static int color256(int n) +{ + if (n < 16) + return n; + if (n >= 232) + { + int v = 8 + (n - 232) * 10; + return nearest16(v, v, v); + } + n -= 16; + return nearest16((n / 36) ? (n / 36) * 40 + 55 : 0, ((n / 6) % 6) ? ((n / 6) % 6) * 40 + 55 : 0, + (n % 6) ? (n % 6) * 40 + 55 : 0); +} + +static void sgr(struct term *t) +{ + int i; + + if (!t->nparams) + t->nparams = 1, t->params[0] = 0; + for (i = 0; i < t->nparams; i++) + { + int p = t->params[i]; + if (p == 0) + { + t->fg = 7; + t->bg = 0; + t->bold = t->reverse = 0; + } + else if (p == 1) t->bold = 1; + else if (p == 22) t->bold = 0; + else if (p == 7) t->reverse = 1; + else if (p == 27) t->reverse = 0; + else if (p >= 30 && p <= 37) t->fg = (uint8_t)(p - 30); + else if (p == 39) t->fg = 7; + else if (p >= 40 && p <= 47) t->bg = (uint8_t)(p - 40); + else if (p == 49) t->bg = 0; + else if (p >= 90 && p <= 97) t->fg = (uint8_t)(p - 90 + 8); + else if (p >= 100 && p <= 107) t->bg = (uint8_t)(p - 100); + else if ((p == 38 || p == 48) && i + 1 < t->nparams) + { + int c = -1; + if (t->params[i + 1] == 5 && i + 2 < t->nparams) + { + c = color256(t->params[i + 2]); + i += 2; + } + else if (t->params[i + 1] == 2 && i + 4 < t->nparams) + { + c = nearest16(t->params[i + 2], t->params[i + 3], t->params[i + 4]); + i += 4; + } + if (c >= 0) + { + if (p == 38) + t->fg = (uint8_t)c; + else + t->bg = (uint8_t)(c & 7); + } + } + } +} + +static void reply(struct term *t, const char *s) +{ + if (t->reply) + put_bytes(t->reply, s, strlen(s)); +} + +static void set_mode(struct term *t, int on) +{ + int i; + + for (i = 0; i < t->nparams; i++) + { + int p = t->params[i]; + if (!t->priv) + continue; /* ANSI modes (insert ...) not supported */ + if (p == 1) + t->app_cursor = on; + else if (p == 7) + t->autowrap = on; + else if (p == 25) + { + t->cursor_on = on; + t->dirty = 1; + } + else if ((p == 47 || p == 1047 || p == 1049) && on != t->alt) + { + int r; + if (on) + { + if (p == 1049) + t->srow = t->row, t->scol = t->col; + memcpy(t->saved, t->cell, sizeof(t->cell)); + for (r = 0; r < TERM_ROWS; r++) + clear_cells(t, r, 0, TERM_COLS); + } + else + { + memcpy(t->cell, t->saved, sizeof(t->cell)); + if (p == 1049) + t->row = t->srow, t->col = t->scol; + } + t->alt = on; + t->dirty = 1; + } + } +} + +static void csi(struct term *t, uint8_t f) +{ + int n = par(t, 0, 1), r; + + switch (f) + { + case 'A': t->row -= n; if (t->row < t->top && t->row + n >= t->top) t->row = t->top; clamp(t); break; + case 'B': t->row += n; if (t->row > t->bottom && t->row - n <= t->bottom) t->row = t->bottom; clamp(t); break; + case 'C': t->col += n; clamp(t); break; + case 'D': t->col -= n; clamp(t); break; + case 'E': t->row += n; t->col = 0; clamp(t); break; + case 'F': t->row -= n; t->col = 0; clamp(t); break; + case 'G': case '`': t->col = n - 1; clamp(t); break; + case 'd': t->row = n - 1; clamp(t); break; + case 'H': case 'f': t->row = par(t, 0, 1) - 1; t->col = par(t, 1, 1) - 1; clamp(t); break; + case 'J': + { + int m = t->nparams ? t->params[0] : 0; + if (m == 0) + { + clear_cells(t, t->row, t->col, TERM_COLS); + for (r = t->row + 1; r < TERM_ROWS; r++) + clear_cells(t, r, 0, TERM_COLS); + } + else if (m == 1) + { + clear_cells(t, t->row, 0, t->col + 1); + for (r = 0; r < t->row; r++) + clear_cells(t, r, 0, TERM_COLS); + } + else + for (r = 0; r < TERM_ROWS; r++) + clear_cells(t, r, 0, TERM_COLS); + break; + } + case 'K': + { + int m = t->nparams ? t->params[0] : 0; + clear_cells(t, t->row, m == 0 ? t->col : 0, m == 1 ? t->col + 1 : TERM_COLS); + break; + } + case 'L': + if (t->row >= t->top && t->row <= t->bottom) + scroll(t, t->row, t->bottom, -n); + break; + case 'M': + if (t->row >= t->top && t->row <= t->bottom) + scroll(t, t->row, t->bottom, n); + break; + case 'P': + if (n > TERM_COLS - t->col) + n = TERM_COLS - t->col; + memmove(&t->cell[t->row][t->col], &t->cell[t->row][t->col + n], + (size_t)(TERM_COLS - t->col - n) * 2); + clear_cells(t, t->row, TERM_COLS - n, TERM_COLS); + break; + case '@': + if (n > TERM_COLS - t->col) + n = TERM_COLS - t->col; + memmove(&t->cell[t->row][t->col + n], &t->cell[t->row][t->col], + (size_t)(TERM_COLS - t->col - n) * 2); + clear_cells(t, t->row, t->col, t->col + n); + break; + case 'X': clear_cells(t, t->row, t->col, t->col + n); break; + case 'S': scroll(t, t->top, t->bottom, n); break; + case 'T': scroll(t, t->top, t->bottom, -n); break; + case 'm': sgr(t); break; + case 'r': + { + int top = par(t, 0, 1) - 1, bottom = par(t, 1, TERM_ROWS) - 1; + if (bottom >= TERM_ROWS) + bottom = TERM_ROWS - 1; + if (top < bottom) + { + t->top = top; + t->bottom = bottom; + t->row = t->col = 0; + clamp(t); + } + break; + } + case 's': t->srow = t->row; t->scol = t->col; break; + case 'u': t->row = t->srow; t->col = t->scol; clamp(t); break; + case 'h': set_mode(t, 1); break; + case 'l': set_mode(t, 0); break; + case 'n': + if (par(t, 0, 0) == 6) + { + char s[40]; + snprintf(s, sizeof(s), "\033[%d;%dR", t->row + 1, t->col + 1); + reply(t, s); + } + else if (par(t, 0, 0) == 5) + reply(t, "\033[0n"); + break; + case 'c': + if (!t->priv) + reply(t, "\033[?1;2c"); + break; + } +} + +static void control(struct term *t, uint8_t c) +{ + switch (c) + { + case '\r': t->col = 0; t->wrap_pending = 0; break; + case '\n': case 0x0b: case 0x0c: line_feed(t); t->wrap_pending = 0; break; + case '\b': if (t->col > 0) t->col--; t->wrap_pending = 0; break; + case '\t': + t->col = (t->col / 8 + 1) * 8; + if (t->col >= TERM_COLS) + t->col = TERM_COLS - 1; + break; + case 0x0e: case 0x0f: break; /* SO/SI: G1 not supported */ + } + t->dirty = 1; +} + +void term_write(struct term *t, const uint8_t *p, size_t n) +{ + size_t i; + + for (i = 0; i < n; i++) + { + uint8_t c = p[i]; + switch (t->state) + { + case S_GROUND: + if (c == 0x1b) + { + t->state = S_ESC; + t->utf_left = 0; + } + else if (c < 0x20) + control(t, c); + else if (c < 0x80) + { + t->utf_left = 0; + put_glyph(t, t->g0_lines ? dec_graphics(c) : c); + } + else if (c >= 0xc0) /* UTF-8 lead byte */ + { + t->utf_left = c >= 0xf0 ? 3 : c >= 0xe0 ? 2 : 1; + t->utf = c & (0x3f >> t->utf_left); + } + else if (t->utf_left) /* continuation */ + { + t->utf = t->utf << 6 | (c & 0x3f); + if (!--t->utf_left) + { + uint8_t g = cp437_from_unicode(t->utf); + put_glyph(t, g ? g : '?'); + } + } + break; + case S_ESC: + t->state = S_GROUND; + switch (c) + { + case '[': + t->state = S_CSI; + t->nparams = 0; + t->priv = 0; + memset(t->params, 0, sizeof(t->params)); + break; + case ']': t->state = S_OSC; break; + case '(': t->state = S_CHARSET; t->priv = 0; break; + case ')': case '*': case '+': t->state = S_CHARSET; t->priv = -1; break; + case '7': t->srow = t->row; t->scol = t->col; break; + case '8': t->row = t->srow; t->col = t->scol; clamp(t); break; + case 'D': line_feed(t); break; + case 'E': t->col = 0; line_feed(t); break; + case 'M': + if (t->row == t->top) + scroll(t, t->top, t->bottom, -1); + else if (t->row > 0) + t->row--; + break; + case 'c': reset(t); break; + } + break; + case S_CHARSET: + if (t->priv != -1) + t->g0_lines = c == '0'; + t->priv = 0; + t->state = S_GROUND; + break; + case S_CSI: + if (c >= '0' && c <= '9') + { + if (!t->nparams) + t->nparams = 1; + if (t->params[t->nparams - 1] < 10000) + t->params[t->nparams - 1] = t->params[t->nparams - 1] * 10 + (c - '0'); + } + else if (c == ';' || c == ':') + { + if (!t->nparams) + t->nparams = 1; + if (t->nparams < 16) + t->nparams++; + } + else if (c == '?' || c == '>' || c == '=') + t->priv = 1; + else if (c >= 0x40 && c <= 0x7e) + { + t->state = S_GROUND; + csi(t, c); + } + else if (c < 0x20) + control(t, c); + break; + case S_OSC: /* window titles etc.: ignored */ + if (c == 0x07) + t->state = S_GROUND; + else if (c == 0x1b) + t->state = S_OSC_ESC; + break; + case S_OSC_ESC: + t->state = c == '\\' ? S_GROUND : S_OSC; + break; + } + } +} + +void term_key(struct term *t, uint16_t key, struct buf *out) +{ + uint8_t ascii = (uint8_t)key, scan = (uint8_t)(key >> 8); + const char *seq = NULL; + char tmp[8]; + + if (ascii && ascii != 0xe0) + { + if (ascii == 0x08) + ascii = 0x7f; /* Backspace: DEL, as xterm */ + if (ascii >= 0x80) /* CP437 -> UTF-8 */ + { + uint32_t u = cp437_to_unicode(ascii); + if (u < 0x800) + { + tmp[0] = (char)(0xc0 | u >> 6); + tmp[1] = (char)(0x80 | (u & 0x3f)); + put_bytes(out, tmp, 2); + } + else + { + tmp[0] = (char)(0xe0 | u >> 12); + tmp[1] = (char)(0x80 | ((u >> 6) & 0x3f)); + tmp[2] = (char)(0x80 | (u & 0x3f)); + put_bytes(out, tmp, 3); + } + return; + } + put_u8(out, ascii); + return; + } + switch (scan) + { + case 0x48: seq = t->app_cursor ? "\033OA" : "\033[A"; break; + case 0x50: seq = t->app_cursor ? "\033OB" : "\033[B"; break; + case 0x4d: seq = t->app_cursor ? "\033OC" : "\033[C"; break; + case 0x4b: seq = t->app_cursor ? "\033OD" : "\033[D"; break; + case 0x47: seq = t->app_cursor ? "\033OH" : "\033[H"; break; + case 0x4f: seq = t->app_cursor ? "\033OF" : "\033[F"; break; + case 0x49: seq = "\033[5~"; break; + case 0x51: seq = "\033[6~"; break; + case 0x52: seq = "\033[2~"; break; + case 0x53: seq = "\033[3~"; break; + case 0x3b: seq = "\033OP"; break; + case 0x3c: seq = "\033OQ"; break; + case 0x3d: seq = "\033OR"; break; + case 0x3e: seq = "\033OS"; break; + case 0x3f: seq = "\033[15~"; break; + case 0x40: seq = "\033[17~"; break; + case 0x41: seq = "\033[18~"; break; + case 0x42: seq = "\033[19~"; break; + case 0x43: seq = "\033[20~"; break; + case 0x44: seq = "\033[21~"; break; + case 0x85: seq = "\033[23~"; break; + case 0x86: seq = "\033[24~"; break; + case 0x03: seq = ""; put_u8(out, 0); break; /* Ctrl+2: NUL */ + } + if (seq) + put_bytes(out, seq, strlen(seq)); +} diff --git a/net/ssh/term.h b/net/ssh/term.h new file mode 100644 index 00000000..16c38f0c --- /dev/null +++ b/net/ssh/term.h @@ -0,0 +1,33 @@ +/* terminal emulator for the SSH client: a subset of xterm (VT100/ANSI) + on an 80x25 text screen of CP437 cells with CGA attributes */ +#ifndef TERM_H +#define TERM_H +#include +#include "buf.h" + +#define TERM_COLS 80 +#define TERM_ROWS 25 + +struct term { + uint16_t cell[TERM_ROWS][TERM_COLS]; /* attribute << 8 | character */ + uint16_t saved[TERM_ROWS][TERM_COLS]; /* main screen while the alternate shows */ + int row, col, wrap_pending; + int top, bottom; /* scrolling region */ + uint8_t fg, bg; /* ANSI colours 0..15 */ + int bold, reverse; + int cursor_on, app_cursor, autowrap, alt; + int g0_lines; /* DEC special graphics in G0 */ + int srow, scol; /* saved cursor */ + int state; /* parser */ + int params[16], nparams, priv; + uint32_t utf, utf_left; /* UTF-8 decoder */ + int dirty; + struct buf *reply; /* answers (DSR, DA) for the host */ +}; + +void term_init(struct term *t, struct buf *reply); +void term_write(struct term *t, const uint8_t *p, size_t n); +/* a key from the BIOS (scan << 8 | ASCII) -> bytes for the host */ +void term_key(struct term *t, uint16_t key, struct buf *out); + +#endif diff --git a/release/README.TXT b/release/README.TXT new file mode 100644 index 00000000..07c03377 --- /dev/null +++ b/release/README.TXT @@ -0,0 +1,77 @@ +modernDOS (alpha) +================= + +DOS, reimagined as if it never faded. A fork of the FreeDOS kernel with +a 32-bit supervisor (MDVMM): DOS runs in a virtual 8086 machine, with a +DPMI host, several DOS sessions, and boot on modern UEFI PCs. + +THIS IS AN ALPHA. It has been tested in QEMU (OVMF and SeaBIOS) only. +Expect it to fail on some real machines. + +Booting +------- +Write the ISO to a USB stick with a raw image writer (dd, balenaEtcher, +Rufus in "DD image" mode), or burn it to a CD. + + UEFI PCs: boot the stick in UEFI mode. Secure Boot must be OFF + (BOOTX64.EFI is not signed). No CSM needed. + BIOS PCs: boot from CD (El Torito floppy emulation). Booting the + USB stick needs UEFI. + +On UEFI, MDVMM starts first and provides the PC BIOS that DOS expects: +text console on the firmware's framebuffer (GOP, or UGA on older Apple +firmware), keyboard (PS/2, or USB on xHCI and UHCI controllers, also +behind hubs), USB mouse (INT 33h), timer, SATA (AHCI) and NVMe disks, VBE +graphics, extended memory for XMS. DOS then boots from \MDOS\BOOT.IMG (drive A:, a RAM +copy: changes to A: are lost at reboot). + +Each UEFI boot writes two files to the stick, in \MDOS: + HWINFO.TXT hardware report (firmware, model, CPU, graphics, PCI) + BOOTLOG.TXT what the loader did, up to the start of the monitor +The monitor then shows its own log on the screen until DOS starts; a file +\MDOS\BOOTWAIT keeps that log visible for 15 seconds. If a machine +does not boot, these two files and a photo of the screen say why. + +Hard disks are READ-ONLY by default. DOS can see FAT partitions on the +internal disks, including the EFI system partition of an installed OS. +To allow writes, create a file \MDOS\DISKRW on the boot medium - +at your own risk. + +At the DOS prompt +----------------- + MDDESK the desktop: launcher (About, Files, Editor, + Settings, Run a DOS program, Exit), window list, clock + MDVMM on UEFI: mouse driver and DOS sessions; on BIOS PCs: + start the virtual machine monitor (needs HIMEMX) + MDVMM NEW start another DOS session; Ctrl+Alt+F1..F4 switch + GFXDEMO draw a test picture in graphics mode for 3 seconds + +Network (new, little tested on real machines) +--------------------------------------------- + NET the SSH server, with a local prompt on Ctrl+Alt+F4. + AUTOEXEC.BAT has started the packet driver PKTDRV (on + MDVMM's card drivers: on UEFI boots iPXE's, for most PCI + network cards) and two DOS sessions for remote shells. + Needs AUTHKEYS.TXT (public keys, authorized_keys format) + or a password (SSHD /PASSWD). Addresses come from DHCP + (WATTCP.CFG). + SSH SSH client: SSH user@host [command], SSH /KEYGEN + MDLOG the monitor's log; MDLOG /N adds the network card's state + MDSYS kind of boot; MDSYS REBOOT restarts the machine + PKG package manager (UEFI boots): PKG UPDATE, LIST, INSTALL +In the desktop (MDDESK): Terminal (a DOS prompt in a window) +and Browser (http and https pages as text). +The BIOS edition (the -bios.img disk image) has INSTALL: it puts +modernDOS on the machine's hard disk (INSTALL alone says how). +A stick made as a personal image offers to install modernDOS on the +machine's disk; an installed machine is updated over SSH (TRYBOOT, KEEP). +From another machine: ssh, sftp and scp to the address SSHD prints; DOS +drives appear as /A, /C, ... +A file \MDOS\NONET on the stick turns the network card drivers off. + +Not yet: starting 32-bit DPMI programs from the desktop or in an SSH +session (one at a time), USB devices plugged in after the start, USB +storage, other network cards. + +Source: https://github.com/kaleaditya28897-linux/modernDOS (branch modern) +License: GNU GPL v2 (see COPYING). FreeCOM and HIMEMX are from FreeDOS. diff --git a/release/build.sh b/release/build.sh new file mode 100755 index 00000000..02195374 --- /dev/null +++ b/release/build.sh @@ -0,0 +1,353 @@ +#!/bin/bash +# Build the modernDOS release ISO (runs inside the build container, after +# scripts/mdbuild.sh). Output: _output/release/modernDOS-$VERSION.iso +# +# The ISO boots three ways (UEFI from CD and from a stick, BIOS from CD): +# - UEFI, from CD or USB stick (dd): an El Torito EFI image that is also +# an appended GPT partition (EFI system partition) holding +# \EFI\BOOT\BOOTX64.EFI and \MDOS\BOOT.IMG +# - BIOS, from CD: El Torito hard disk emulation of the BIOS disk image +# (the BIOS edition, read-only there; INSTALL puts it on the hard disk) +# BOOT.IMG is a DOS disk image: kernel, FreeCOM, HIMEMX, MDDESK, CTMOUSE (BIOS +# boots; on UEFI boots MDVMM installs the virtual BIOS mouse driver), MDVMM, +# demo, and the network programs: PKTDRV (packet driver on MDVMM's network +# card drivers), SSHSLOT, SSHD, SSH, PKG, MDLOG, MDSYS, NET.BAT: 8 MB, the +# UEFI edition's boot disk. The BIOS edition is a hard disk image of its +# own (below), also released as modernDOS-$VERSION-bios.img. +# +# A personal image for one's own machine: PERSONAL= adds the files of +# that directory to BOOT.IMG, typically AUTHKEYS.TXT (public keys allowed +# to log in) and HOSTKEY.ED (32 random bytes: the SSH host key, so it stays +# the same over reboots; A: is a RAM disk). With a file AUTONET on the disk +# AUTOEXEC.BAT starts the network and the SSH server (NET.BAT). Never +# publish such an image: it contains the host's private key. +# +# On UEFI boots the loader writes \MDOS\HWINFO.TXT (hardware report) +# and \MDOS\BOOTLOG.TXT (its own log) to the stick. A version ending +# in "-dev" is a diagnostic build: it also has \MDOS\BOOTWAIT, which +# keeps the monitor's boot log on the screen for 15 seconds. +# +# Usage: release/build.sh [version] + +set -e +VERSION=${1:-0.0.1-alpha} +ROOT=$(cd "$(dirname "$0")/.." && pwd) +HERE="$ROOT/release" +TEST="$ROOT/test" +KERNEL="$ROOT/_output/gcc/kgc8632.sys" +OUT="$ROOT/_output/release" +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +. "$TEST/cfg.sh" +export MTOOLS_SKIP_CHECK=1 + +[ -f "$KERNEL" ] || { echo "no $KERNEL: run scripts/mdbuild.sh first"; exit 1; } +make -s -C "$ROOT/mdvmm" +make -s -C "$ROOT/gui" +make -s -C "$ROOT/net/ssh" +make -s -C "$ROOT/net/pkg" +/opt/djgpp/bin/i586-pc-msdosdjgpp-gcc -O2 -s -I"$ROOT/gui/lib" -o "$WORK/gfxdemo.exe" \ + "$ROOT/tests/gui/gfxtest.c" "$ROOT/gui/build/mdgui.o" + +echo "== BOOT.IMG" +cd "$WORK" +printf 'DEVICE=A:\\HIMEMX.EXE\r\nDOS=HIGH\r\nSHELL=A:\\COMMAND.COM A:\\ /E:1024 /P\r\n' > fdconfig.sys +cat > autoexec.bat <NUL +A:\\MDVMM.COM +REM the packet driver, then DOS sessions for the desktop's terminal and for +REM remote shells (this order: every session gets the network) +A:\\PKTDRV.COM >NUL +A:\\SSHSLOT.COM 2 >NUL +REM installed on a disk: C:\\MDOS keeps the SSH keys and settings +REM (not on a start from a stick: the machine's disks are read-only then) +A:\\MDSYS.COM DISK +IF ERRORLEVEL 1 GOTO NODISK +IF NOT EXIST C:\\MDOS\\BOOT.IMG GOTO NODISK +IF EXIST C:\\MDOS\\SSH\\HOSTKEY.ED GOTO HAVESSH +MD C:\\MDOS\\SSH +IF EXIST A:\\AUTHKEYS.TXT COPY A:\\AUTHKEYS.TXT C:\\MDOS\\SSH >NUL +IF EXIST A:\\HOSTKEY.ED COPY A:\\HOSTKEY.ED C:\\MDOS\\SSH >NUL +COPY A:\\WATTCP.CFG C:\\MDOS\\SSH >NUL +:HAVESSH +SET SSHDIR=C:\\MDOS\\SSH +SET WATTCP.CFG=C:\\MDOS\\SSH +SET TEMP=C:\\MDOS +SET PKGDIR=C:\\MDOS +IF EXIST C:\\MDOS\\SSH\\AUTHKEYS.TXT CALL A:\\NET.BAT +GOTO END +:NODISK +IF EXIST A:\\AUTONET CALL A:\\NET.BAT +IF EXIST A:\\AUTONET GOTO END +REM a personal stick: its keys are on A: +IF EXIST A:\\AUTHKEYS.TXT CALL A:\\NET.BAT +:END +EOF +cat > tryboot.bat < C:\\MDOS\\TRYONCE +A:\\MDSYS.COM REBOOT +:MISSING +ECHO Put BOOTX64.EFI and BOOT.IMG into C:\\MDOS\\TRY first. +EOF +cat > keep.bat < net.bat < wattcp.cfg +sed -i 's/$/\r/' autoexec.bat net.bat tryboot.bat keep.bat +sed 's/$/\r/' "$HERE/README.TXT" > readme.txt + +# make_image file sectors per-cluster FAT-sectors sectors-per-track: a FAT12 +# boot disk image with the kernel +make_image() { + "$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_LBA=0 -D_USE_PART_INFO=0 -D_QUERY_GEOMETRY=0 \ + -D_FAT12 -D_UNIT=00h -D_CHS_SECTORS=$5 -D_CHS_HEADS=2 -o boot.bin + "$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,fdconfig.sys" \ + -D_BOOTPATCHFILE="'boot.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR_PART_TYPE=ptFAT12 -D_BPE=12 -D_SPC=$3 -D_SPI=$2 \ + -D_SPF=$4 -D_NUMROOT=224 -D_CHS_SECTORS=$5 -D_CHS_HEADS=2 -D_UNIT=00h -o "$1" +} +# put name=file ... image: files onto an image +put() { + local img=$1 f; shift + for f in "$@"; do mcopy -i "$img" "${f#*=}" "::${f%%=*}"; done +} +BASE="COMMAND.COM=/opt/fdos/bin/command.com HIMEMX.EXE=/opt/fdos/bin/himemx.exe + AUTOEXEC.BAT=autoexec.bat README.TXT=readme.txt MDVMM.COM=$ROOT/mdvmm/build/MDVMM.COM + GFXDEMO.EXE=gfxdemo.exe MDDESK.EXE=$ROOT/gui/build/MDDESK.EXE CTMOUSE.EXE=/opt/fdos/bin/ctmouse.exe + PKTDRV.COM=$ROOT/mdvmm/build/PKTDRV.COM SSHSLOT.COM=$ROOT/mdvmm/build/SSHSLOT.COM + MDLOG.COM=$ROOT/mdvmm/build/MDLOG.COM MDSYS.COM=$ROOT/mdvmm/build/MDSYS.COM + SSHD.EXE=$ROOT/net/ssh/build/sshd.exe NET.BAT=net.bat TRYBOOT.BAT=tryboot.bat KEEP.BAT=keep.bat + WATTCP.CFG=wattcp.cfg" +# and the programs that did not fit the 2.88 MB floppy image of old +MORE="SSH.EXE=$ROOT/net/ssh/build/ssh.exe PKG.EXE=$ROOT/net/pkg/build/pkg.exe" + +# uefi.img, the UEFI edition's boot disk (a RAM disk A: there): 8 MB (130 +# cylinders, 2 heads, 63 sectors) +make_image uefi.img 16380 8 6 63 +put uefi.img $BASE $MORE +if [ -n "$PERSONAL" ]; then + for f in "$PERSONAL"/*; do + [ -f "$f" ] || continue + mcopy -i uefi.img "$f" "::$(basename "$f" | tr a-z A-Z)" + done + echo "personal image: files of $PERSONAL added - do not publish it" +fi +mdir -i uefi.img :: + +# The BIOS edition: a hard disk image (MBR, one active 64 MB FAT16 +# partition) for a USB stick or a disk, started by a PC BIOS. The system is +# in C:\MDOS; C: is the stick or disk itself, so everything is kept. +echo "== BIOS disk image" +mkdir -p hd +printf 'DEVICE=C:\\MDOS\\HIMEMX.EXE\r\nDOS=HIGH\r\nSHELL=C:\\COMMAND.COM C:\\ /E:1024 /P\r\n' > hd/fdconfig.sys +cat > hd/autoexec.bat <NUL +MDVMM.COM +REM the packet driver, then DOS sessions for remote shells (this order: +REM every session gets the network) +PKTDRV.COM >NUL +SSHSLOT.COM 2 >NUL +IF EXIST C:\\MDOS\\SSH\\AUTHKEYS.TXT CALL C:\\MDOS\\NET.BAT +EOF +cat > hd/install.bat <NUL +COPY /Y C:\\AUTOEXEC.BAT D:\\ >NUL +FDISK 2 /ACTIVATE:1 +ECHO. +ECHO modernDOS is installed. Take the stick out and restart (MDSYS REBOOT). +GOTO END +:NODRIVE +ECHO There is no drive D: - the disk has no FAT partition (see INSTALL NEW). +GOTO END +:FAILED +ECHO INSTALL: that did not work; nothing more was done. +:END +EOF +sed -i 's/$/\r/' hd/autoexec.bat hd/install.bat +"$NASM" -f bin -o mbr.bin "$HERE/mbr.asm" +# CHS only: the partition is small and near the start of the disk, and +# old BIOSes have nothing else +"$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_FAT16=1 -D_UNIT=80h -D_LBA=0 -D_RPL=0 -o boot16.bin +"$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,hd/fdconfig.sys,hd/autoexec.bat" \ + -D_BOOTPATCHFILE="'boot16.bin'" -D_MBRPATCHFILE="'mbr.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR -D_MBR_PART_TYPE=ptFAT16 -D_BPE=16 -D_SPC=4 -D_SPI=131072 -D_SPF=128 \ + -D_NUMROOT=512 -D_CHS_SECTORS=63 -D_CHS_HEADS=16 -D_UNIT=80h -o bios.img +HD="bios.img@@$((1008 * 512))" # the partition (after one cylinder) +mcopy -i "$HD" /opt/fdos/bin/command.com ::COMMAND.COM +mmd -i "$HD" ::/MDOS ::/MDOS/SSH ::/MDOS/TEMP +for f in $BASE $MORE; do + case "${f%%=*}" in + COMMAND.COM|AUTOEXEC.BAT|TRYBOOT.BAT|KEEP.BAT|WATTCP.CFG) ;; # not here / UEFI only + *) mcopy -i "$HD" "${f#*=}" "::/MDOS/${f%%=*}" ;; + esac +done +mcopy -i "$HD" wattcp.cfg ::/MDOS/SSH/WATTCP.CFG +# INSTALL and what it needs: the kernel's SYS, FreeDOS FDISK, FORMAT, XCOPY +mcopy -i "$HD" hd/install.bat ::/MDOS/INSTALL.BAT +mcopy -i "$HD" "$ROOT/sys/sys.com" ::/MDOS/SYS.COM +mcopy -i "$HD" /opt/fdos/bin/fdisk.exe ::/MDOS/FDISK.EXE +mcopy -i "$HD" /opt/fdos/bin/fdisk.ini ::/MDOS/FDISK.INI +mcopy -i "$HD" /opt/fdos/bin/format.exe ::/MDOS/FORMAT.EXE +mcopy -i "$HD" /opt/fdos/bin/xcopy.exe ::/MDOS/XCOPY.EXE +if [ -n "$PERSONAL" ]; then + for f in "$PERSONAL"/*; do + [ -f "$f" ] && mcopy -i "$HD" "$f" "::/MDOS/SSH/$(basename "$f" | tr a-z A-Z)" + done +fi +mdir -i "$HD" ::/MDOS | tail -3 + +echo "== EFI system partition image" +# 30 MB, FAT16: an El Torito EFI image must stay below 32 MB (16 bit sector +# count), which rules out FAT32; room for the report files and more +dd if=/dev/zero of=efiboot.img bs=1M count=30 status=none +mformat -i efiboot.img -v MODERNDOS :: +mmd -i efiboot.img ::/EFI ::/EFI/BOOT ::/MDOS +mcopy -i efiboot.img "$ROOT/mdvmm/build/BOOTX64.EFI" ::/EFI/BOOT/BOOTX64.EFI +mcopy -i efiboot.img uefi.img ::/MDOS/BOOT.IMG +mcopy -i efiboot.img readme.txt ::/README.TXT +if [ -n "$PERSONAL" ]; then + # a personal stick offers to install itself on the machine's disk + printf 'The loader offers to install modernDOS on the internal disk.\r\n' > install + mcopy -i efiboot.img install ::/MDOS/INSTALL +fi +case "$VERSION" in + *-dev*) + printf 'Keeps the boot log on the screen for 15 seconds. Delete this file to boot faster.\r\n' > bootwait + mcopy -i efiboot.img bootwait ::/MDOS/BOOTWAIT + echo "diagnostic build: \\MDOS\\BOOTWAIT added" ;; +esac +minfo -i efiboot.img :: | grep -i "disk type" + +echo "== ISO" +mkdir -p iso/MDOS iso/EFI/BOOT +cp bios.img iso/MDOS/BIOS.IMG +cp "$ROOT/mdvmm/build/BOOTX64.EFI" iso/EFI/BOOT/BOOTX64.EFI +cp readme.txt iso/README.TXT +sed 's/$/\r/' "$ROOT/COPYING" > iso/COPYING.TXT +mkdir -p "$OUT" +ISO="$OUT/modernDOS-$VERSION.iso" +xorriso -as mkisofs -o "$ISO" -V "MODERNDOS" -R -J \ + -b MDOS/BIOS.IMG -hard-disk-boot -c MDOS/BOOT.CAT \ + -eltorito-alt-boot -e --interval:appended_partition_2:all:: -no-emul-boot \ + -append_partition 2 0xef efiboot.img -appended_part_as_gpt \ + iso 2>&1 | grep -v "^xorriso : UPDATE" || true +[ -f "$ISO" ] || { echo "xorriso failed"; exit 1; } +cp bios.img "$OUT/modernDOS-$VERSION-bios.img" +(cd "$OUT" && sha256sum "$(basename "$ISO")" > "$(basename "$ISO").sha256" && + sha256sum "modernDOS-$VERSION-bios.img" > "modernDOS-$VERSION-bios.img.sha256") +ls -l "$OUT" diff --git a/release/mbr.asm b/release/mbr.asm new file mode 100644 index 00000000..bd507e46 --- /dev/null +++ b/release/mbr.asm @@ -0,0 +1,94 @@ +; Master boot record for the modernDOS BIOS disk image: starts the active +; partition's boot sector (LBA when the BIOS has it, else CHS), passing the +; drive in DL and the partition entry in DS:SI. + + cpu 8086 + org 600h + +start: cli + xor ax, ax + mov ss, ax + mov sp, 7c00h + mov ds, ax + mov es, ax + sti + cld + mov si, 7c00h + mov di, 600h + mov cx, 256 + rep movsw + jmp 0:go + +go: mov si, 600h + 1beh + mov cx, 4 +.find: test byte [si], 80h + jnz .found + add si, 16 + loop .find + mov si, msg_none + jmp fail + +.found: mov bp, si + mov [drive], dl + mov di, 3 ; tries +.again: mov ah, 41h ; LBA extensions? + mov bx, 55aah + mov dl, [drive] + int 13h + jc .chs + cmp bx, 0aa55h + jne .chs + test cl, 1 + jz .chs + mov si, dap + mov ax, [bp + 8] + mov [si + 8], ax + mov ax, [bp + 10] + mov [si + 10], ax + mov ah, 42h + mov dl, [drive] + int 13h + jnc .loaded +.chs: mov ax, 0201h + mov bx, 7c00h + mov cx, [bp + 2] + mov dh, [bp + 1] + mov dl, [drive] + int 13h + jnc .loaded + xor ax, ax ; reset, try again + mov dl, [drive] + int 13h + dec di + jnz .again + mov si, msg_read + jmp fail +.loaded: + cmp word [7c00h + 510], 0aa55h + mov si, msg_boot + jne fail + mov si, bp + mov dl, [drive] + jmp 0:7c00h + +fail: lodsb + test al, al + jz .stop + mov ah, 0eh + mov bx, 7 + int 10h + jmp fail +.stop: xor ax, ax + int 16h + int 18h + +msg_none db 'No active partition.', 0 +msg_read db 'Disk read error.', 0 +msg_boot db 'No boot sector on the partition.', 0 +drive db 0 +dap db 16, 0 + dw 1 ; sectors + dw 7c00h, 0 ; to 0:7C00 + dd 0, 0 ; LBA + + times 1b8h - ($ - $$) db 0 diff --git a/scripts/mdbuild.sh b/scripts/mdbuild.sh new file mode 100755 index 00000000..36315d81 --- /dev/null +++ b/scripts/mdbuild.sh @@ -0,0 +1,28 @@ +#!/bin/sh +# Build the modernDOS kernel inside the build container. +# scripts/mdbuild.sh [gcc|wc|all] (default: all) +# Output: _output/gcc/kgc8632.sys, _output/wc/kwc8632.sys (+ .map, country.sys), +# mdvmm/build/MDVMM.COM, mdvmm/build/BOOTX64.EFI, gui/build/mdgui.o +. "$(dirname "$0")/mdenv.sh" +WHICH=${1:-all} +md_run sh -c ' + set -e + build() { # build + make -C country clean >/dev/null + make clean >/dev/null 2>&1 || true + # artifacts of the other compiler are not removed by make clean + find lib drivers kernel boot sys utils setver \( -name "*.obj" -o \ + -name "*.lib" -o -name "*.lnk" -o -name "*.o" \) -delete + make all COMPILER=$1 + mkdir -p _output/$2 + mv -f bin/$3*.map bin/$3*.sys bin/country.sys _output/$2/ + } + case '"$WHICH"' in gcc|all) build gcc gcc kgc ;; esac + case '"$WHICH"' in wc|all) + export PATH=/src/bin:$PATH:$WATCOM/binl64 + build owlinux wc kwc ;; + esac + make -s -C mdvmm + make -s -C gui + ls -l _output/*/k*.sys mdvmm/build/MDVMM.COM mdvmm/build/BOOTX64.EFI gui/build/mdgui.o +' diff --git a/scripts/mdenv.sh b/scripts/mdenv.sh new file mode 100755 index 00000000..3e7f328a --- /dev/null +++ b/scripts/mdenv.sh @@ -0,0 +1,17 @@ +#!/bin/sh +# Shared helpers: build the container image on demand and run a command in it. +set -e +ROOT=$(cd "$(dirname "$0")/.." && pwd) +IMAGE=${MD_IMAGE:-localhost/moderndos-build:latest} +ENGINE=${MD_ENGINE:-podman} + +md_image() { + if ! $ENGINE image exists "$IMAGE" 2>/dev/null; then + $ENGINE build -t "$IMAGE" -f "$ROOT/build/Containerfile" "$ROOT/build" + fi +} + +md_run() { + md_image + $ENGINE run --rm --userns=keep-id -v "$ROOT":/src:Z -w /src "$IMAGE" "$@" +} diff --git a/scripts/mdpush.sh b/scripts/mdpush.sh new file mode 100755 index 00000000..64c1b981 --- /dev/null +++ b/scripts/mdpush.sh @@ -0,0 +1,53 @@ +#!/bin/sh +# Push a build to an installed modernDOS machine over SSH and try it once. +# +# scripts/mdpush.sh [iso] upload and start the trial +# scripts/mdpush.sh keep keep the running trial +# scripts/mdpush.sh status what is running there +# +# The machine restarts into the new build as a TRIAL. If it comes up, test +# it and run "scripts/mdpush.sh keep". If you do nothing (or it does +# not come up on the network), it restarts into the installed build after +# ten minutes by itself. +# iso: a modernDOS ISO built with scripts/mkiso.sh (default: the newest +# *personal* ISO in _output/release: the machine needs its keys). +set -e +ROOT=$(cd "$(dirname "$0")/.." && pwd) +HOST=$1 +[ -n "$HOST" ] || { sed -n '2,13p' "$0"; exit 2; } +SSH="ssh -o ConnectTimeout=15 -o ServerAliveInterval=5 -o ServerAliveCountMax=2 dos@$HOST" + +case "$2" in + keep) $SSH KEEP; exit ;; + status) $SSH MDSYS; exit ;; +esac +ISO=${2:-$(ls -t "$ROOT"/_output/release/*personal*.iso 2>/dev/null | head -1)} +[ -f "$ISO" ] || { echo "no ISO (build one: scripts/mkiso.sh _output/personal)"; exit 1; } +W=$(mktemp -d) +trap 'rm -rf "$W"' EXIT +echo "build: $ISO" +# the two files of a build are on the ISO's EFI partition +. "$ROOT/scripts/mdenv.sh" +cp "$ISO" "$ROOT/_output/push.iso" +md_run sh -c ' + export MTOOLS_SKIP_CHECK=1 + off=$(python3 -c " +import struct +f = open(\"_output/push.iso\", \"rb\"); f.seek(512); h = f.read(92) +lba, n, size = struct.unpack_from(\" "$W/batch" +sftp -b "$W/batch" "dos@$HOST" +echo "uploaded; restarting $HOST into the trial" +$SSH TRYBOOT || true +echo "When it is back: scripts/mdpush.sh $HOST status then scripts/mdpush.sh $HOST keep" diff --git a/scripts/mdtest.sh b/scripts/mdtest.sh new file mode 100755 index 00000000..0e051ddf --- /dev/null +++ b/scripts/mdtest.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# Run the modernDOS test suite in QEMU (headless) inside the build container: +# - upstream boot test (test/test.sh) for every kernel that was built +# - long filename API + DJGPP libc test (tests/lfn/run.sh), GCC kernel +# - MDVMM supervisor: DOS + tests inside the V86 monitor (tests/mdvmm/run.sh) +# - UEFI boot: OVMF -> BOOTX64.EFI -> MDVMM core + virtual BIOS -> DOS +# (tests/uefi/run.sh) +# - release ISO, if built (scripts/mkiso.sh): UEFI CD/USB, BIOS CD boots +# (tests/iso/run.sh) +. "$(dirname "$0")/mdenv.sh" +md_run bash -c ' + rc=0 + for k in _output/gcc/kgc8632.sys _output/wc/kwc8632.sys; do + [ -f "$k" ] || continue + (cd test && ./test.sh ../$k disk_t boot_t "boot $(basename $k): ") || rc=1 + done + tests/lfn/run.sh _output/gcc/kgc8632.sys || rc=1 + tests/mdvmm/run.sh _output/gcc/kgc8632.sys || rc=1 + tests/uefi/run.sh _output/gcc/kgc8632.sys || rc=1 + tests/usb/run.sh _output/gcc/kgc8632.sys || rc=1 + tests/net/run.sh _output/gcc/kgc8632.sys || rc=1 + tests/ssh/host.sh || rc=1 + tests/ssh/run.sh _output/gcc/kgc8632.sys || rc=1 + tests/install/run.sh _output/gcc/kgc8632.sys || rc=1 + tests/bios/run.sh || rc=1 + tests/compat/run.sh || rc=1 + tests/compat/uefi.sh _output/gcc/kgc8632.sys || rc=1 + tests/compat/game.sh _output/gcc/kgc8632.sys || rc=1 + tests/pkg/host.sh || rc=1 + tests/pkg/run.sh _output/gcc/kgc8632.sys || rc=1 + for iso in _output/release/*.iso; do + [ -f "$iso" ] && { tests/iso/run.sh "$iso" || rc=1; } + done + exit $rc +' diff --git a/scripts/mkiso.sh b/scripts/mkiso.sh new file mode 100755 index 00000000..25abf9d6 --- /dev/null +++ b/scripts/mkiso.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Build the release ISO inside the build container (after scripts/mdbuild.sh). +# scripts/mkiso.sh [version] [personal-dir] (default: 0.0.1-alpha) +# personal-dir (inside the repository, e.g. _output/personal): files added +# to the boot disk, see release/build.sh. Such an image is for one's own +# machine only. +# Output: _output/release/modernDOS-.iso (+ .sha256) +. "$(dirname "$0")/mdenv.sh" +if [ -n "$2" ]; then + md_run env PERSONAL="/src/$2" release/build.sh "$1" +else + md_run release/build.sh "$@" +fi diff --git a/scripts/mkrepo.sh b/scripts/mkrepo.sh new file mode 100755 index 00000000..ffe44ef0 --- /dev/null +++ b/scripts/mkrepo.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Make a package repository for PKG (runs the tools in the build container). +# +# scripts/mkrepo.sh [keyfile] +# +# has a directory per package: +# /PKGINFO version=1.0 +# description=What it is +# /root/... the files, as they go below the install root +# (e.g. root/APPS/HELLO/HELLO.BAT -> C:\APPS\HELLO\HELLO.BAT) +# gets .TAR for each, INDEX.TXT and INDEX.SIG; serve it +# with any web server (python3 -m http.server 8080 -d ). +# keyfile (default /../repo.key, made if missing) is the +# repository's secret key; the public key for PKG.CFG is printed. +# Paths must be inside the modernDOS source tree (the container sees that). +. "$(dirname "$0")/mdenv.sh" +SRC=$1; OUT=$2; KEY=${3:-$(dirname "$2")/repo.key} +[ -d "$SRC" ] && [ -n "$OUT" ] || { sed -n '2,16p' "$0"; exit 2; } +rel() { realpath --relative-to="$ROOT" "$1"; } +mkdir -p "$OUT" +md_run sh -c 'make -s -C net/pkg host && net/pkg/mkrepo.sh "$1" "$2" "$3"' sh "$(rel "$SRC")" "$(rel "$OUT")" "$(rel "$KEY")" diff --git a/tests/bios/run.sh b/tests/bios/run.sh new file mode 100755 index 00000000..5d5bd79b --- /dev/null +++ b/tests/bios/run.sh @@ -0,0 +1,126 @@ +#!/bin/bash +# BIOS edition test (runs inside the build container). +# +# The BIOS disk image (release/build.sh, a personal one with a test key), +# started by SeaBIOS as an IDE disk and as a USB stick, with different +# network cards. Each boot must bring up the SSH server by itself; over SSH: +# - the system is on C: (the stick itself), files written stay +# - a page comes over http from a server here (HTTPGET) +# - PKG and the SSH client are there +# +# Usage: tests/bios/run.sh + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +WORK=$(mktemp -d) +VER=0.0.0-biostest +OUT="$ROOT/_output/release" +trap 'kill $QPID $WEB 2>/dev/null || true; rm -rf "$WORK" "$OUT/modernDOS-$VER"*' EXIT +PORT=2223 +export MTOOLS_SKIP_CHECK=1 + +echo "== building a personal BIOS image" +cd "$WORK" +mkdir personal site +ssh-keygen -q -t ed25519 -N "" -C tester -f id +sed 's/$/\r/' id.pub > personal/AUTHKEYS.TXT +head -c 32 /dev/urandom > personal/HOSTKEY.ED +PERSONAL="$WORK/personal" "$ROOT/release/build.sh" $VER > build.log 2>&1 || { tail -20 build.log; exit 1; } +cp "$OUT/modernDOS-$VER-bios.img" disk.img +PART=$((1008 * 512)) +mcopy -i disk.img@@$PART "$ROOT/net/pkg/build/httpget.exe" ::/MDOS/HTTPGET.EXE +echo 'helloplain page' > site/index.html +python3 -m http.server 8379 --bind 127.0.0.1 -d site > /dev/null 2>&1 & +WEB=$! + +fail=0 +ok() { echo " ok $1"; } +bad() { echo " FAIL $1"; fail=1; } +OPTS=(-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="$WORK/known" -o LogLevel=ERROR + -o BatchMode=yes -o IdentitiesOnly=yes -o ConnectTimeout=15 -o ServerAliveInterval=5 + -o ServerAliveCountMax=2 -i "$WORK/id" -p $PORT) +dos() { timeout 90 ssh "${OPTS[@]}" dos@127.0.0.1 "$@" 2>&1 | tr -d '\r'; } +dosgrep() { # dosgrep "what" "pattern" command + local what=$1 pat=$2 t0=$SECONDS; shift 2 + dos "$@" > out.txt || true + if grep -aq "$pat" out.txt; then ok "$what ($((SECONDS - t0)) s)"; else bad "$what"; sed 's/^/ /' out.txt | head -8; snapshot; fi +} +snapshot() { # what the machine shows and where its CPU is, for a failure + python3 - "$ROOT/_output/bios-fail" <<'PY' 2>/dev/null || true +import socket, sys, time +s = socket.socket(socket.AF_UNIX); s.connect("mon.sock"); time.sleep(0.3); s.recv(65536) +s.sendall(("screendump %s.ppm\n" % sys.argv[1]).encode()); time.sleep(1); s.recv(65536) +for i in range(5): + s.sendall(b"info registers\n"); time.sleep(0.5) + d = s.recv(65536).decode("latin1") + print(" cpu: " + " ".join(x for x in d.split() if x.startswith(("EIP=", "EFL=", "ESP=", "EAX=", "CR0="))) + + " | " + " ; ".join(l[:14] for l in d.split("\n") if l.startswith(("CS ", "SS ")))) +PY + # the sessions' state to the log: Ctrl+Alt+F12, three times a second apart + python3 -c 'import socket,time +for i in range(3): + s=socket.socket(socket.AF_UNIX); s.connect("mon.sock"); s.sendall(b"sendkey ctrl-alt-f12\n"); time.sleep(1.2); s.close()' 2>/dev/null || true + grep -a "PANIC\|^kbd: \|^bios: INT\|^v86: a program\|^vm: \|^ipxe\|^nic" debug.log | grep -v "instance data" | tail -60 | sed 's/^/ monitor: /' +} +boot() { # boot name qemu-args...: wait for the SSH server + local name=$1 i; shift + echo "== $name" + rm -f debug.log + qemu-system-i386 -m 128 -display none "$@" -debugcon file:debug.log \ + -monitor unix:mon.sock,server,nowait /dev/null && break; sleep 1; done + if grep -aq "sshd: listening" debug.log; then ok "$name: started, SSH server listening"; return 0; fi + bad "$name: no SSH server"; grep -a "nic:\|PANIC\|sshd" debug.log | head -5 + python3 -c 'import socket,sys,time; s=socket.socket(socket.AF_UNIX); s.connect("mon.sock"); s.sendall(("screendump %s\n" % sys.argv[1]).encode()); time.sleep(1)' \ + "$ROOT/_output/bios-fail.ppm" 2>/dev/null || true + return 1 +} +stop() { kill $QPID 2>/dev/null || true; wait $QPID 2>/dev/null || true; } +NET="user,hostfwd=tcp:127.0.0.1:$PORT-:22" + +if boot "IDE disk, e1000" -drive file=disk.img,format=raw,if=ide -nic $NET,model=e1000; then + dosgrep "C: is the system disk" "MDVMM *COM" 'DIR C:\MDOS\MDVMM.COM' + dosgrep "MDSYS: a DOS boot" "DOS boot" MDSYS + dosgrep "PKG is there" "PKG" 'DIR C:\MDOS\PKG.EXE /B' + dosgrep "the SSH client is there" "SSH" 'DIR C:\MDOS\SSH.EXE /B' + # a second 32-bit program (HTTPGET) beside the SSH server: each DOS + # session has its own DPMI client + dosgrep "a 32-bit program beside the SSH server: a page over http" "HTTPGET: ok" 'HTTPGET http://10.0.2.2:8379/' + dos 'COPY C:\FDCONFIG.SYS C:\KEPT.TXT' > /dev/null || true + dos 'MDSYS REBOOT' > /dev/null 2>&1 || true +fi +stop +if boot "the same disk again" -drive file=disk.img,format=raw,if=ide -nic $NET,model=e1000; then + dosgrep "a file written before is still there" "HIMEMX" 'TYPE C:\KEPT.TXT' + [ "$(wc -l < "$WORK/known")" = 1 ] && ok "one host key" || bad "the host key changed" +fi +stop +if boot "USB stick (UHCI), rtl8139" -usb -drive if=none,id=stick,format=raw,file=disk.img \ + -device usb-storage,drive=stick,bootindex=0 -nic $NET,model=rtl8139; then + dosgrep "C: is the stick" "HIMEMX" 'TYPE C:\KEPT.TXT' + dosgrep "a page over http" "HTTPGET: ok" 'HTTPGET http://10.0.2.2:8379/' +fi +stop +# INSTALL: from the stick onto an empty hard disk, then the disk alone +truncate -s 300M target.img +if boot "stick and an empty hard disk" -usb -drive if=none,id=stick,format=raw,file=disk.img \ + -device usb-storage,drive=stick,bootindex=0 -drive file=target.img,format=raw,if=ide \ + -nic $NET,model=e1000; then + dosgrep "INSTALL NEW: a partition on the disk" "INSTALL FORMAT" 'INSTALL NEW' + dos 'MDSYS REBOOT' > /dev/null 2>&1 || true + sleep 5 + for i in $(seq 1 120); do [ "$(grep -ac "sshd: listening" debug.log)" -ge 2 ] && break; sleep 1; done + dosgrep "INSTALL FORMAT: formatted and installed" "modernDOS is installed" 'INSTALL FORMAT' + dos 'MDSYS REBOOT' > /dev/null 2>&1 || true + sleep 3 +fi +stop +if boot "the hard disk alone" -drive file=target.img,format=raw,if=ide -nic $NET,model=e1000; then + dosgrep "the installed system: C:\\MDOS" "MDVMM *COM" 'DIR C:\MDOS\MDVMM.COM' + dosgrep "the volume is the formatted one" "MODERNDOS" 'VOL C:' + [ "$(wc -l < "$WORK/known")" = 1 ] && ok "the host key came along" || bad "another host key" +fi +stop +if [ $fail = 0 ]; then echo "BIOS TEST: success"; exit 0; else echo "BIOS TEST: failure"; exit 1; fi diff --git a/tests/compat/ega.c b/tests/compat/ega.c new file mode 100644 index 00000000..d3bdb109 --- /dev/null +++ b/tests/compat/ega.c @@ -0,0 +1,175 @@ +/* The 16 colour VGA modes (tests/compat): 12h (640x480), 10h (640x350), + 0Dh (320x200), 0Eh (640x200) - four bit planes behind A000:0, written + through the card's registers as programs of the time did. Built for real + mode and for DOS/4GW. Per mode named on the command line (hex): + - the upper third red: write mode 0 with set/reset + - the middle third green: write mode 2 + - the lower third: plane 0 alone (map mask), colour 1; its palette + register is set to 3Dh through the attribute controller: light magenta + - a yellow stripe, the right half of the bytes 10-19 of every line: + write mode 2 with a bit mask (the latches keep the left half) + - a white line of 100 pixels in the middle through INT 10h AH=0Ch + - "Hi" through INT 10h AH=0Eh in the second text line + - read back: read mode 0 (a plane), read mode 1 (colour compare), + INT 10h AH=0Dh + "VGA: showing -" on the debug port tells the test to take + its picture. */ +#include +#include +#include +#include +#include +#include + +#ifdef __386__ +#define SCREEN ((volatile unsigned char *)0xA0000) +#define INT86 int386 +#define RW(r) r.w +#else +#define SCREEN ((volatile unsigned char far *)MK_FP(0xA000, 0)) +#define INT86 int86 +#define RW(r) r.x +#endif + +static void say(const char *s) +{ + for (; *s; s++) + outp(0xe9, *s); +} + +static unsigned long ticks(void) +{ + union REGS r; + + memset(&r, 0, sizeof(r)); + INT86(0x1a, &r, &r); + return ((unsigned long)RW(r).cx << 16) | RW(r).dx; +} + +static void gc(int index, int value) +{ + outp(0x3ce, index); + outp(0x3cf, value); +} + +static int one(int mode) +{ + union REGS r; + unsigned w, h, rb, third, x, y; + unsigned long t; + unsigned i; + int ok = 1, got, plane2, plane0, compare, pixel, cols; + char line[40]; + unsigned char dummy; + + switch (mode) + { + case 0x0d: w = 320; h = 200; break; + case 0x0e: w = 640; h = 200; break; + case 0x10: w = 640; h = 350; break; + default: mode = 0x12; w = 640; h = 480; break; + } + rb = w / 8; + third = h / 3; + memset(&r, 0, sizeof(r)); + RW(r).ax = (unsigned short)mode; + INT86(0x10, &r, &r); + memset(&r, 0, sizeof(r)); + r.h.ah = 0x0f; + INT86(0x10, &r, &r); + got = r.h.al; + cols = r.h.ah; + + gc(0, 4); /* set/reset: red, for all planes */ + gc(1, 0x0f); + for (i = 0; i < third * rb; i++) + SCREEN[i] = 0; + gc(1, 0); + + gc(5, 2); /* write mode 2: the byte is the colour */ + for (i = third * rb; i < 2 * third * rb; i++) + SCREEN[i] = 2; + gc(5, 0); + + outp(0x3c4, 2); /* plane 0 alone */ + outp(0x3c5, 1); + for (i = 2 * third * rb; i < h * rb; i++) + SCREEN[i] = 0xff; + outp(0x3c5, 0x0f); + inp(0x3da); /* its palette register: light magenta */ + outp(0x3c0, 1); + outp(0x3c0, 0x3d); + inp(0x3da); + outp(0x3c0, 0x20); + + gc(5, 2); /* the stripe */ + gc(8, 0x0f); + for (y = 0; y < h; y++) + for (x = 10; x < 20; x++) + { + dummy = SCREEN[y * rb + x]; /* loads the latches */ + SCREEN[y * rb + x] = 14; + } + (void)dummy; + gc(8, 0xff); + gc(5, 0); + + for (x = 0; x < 100; x++) /* the line */ + { + memset(&r, 0, sizeof(r)); + RW(r).ax = 0x0c0f; + RW(r).cx = (unsigned short)(w / 2 + x); + RW(r).dx = (unsigned short)(h / 2); + INT86(0x10, &r, &r); + } + memset(&r, 0, sizeof(r)); /* the text */ + r.h.ah = 0x02; + RW(r).dx = 0x0101; + INT86(0x10, &r, &r); + for (i = 0; i < 2; i++) + { + memset(&r, 0, sizeof(r)); + RW(r).ax = (unsigned short)(0x0e00 | "Hi"[i]); + RW(r).bx = 0x0007; + INT86(0x10, &r, &r); + } + + gc(4, 2); /* red is plane 2 */ + plane2 = SCREEN[(third / 2) * rb + 40 % rb + 30 % rb]; + plane2 = SCREEN[(third / 2) * rb + rb - 4]; + gc(4, 0); + plane0 = SCREEN[(third / 2) * rb + rb - 4]; + gc(5, 8); /* read mode 1: which pixels are red? */ + gc(2, 4); + gc(7, 0x0f); + compare = SCREEN[(third / 2) * rb + rb - 4]; + gc(5, 0); + memset(&r, 0, sizeof(r)); + r.h.ah = 0x0d; + RW(r).cx = (unsigned short)(w / 2 + 50); + RW(r).dx = (unsigned short)(h / 2); + INT86(0x10, &r, &r); + pixel = r.h.al; + if (got != mode || cols != (int)(w / 8) || plane2 != 0xff || plane0 != 0 || compare != 0xff || pixel != 15) + ok = 0; + + sprintf(line, "VGA: showing %02x-%u\r\n", mode, (unsigned)(sizeof(int) * 8)); + say(line); + for (t = ticks(); ticks() - t < 55;) /* three seconds */ + ; + memset(&r, 0, sizeof(r)); + RW(r).ax = 0x0003; + INT86(0x10, &r, &r); + printf("ega: %u bit, mode %02Xh (%d columns), planes %02X/%02X, compare %02X, pixel %d: %s\n", + (unsigned)(sizeof(int) * 8), got, cols, plane2, plane0, compare, pixel, ok ? "all ok" : "FAILED"); + return ok; +} + +int main(int argc, char **argv) +{ + int i, ok = 1; + + for (i = 1; i < argc; i++) + ok &= one((int)strtol(argv[i], NULL, 16)); + return !ok; +} diff --git a/tests/compat/egacheck.py b/tests/compat/egacheck.py new file mode 100755 index 00000000..9fb4d96c --- /dev/null +++ b/tests/compat/egacheck.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Check a screendump of tests/compat/ega.c in a 16 colour mode: red above, +green in the middle, light magenta below, the yellow stripe, the white +line, the text. + +The emulated VGA card shows the mode at its size (lines twice in the 200 +line modes, 320 pixels twice); the monitor's VGA on a UEFI boot enlarges it +by a whole factor in the middle of the framebuffer. + +Usage: egacheck.py shot.ppm mode(hex)""" +import sys + +SIZE = {0x0d: (320, 200), 0x0e: (640, 200), 0x10: (640, 350), 0x12: (640, 480)} + + +def main(): + d = open(sys.argv[1], "rb").read() + mode = int(sys.argv[2], 16) + w, h = SIZE[mode] + parts = d.split(b"\n", 3) + iw, ih = map(int, parts[1].split()) + px = parts[3] + if ih <= 480: # the card's picture + xs, ys, x0, y0 = iw // w, ih // h, 0, 0 + else: # in the middle of a framebuffer + ya = 2 if mode == 0x0e else 1 + xs = min(iw // w, ih // (h * ya)) + ys = xs * ya + x0, y0 = (iw - w * xs) // 2, (ih - h * ys) // 2 + if xs < 1 or ys < 1: + print(" %dx%d: not a picture of mode %02Xh" % (iw, ih, mode)) + return 1 + + def at(x, y): + o = ((y0 + y * ys + ys // 2) * iw + x0 + x * xs + xs // 2) * 3 + return tuple(px[o:o + 3]) + + def near(c, want): + return all(abs(a - b) <= 14 for a, b in zip(c, want)) + + third = h // 3 + red, green, magenta, yellow, white, grey = (170, 0, 0), (0, 170, 0), (255, 85, 255), (255, 255, 85), \ + (255, 255, 255), (170, 170, 170) + checks = [ + ("red above", at(w * 3 // 4, third // 2), red), + ("green in the middle", at(w * 3 // 4, h // 2 + 6), green), + ("light magenta below", at(w * 3 // 4, h - third // 2), magenta), + ("the stripe's yellow half", at(10 * 8 + 6, third // 2), yellow), + ("the stripe's other half", at(10 * 8 + 1, third // 2), red), + ("the stripe below", at(15 * 8 + 5, h - third // 2), yellow), + ("the white line", at(w // 2 + 50, h // 2), white), + ("beside the line", at(w // 2 + 150, h // 2), green), + ] + bad = [(n, c) for n, c, want in checks if not near(c, want)] + ch = 8 if h == 200 else 14 if h == 350 else 16 + text = sum(1 for y in range(ch, 2 * ch) for x in range(8, 24) if near(at(x, y), grey)) + dark = sum(1 for y in range(ch, 2 * ch) for x in range(8, 24) if near(at(x, y), (0, 0, 0))) + if not (16 * ch // 16 <= text <= 16 * ch * 6 // 10 and dark >= 16 * ch * 35 // 100): + bad.append(("the text (%d grey, %d black pixels)" % (text, dark), None)) + print(" mode %02Xh, %dx%d: %s" % (mode, iw, ih, "as expected" if not bad else + "; ".join("%s is %s" % (n, c) if c else n for n, c in bad))) + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/compat/game.sh b/tests/compat/game.sh new file mode 100755 index 00000000..fce65dcb --- /dev/null +++ b/tests/compat/game.sh @@ -0,0 +1,132 @@ +#!/bin/bash +# A game off the shelf on both editions (runs inside the build container): +# Kiloblaster (Epic MegaGames 1992, freeware since 2008; the copy of the +# FreeDOS games repository, in the build image under /opt/games). A real +# mode program with its own keyboard and timer handlers, on the VGA in its +# unchained 256 colour mode (four planes, "mode X"). +# +# It is started on the BIOS edition (SeaBIOS, the emulated VGA card: the +# reference) and on a UEFI boot (OVMF, the monitor's own VGA on the +# framebuffer). A key takes it past its first screen; then pictures are +# taken. Screens that stand still (loading, title, main menu) must look the +# same on both. +# +# Usage: tests/compat/game.sh [kernel.sys] + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +KERNEL=$(realpath "${1:-$ROOT/_output/gcc/kgc8632.sys}") +GAME=${GAMEDIR:-/opt/games/kiloblas} +WORK=$(mktemp -d) +VER=0.0.0-gametest +OUT="$ROOT/_output/release" +trap 'kill $QPID 2>/dev/null || true; rm -rf "$WORK" "$OUT/modernDOS-$VER"*' EXIT +TEST="$ROOT/test" +. "$TEST/cfg.sh" +OVMF=/usr/share/ovmf/OVMF.fd +export MTOOLS_SKIP_CHECK=1 +[ -f "$GAME/KFILE1.EXE" ] || { echo "no game in $GAME (build/games.sh)"; exit 1; } + +echo "== building" +make -s -C "$ROOT/mdvmm" +cd "$WORK" +"$ROOT/release/build.sh" $VER > build.log 2>&1 || { tail -20 build.log; exit 1; } +"$NASM" -f bin -o poweroff.com "$ROOT/tests/mdvmm/poweroff.asm" + +# the game's disk: one FAT16 partition at 1 MB +make_disk() { + dd if=/dev/zero of="$1" bs=512 count=131072 status=none + python3 - "$1" 131072 <<'PY' +import struct, sys +path, total = sys.argv[1], int(sys.argv[2]) +entry = struct.pack(" autoexec.bat +printf '%s\r\n' 'D:' 'CD \KB' 'KFILE1.EXE' 'C:\POWEROFF.COM' >> autoexec.bat +mdel -i bios.img@@$PART ::AUTOEXEC.BAT +mcopy -i bios.img@@$PART autoexec.bat ::AUTOEXEC.BAT +mcopy -i bios.img@@$PART poweroff.com ::POWEROFF.COM + +# UEFI: a boot disk of its own, the game on an AHCI disk (C:) +make_disk uefi-hd.img +printf 'DEVICE=A:\\HIMEMX.EXE\r\nDOS=HIGH\r\nFILES=40\r\nSHELL=A:\\COMMAND.COM A:\\ /E:1024 /P\r\n' > fdconfig.sys +printf '%s\r\n' '@ECHO OFF' 'PATH A:\' 'C:' 'CD \KB' 'KFILE1.EXE' 'A:\POWEROFF.COM' > autoexec.bat +"$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_LBA=0 -D_USE_PART_INFO=0 -D_QUERY_GEOMETRY=0 \ + -D_FAT12 -D_UNIT=00h -D_CHS_SECTORS=36 -D_CHS_HEADS=2 -o boot.bin +"$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,fdconfig.sys" \ + -D_BOOTPATCHFILE="'boot.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR_PART_TYPE=ptFAT12 -D_BPE=12 -D_SPC=2 -D_SPI=5760 \ + -D_SPF=9 -D_NUMROOT=224 -D_CHS_SECTORS=36 -D_CHS_HEADS=2 -D_UNIT=00h -o boot.img +for f in /opt/fdos/bin/command.com /opt/fdos/bin/himemx.exe autoexec.bat poweroff.com; do + mcopy -i boot.img "$f" "::$(basename "$f" | tr a-z A-Z)" +done +dd if=/dev/zero of=esp.img bs=1M count=16 status=none +mformat -i esp.img -h 64 -s 32 -t 16 :: +mmd -i esp.img ::/EFI ::/EFI/BOOT ::/MDOS +mcopy -i esp.img "$ROOT/mdvmm/build/BOOTX64.EFI" ::/EFI/BOOT/BOOTX64.EFI +mcopy -i esp.img boot.img ::/MDOS/BOOT.IMG +printf 'the disks may be written\r\n' > diskrw +mcopy -i esp.img diskrw ::/MDOS/DISKRW + +fail=0 +play() { # play name qemu...: pictures into $WORK/name-NN.ppm + local name=$1; shift + echo "== $name" + rm -f debug.log mon.sock + "$@" -display none -debugcon file:debug.log -monitor unix:mon.sock,server,nowait -no-reboot /dev/null || true + wait $QPID 2>/dev/null || true + grep -a "^vga: \|^v86: a program\|^kbd: \|PANIC" -A5 debug.log | head -12 | sed 's/^/ monitor: /' || true + if grep -aq "PANIC" debug.log; then echo " FAIL $name: monitor panic"; fail=1; fi +} +play bios qemu-system-i386 -m 128 -drive file=bios.img,format=raw,if=ide -drive file=bios-hd.img,format=raw,if=ide +play uefi qemu-system-x86_64 -m 256 -bios "$OVMF" -drive file=esp.img,format=raw,if=ide \ + -device ahci,id=ahci -drive id=hd,file=uefi-hd.img,format=raw,if=none -device ide-hd,drive=hd,bus=ahci.0 + +[ -n "$SHOTS" ] && mkdir -p "$SHOTS" && cp "$WORK"/*.ppm "$SHOTS"/ 2>/dev/null || true +if python3 "$HERE/gamecheck.py" "$WORK/bios" "$WORK/uefi"; then + echo " ok the game's still screens look the same on the BIOS edition and on UEFI" +else + echo " FAIL the game's screens on UEFI are not those of the BIOS edition"; fail=1 +fi +if [ $fail = 0 ]; then echo "GAME TEST: success"; exit 0; else echo "GAME TEST: failure"; exit 1; fi diff --git a/tests/compat/gamecheck.py b/tests/compat/gamecheck.py new file mode 100644 index 00000000..264d923c --- /dev/null +++ b/tests/compat/gamecheck.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Compare the pictures of tests/compat/game.sh: the screens of the game +that stand still (the same in two pictures in a row) on the BIOS edition +must turn up on the UEFI boot too, looking the same. + +Pictures are brought to 320x200: the emulated VGA card shows the mode as +640x400, the monitor's VGA enlarges it by a whole factor in the middle of +the framebuffer. + +Usage: gamecheck.py bios-prefix uefi-prefix""" +import glob +import sys + +W, H = 320, 200 + + +def load(path): + d = open(path, "rb").read() + parts = d.split(b"\n", 3) + w, h = map(int, parts[1].split()) + px = parts[3] + s = min(w // W, h // H) + if s < 1: + return None + x0, y0 = (w - W * s) // 2, (h - H * s) // 2 + out = bytearray(W * H * 3) + for y in range(H): + row = ((y0 + y * s + s // 2) * w + x0 + s // 2) * 3 + for x in range(W): + o = row + x * s * 3 + out[(y * W + x) * 3:(y * W + x) * 3 + 3] = px[o:o + 3] + return bytes(out) + + +def still(prefix): + """The pictures that are the same as the one before them.""" + frames, last, found = sorted(glob.glob(prefix + "-[0-9][0-9].ppm")), None, [] + for f in frames: + p = load(f) + if p is not None and p == last and p not in found: + found.append(p) + last = p + return found, len(frames) + + +def colours(p): + return len({p[i:i + 3] for i in range(0, len(p), 3)}) + + +def differ(a, b): + """Share of pixels that differ by more than the rounding of a 6 bit + colour component.""" + n = 0 + for i in range(0, len(a), 3): + if abs(a[i] - b[i]) > 6 or abs(a[i + 1] - b[i + 1]) > 6 or abs(a[i + 2] - b[i + 2]) > 6: + n += 1 + return n / (len(a) // 3) + + +def main(): + bios, nb = still(sys.argv[1]) + uefi, nu = still(sys.argv[2]) + print(" BIOS: %d pictures, %d still screens; UEFI: %d pictures, %d still screens" % + (nb, len(bios), nu, len(uefi))) + rich = [p for p in bios if colours(p) >= 24] + if not rich: + print(" no still screen with many colours on the BIOS edition") + return 1 + matched = 0 + for p in rich: + best = min((differ(p, q) for q in uefi), default=1.0) + print(" a screen of %d colours: %.1f%% of its pixels differ on UEFI" % (colours(p), best * 100)) + if best < 0.02: + matched += 1 + return 0 if matched else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/compat/gameplay.py b/tests/compat/gameplay.py new file mode 100644 index 00000000..2e929f27 --- /dev/null +++ b/tests/compat/gameplay.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Play the start of the game for tests/compat/game.sh through the QEMU +monitor: Enter until it is in its graphics mode, then a picture every two +seconds for a while. + +Usage: gameplay.py debug.log monitor.sock prefix -> prefix-NN.ppm""" +import os +import socket +import sys +import time + + +def mon(sock, cmd): + try: + s = socket.socket(socket.AF_UNIX) + s.connect(sock) + s.sendall((cmd + "\n").encode()) + time.sleep(0.4) + s.close() + except OSError: + pass + + +def tick_byte(sock): + """The low byte of the BIOS tick count (0040:006C); None if not read.""" + try: + s = socket.socket(socket.AF_UNIX) + s.settimeout(2) + s.connect(sock) + time.sleep(0.2) + s.recv(65536) + s.sendall(b"x /1xb 0x46c\n") + time.sleep(0.3) + d = s.recv(65536).decode("latin1") + s.close() + return int(d.split("0x")[-1].split()[0], 16) + except (OSError, ValueError, IndexError): + return None + + +def safe_moment(sock): + """The game measures the machine's speed when it starts: it waits for + the tick count's low byte to go up by 5, taking the byte for a signed + number - from 123 to 127 on that never comes, and the game hangs (on + any PC, one start in fifty). So the key that starts it is pressed just + after that range: the next time round is ten seconds away.""" + for i in range(60): + b = tick_byte(sock) + if b is None or 0x84 <= b <= 0xc0: + return + time.sleep(0.5) + + +def size(path): + try: + with open(path, "rb") as f: + head = f.read(32).split(b"\n") + w, h = head[1].split() + return int(w), int(h) + except (OSError, IndexError, ValueError): + return 0, 0 + + +def graphics(log, probe): + """In a graphics mode? The monitor's VGA says so on a UEFI boot; the + emulated card's picture is 640 wide in mode 13h and its relatives (720 + in text mode).""" + try: + if b"vga: mode 13h" in open(log, "rb").read(): + return True + except OSError: + pass + return size(probe)[0] == 640 + + +def main(): + log, sock, prefix = sys.argv[1:4] + probe = prefix + "-probe.ppm" + start = time.time() + # the game's first screen (text) waits for a key + time.sleep(20) + while time.time() - start < 120: + mon(sock, "screendump " + probe) + if graphics(log, probe): + break + safe_moment(sock) + mon(sock, "sendkey ret") + time.sleep(4) + else: + print(" the game did not reach its graphics mode") + return 1 + if os.path.exists(probe): + os.remove(probe) + for n in range(24): # loading, title, main menu, demo + time.sleep(2) + mon(sock, "screendump %s-%02d.ppm" % (prefix, n)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/compat/hello.c b/tests/compat/hello.c new file mode 100644 index 00000000..74b7216f --- /dev/null +++ b/tests/compat/hello.c @@ -0,0 +1,102 @@ +/* A plain DOS program for tests/compat: built with Open Watcom for real + mode and for each DOS extender, and compiled once more on modernDOS + itself. It does what DOS programs do - memory, files, DOS and BIOS calls, + the timer - and says so on standard output. */ +#include +#include +#include +#include +#include + +static int ok, checks; + +static void check(int good, const char *what) +{ + checks++; + ok += good != 0; + printf(" %s %s\n", good ? "ok " : "FAIL", what); +} + +int main(void) +{ + union REGS r; + char *p; + FILE *f; + char buf[64]; + unsigned long n = sizeof(int) == 4 ? 4ul * 1024 * 1024 : 40000ul, i, sum = 0; + + printf("hello: %u bit program\n", (unsigned)(sizeof(int) * 8)); + + /* memory: 4 MB for a 32 bit program, 40000 bytes in real mode */ + p = malloc((size_t)n); + if (p) + { + for (i = 0; i < n; i += 997) + p[i] = (char)i; + for (i = 0; i < n; i += 997) + sum += (unsigned char)p[i] == (unsigned char)i; + } + check(p && sum == (n + 996) / 997, "memory: allocated, written, read back"); + free(p); + + /* a file */ + f = fopen("HELLO.TMP", "w"); + if (f) + { + fputs("written by hello\n", f); + fclose(f); + } + buf[0] = 0; + f = fopen("HELLO.TMP", "r"); + if (f) + { + fgets(buf, sizeof(buf), f); + fclose(f); + } + remove("HELLO.TMP"); + check(!strcmp(buf, "written by hello\n"), "file: written, read back, deleted"); + + /* DOS: version (INT 21h AH=30h) */ + memset(&r, 0, sizeof(r)); + r.h.ah = 0x30; + intdos(&r, &r); + check(r.h.al >= 5, "DOS call: version 5 or later"); + + /* BIOS: equipment word (INT 11h), the timer ticks (INT 1Ah) */ + memset(&r, 0, sizeof(r)); +#ifdef __386__ + int386(0x11, &r, &r); +#else + int86(0x11, &r, &r); +#endif + check(1, "BIOS call: INT 11h returned"); + { + unsigned long t0, t1; + long spin; + memset(&r, 0, sizeof(r)); +#ifdef __386__ + int386(0x1a, &r, &r); + t0 = ((unsigned long)r.w.cx << 16) | r.w.dx; +#else + int86(0x1a, &r, &r); + t0 = ((unsigned long)r.x.cx << 16) | r.x.dx; +#endif + t1 = t0; + for (spin = 0; spin < 40000000L && t1 == t0; spin++) + { + if (spin % 1000) + continue; + memset(&r, 0, sizeof(r)); +#ifdef __386__ + int386(0x1a, &r, &r); + t1 = ((unsigned long)r.w.cx << 16) | r.w.dx; +#else + int86(0x1a, &r, &r); + t1 = ((unsigned long)r.x.cx << 16) | r.x.dx; +#endif + } + check(t1 != t0, "timer: the BIOS tick count advances"); + } + printf("hello: %s %d ok\n", ok == checks ? "all" : "only", ok); + return ok == checks ? 0 : 1; +} diff --git a/tests/compat/run.sh b/tests/compat/run.sh new file mode 100755 index 00000000..96fc8d2b --- /dev/null +++ b/tests/compat/run.sh @@ -0,0 +1,131 @@ +#!/bin/bash +# Compatibility test with existing DOS software (runs inside the build +# container): programs nobody here wrote, of the kinds DOS software comes +# in, on the BIOS edition's disk (started by SeaBIOS) under the monitor: +# +# - a 16-bit real mode program (Open Watcom, large model) +# - 32-bit programs under the DOS extenders of the DOS years: DOS/4GW, +# PMODE/W, DOS/32A, CauseWay (each finds the monitor's DPMI host, or +# must cope with running in V86 mode without VCPI) +# - the Open Watcom C compiler itself, hosted on DOS: WCL386 compiles and +# links a program on modernDOS (a DOS/4GW program that runs the +# compiler and the linker: DPMI clients started by a DPMI client) +# - FreeDOS FDISK, FORMAT, XCOPY and the kernel's SYS run in tests/bios +# +# The programs write to C:\OUT.TXT, which is read from the disk image +# afterwards. +# +# Usage: tests/compat/run.sh + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +WORK=$(mktemp -d) +VER=0.0.0-compattest +OUT="$ROOT/_output/release" +trap 'rm -rf "$WORK" "$OUT/modernDOS-$VER"*' EXIT +export MTOOLS_SKIP_CHECK=1 +export WATCOM=/opt/watcom +export PATH=$WATCOM/binl64:$WATCOM/binw:$PATH # binw: the extenders' stubs for the linker +export INCLUDE=$WATCOM/h +. "$ROOT/test/cfg.sh" + +echo "== building" +cd "$WORK" +"$ROOT/release/build.sh" $VER > build.log 2>&1 || { tail -20 build.log; exit 1; } +cp "$OUT/modernDOS-$VER-bios.img" disk.img +PART=$((1008 * 512)) +"$NASM" -f bin -o poweroff.com "$ROOT/tests/mdvmm/poweroff.asm" +cp "$HERE/hello.c" hello.c +# the same program for every kind +wcl -q -bt=dos -ml -fe=hello16.exe hello.c > w16.log 2>&1 || { cat w16.log; exit 1; } +for ext in dos4g pmodew dos32a causeway; do + wcl386 -q -bt=dos -l=$ext -fe=h_$ext.exe hello.c > w_$ext.log 2>&1 || { cat w_$ext.log; exit 1; } +done +# VGA mode 13h, in real mode and under DOS/4GW +wcl -q -bt=dos -ml -fe=vga16.exe "$HERE/vga.c" > v16.log 2>&1 || { cat v16.log; exit 1; } +wcl386 -q -bt=dos -l=dos4g -fe=vga32.exe "$HERE/vga.c" > v32.log 2>&1 || { cat v32.log; exit 1; } +wcl -q -bt=dos -ml -fe=ega16.exe "$HERE/ega.c" > e16.log 2>&1 || { cat e16.log; exit 1; } +wcl386 -q -bt=dos -l=dos4g -fe=ega32.exe "$HERE/ega.c" > e32.log 2>&1 || { cat e32.log; exit 1; } +ls -l hello16.exe h_*.exe vga*.exe | awk '{print " " $5, $9}' + +# the DOS-hosted compiler: what WCL386 needs to compile and link for DOS/4GW +mmd -i disk.img@@$PART ::/WATCOM ::/WATCOM/BINW ::/WATCOM/H ::/WATCOM/LIB386 ::/WATCOM/LIB386/DOS ::/T +for f in wcl386.exe wcc386.exe wlink.exe wlink.lnk dos4gw.exe wstub.exe wcc38601.int; do + mcopy -i disk.img@@$PART $WATCOM/binw/$f ::/WATCOM/BINW/ +done +for f in stdio.h stdlib.h string.h dos.h i86.h _comdef.h malloc.h; do + [ -f $WATCOM/h/$f ] && mcopy -i disk.img@@$PART $WATCOM/h/$f ::/WATCOM/H/ +done +mcopy -i disk.img@@$PART $WATCOM/lib386/dos/clib3r.lib $WATCOM/lib386/dos/emu387.lib ::/WATCOM/LIB386/DOS/ +mcopy -i disk.img@@$PART $WATCOM/lib386/math387r.lib ::/WATCOM/LIB386/ +mcopy -i disk.img@@$PART $WATCOM/binw/dos4gw.exe $WATCOM/binw/pmodew.exe $WATCOM/binw/dos32a.exe ::/T/ +mcopy -i disk.img@@$PART hello16.exe h_dos4g.exe h_pmodew.exe h_dos32a.exe h_causeway.exe hello.c poweroff.com \ + vga16.exe vga32.exe ega16.exe ega32.exe ::/T/ + +# AUTOEXEC.BAT: the edition's own, then the programs +mtype -i disk.img@@$PART ::AUTOEXEC.BAT > autoexec.bat +printf '%s\r\n' 'SET WATCOM=C:\WATCOM' 'SET INCLUDE=C:\WATCOM\H' 'PATH C:\MDOS;C:\;C:\WATCOM\BINW' \ + 'C:' 'CD \T' ${COMPAT_FIRST:+"$COMPAT_FIRST"} \ + 'ECHO === real mode >C:\OUT.TXT' 'HELLO16.EXE >>C:\OUT.TXT' \ + 'ECHO === DOS/4GW >>C:\OUT.TXT' 'H_DOS4G.EXE >>C:\OUT.TXT' \ + 'ECHO === PMODE/W >>C:\OUT.TXT' 'H_PMODEW.EXE >>C:\OUT.TXT' \ + 'ECHO === DOS/4GW again >>C:\OUT.TXT' 'H_DOS4G.EXE >>C:\OUT.TXT' \ + 'ECHO === compiled here >>C:\OUT.TXT' 'COPY HELLO.C MADE.C >NUL' \ + 'WCL386 -q -bt=dos -l=dos4g MADE.C >C:\WCL.TXT' 'MADE.EXE >>C:\OUT.TXT' \ + 'ECHO === DOS/32A >>C:\OUT.TXT' 'H_DOS32A.EXE >>C:\OUT.TXT' \ + 'ECHO === CauseWay >>C:\OUT.TXT' 'H_CAUSEW.EXE >>C:\OUT.TXT' \ + 'ECHO === VGA 16 >>C:\OUT.TXT' 'VGA16.EXE >>C:\OUT.TXT' \ + 'ECHO === VGA 32 >>C:\OUT.TXT' 'VGA32.EXE >>C:\OUT.TXT' \ + 'ECHO === EGA 16 >>C:\OUT.TXT' 'EGA16.EXE 12 10 0d 0e >>C:\OUT.TXT' \ + 'ECHO === EGA 32 >>C:\OUT.TXT' 'EGA32.EXE 12 0d >>C:\OUT.TXT' \ + 'ECHO === end >>C:\OUT.TXT' 'POWEROFF.COM' >> autoexec.bat +mdel -i disk.img@@$PART ::AUTOEXEC.BAT +mcopy -i disk.img@@$PART autoexec.bat ::AUTOEXEC.BAT +mren -i disk.img@@$PART ::/T/h_causeway.exe ::/T/H_CAUSEW.EXE 2>/dev/null || true + +echo "== booting" +qemu-system-i386 -m 128 -display none -drive file=disk.img,format=raw,if=ide \ + -nic user,model=e1000 -debugcon file:debug.log -no-reboot -monitor unix:mon.sock,server,nowait /dev/null || break; sleep 1; done +if kill -0 $QPID 2>/dev/null; then # still there: what is on its screen? + python3 -c 'import socket,sys,time; s=socket.socket(socket.AF_UNIX); s.connect("mon.sock"); s.sendall(("screendump %s\n" % sys.argv[1]).encode()); time.sleep(1)' \ + "$ROOT/_output/compat-hang.ppm" 2>/dev/null || true + python3 -c 'import socket,time +s=socket.socket(socket.AF_UNIX); s.connect("mon.sock"); time.sleep(0.3); s.recv(65536) +for i in range(4): + s.sendall(b"info registers\n"); time.sleep(0.4) + d=s.recv(65536).decode("latin1") + print(" cpu: "+" ".join(x for x in d.split() if x.startswith(("EIP=","CS","SS","EFL=","ESP=","EAX="))))' 2>/dev/null || true + kill $QPID 2>/dev/null || true +fi +wait $QPID 2>/dev/null || true +mtype -i disk.img@@$PART ::OUT.TXT 2>/dev/null | tr -d '\r' > out.txt || true +mtype -i disk.img@@$PART ::WCL.TXT 2>/dev/null | tr -d '\r' > wcl.txt || true +sed 's/^/ /' out.txt +[ -s wcl.txt ] && sed 's/^/ wcl386: /' wcl.txt | head -12 +grep -a "^v86: \|^dpmi: \|PANIC" -A6 debug.log | grep -av "^--\|^vm: \|^nic: " | head -40 | sed "s/^/ monitor: /" || true + +fail=0 +section() { sed -n "/^=== $1 *\$/,/^=== [^ ]* *[^ ]* *\$/p" out.txt; } +for kind in "real mode" "DOS\\/4GW" "PMODE\\/W" "DOS\\/4GW again" "compiled here" "DOS\\/32A" "CauseWay"; do + name=$(echo "$kind" | tr -d '\\') + if section "$kind" | grep -q "hello: all 5 ok"; then echo " ok $name"; else echo " FAIL $name"; fail=1; fi +done +for bits in 16 32; do + if section "VGA $bits" | grep -q "vga: $bits bit, mode 13h, palette 63/0/0: all ok" && + python3 "$HERE/vgacheck.py" vga$bits.ppm; then + echo " ok VGA mode 13h, $bits bit: palette, pixels, the picture on the display" + else echo " FAIL VGA mode 13h, $bits bit"; fail=1; fi +done +for shot in 12-16 10-16 0d-16 0e-16 12-32 0d-32; do + mode=${shot%-*}; bits=${shot#*-} + if section "EGA $bits" | grep -qi "ega: $bits bit, mode ${mode}h.*all ok" && + python3 "$HERE/egacheck.py" vga$shot.ppm $mode; then + echo " ok VGA mode ${mode}h (16 colours), $bits bit: planes, registers, BIOS pixels and text" + else echo " FAIL VGA mode ${mode}h (16 colours), $bits bit"; fail=1; fi +done +grep -q "^=== end" out.txt && echo " ok ran to the end" || { echo " FAIL did not run to the end"; fail=1; } +if [ $fail = 0 ]; then echo "COMPAT TEST: success"; exit 0; else echo "COMPAT TEST: failure"; exit 1; fi diff --git a/tests/compat/uefi.sh b/tests/compat/uefi.sh new file mode 100755 index 00000000..f30f2a2a --- /dev/null +++ b/tests/compat/uefi.sh @@ -0,0 +1,114 @@ +#!/bin/bash +# The compatibility test of run.sh on a UEFI boot (runs inside the build +# container): the same programs - real mode, DOS/4GW, PMODE/W, DOS/32A, +# CauseWay, and the DOS-hosted Open Watcom compiler - under the monitor's +# own BIOS (OVMF, BOOTX64.EFI). The boot disk is the 8 MB RAM disk A:; the +# screen comes back over the serial mirror of the console. +# +# Usage: tests/compat/uefi.sh [kernel.sys] + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +KERNEL=$(realpath "${1:-$ROOT/_output/gcc/kgc8632.sys}") +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +TEST="$ROOT/test" +. "$TEST/cfg.sh" +OVMF=/usr/share/ovmf/OVMF.fd +export MTOOLS_SKIP_CHECK=1 +export WATCOM=/opt/watcom +export PATH=$WATCOM/binl64:$WATCOM/binw:$PATH +export INCLUDE=$WATCOM/h + +echo "== building" +make -s -C "$ROOT/mdvmm" +"$NASM" -f bin -o "$WORK/poweroff.com" "$ROOT/tests/mdvmm/poweroff.asm" +cd "$WORK" +cp "$HERE/hello.c" hello.c +wcl -q -bt=dos -ml -fe=hello16.exe hello.c > w16.log 2>&1 || { cat w16.log; exit 1; } +for ext in dos4g pmodew dos32a causeway; do + wcl386 -q -bt=dos -l=$ext -fe=h_$ext.exe hello.c > w_$ext.log 2>&1 || { cat w_$ext.log; exit 1; } +done +mv h_causeway.exe h_causew.exe +wcl -q -bt=dos -ml -fe=vga16.exe "$HERE/vga.c" > v16.log 2>&1 || { cat v16.log; exit 1; } +wcl386 -q -bt=dos -l=dos4g -fe=vga32.exe "$HERE/vga.c" > v32.log 2>&1 || { cat v32.log; exit 1; } +wcl -q -bt=dos -ml -fe=ega16.exe "$HERE/ega.c" > e16.log 2>&1 || { cat e16.log; exit 1; } +wcl386 -q -bt=dos -l=dos4g -fe=ega32.exe "$HERE/ega.c" > e32.log 2>&1 || { cat e32.log; exit 1; } + +printf 'DEVICE=A:\\HIMEMX.EXE\r\nDOS=HIGH\r\nSHELL=A:\\COMMAND.COM A:\\ /E:1024 /P\r\n' > fdconfig.sys +printf '%s\r\n' '@ECHO OFF' 'SET WATCOM=A:\W' 'SET INCLUDE=A:\W\H' 'PATH A:\;A:\W\BINW' \ + 'ECHO === real mode' 'HELLO16.EXE' \ + 'ECHO === DOS/4GW' 'H_DOS4G.EXE' \ + 'ECHO === PMODE/W' 'H_PMODEW.EXE' \ + 'ECHO === DOS/4GW again' 'H_DOS4G.EXE' \ + 'ECHO === compiled here' 'COPY HELLO.C MADE.C >NUL' 'WCL386 -q -bt=dos -l=dos4g MADE.C' 'MADE.EXE' \ + 'ECHO === DOS/32A' 'H_DOS32A.EXE' \ + 'ECHO === CauseWay' 'H_CAUSEW.EXE' \ + 'ECHO === VGA 16' 'VGA16.EXE' \ + 'ECHO === VGA 32' 'VGA32.EXE' \ + 'ECHO === EGA 16' 'EGA16.EXE 12 10 0d 0e' \ + 'ECHO === EGA 32' 'EGA32.EXE 12 0d' \ + 'ECHO === end' 'A:\POWEROFF.COM' > autoexec.bat +"$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_LBA=0 -D_USE_PART_INFO=0 -D_QUERY_GEOMETRY=0 \ + -D_FAT12 -D_UNIT=00h -D_CHS_SECTORS=63 -D_CHS_HEADS=2 -o boot.bin +"$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,fdconfig.sys" \ + -D_BOOTPATCHFILE="'boot.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR_PART_TYPE=ptFAT12 -D_BPE=12 -D_SPC=8 -D_SPI=16380 \ + -D_SPF=6 -D_NUMROOT=224 -D_CHS_SECTORS=63 -D_CHS_HEADS=2 -D_UNIT=00h -o boot.img +for f in /opt/fdos/bin/command.com /opt/fdos/bin/himemx.exe autoexec.bat poweroff.com \ + hello16.exe h_dos4g.exe h_pmodew.exe h_dos32a.exe h_causew.exe hello.c vga16.exe vga32.exe ega16.exe ega32.exe \ + $WATCOM/binw/dos4gw.exe $WATCOM/binw/pmodew.exe $WATCOM/binw/dos32a.exe; do + mcopy -i boot.img "$f" "::$(basename "$f" | tr a-z A-Z)" +done +mmd -i boot.img ::/W ::/W/BINW ::/W/H ::/W/LIB386 ::/W/LIB386/DOS +for f in wcl386.exe wcc386.exe wlink.exe wlink.lnk dos4gw.exe wstub.exe wcc38601.int; do + mcopy -i boot.img $WATCOM/binw/$f ::/W/BINW/ +done +for f in stdio.h stdlib.h string.h dos.h i86.h _comdef.h malloc.h; do + [ -f $WATCOM/h/$f ] && mcopy -i boot.img $WATCOM/h/$f ::/W/H/ +done +mcopy -i boot.img $WATCOM/lib386/dos/clib3r.lib $WATCOM/lib386/dos/emu387.lib ::/W/LIB386/DOS/ +mcopy -i boot.img $WATCOM/lib386/math387r.lib ::/W/LIB386/ +dd if=/dev/zero of=esp.img bs=1M count=24 status=none +mformat -i esp.img -h 64 -s 32 -t 24 :: +mmd -i esp.img ::/EFI ::/EFI/BOOT ::/MDOS +mcopy -i esp.img "$ROOT/mdvmm/build/BOOTX64.EFI" ::/EFI/BOOT/BOOTX64.EFI +mcopy -i esp.img boot.img ::/MDOS/BOOT.IMG + +echo "== booting" +python3 "$HERE/vgawatch.py" debug.log mon.sock "$WORK/vga" 16 32 12-16 10-16 0d-16 0e-16 12-32 0d-32 & +WATCH=$! +timeout --foreground 400 qemu-system-x86_64 -m 256 -bios "$OVMF" -display none \ + -drive file=esp.img,format=raw,if=ide -nic user,model=e1000 \ + -debugcon file:debug.log -serial file:serial.log -monitor unix:mon.sock,server,nowait \ + -no-reboot /dev/null || true +sed 's/\r//g; s/\x1b\[[0-9;]*[A-Za-z]//g' serial.log | tr -d '\000' | grep -av '^$' > screen.txt +sed -n '/^=== real mode/,$p' screen.txt | grep -av "^ ok " | head -60 | sed 's/^/ /' +grep -a "^v86: a program\|^vga: \|PANIC" -A6 debug.log | head -12 | sed "s/^/ monitor: /" || true + +fail=0 +section() { sed -n "/^=== $1 *\$/,/^=== [^ ]* *[^ ]* *\$/p" screen.txt; } +for kind in "real mode" "DOS\\/4GW" "PMODE\\/W" "DOS\\/4GW again" "compiled here" "DOS\\/32A" "CauseWay"; do + name=$(echo "$kind" | tr -d '\\') + if section "$kind" | grep -aq "hello: all 5 ok"; then echo " ok UEFI: $name"; else echo " FAIL UEFI: $name"; fail=1; fi +done +for bits in 16 32; do + if section "VGA $bits" | grep -aq "vga: $bits bit, mode 13h, palette 63/0/0: all ok" && + python3 "$HERE/vgacheck.py" vga$bits.ppm; then + echo " ok UEFI: VGA mode 13h, $bits bit: palette, pixels, the picture on the framebuffer" + else echo " FAIL UEFI: VGA mode 13h, $bits bit"; fail=1; fi +done +for shot in 12-16 10-16 0d-16 0e-16 12-32 0d-32; do + mode=${shot%-*}; bits=${shot#*-} + if section "EGA $bits" | grep -aqi "ega: $bits bit, mode ${mode}h.*all ok" && + python3 "$HERE/egacheck.py" vga$shot.ppm $mode; then + echo " ok UEFI: VGA mode ${mode}h (16 colours), $bits bit: planes, registers, BIOS pixels and text" + else echo " FAIL UEFI: VGA mode ${mode}h (16 colours), $bits bit"; fail=1; fi +done +grep -aq "^=== end" screen.txt && echo " ok UEFI: ran to the end" || { echo " FAIL UEFI: did not run to the end"; fail=1; } +if [ $fail = 0 ]; then echo "COMPAT UEFI TEST: success"; exit 0; else echo "COMPAT UEFI TEST: failure"; exit 1; fi diff --git a/tests/compat/vga.c b/tests/compat/vga.c new file mode 100644 index 00000000..a8e5ae2b --- /dev/null +++ b/tests/compat/vga.c @@ -0,0 +1,88 @@ +/* VGA mode 13h, as DOS games use it (tests/compat): 320x200 in 256 + colours, pixels written to A000:0, the palette set through the DAC + ports and through the BIOS. Built for real mode and for DOS/4GW. The + upper half of the screen becomes red (colour 1, set through the ports), + the lower half green (colour 2, set through INT 10h); "VGA: showing" on + the debug port tells the test to take its picture. */ +#include +#include +#include +#include +#include + +#ifdef __386__ +#define SCREEN ((unsigned char *)0xA0000) +#define INT86 int386 +#define RW(r) r.w +#else +#define SCREEN ((unsigned char far *)MK_FP(0xA000, 0)) +#define INT86 int86 +#define RW(r) r.x +#endif + +static void say(const char *s) +{ + for (; *s; s++) + outp(0xe9, *s); +} + +static unsigned long ticks(void) +{ + union REGS r; + + memset(&r, 0, sizeof(r)); + INT86(0x1a, &r, &r); + return ((unsigned long)RW(r).cx << 16) | RW(r).dx; +} + +int main(void) +{ + union REGS r; + unsigned long t, i; + int ok = 1, mode, red, green, blue; + + memset(&r, 0, sizeof(r)); + RW(r).ax = 0x0013; + INT86(0x10, &r, &r); + memset(&r, 0, sizeof(r)); + r.h.ah = 0x0f; + INT86(0x10, &r, &r); + mode = r.h.al; + + outp(0x3c8, 1); /* colour 1: red, through the DAC */ + outp(0x3c9, 63); + outp(0x3c9, 0); + outp(0x3c9, 0); + memset(&r, 0, sizeof(r)); /* colour 2: green, through the BIOS */ + RW(r).ax = 0x1010; + RW(r).bx = 2; + r.h.ch = 63; + INT86(0x10, &r, &r); + for (i = 0; i < 32000u; i++) + SCREEN[i] = 1; + for (i = 32000u; i < 64000u; i++) + SCREEN[i] = 2; + + while (inp(0x3da) & 8) /* a vertical retrace comes and goes */ + ; + while (!(inp(0x3da) & 8)) + ; + outp(0x3c7, 1); /* the palette reads back */ + red = inp(0x3c9); + green = inp(0x3c9); + blue = inp(0x3c9); + if (red != 63 || green != 0 || blue != 0) + ok = 0; + if (SCREEN[100] != 1 || SCREEN[63999u] != 2) + ok = 0; + + say(sizeof(int) == 4 ? "VGA: showing 32\r\n" : "VGA: showing 16\r\n"); + for (t = ticks(); ticks() - t < 55;) /* three seconds */ + ; + memset(&r, 0, sizeof(r)); + RW(r).ax = 0x0003; + INT86(0x10, &r, &r); + printf("vga: %u bit, mode %02Xh, palette %d/%d/%d: %s\n", (unsigned)(sizeof(int) * 8), mode, red, green, blue, + ok && mode == 0x13 ? "all ok" : "FAILED"); + return !(ok && mode == 0x13); +} diff --git a/tests/compat/vgacheck.py b/tests/compat/vgacheck.py new file mode 100644 index 00000000..10241a02 --- /dev/null +++ b/tests/compat/vgacheck.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Check a QEMU screendump of tests/compat/vga.c: red above, green below. + +Usage: vgacheck.py shot.ppm""" +import sys + + +def main(): + d = open(sys.argv[1], "rb").read() + parts = d.split(b"\n", 3) + w, h = map(int, parts[1].split()) + px = parts[3] + + def at(x, y): + o = (y * w + x) * 3 + return tuple(px[o:o + 3]) + + top = at(w // 2, h // 2 - h // 8) + bottom = at(w // 2, h // 2 + h // 8) + good = top[0] > 200 and top[1] < 60 and top[2] < 60 and bottom[1] > 200 and bottom[0] < 60 and bottom[2] < 60 + print(" %dx%d, above the middle %s, below %s" % (w, h, top, bottom)) + return 0 if good else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/compat/vgawatch.py b/tests/compat/vgawatch.py new file mode 100644 index 00000000..72adda8b --- /dev/null +++ b/tests/compat/vgawatch.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Take QEMU screendumps when tests/compat/vga.c or ega.c say their picture +is up ("VGA: showing " on the debug port). + +Usage: vgawatch.py debug.log monitor.sock prefix [tag...] -> prefix.ppm +(without tags: 16 and 32)""" +import socket +import sys +import time + + +def main(): + log, sock, prefix = sys.argv[1:4] + tags = sys.argv[4:] or ["16", "32"] + done = set() + end = time.time() + 600 + while time.time() < end and len(done) < len(tags): + try: + text = open(log, "rb").read() + except OSError: + text = b"" + for bits in tags: + if bits not in done and ("VGA: showing %s\r" % bits).encode() in text: + time.sleep(1) # the monitor draws about 30 times a second + try: + s = socket.socket(socket.AF_UNIX) + s.connect(sock) + s.sendall(("screendump %s%s.ppm\n" % (prefix, bits)).encode()) + time.sleep(0.8) + s.close() + except OSError: + pass + done.add(bits) + time.sleep(0.2) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gui/deskcheck.py b/tests/gui/deskcheck.py new file mode 100644 index 00000000..e19afed6 --- /dev/null +++ b/tests/gui/deskcheck.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Check MDDESK's test run (see deskdrive.py). + +Usage: deskcheck.py debug.log screen.ppm +""" +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from gfxcheck import read_ppm # noqa: E402 + +PANEL = (24, 30, 40) +ACTIVE = (32, 128, 136) + + +def main(): + log = open(sys.argv[1], "rb").read().decode("latin-1") + about = re.search(r"MDDESK: window About at (\d+),(\d+)", log) + tasks = re.findall(r"MDDESK: taskbar(.*)", log) + checks = [ + ("the clock shows HH:MM", bool(re.search(r"MDDESK: clock \d\d:\d\d", log))), + ("About opened from the launcher", bool(about)), + ("MDVMM's API answers a DPMI program (About: boot via MDVMM)", + bool(re.search(r"MDDESK: about Boot: (UEFI|BIOS), MDVMM", log))), + ("the panel lists the About window", any("About modernDOS=" in t for t in tasks)), + ("Run started V86CHK (it logged again)", + log.count("v86chk: protected mode bit set") >= 2 and "MDDESK: ran A:\\V86CHK exit 0" in log), + ("back in graphics after the program", "MDDESK: resumed" in log), + ("Exit to DOS", "MDDESK: exit" in log), + ("Files: listed A:\\", bool(re.search(r"MDDESK: files A:\\ \d+:.*kernel\.sys", log, re.I))), + ("Files: new folder", "MDDESK: created A:\\Test Folder" in log), + ("Files: renamed", "MDDESK: renamed Test Folder to Renamed Dir" in log), + ("Files: opened the folder (only ..)", "MDDESK: files A:\\Renamed Dir\\ 1: .." in log), + ("Files: deleted", "MDDESK: deleted A:\\Renamed Dir" in log), + ("Editor: opened from Files", "MDDESK: editor opened A:\\Created On Linux.txt, 1 lines" in log), + ("Editor: saved with Ctrl+S (53 bytes, CRLF)", + "MDDESK: editor saved A:\\Created On Linux.txt, 53 bytes: hello from linux - edited in modernDOS" + in log), + ("Editor: closed", "MDDESK: editor closed" in log), + ("Settings: saved", "MDDESK: settings saved background=Ocean accent=Orange clock=12 mouse=Normal" + in log), + ("Settings: the clock went to 12 hours", bool(re.search(r"MDDESK: clock \d{1,2}:\d\d [AP]M", log))), + ("Settings: the next MDDESK loads them", + "MDDESK: settings loaded background=Ocean accent=Orange clock=12 mouse=Normal" in log), + # a 32-bit program started from the desktop: a client's client + ("Run started DPMITEST, a DPMI program (a client started by a client), it passed", + bool(re.search(r"dpmi: 32 bit client, PSP \w+, session \d, started by a client", log)) + and bool(re.search(r"MDDESK: ran A:\\DPMITEST exit [01]\b", log)) + and len(re.findall(r"DPMI: [01] failures", log)) >= 2), # (its 24 MB may not be free beside the desktop) + # the terminal: a DOS session in a window where there are job slots + # (TERMINAL=1), a message elsewhere + ("Terminal: a DOS session in a window, typed command's output shown, closed by EXIT" + if os.environ.get("TERMINAL") else "Terminal: says why it cannot open here", + ("MDDESK: term opened in session" in log and "MDDESK: term line Terminal 123" in log + and "MDDESK: term closed" in log) + if os.environ.get("TERMINAL") else "MDDESK: term unavailable" in log), + ("Terminal: a DPMI program ran in its session beside the desktop" + if os.environ.get("TERMINAL") else "Terminal: no DPMI program tried", + len(re.findall(r"DPMI: [01] failures", log)) >= 3 if os.environ.get("TERMINAL") else True), + # the browser, where the test has a web server (BROWSER=port) + ("Browser: start page, a page by its address, a link followed" + if os.environ.get("BROWSER") else "Browser: not tested on this boot", + ("MDDESK: browser loaded about:start" in log + and bool(re.search(r"MDDESK: browser loaded http://10\.0\.2\.2:\d+/ title=Test Page lines=\d+ links=2", log)) + and bool(re.search(r"MDDESK: browser loaded http://10\.0\.2\.2:\d+/sub/page2\.html title=Second Page", log))) + if os.environ.get("BROWSER") else True), + ("Files: gone from the listing", + bool(re.findall(r"MDDESK: files A:\\ \d+:(.*)", log)) + and "Renamed Dir" not in re.findall(r"MDDESK: files A:\\ \d+:(.*)", log)[-1]), + ] + try: + w, h, px = read_ppm(sys.argv[2]) + + def pixel(x, y): + i = (y * w + x) * 3 + return tuple(px[i:i + 3]) + + checks.append(("panel drawn after resuming", pixel(w // 2, 2) == PANEL)) + if about: + ax, ay = int(about.group(1)), int(about.group(2)) + checks.append(("About window drawn, active", pixel(ax + 200, ay + 12) == ACTIVE)) + except (OSError, ValueError) as e: + checks.append(("screenshot: %s" % e, False)) + try: + sw, sh, spx = read_ppm(os.path.join(os.path.dirname(os.path.abspath(sys.argv[2])), + "settings.ppm")) + + def spixel(x, y): + i = (y * sw + x) * 3 + return tuple(spx[i:i + 3]) + + win = re.search(r"MDDESK: window Settings at (\d+),(\d+)", log) + checks.append(("Settings: Ocean desktop", spixel(10, sh - 1) == (8, 28, 52))) + if win: + wx, wy = int(win.group(1)), int(win.group(2)) + checks.append(("Settings: Orange title bar", + spixel(wx + 200, wy + 12) == (196, 104, 32))) + except (OSError, ValueError) as e: + checks.append(("settings screenshot: %s" % e, False)) + fail = 0 + for name, ok in checks: + print(" %s desk: %s" % ("ok " if ok else "FAIL", name)) + fail |= not ok + return fail + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gui/deskdrive.py b/tests/gui/deskdrive.py new file mode 100644 index 00000000..e270efc3 --- /dev/null +++ b/tests/gui/deskdrive.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +r"""Drive MDDESK /TEST through the QEMU monitor (see gui/desk/desk.c). + +Usage: deskdrive.py debug.log monitor.sock out.ppm +Opens About from the launcher, opens Run, runs V86CHK (a DOS program: +it logs again), returns to the desktop with a key, takes a screenshot; +then the file manager: creates, renames, opens and deletes a folder on +A:; then opens A:\Created On Linux.txt in the editor from Files, adds to +it, saves with Ctrl+S, closes; then Settings: Ocean, Orange, 12-hour +clock, Save; exits through the launcher. (AUTOEXEC then starts MDDESK +/TEST /EXIT, which must load those settings.) +""" +import os +import re +import sys +import time + +from guidrive import Mouse, send, text, type_text, wait + + +def point(log, name, kind="(?:widget|item)"): + found = re.findall(r"MDDESK: %s %s (\d+),(\d+)" % (kind, re.escape(name)), text(log)) + return int(found[-1][0]), int(found[-1][1]) + + +def file_item(log, name): + return point(log, name, "fileitem") + + +def files(mouse, sock, log, shot): + """The file manager: create, rename, open, leave, delete a folder.""" + mouse.click(*point(log, "launcher")) + time.sleep(0.5) + mouse.click(*point(log, "files")) + wait(log, "MDDESK: window Files", 10) + time.sleep(0.5) + mouse.click(*point(log, "files_newfolder")) + wait(log, "MDDESK: widget dialogfield", 5) + type_text(sock, "Test Folder\n") + wait(log, "MDDESK: created", 10) + time.sleep(0.5) + mouse.click(*file_item(log, "Test Folder")) + mouse.click(*point(log, "files_rename")) + time.sleep(0.5) + for _ in range(len("Test Folder")): + send(sock, "sendkey backspace") + type_text(sock, "Renamed Dir\n") + wait(log, "MDDESK: renamed", 10) + time.sleep(1) + send(sock, "screendump %s" % shot) + time.sleep(1) + mouse.click(*file_item(log, "Renamed Dir")) + send(sock, "sendkey ret") # open the folder + wait(log, "MDDESK: files A:\\Renamed Dir\\", 10) + time.sleep(0.5) + mouse.click(*point(log, "files_up")) + time.sleep(1) + mouse.click(*file_item(log, "Renamed Dir")) + mouse.click(*point(log, "files_delete")) + wait(log, "MDDESK: widget confirmyes", 5) + time.sleep(0.3) + send(sock, "sendkey ret") # Yes + wait(log, "MDDESK: deleted", 10) + + +def editor(mouse, sock, log, shot): + """Open a text file from Files in the editor, change it, save, close.""" + mouse.click(*file_item(log, "Created On Linux.txt")) + send(sock, "sendkey ret") + if not wait(log, "MDDESK: editor opened", 10): + return + m = re.findall(r"MDDESK: window Editor at (\d+),(\d+)", text(log))[-1] + time.sleep(0.5) + send(sock, "sendkey end") + type_text(sock, " - edited in modernDOS\nsecond line") + send(sock, "sendkey ctrl-s") + wait(log, "MDDESK: editor saved", 10) + time.sleep(1) + send(sock, "screendump %s" % shot) + time.sleep(1) + x, y = int(m[0]), int(m[1]) + mouse.click(x + 660 - 22 + 9, y + 12) # the close button + wait(log, "MDDESK: editor closed", 10) + + +def settings(mouse, sock, log, shot): + """Settings: Ocean background, Orange accent, 12-hour clock, save.""" + mouse.click(*point(log, "launcher")) + time.sleep(0.5) + mouse.click(*point(log, "settings")) + if not wait(log, "MDDESK: window Settings", 10): + return + time.sleep(0.5) + mouse.click(*point(log, "bg_Ocean")) + mouse.click(*point(log, "accent_Orange")) + mouse.click(*point(log, "settings_clock24")) + mouse.click(*point(log, "settings_save")) + wait(log, "MDDESK: settings saved", 10) + time.sleep(1) + send(sock, "screendump %s" % shot) + time.sleep(1) + mouse.click(*point(log, "settings_close")) + time.sleep(0.5) + + +def terminal(mouse, sock, log, shot): + """The terminal: a DOS session in a window (with job slots; without it + says why not).""" + mouse.click(*point(log, "launcher")) + time.sleep(0.5) + mouse.click(*point(log, "terminal")) + if not wait(log, "MDDESK: term opened", 5): + return # "term unavailable": a message window + if not wait(log, "MDDESK: term ready", 30): + return + time.sleep(0.5) + type_text(sock, "ECHO Terminal 123\n") + wait(log, "MDDESK: term line Terminal 123", 20) + # a 32-bit program in the terminal's session, beside the desktop (each + # session has its own DPMI client) + before = len(re.findall(r"DPMI: \d+ failures", text(log))) + type_text(sock, "A:\\DPMITEST\n") + end = time.time() + 60 + while time.time() < end and len(re.findall(r"DPMI: \d+ failures", text(log))) == before: + time.sleep(0.5) + print("deskdrive: DPMITEST in the terminal: %s" % + ("done" if len(re.findall(r"DPMI: \d+ failures", text(log))) > before else "NOT done")) + time.sleep(1) + send(sock, "screendump %s" % shot) + time.sleep(1) + type_text(sock, "EXIT\n") + wait(log, "MDDESK: term closed", 20) + time.sleep(0.5) + + +def browser(mouse, sock, log, shot): + """The browser (BROWSER=port: a web server at 10.0.2.2:port): the start + page, a page by address, a link.""" + port = os.environ.get("BROWSER") + if not port: + return + mouse.click(*point(log, "launcher")) + time.sleep(0.5) + mouse.click(*point(log, "browser")) + if not wait(log, "MDDESK: browser loaded about:start", 10): + return + time.sleep(0.5) + mouse.click(*point(log, "browser_addr")) + for _ in range(len("about:start")): + send(sock, "sendkey backspace") + type_text(sock, "10.0.2.2:%s/\n" % port) + if not wait(log, "title=Test Page", 60): + return + time.sleep(1) + found = re.findall(r"MDDESK: browser link 1 at (\d+),(\d+)", text(log)) + if found: + mouse.click(int(found[-1][0]), int(found[-1][1])) + wait(log, "title=Second Page", 60) + time.sleep(1) + send(sock, "screendump %s" % shot) + time.sleep(1) + + +def main(): + log, sock, out = sys.argv[1:4] + if not wait(log, "MDDESK: ready", 290): + return 1 + mouse = Mouse(sock, log, "MDDESK") + time.sleep(1) + mouse.click(*point(log, "launcher")) + wait(log, "MDDESK: item exit", 5) + mouse.click(*point(log, "about")) # About modernDOS + wait(log, "MDDESK: window About", 5) + mouse.click(*point(log, "launcher")) + time.sleep(0.5) + mouse.click(*point(log, "run")) # Run... + wait(log, "MDDESK: widget runbutton", 5) + mouse.click(*point(log, "runfield")) + type_text(sock, "A:\\V86CHK") # full path: DJTEST left the cwd elsewhere + send(sock, "sendkey ret") + wait(log, "MDDESK: ran", 30) + time.sleep(1) + send(sock, "sendkey spc") # back to the desktop + wait(log, "MDDESK: resumed", 10) + time.sleep(1.5) + # Run... with a 32-bit program: a DPMI client started by a client + mouse.click(*point(log, "launcher")) + time.sleep(0.5) + mouse.click(*point(log, "run")) + wait(log, "MDDESK: widget runbutton", 5) + time.sleep(0.5) + mouse.click(*point(log, "runfield")) + time.sleep(0.5) + type_text(sock, "A:\\DPMITEST") + send(sock, "sendkey ret") + wait(log, "MDDESK: ran A:\\DPMITEST", 60) + time.sleep(1) + send(sock, "sendkey spc") + time.sleep(3) + send(sock, "screendump %s" % out) + time.sleep(1) + files(mouse, sock, log, os.path.join(os.path.dirname(out), "files.ppm")) + time.sleep(1) + editor(mouse, sock, log, os.path.join(os.path.dirname(out), "editor.ppm")) + time.sleep(1) + settings(mouse, sock, log, os.path.join(os.path.dirname(out), "settings.ppm")) + time.sleep(1) + terminal(mouse, sock, log, os.path.join(os.path.dirname(out), "term.ppm")) + time.sleep(1) + browser(mouse, sock, log, os.path.join(os.path.dirname(out), "browser.ppm")) + time.sleep(1) + mouse.click(*point(log, "launcher")) + time.sleep(0.5) + mouse.click(*point(log, "exit")) # Exit to DOS + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gui/gfxcheck.py b/tests/gui/gfxcheck.py new file mode 100644 index 00000000..dd40f88f --- /dev/null +++ b/tests/gui/gfxcheck.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Check a screenshot (PPM) of GFXTEST's pattern. + +Usage: gfxcheck.py screen.ppm debug.log +The mode size comes from the "GFXTEST: drawn WxH" line in the debug log. +Prints ok/FAIL lines, exit code 1 on failure. +""" +import re +import sys + + +def read_ppm(path): + data = open(path, "rb").read() + fields, pos = [], 0 + while len(fields) < 4: # P6, width, height, maxval + while data[pos:pos + 1].isspace(): + pos += 1 + if data[pos:pos + 1] == b"#": + pos = data.index(b"\n", pos) + 1 + continue + end = pos + while not data[end:end + 1].isspace(): + end += 1 + fields.append(data[pos:end]) + pos = end + pos += 1 + if fields[0] != b"P6" or int(fields[3]) != 255: + raise ValueError("not a P6 PPM with maxval 255") + return int(fields[1]), int(fields[2]), data[pos:] + + +def main(): + ppm, log = sys.argv[1], sys.argv[2] + m = re.search(rb"GFXTEST: drawn (\d+)x(\d+)", open(log, "rb").read()) + if not m: + print(" FAIL gfx: no 'GFXTEST: drawn' in the log") + return 1 + w, h = int(m.group(1)), int(m.group(2)) + try: + pw, ph, px = read_ppm(ppm) + except (OSError, ValueError) as e: + print(" FAIL gfx: screenshot: %s" % e) + return 1 + + def pixel(x, y): + i = (y * pw + x) * 3 + return tuple(px[i:i + 3]) + + checks = [ + ("screenshot is %dx%d" % (w, h), (pw, ph) == (w, h)), + ("top left red", pixel(60, 60) == (255, 0, 0)), + ("top right green", pixel(w - 60, 60) == (0, 255, 0)), + ("bottom left blue", pixel(60, h - 60) == (0, 0, 255)), + ("bottom right white", pixel(w - 60, h - 60) == (255, 255, 255)), + ("background", pixel(w // 2, h // 4) == (32, 48, 64)), + ("clipped fill left the red box alone", pixel(122, 60) == (32, 48, 64) + and pixel(5, 5) == (255, 0, 0)), + ("gradient: top darker than bottom", sum(pixel(w // 2, h // 2 - 58)) < + sum(pixel(w // 2, h // 2 - 23))), + ] + fail = 0 + for name, ok in checks: + print(" %s gfx: %s" % ("ok " if ok else "FAIL", name)) + fail |= not ok + return fail + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gui/gfxshot.py b/tests/gui/gfxshot.py new file mode 100644 index 00000000..d6f85fbc --- /dev/null +++ b/tests/gui/gfxshot.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Wait for "GFXTEST: drawn" in the debug log, then save the screen. + +Usage: gfxshot.py debug.log monitor.sock out.ppm [timeout] +Runs next to QEMU (in the background); the monitor is the HMP socket. +""" +import os +import socket +import sys +import time + + +def main(): + log, sock, out = sys.argv[1:4] + deadline = time.time() + (float(sys.argv[4]) if len(sys.argv) > 4 else 290) + while time.time() < deadline: + try: + if b"GFXTEST: drawn" in open(log, "rb").read(): + break + except OSError: + pass + time.sleep(0.2) + else: + return 1 + time.sleep(0.5) # let the display update + s = socket.socket(socket.AF_UNIX) + s.connect(sock) + s.sendall(("screendump %s\n" % out).encode()) + time.sleep(1) + s.close() + return 0 if os.path.exists(out) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gui/gfxtest.c b/tests/gui/gfxtest.c new file mode 100644 index 00000000..6709b43d --- /dev/null +++ b/tests/gui/gfxtest.c @@ -0,0 +1,80 @@ +/* + * GFXTEST - mdgui graphics test (DJGPP). + * + * Opens a 32 bpp linear framebuffer mode (1024x768 if there is one), + * draws a known pattern and logs "GFXTEST: drawn WxH" to port E9h; the + * harness then takes a screenshot and checks pixels (tests/gui/gfxcheck.py): + * - 120x120 boxes in the corners: red, green, blue, white (top left, + * top right, bottom left, bottom right) + * - background RGB(32,48,64) + * - a gradient bar and text in the middle + * After 3 seconds it returns to text mode; exit code 0 if all went well. + */ +#include +#include +#include +#include +#include +#include "mdgui.h" + +static void out(const char *s) +{ + for (; *s; s++) + { + if (*s == '\n') + outportb(0xe9, '\r'); + outportb(0xe9, *s); + } +} + +static unsigned long ticks(void) +{ + return _farpeekl(_dos_ds, 0x46c); +} + +int main(void) +{ + struct surface *s; + const struct gfx_mode *m; + char buf[128]; + unsigned long t; + int w, h; + + out("\ngraphics test\n"); + if (gfx_open(1024, 768)) + { + sprintf(buf, "GFXTEST: failed: %s\n", gfx_error()); + out(buf); + return 1; + } + m = gfx_mode(); + s = gfx_screen(); + w = m->w; + h = m->h; + + draw_fill(s, 0, 0, w, h, RGB(32, 48, 64)); + draw_fill(s, 0, 0, 120, 120, RGB(255, 0, 0)); + draw_fill(s, w - 120, 0, 120, 120, RGB(0, 255, 0)); + draw_fill(s, 0, h - 120, 120, 120, RGB(0, 0, 255)); + draw_fill(s, w - 120, h - 120, 120, 120, RGB(255, 255, 255)); + draw_gradient(s, w / 2 - 200, h / 2 - 60, 400, 40, RGB(40, 80, 200), RGB(200, 230, 255)); + draw_frame(s, w / 2 - 201, h / 2 - 61, 402, 42, RGB(255, 255, 255)); + draw_text(s, w / 2 - text_width("modernDOS graphics") / 2, h / 2 + 10, + "modernDOS graphics", RGB(255, 220, 80), TEXT_TRANSPARENT); + draw_line(s, 120, 120, w - 120, h - 120, RGB(255, 128, 0)); + /* clipping: this must not touch the top left box */ + surface_clip(s, 130, 0, w - 130, h); + draw_fill(s, 0, 0, 125, 125, RGB(255, 0, 255)); + surface_noclip(s); + gfx_present_all(); + + sprintf(buf, "GFXTEST: drawn %dx%d, VBE mode %x, framebuffer %08lx\n", w, h, m->vbe_mode, + (unsigned long)m->phys); + out(buf); + for (t = ticks(); ticks() - t < 55;) /* 3 s for the screenshot */ + ; + gfx_close(); + printf("Back in text mode after graphics.\n"); + out("GFXTEST: text mode again\n"); + return 0; +} diff --git a/tests/gui/guidrive.py b/tests/gui/guidrive.py new file mode 100644 index 00000000..1dbee60f --- /dev/null +++ b/tests/gui/guidrive.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Shared helpers for driving GUI tests through the QEMU monitor. + +QEMU sends relative mouse motion, which mouse drivers scale and accelerate +(CTMOUSE does), so the pointer is steered closed loop: the test program +logs every position (": at X,Y", first ": ready at X,Y") +and moves are repeated until it is there. +""" +import re +import time + +from mousedrive import send, text, wait # noqa: F401 (re-exported) + +STEP = 40 + + +class Mouse: + def __init__(self, sock, log, prefix): + self.sock, self.log = sock, log + self.pattern = re.compile(prefix + r": (?:ready )?at (\d+),(\d+)") + + def pos(self): + found = self.pattern.findall(text(self.log)) + return int(found[-1][0]), int(found[-1][1]) + + def go(self, x, y): + """Steer to x,y; the step halves on an axis when it overshoots + (accelerating drivers). Exact if possible, else within 3 pixels.""" + step = [STEP, STEP] + last = [0, 0] + for i in range(300): + cx, cy = self.pos() + err = [x - cx, y - cy] + if err == [0, 0] or (i > 150 and abs(err[0]) <= 3 and abs(err[1]) <= 3): + return True + for a in (0, 1): + if err[a] * last[a] < 0: # overshot: smaller steps + step[a] = max(1, step[a] // 2) + last[a] = err[a] + dx = max(-step[0], min(step[0], err[0])) + dy = max(-step[1], min(step[1], err[1])) + send(self.sock, "mouse_move %d %d" % (dx, dy)) + time.sleep(0.15) + return False + + def button(self, down): + send(self.sock, "mouse_button %d" % (1 if down else 0)) + time.sleep(0.3) + + def click(self, x, y): + self.go(x, y) + self.button(True) + self.button(False) + + +KEYS = {" ": "spc", "\n": "ret", "\t": "tab", ".": "dot", ",": "comma", "-": "minus", + ":": "shift-semicolon", "\\": "backslash", "/": "slash"} + + +def type_text(sock, s): + for c in s: + k = KEYS.get(c, c) + if c.isupper(): + k = "shift-" + c.lower() + send(sock, "sendkey " + k) + time.sleep(0.1) diff --git a/tests/gui/mousecheck.py b/tests/gui/mousecheck.py new file mode 100644 index 00000000..073ac40a --- /dev/null +++ b/tests/gui/mousecheck.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Check MOUSETEST's results: the click position and the screenshot. + +Usage: mousecheck.py debug.log screen.ppm [loose] +The click must be at the start position + (120, 60) (mousedrive.py); with +"loose" (a mouse driver with acceleration, e.g. CTMOUSE) only right and +down. The screenshot must show the orange square there and the cursor. +""" +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from gfxcheck import read_ppm # noqa: E402 + +DX, DY = 120, 60 + + +def main(): + log = open(sys.argv[1], "rb").read().decode("latin-1") + ready = re.search(r"MOUSETEST: ready (\d+)x(\d+) at (\d+),(\d+), mouse (\w+)", log) + click = re.search(r"MOUSETEST: click at (\d+),(\d+)", log) + checks = [("mouse driver found", bool(ready) and ready.group(5) == "yes"), + ("a click arrived", bool(click))] + if ready and click: + x0, y0 = int(ready.group(3)), int(ready.group(4)) + cx, cy = int(click.group(1)), int(click.group(2)) + if len(sys.argv) > 3 and sys.argv[3] == "loose": + checks.append(("click moved right and down: (%d,%d)" % (cx - x0, cy - y0), + cx > x0 and cy > y0)) + else: + checks.append(("click at start + (%d,%d): got (%d,%d)" % (DX, DY, cx - x0, cy - y0), + (cx - x0, cy - y0) == (DX, DY))) + try: + w, h, px = read_ppm(sys.argv[2]) + + def pixel(x, y): + i = (y * w + x) * 3 + return tuple(px[i:i + 3]) + + checks.append(("orange square at the click", pixel(cx - 8, cy - 8) == (255, 140, 0))) + # the cursor's tip is at the click position: outline, then fill + checks.append(("cursor drawn at the click", + pixel(cx, cy) == (16, 16, 16) and pixel(cx + 1, cy + 3) == (255, 255, 255))) + except (OSError, ValueError) as e: + checks.append(("screenshot: %s" % e, False)) + checks.append(("MOUSETEST finished", "MOUSETEST: done" in log)) + fail = 0 + for name, ok in checks: + print(" %s mouse: %s" % ("ok " if ok else "FAIL", name)) + fail |= not ok + return fail + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gui/mousedrive.py b/tests/gui/mousedrive.py new file mode 100644 index 00000000..1ef0f42b --- /dev/null +++ b/tests/gui/mousedrive.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Drive MOUSETEST through the QEMU monitor and check it. + +Usage: mousedrive.py debug.log monitor.sock out.ppm +Waits for "MOUSETEST: ready", moves the mouse by (+120, +60) in small +steps, clicks the left button, waits for "MOUSETEST: click", saves a +screenshot and presses q. Runs next to QEMU (in the background); the +checks are done afterwards by mousecheck.py. +""" +import socket +import sys +import time + +DX, DY, STEPS = 120, 60, 12 + + +def text(path): + try: + return open(path, "rb").read().decode("latin-1") + except OSError: + return "" + + +def send(sock, cmd): + for _ in range(20): # the monitor serves one client at a time + try: + s = socket.socket(socket.AF_UNIX) + s.connect(sock) + s.sendall((cmd + "\n").encode()) + time.sleep(0.2) + s.close() + return + except OSError: + time.sleep(0.3) + + +def wait(log, marker, seconds): + end = time.time() + seconds + while time.time() < end: + if marker in text(log): + return True + time.sleep(0.2) + return False + + +def main(): + log, sock, out = sys.argv[1:4] + if not wait(log, "MOUSETEST: ready", 290): + return 1 + time.sleep(1) + for _ in range(STEPS): + send(sock, "mouse_move %d %d" % (DX // STEPS, DY // STEPS)) + time.sleep(0.5) + send(sock, "mouse_button 1") + send(sock, "mouse_button 0") + if wait(log, "MOUSETEST: click", 10): + time.sleep(0.5) + send(sock, "screendump %s" % out) + time.sleep(1) + send(sock, "sendkey q") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gui/mousetest.c b/tests/gui/mousetest.c new file mode 100644 index 00000000..40df0b6e --- /dev/null +++ b/tests/gui/mousetest.c @@ -0,0 +1,75 @@ +/* + * MOUSETEST - mdgui input test (DJGPP). + * + * Graphics mode with the mouse cursor in the middle; logs to port E9h: + * "MOUSETEST: ready WxH at X,Y" - start position + * "MOUSETEST: click at X,Y" - left button pressed (an orange + * square is drawn there) + * "MOUSETEST: done" - after 'q' or Esc + * The harness (tests/gui/mousedrive.py) moves the mouse, clicks, takes a + * screenshot and presses q. Exit code 1 without a mouse or a click. + */ +#include +#include +#include "mdgui.h" + +static void out(const char *s) +{ + for (; *s; s++) + { + if (*s == '\n') + outportb(0xe9, '\r'); + outportb(0xe9, *s); + } +} + +int main(void) +{ + struct surface *s; + struct event e; + char buf[96]; + int clicks = 0, moves = 0, mouse; + + out("\nmouse test\n"); + if (gfx_open(1024, 768)) + { + sprintf(buf, "MOUSETEST: failed: %s\n", gfx_error()); + out(buf); + return 1; + } + s = gfx_screen(); + draw_gradient(s, 0, 0, s->w, s->h, RGB(20, 40, 70), RGB(60, 90, 120)); + draw_text(s, 20, 20, "Mouse test: click, then press q", RGB(255, 255, 255), TEXT_TRANSPARENT); + gfx_present_all(); + mouse = input_open(); + gfx_cursor_move(s->w / 2, s->h / 2); + gfx_cursor_show(1); + sprintf(buf, "MOUSETEST: ready %dx%d at %d,%d, mouse %s\n", s->w, s->h, s->w / 2, s->h / 2, + mouse ? "yes" : "no"); + out(buf); + + for (;;) + { + input_wait(&e); + if (e.type == EV_MOUSE_MOVE) + { + gfx_cursor_move(e.x, e.y); + moves++; + } + else if (e.type == EV_MOUSE_DOWN && e.button == MB_LEFT) + { + draw_fill(s, e.x - 10, e.y - 10, 20, 20, RGB(255, 140, 0)); + gfx_present(e.x - 10, e.y - 10, 20, 20); + sprintf(buf, "MOUSETEST: click at %d,%d\n", e.x, e.y); + out(buf); + clicks++; + } + else if (e.type == EV_KEY && (e.ascii == 'q' || e.ascii == 27)) + break; + } + input_close(); + gfx_close(); + sprintf(buf, "MOUSETEST: done, %d moves, %d clicks\n", moves, clicks); + out(buf); + return !(mouse && clicks); +} diff --git a/tests/gui/ppm2png.py b/tests/gui/ppm2png.py new file mode 100644 index 00000000..f59450fd --- /dev/null +++ b/tests/gui/ppm2png.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +"""Convert QEMU screendumps (PPM) to PNG, next to the originals. +Usage: ppm2png.py shot.ppm ...""" +import struct +import sys +import zlib + + +def conv(src, dst): + d = open(src, "rb").read() + parts = d.split(b"\n", 3) + w, h = map(int, parts[1].split()) + px = parts[3] + raw = b"".join(b"\0" + px[y * w * 3:(y + 1) * w * 3] for y in range(h)) + + def chunk(t, b): + return struct.pack(">I", len(b)) + t + b + struct.pack(">I", zlib.crc32(t + b)) + + open(dst, "wb").write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")) + + +for a in sys.argv[1:]: + conv(a, a[:-4] + ".png") diff --git a/tests/gui/uicheck.py b/tests/gui/uicheck.py new file mode 100644 index 00000000..f3d2a705 --- /dev/null +++ b/tests/gui/uicheck.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Check UITEST's results (see uitest.c, uidrive.py). + +Usage: uicheck.py debug.log screen.ppm +""" +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from gfxcheck import read_ppm # noqa: E402 + +ACCENT = (32, 128, 136) +SELECTED_UNFOCUSED = (196, 204, 214) + + +def main(): + log = open(sys.argv[1], "rb").read().decode("latin-1") + w = {m[0]: (int(m[1]), int(m[2])) + for m in re.findall(r"UITEST: widget (\w+) (\d+),(\d+)", log)} + checks = [ + ("OK: typed text, checkbox on (Tab+Space), Item 3", + "UITEST: ok text=hello check=1 list=Item 3" in log), + ("File/Quit chosen with the keyboard", "UITEST: menu File/Quit" in log), + ("UITEST finished", "UITEST: done" in log), + ] + try: + width, h, px = read_ppm(sys.argv[2]) + + def pixel(x, y): + i = (y * width + x) * 3 + return tuple(px[i:i + 3]) + + cx, cy = w["checkbox"] + checks.append(("checkbox drawn checked", pixel(cx, cy) == ACCENT)) + ix, iy = w["item3"] + checks.append(("Item 3 drawn selected", pixel(ix + 60, iy - 7) == SELECTED_UNFOCUSED)) + tx, ty = w["text"] + dark = sum(1 for x in range(tx - 106, tx - 60) for y in range(ty - 6, ty + 6) + if sum(pixel(x, y)) < 200) + checks.append(("text field shows the typed text", dark > 20)) + except (OSError, ValueError, KeyError) as e: + checks.append(("screenshot: %s" % e, False)) + fail = 0 + for name, ok in checks: + print(" %s ui: %s" % ("ok " if ok else "FAIL", name)) + fail |= not ok + return fail + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gui/uidrive.py b/tests/gui/uidrive.py new file mode 100644 index 00000000..07e808d3 --- /dev/null +++ b/tests/gui/uidrive.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Drive UITEST through the QEMU monitor (see uitest.c). + +Usage: uidrive.py debug.log monitor.sock out.ppm +""" +import re +import sys +import time + +from guidrive import Mouse, send, text, type_text, wait + + +def main(): + log, sock, out = sys.argv[1:4] + if not wait(log, "UITEST: ready", 290): + return 1 + w = {m[0]: (int(m[1]), int(m[2])) + for m in re.findall(r"UITEST: widget (\w+) (\d+),(\d+)", text(log))} + mouse = Mouse(sock, log, "UITEST") + time.sleep(1) + mouse.click(*w["text"]) # the text field + type_text(sock, "hello") + send(sock, "sendkey tab") # focus: the checkbox + send(sock, "sendkey spc") # on + mouse.click(*w["item3"]) + mouse.click(*w["ok"]) + wait(log, "UITEST: ok", 10) + time.sleep(1) + send(sock, "screendump %s" % out) + time.sleep(1) + mouse.click(*w["file"]) # File menu + time.sleep(0.5) + send(sock, "sendkey down") # Quit + send(sock, "sendkey ret") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gui/uitest.c b/tests/gui/uitest.c new file mode 100644 index 00000000..9c57f135 --- /dev/null +++ b/tests/gui/uitest.c @@ -0,0 +1,151 @@ +/* + * UITEST - mdgui widget toolkit test (DJGPP). + * + * A window with a menu bar (File: New, Quit; Help: About), a label, a + * text field, a checkbox, a scrolling list of 12 items and OK / Cancel + * buttons. Logs to port E9h: + * "UITEST: ready at X,Y", "UITEST: at X,Y" (mouse; the harness steers + * by it), "UITEST: widget NAME X,Y" (screen points to click), + * "UITEST: ok text=T check=C list=L" (OK button), + * "UITEST: menu MENU/ITEM", "UITEST: done" + * The harness (tests/gui/uidrive.py) types into the field, toggles the + * checkbox with Tab + Space, picks Item 3, clicks OK, takes a screenshot + * and quits through File/Quit with the keyboard. + */ +#include +#include +#include +#include "mdgui.h" + +static int quit; +static struct widget *text, *check, *list; + +static const char *const items[] = { + "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", + "Item 7", "Item 8", "Item 9", "Item 10", "Item 11", "Item 12", +}; +static const char *const file_items[] = { "New", "Quit" }; +static const char *const help_items[] = { "About" }; +static const struct ui_menu menus[] = { + { "File", file_items, 2 }, + { "Help", help_items, 1 }, +}; + +static void out(const char *s) +{ + for (; *s; s++) + { + if (*s == '\n') + outportb(0xe9, '\r'); + outportb(0xe9, *s); + } +} + +static void ok(struct widget *w) +{ + char buf[200]; + + (void)w; + sprintf(buf, "UITEST: ok text=%s check=%d list=%s\n", text->text, check->value, + list->value >= 0 ? items[list->value] : "none"); + out(buf); +} + +static void cancel(struct widget *w) +{ + (void)w; + out("UITEST: cancel\n"); +} + +static void menu(struct widget *w) +{ + char buf[96]; + const struct ui_menu *m = &w->menus[w->menu]; + + sprintf(buf, "UITEST: menu %s/%s\n", m->title, m->items[w->value]); + out(buf); + if (!strcmp(m->items[w->value], "Quit")) + quit = 1; +} + +static int window_events(struct window *w, const struct event *e) +{ + (void)w; + if (e->type == EV_CLOSE) + { + quit = 1; + return 1; + } + return 0; +} + +static void widget_at(const char *name, struct widget *w, int dx, int dy) +{ + char buf[96]; + int x, y; + + ui_widget_center(w, &x, &y); + sprintf(buf, "UITEST: widget %s %d,%d\n", name, x + dx, y + dy); + out(buf); +} + +int main(void) +{ + struct surface *s; + struct window *win; + struct widget *bar, *okb; + struct ui *ui; + char buf[96]; + + out("\nwidget test\n"); + if (gfx_open(1024, 768)) + { + sprintf(buf, "UITEST: failed: %s\n", gfx_error()); + out(buf); + return 1; + } + s = gfx_screen(); + input_open(); + wm_init(); + win = wm_window_new(150, 90, 480, 380, "Widgets"); + win->handler = window_events; + ui = ui_new(win); + bar = ui_menubar(ui, menus, 2, menu); + ui_label(ui, 16, 40, "Name:"); + text = ui_textfield(ui, 80, 36, 220, 0); + check = ui_check(ui, 16, 76, "Subscribe to news", 0); + list = ui_list(ui, 16, 110, 200, 124, items, 12, 0); + okb = ui_button(ui, 240, 110, 100, 30, "OK", ok); + ui_button(ui, 240, 150, 100, 30, "Cancel", cancel); + ui_label(ui, 16, 250, "Tab moves the focus, F10 opens the menu."); + ui_focus(text); + ui_redraw(ui); + wm_update(); + + widget_at("text", text, 0, 0); + widget_at("checkbox", check, -check->w / 2 + 4, -check->h / 2 + 5); /* in the box */ + widget_at("item3", list, 0, -list->h / 2 + 2 + 2 * 20 + 10); + widget_at("ok", okb, 0, 0); + widget_at("file", bar, -bar->w / 2 + 8 + text_width("File") / 2, 0); + gfx_cursor_move(s->w / 2, s->h / 2); + gfx_cursor_show(1); + sprintf(buf, "UITEST: ready at %d,%d\n", s->w / 2, s->h / 2); + out(buf); + + while (!quit) + { + struct event e; + input_wait(&e); + if (e.type == EV_MOUSE_MOVE) + { + sprintf(buf, "UITEST: at %d,%d\n", e.x, e.y); + out(buf); + } + wm_dispatch(&e); + wm_update(); + } + input_close(); + gfx_close(); + out("UITEST: done\n"); + return 0; +} diff --git a/tests/gui/wmcheck.py b/tests/gui/wmcheck.py new file mode 100644 index 00000000..fbe0c670 --- /dev/null +++ b/tests/gui/wmcheck.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Check WMTEST's results (see wmtest.c, wmdrive.py). + +Usage: wmcheck.py debug.log screen.ppm +""" +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from gfxcheck import read_ppm # noqa: E402 + +RED, GREEN, BLUE = (200, 60, 60), (60, 180, 90), (60, 100, 200) +TITLE_ACTIVE = (32, 128, 136) + + +def near(pos, want, tol=3): + return pos is not None and abs(pos[0] - want[0]) <= tol and abs(pos[1] - want[1]) <= tol + + +def main(): + log = open(sys.argv[1], "rb").read().decode("latin-1") + done = re.search(r"WMTEST: done(.*)", log) + pos = {} + if done: + for name, x, y in re.findall(r"(\w+)=(\d+),(\d+)", done.group(1)): + pos[name] = (int(x), int(y)) + checks = [ + ("Beta got the click", "WMTEST: click in Beta" in log), + ("Alpha dragged to (300,350): %s" % (pos.get("Alpha"),), near(pos.get("Alpha"), (300, 350))), + ("Beta and Gamma stayed", pos.get("Beta") == (300, 200) and pos.get("Gamma") == (600, 120)), + ("Beta on top", bool(done) and "top=Beta" in done.group(1)), + ] + try: + w, h, px = read_ppm(sys.argv[2]) + + def pixel(x, y): + i = (y * w + x) * 3 + return tuple(px[i:i + 3]) + + checks += [ + ("overlap shows Beta (on top)", pixel(450, 380) == GREEN), + ("moved Alpha below it", pixel(450, 500) == RED), + ("Gamma unchanged", pixel(700, 250) == BLUE), + ("Beta's title bar is active", pixel(400, 212) == TITLE_ACTIVE), + ("Alpha's old place is desktop", pixel(150, 200) not in (RED, GREEN, BLUE)), + ] + except (OSError, ValueError) as e: + checks.append(("screenshot: %s" % e, False)) + fail = 0 + for name, ok in checks: + print(" %s wm: %s" % ("ok " if ok else "FAIL", name)) + fail |= not ok + return fail + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gui/wmdrive.py b/tests/gui/wmdrive.py new file mode 100644 index 00000000..b4ae93c9 --- /dev/null +++ b/tests/gui/wmdrive.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Drive WMTEST through the QEMU monitor. The pointer is steered +closed loop by the positions WMTEST logs (guidrive.py). + +Usage: wmdrive.py debug.log monitor.sock out.ppm +Drags Alpha's title bar from (160,112) to (360,362), clicks into Beta at +(450,280), saves a screenshot and presses q. +""" +import sys +import time + +from guidrive import Mouse, send, wait + + +def main(): + log, sock, out = sys.argv[1:4] + if not wait(log, "WMTEST: ready", 290): + return 1 + mouse = Mouse(sock, log, "WMTEST") + time.sleep(1) + mouse.go(160, 112) # Alpha's title bar + mouse.button(True) + mouse.go(360, 362) # Alpha to (300,350) + mouse.button(False) + mouse.go(450, 280) # into Beta: raises it + mouse.button(True) + mouse.button(False) + wait(log, "WMTEST: click in Beta", 10) + time.sleep(1) + send(sock, "screendump %s" % out) + time.sleep(1) + send(sock, "sendkey q") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gui/wmtest.c b/tests/gui/wmtest.c new file mode 100644 index 00000000..fb5f4f99 --- /dev/null +++ b/tests/gui/wmtest.c @@ -0,0 +1,105 @@ +/* + * WMTEST - mdgui window manager test (DJGPP). + * + * Three overlapping windows (bottom to top): + * Alpha (100,100 300x200) red, Beta (300,200 300x200) green, + * Gamma (600,120 250x180) blue + * Logs to port E9h: "WMTEST: ready at X,Y" and "WMTEST: at X,Y" (the + * mouse, on every move), clicks in the windows, and on q: "WMTEST: done Alpha=x,y Beta=x,y Gamma=x,y top=T". + * The harness (tests/gui/wmdrive.py) drags Alpha by its title bar to + * (300,350), clicks into Beta to raise it, takes a screenshot, presses q. + */ +#include +#include +#include +#include "mdgui.h" + +static void out(const char *s) +{ + for (; *s; s++) + { + if (*s == '\n') + outportb(0xe9, '\r'); + outportb(0xe9, *s); + } +} + +static int handler(struct window *w, const struct event *e) +{ + char buf[96]; + + if (e->type == EV_MOUSE_DOWN) + { + sprintf(buf, "WMTEST: click in %s at %d,%d\n", w->title, e->x, e->y); + out(buf); + return 1; + } + return 0; +} + +static struct window *make(int x, int y, int w, int h, const char *title, color_t c) +{ + struct window *win = wm_window_new(x, y, w, h, title); + char buf[64]; + + draw_fill(win->client, 0, 0, win->client->w, win->client->h, c); + sprintf(buf, "This is %s", title); + draw_text(win->client, 12, 12, buf, RGB(255, 255, 255), TEXT_TRANSPARENT); + win->handler = handler; + wm_invalidate(win); + return win; +} + +int main(void) +{ + struct surface *s; + char buf[160]; + int i, n; + + out("\nwindow manager test\n"); + if (gfx_open(1024, 768)) + { + sprintf(buf, "WMTEST: failed: %s\n", gfx_error()); + out(buf); + return 1; + } + s = gfx_screen(); + input_open(); + wm_init(); + make(100, 100, 300, 200, "Alpha", RGB(200, 60, 60)); + make(300, 200, 300, 200, "Beta", RGB(60, 180, 90)); + make(600, 120, 250, 180, "Gamma", RGB(60, 100, 200)); + wm_update(); + gfx_cursor_move(s->w / 2, s->h / 2); + gfx_cursor_show(1); + sprintf(buf, "WMTEST: ready at %d,%d\n", s->w / 2, s->h / 2); + out(buf); + + /* wm_run, logging the mouse position (the harness steers by it) */ + for (;;) + { + struct event e; + input_wait(&e); + if (e.type == EV_MOUSE_MOVE) + { + sprintf(buf, "WMTEST: at %d,%d\n", e.x, e.y); + out(buf); + } + wm_dispatch(&e); + if (e.type == EV_KEY && (e.ascii == 'q' || e.ascii == 27)) + break; + wm_update(); + } + + n = sprintf(buf, "WMTEST: done"); + for (i = 0; i < wm_count(); i++) + { + struct window *w = wm_window(i); + n += sprintf(buf + n, " %s=%d,%d", w->title, w->x, w->y); + } + sprintf(buf + n, " top=%s\n", wm_top() ? wm_top()->title : "none"); + input_close(); + gfx_close(); + out(buf); + return 0; +} diff --git a/tests/install/mkgpt.py b/tests/install/mkgpt.py new file mode 100644 index 00000000..03cd8f42 --- /dev/null +++ b/tests/install/mkgpt.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Make a disk image with a GUID partition table, like a UEFI machine's +system disk: an EFI system partition (FAT32, empty) and a second partition +of another type (an "operating system" the installer must not touch). + + mkgpt.py image size_mb esp_mb prints the ESP's offset in bytes +""" +import struct, sys, uuid, zlib + +img, size_mb, esp_mb = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]) +sectors = size_mb * 2048 +esp_first, esp_last = 2048, 2048 + esp_mb * 2048 - 1 +os_first, os_last = esp_last + 1, sectors - 34 - 1 + +def entry(type_guid, first, last, name): + return (uuid.UUID(type_guid).bytes_le + uuid.uuid4().bytes_le + struct.pack("/dev/null || true; rm -rf "$WORK" "${ISO%.iso}"*' EXIT +OVMF=/usr/share/ovmf/OVMF.fd +PORT=2222 +export MTOOLS_SKIP_CHECK=1 + +echo "== building a personal stick image" +cd "$WORK" +mkdir personal +ssh-keygen -q -t ed25519 -N "" -C tester -f id +sed 's/$/\r/' id.pub > personal/AUTHKEYS.TXT +head -c 32 /dev/urandom > personal/HOSTKEY.ED +PERSONAL="$WORK/personal" "$ROOT/release/build.sh" 0.0.0-installtest > build.log 2>&1 || { tail -20 build.log; exit 1; } +cp "$ISO" stick.img +truncate -s 128M stick.img +ESP=$(python3 "$HERE/mkgpt.py" disk.img 512 200) +mformat -i disk.img@@$ESP -F -T $((200 * 2048)) -h 255 -s 63 -v EFI :: +cp "$ROOT/mdvmm/build/BOOTX64.EFI" new.efi +mcopy -i "$ISO@@$(python3 - "$ISO" <<'PY' +import struct, sys +f = open(sys.argv[1], "rb"); f.seek(512); h = f.read(92) +lba, n, size = struct.unpack_from(" out.txt 2>&1; then ok "$what"; else bad "$what"; sed 's/^/ /' out.txt | head -12; fi; } +DISK="-device ahci,id=ahci -drive id=hd,file=disk.img,format=raw,if=none -device ide-hd,drive=hd,bus=ahci.0,bootindex=1" + +echo "== 1. install from the stick" +qemu-system-x86_64 -m 256 -bios "$OVMF" -display none -nic user,model=e1000 $DISK \ + -drive if=none,id=stick,format=raw,file=stick.img -device qemu-xhci -device usb-storage,drive=stick,bootindex=0 \ + -serial file:serial.log -debugcon file:debug.log -monitor unix:mon.sock,server,nowait /dev/null || true; wait $QPID 2>/dev/null || true +sed 's/\r//g; s/\x1b\[[0-9;=?]*[A-Za-z]//g' serial.log | grep -a "INSTALL\|copied\|FAILED\|Installed\|Install:" | sed 's/^/ /' +check "the loader reports: Installed" grep -aq "^Installed" serial.log +check "BOOTX64.EFI on the disk's EFI partition" bash -c "mcopy -i disk.img@@$ESP ::/EFI/BOOT/BOOTX64.EFI a.efi && cmp a.efi $ROOT/mdvmm/build/BOOTX64.EFI" +check "BOOT.IMG and DISKRW on the disk" bash -c "mdir -i disk.img@@$ESP ::/MDOS | grep -q 'BOOT *IMG' && mdir -i disk.img@@$ESP ::/MDOS | grep -q DISKRW" +check "the other system's partition is untouched" bash -c "dd if=disk.img bs=512 skip=$((2048 + 200 * 2048)) count=1 status=none | grep -aq OTHER-OS-DATAOTHER-OS-DATA" + +echo "== 2. boot from the disk" +OPTS=(-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="$WORK/known" -o LogLevel=ERROR + -o BatchMode=yes -o IdentitiesOnly=yes -o ConnectTimeout=15 -o ServerAliveInterval=5 + -o ServerAliveCountMax=2 -i "$WORK/id" -p $PORT) +rm -f debug.log +qemu-system-x86_64 -m 256 -bios "$OVMF" -display none $DISK \ + -nic user,model=e1000,hostfwd=tcp:127.0.0.1:$PORT-:22 -debugcon file:debug.log \ + -serial file:serial2.log /dev/null) || true; echo "${n:-0}"; } +wait_boot() { # wait_boot n seconds: the n-th "listening" + local i + for i in $(seq 1 "$2"); do [ "$(boots)" -ge "$1" ] && return 0; sleep 1; done + return 1 +} +dos() { timeout 60 ssh "${OPTS[@]}" dos@127.0.0.1 "$@" 2>&1 | tr -d '\r'; } +# dosgrep "what" "pattern" command: its output must have the pattern +dosgrep() { + local what=$1 pat=$2; shift 2 + dos "$@" > out.txt || true + if grep -q "$pat" out.txt; then ok "$what"; else bad "$what"; sed 's/^/ /' out.txt | head -14; fi +} + +check "booted from the disk, SSHD listening" wait_boot 1 120 +[ "$(boots)" -ge 1 ] || { sed 's/\r//g; s/\x1b\[[0-9;=?]*[A-Za-z]//g' serial2.log | tr -d '\000' | grep -av "^$" | grep -av "Press ESC" | head -30; sed 's/\r$//' debug.log | tail -25; [ -n "$KEEP" ] && cp debug.log "$KEEP/install-debug.log"; echo "INSTALL TEST: failure"; exit 1; } +check "C: is the EFI system partition (GPT)" grep -aq "GPT partition 1: FAT32" debug.log +dosgrep "the SSH keys are kept on C:" 'HOSTKEY ED' 'DIR C:\MDOS\SSH' +dos 'COPY A:\WATTCP.CFG C:\MDOS\NOTE.TXT' > /dev/null +dosgrep "MDSYS: installed system" 'Installed system' MDSYS + +if [ -n "$DIAG" ]; then # DIAG=1: show the disk as DOS sees it, stop here + for c in 'DIR A:\MDSYS.COM' 'DIR C:\' 'DIR C:\MDOS /B' 'IF EXIST C:\MDOS\SSH\HOSTKEY.ED ECHO key-file-exists' 'TYPE C:\MDOS\SSH\WATTCP.CFG' 'VOL C:' 'CHKDSK C:'; do + echo "--- $c"; dos "$c" | head -12 + done + printf 'ls -l /C/MDOS/SSH\nls -l /C/MDOS\n' > b2; echo "--- sftp ls"; sftp -b b2 -P $PORT "${OPTS[@]:0:16}" -i "$WORK/id" dos@127.0.0.1 2>&1 | head -20 + echo "--- monitor"; grep -a "bios:.*GPT\|bios: hard" debug.log | sed 's/\r//' + kill $QPID 2>/dev/null || true; exit 1 +fi +echo "== 3. a trial that nobody confirms" +: > fast +printf 'mkdir /C/MDOS/TRY\nput new.efi /C/MDOS/TRY/BOOTX64.EFI\nput new.img /C/MDOS/TRY/BOOT.IMG\nput fast /C/MDOS/TRY/FAST\n' > batch +check "build uploaded to C:\\MDOS\\TRY (sftp)" sftp -b batch -P $PORT "${OPTS[@]:0:16}" -i "$WORK/id" dos@127.0.0.1 +dos TRYBOOT > /dev/null || true +check "restarted into the trial" wait_boot 2 120 +dosgrep "MDSYS: trial boot" 'TRIAL boot' MDSYS +check "not confirmed: restarted by itself" wait_boot 3 300 +check "the monitor says why" grep -aq "trial boot: not confirmed in time, restarting" debug.log +dosgrep "MDSYS: the installed system again" 'Installed system' MDSYS + +echo "== 4. a trial that is kept" +dos TRYBOOT > /dev/null || true +check "restarted into the trial" wait_boot 4 120 +dosgrep "KEEP makes it the installed build" 'installed one now' KEEP +sleep 135 +check "confirmed: no restart after the trial time" test "$(boots)" = 4 +dos 'MDSYS REBOOT' > /dev/null || true +check "restarted on request" wait_boot 5 120 +dosgrep "MDSYS: installed system" 'Installed system' MDSYS +dosgrep "a file written to C: before is still there" 'dhcp' 'TYPE C:\MDOS\NOTE.TXT' +check "one host key through all restarts" test "$(grep -c . known)" = 1 + +kill $QPID 2>/dev/null || true; wait $QPID 2>/dev/null || true +[ -n "$KEEP" ] && cp debug.log "$KEEP/install-debug.log" +echo " monitor log (trial lines):"; grep -a "trial\|TRIAL\|restart" debug.log | sed 's/\r$//; s/^/ /' | head -12 +if [ $fail = 0 ]; then echo "INSTALL TEST: success"; exit 0; else echo "INSTALL TEST: failure"; exit 1; fi diff --git a/tests/iso/run.sh b/tests/iso/run.sh new file mode 100755 index 00000000..89e4f114 --- /dev/null +++ b/tests/iso/run.sh @@ -0,0 +1,137 @@ +#!/bin/bash +# Release ISO boot test (runs inside the build container). +# Boots the ISO three ways and waits for the monitor to be up: +# UEFI from CD, UEFI from a USB stick (the ISO written with dd), +# BIOS from CD (El Torito hard disk emulation of the BIOS disk image) +# UEFI boots also get a SATA disk, which must come up read-only (the ISO +# has no \MDOS\DISKRW). +# Then the stick as on a real machine: the ISO written to a larger, +# writable stick; after the boot \MDOS\HWINFO.TXT and BOOTLOG.TXT +# must be on its EFI partition (found through the GPT, as an OS would), +# also after a second boot (the files are replaced). And a boot under +# conditions like an older Mac: stick on EHCI, no GOP graphics, no PS/2 +# keyboard controller. +# +# Usage: tests/iso/run.sh [modernDOS.iso] + +set -e +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +ISO=$(realpath "${1:-$ROOT/_output/release/modernDOS-0.0.1-alpha.iso}") +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +OVMF=/usr/share/ovmf/OVMF.fd +cd "$WORK" +dd if=/dev/zero of=hd.img bs=1M count=16 status=none +fail=0 + +# boot name markers... -- qemu options +boot() { + local name=$1 markers=$2; shift 2 + rm -f debug.log + timeout --foreground 120 qemu-system-x86_64 -m 256 -display none -net none \ + -debugcon file:debug.log -no-reboot "$@" /dev/null || true + wait $qemu 2>/dev/null || true + local IFS='|' m + for m in $markers; do + if grep -aq "$m" debug.log; then echo " ok $name: $m"; else + echo " FAIL $name: missing '$m'"; fail=1; fi + done +} + +UEFI_MARKERS="MDVMM core:|bios: disk image|v86: entering VM1|vm: sessions enabled|bios: hard disks are read-only|bios: mouse driver installed" +SATA="-device ahci,id=ahci -drive id=hd,file=hd.img,format=raw,if=none -device ide-hd,drive=hd,bus=ahci.0" + +echo "== UEFI, CD" +boot "UEFI CD" "$UEFI_MARKERS" -bios "$OVMF" -cdrom "$ISO" $SATA +echo "== UEFI, USB stick" +boot "UEFI USB" "$UEFI_MARKERS" -bios "$OVMF" \ + -drive if=none,id=stick,format=raw,readonly=on,file="$ISO" \ + -device qemu-xhci -device usb-storage,drive=stick $SATA +echo "== BIOS, CD" +boot "BIOS CD" "MDVMM core:|v86: entering VM1|vm: sessions enabled" -cdrom "$ISO" -boot d + +# ------------------------------------------------------------------ +# the EFI system partition of a stick image: offset in bytes, via the GPT +esp_offset() { + python3 - "$1" <<'PY' +import struct, sys +f = open(sys.argv[1], "rb") +f.seek(512) +h = f.read(92) +assert h[:8] == b"EFI PART", "no GPT" +lba, n, size = struct.unpack_from("/dev/null | tr -d '\r' > hwinfo.txt || true + MTOOLS_SKIP_CHECK=1 mtype -i "$img@@$off" ::/MDOS/BOOTLOG.TXT 2>/dev/null | tr -d '\r' > bootlog.txt || true + for m in "$@" "PCI devices" "End of report"; do + if grep -q "$m" hwinfo.txt; then echo " ok $name: HWINFO.TXT: $m"; else + echo " FAIL $name: HWINFO.TXT lacks '$m'"; fail=1; fi + done + for m in "Hardware report written" "Starting the monitor"; do + if grep -q "$m" bootlog.txt; then echo " ok $name: BOOTLOG.TXT: $m"; else + echo " FAIL $name: BOOTLOG.TXT lacks '$m'"; fail=1; fi + done + if [ "$(MTOOLS_SKIP_CHECK=1 mdir -i "$img@@$off" ::/MDOS | grep -c 'HWINFO\|BOOTLOG')" = 2 ]; then + echo " ok $name: one HWINFO.TXT and one BOOTLOG.TXT"; else + echo " FAIL $name: directory:"; MTOOLS_SKIP_CHECK=1 mdir -i "$img@@$off" ::/MDOS; fail=1; fi + if command -v fsck.vfat > /dev/null; then + dd if="$img" of=esp.part bs=512 skip=$((off / 512)) count=61440 status=none + if fsck.vfat -n esp.part > fsck.log 2>&1; then echo " ok $name: the FAT file system is clean"; else + echo " FAIL $name: fsck.vfat:"; sed 's/^/ /' fsck.log | head; fail=1; fi + fi +} + +MON_MARKERS="MDVMM core:|timer: ok - the 8254 ticks and its interrupt reaches the CPU|v86: entering VM1|vm: sessions enabled" + +echo "== UEFI, USB stick (xHCI), larger and writable" +cp "$ISO" stick.img +truncate -s 256M stick.img +boot "USB stick" "fbcon: [0-9]*x[0-9]* framebuffer|$MON_MARKERS" -bios "$OVMF" \ + -drive if=none,id=stick,format=raw,file=stick.img \ + -device qemu-xhci -device usb-storage,drive=stick $SATA +stick_files "USB stick" stick.img "GOP: mode" "Firmware: " +echo "== the same stick, booted again" +boot "USB stick, 2nd boot" "$MON_MARKERS" -bios "$OVMF" \ + -drive if=none,id=stick,format=raw,file=stick.img \ + -device qemu-xhci -device usb-storage,drive=stick $SATA +stick_files "USB stick, 2nd boot" stick.img "GOP: mode" + +echo "== like an older Mac: stick on EHCI, no GOP, no PS/2 controller" +cp "$ISO" stick2.img +truncate -s 256M stick2.img +boot "Mac-like" "fbcon: no usable framebuffer|$MON_MARKERS" -machine q35,i8042=off -bios "$OVMF" -vga none \ + -drive if=none,id=stick,format=raw,file=stick2.img \ + -device usb-ehci -device usb-storage,drive=stick +stick_files "Mac-like" stick2.img "GOP: none" +grep -a "apic:\|hpet:\|timer:" debug.log | sed 's/\r$//; s/^/ /' + +if [ $fail = 0 ]; then echo "ISO TEST: success"; else echo "ISO TEST: failure"; exit 1; fi diff --git a/tests/lfn/djtest.c b/tests/lfn/djtest.c new file mode 100644 index 00000000..bb3a94ce --- /dev/null +++ b/tests/lfn/djtest.c @@ -0,0 +1,153 @@ +/* + * modernDOS long filename test using a real libc (DJGPP, 32-bit DPMI). + * + * Uses only portable C/POSIX file calls; DJGPP's libc maps them to the + * INT 21h AX=71xxh API when the kernel reports LFN support. Logs to the + * QEMU debug console (port E9h); the exit code is the number of failures. + * + * Build: i586-pc-msdosdjgpp-gcc -O2 -o djtest.exe djtest.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int failures, checks; + +static void out(const char *s) +{ + for (; *s; s++) + { + if (*s == '\n') + outportb(0xe9, '\r'); + outportb(0xe9, *s); + } +} + +static void check(int ok, const char *what) +{ + checks++; + if (!ok) + failures++; + out(ok ? " ok " : " FAIL "); + out(what); + out("\n"); +} + +static void checkstr(const char *got, const char *want, const char *what) +{ + int ok = got && strcmp(got, want) == 0; + check(ok, what); + if (!ok) + { + out(" got \""); + out(got ? got : "(null)"); + out("\"\n want \""); + out(want); + out("\"\n"); + } +} + +static int write_file(const char *name, const char *text) +{ + FILE *f = fopen(name, "wb"); + if (!f) + return 0; + fputs(text, f); + return fclose(f) == 0; +} + +static int file_has(const char *name, const char *text) +{ + char buf[200]; + FILE *f = fopen(name, "rb"); + size_t n; + if (!f) + return 0; + n = fread(buf, 1, sizeof(buf) - 1, f); + fclose(f); + buf[n] = 0; + return strcmp(buf, text) == 0; +} + +static int dir_contains(const char *dir, const char *name) +{ + DIR *d = opendir(dir); + struct dirent *e; + int found = 0; + if (!d) + return 0; + while ((e = readdir(d)) != NULL) + if (strcmp(e->d_name, name) == 0) + found = 1; + closedir(d); + return found; +} + +int main(void) +{ + char cwd[300], buf[300]; + struct stat st; + const char *tail; + + out("\nDJGPP libc LFN test\n"); + check(_use_lfn(NULL), "libc detects LFN support"); + + check(mkdir("A:/DJGPP Long Folder Name", 0777) == 0, "mkdir long name"); + check(chdir("A:/DJGPP Long Folder Name") == 0, "chdir long name"); + check(getcwd(cwd, sizeof(cwd)) != NULL, "getcwd"); + tail = strchr(cwd, '/'); + checkstr(tail, "/DJGPP Long Folder Name", "getcwd keeps long name"); + + check(write_file("A Source File With A Really Long Name.c", "int x;\n"), + "fopen/write long name"); + check(file_has("a source file with a really long name.C", "int x;\n"), + "fopen/read, different case"); + check(stat("A Source File With A Really Long Name.c", &st) == 0 && + S_ISREG(st.st_mode) && st.st_size == 7, "stat size and type"); + check(write_file("MixedCase.TXT", "m\n"), "create mixed case name"); + check(dir_contains(".", "A Source File With A Really Long Name.c"), + "readdir returns long name"); + check(dir_contains(".", "MixedCase.TXT"), "readdir preserves case"); + + check(rename("A Source File With A Really Long Name.c", + "Renamed To Another Long Name.txt") == 0, "rename"); + check(access("A Source File With A Really Long Name.c", F_OK) != 0, + "old name gone"); + check(file_has("Renamed To Another Long Name.txt", "int x;\n"), + "content follows rename"); + + check(mkdir("Sub Folder", 0777) == 0 && + write_file("Sub Folder/Deep File Name.dat", "deep\n"), + "relative path with long components"); + check(file_has("A:/DJGPP Long Folder Name/Sub Folder/Deep File Name.dat", + "deep\n"), "absolute path with long components"); + check(_truename("Sub Folder/Deep File Name.dat", buf) != NULL, + "_truename"); + check(strcasecmp(buf, "A:\\DJGPP Long Folder Name\\Sub Folder\\Deep File Name.dat") == 0, + "_truename returns long path"); + + check(unlink("Sub Folder/Deep File Name.dat") == 0, "unlink long name"); + check(rmdir("Sub Folder") == 0, "rmdir long name"); + check(unlink("MixedCase.TXT") == 0, "unlink mixed case"); + + { + int fd = open("Exclusive Create Test.bin", O_CREAT | O_EXCL | O_WRONLY, 0666); + check(fd >= 0, "open O_CREAT|O_EXCL"); + if (fd >= 0) + close(fd); + check(open("Exclusive Create Test.bin", O_CREAT | O_EXCL | O_WRONLY, 0666) < 0, + "O_EXCL on existing name fails"); + check(unlink("Exclusive Create Test.bin") == 0, "cleanup"); + } + + sprintf(buf, "DJGPP: %d failures / %d checks\n", failures, checks); + out(buf); + return failures; +} diff --git a/tests/lfn/lfntest.c b/tests/lfn/lfntest.c new file mode 100644 index 00000000..23e4d16d --- /dev/null +++ b/tests/lfn/lfntest.c @@ -0,0 +1,591 @@ +/* + * modernDOS long filename API test. + * + * Runs as the shell (SHELL=LFNTEST.EXE) on a test floppy booted in QEMU. + * Exercises INT 21h AX=71xxh, logs every check to the QEMU debug console + * (port E9h) and writes "success" or "failure" to A:\RESULT.TXT, then + * powers the machine off via APM. + * + * Build: ia16-elf-gcc -mcmodel=small -Os -o lfntest.exe lfntest.c -li86 + */ + +#include +#include +#include +#include + +static int failures, checks; +static union REGS r; +static struct SREGS sr; +static char buf[400], buf2[400]; +static unsigned char fd[0x13e]; /* Win95 find data */ + +/* ---------------- output ---------------- */ + +static void out(const char *s) +{ + for (; *s; s++) + { + if (*s == '\n') + outp(0xe9, '\r'); + outp(0xe9, *s); + } +} + +static void outhex(unsigned v) +{ + static const char hx[] = "0123456789ABCDEF"; + char t[5]; + int i; + for (i = 3; i >= 0; i--, v >>= 4) + t[i] = hx[v & 15]; + t[4] = 0; + out(t); +} + +static void check(int ok, const char *what) +{ + checks++; + if (!ok) + failures++; + out(ok ? " ok " : " FAIL "); + out(what); + if (!ok) + { + out(" (CF="); + out(r.x.cflag ? "1" : "0"); + out(" AX="); + outhex(r.x.ax); + out(")"); + } + out("\n"); +} + +static void checkstr(const char *got, const char *want, const char *what) +{ + int ok = strcmp(got, want) == 0; + check(ok, what); + if (!ok) + { + out(" got \""); + out(got); + out("\"\n want \""); + out(want); + out("\"\n"); + } +} + +/* ---------------- INT 21h wrappers ---------------- */ + +static int dos(void) +{ + r.x.cflag = 1; + intdosx(&r, &r, &sr); + return !r.x.cflag; +} + +static void ds_dx(const char *p) +{ + segread(&sr); + r.x.dx = FP_OFF(p); +} + +static int lfn_mkdir(const char *p) +{ + r.x.ax = 0x7139; + ds_dx(p); + return dos(); +} + +static int lfn_rmdir(const char *p) +{ + r.x.ax = 0x713a; + ds_dx(p); + return dos(); +} + +static int lfn_chdir(const char *p) +{ + r.x.ax = 0x713b; + ds_dx(p); + return dos(); +} + +static int lfn_getcwd(char *out_) +{ + r.x.ax = 0x7147; + r.h.dl = 0; + segread(&sr); + r.x.si = FP_OFF(out_); + return dos(); +} + +/* returns handle or -1; action in *act */ +static int lfn_open(const char *p, unsigned mode, unsigned action, int *act) +{ + r.x.ax = 0x716c; + r.x.bx = mode; + r.x.cx = 0; + r.x.dx = action; + segread(&sr); + r.x.si = FP_OFF(p); + r.x.di = 0; + if (!dos()) + return -1; + if (act) + *act = r.x.cx; + return r.x.ax; +} + +static int dos_write(int h, const char *data, unsigned n) +{ + r.h.ah = 0x40; + r.x.bx = h; + r.x.cx = n; + ds_dx(data); + return dos() && r.x.ax == n; +} + +static int dos_read(int h, char *data, unsigned n) +{ + r.h.ah = 0x3f; + r.x.bx = h; + r.x.cx = n; + ds_dx(data); + return dos() ? (int)r.x.ax : -1; +} + +static void dos_close(int h) +{ + r.h.ah = 0x3e; + r.x.bx = h; + dos(); +} + +static int lfn_findfirst(const char *spec, unsigned attr) +{ + r.x.ax = 0x714e; + r.x.cx = attr; + r.x.si = 1; /* DOS date/time format */ + segread(&sr); + r.x.dx = FP_OFF(spec); + r.x.di = FP_OFF(fd); + sr.es = sr.ds; + return dos() ? (int)r.x.ax : -1; +} + +static int lfn_findnext(int h) +{ + r.x.ax = 0x714f; + r.x.bx = h; + r.x.si = 1; + segread(&sr); + r.x.di = FP_OFF(fd); + sr.es = sr.ds; + return dos(); +} + +static void lfn_findclose(int h) +{ + r.x.ax = 0x71a1; + r.x.bx = h; + dos(); +} + +#define FD_LONG ((char *)fd + 0x2c) +#define FD_SHORT ((char *)fd + 0x130) + +static int lfn_truename(const char *in, char *out_, int mode) +{ + r.x.ax = 0x7160; + r.x.cx = mode; + segread(&sr); + r.x.si = FP_OFF(in); + r.x.di = FP_OFF(out_); + sr.es = sr.ds; + return dos(); +} + +static int lfn_rename(const char *from, const char *to) +{ + r.x.ax = 0x7156; + segread(&sr); + r.x.dx = FP_OFF(from); + r.x.di = FP_OFF(to); + sr.es = sr.ds; + return dos(); +} + +static int lfn_delete(const char *p, int wild) +{ + r.x.ax = 0x7141; + r.x.si = wild; + r.x.cx = 0; + ds_dx(p); + return dos(); +} + +/* count matches of a spec, using 714E/714F */ +static int count_matches(const char *spec, unsigned attr) +{ + int h = lfn_findfirst(spec, attr), n = 0; + if (h < 0) + return 0; + do + n++; + while (lfn_findnext(h)); + lfn_findclose(h); + return n; +} + +static int create_file(const char *name, const char *data) +{ + int act, h = lfn_open(name, 0x0002, 0x0012, &act); /* r/w, create/truncate */ + if (h < 0) + return 0; + if (!dos_write(h, data, strlen(data))) + return 0; + dos_close(h); + return 1; +} + +static int read_file(const char *name, char *data, unsigned max) +{ + int n, h = lfn_open(name, 0x0000, 0x0001, 0); /* r/o, open */ + if (h < 0) + return -1; + n = dos_read(h, data, max - 1); + dos_close(h); + if (n >= 0) + data[n] = 0; + return n; +} + +/* ---------------- tests ---------------- */ + +static void t_volume(void) +{ + static char root[] = "A:\\"; + out("volume information (71A0)\n"); + r.x.ax = 0x71a0; + r.x.cx = sizeof(buf); + segread(&sr); + r.x.dx = FP_OFF(root); + r.x.di = FP_OFF(buf); + sr.es = sr.ds; + check(dos(), "71A0 succeeds"); + check((r.x.bx & 0x4000) != 0, "reports LFN support (BX bit 14)"); + check(r.x.cx == 255 && r.x.dx == 260, "max name 255 / path 260"); + checkstr(buf, "FAT", "file system name"); +} + +static void t_linux_file(void) +{ + out("file created on Linux by mtools\n"); + check(read_file("A:\\Created On Linux.txt", buf, sizeof(buf)) > 0, + "open long name written by Linux"); + checkstr(buf, "hello from linux\n", "content"); + check(read_file("a:\\CREATED ON LINUX.TXT", buf, sizeof(buf)) > 0, + "case-insensitive long name lookup"); +} + +static void t_dirs(void) +{ + out("directories (7139/713B/7147)\n"); + check(lfn_mkdir("A:\\Long Directory Name"), "mkdir long name"); + check(!lfn_mkdir("A:\\long directory name"), "mkdir duplicate fails"); + check(lfn_chdir("A:\\long directory name"), "chdir, different case"); + check(lfn_getcwd(buf), "getcwd"); + checkstr(buf, "Long Directory Name", "getcwd returns long name"); + check(lfn_mkdir("Nested Folder"), "mkdir relative"); + check(lfn_chdir("Nested Folder"), "chdir relative"); + check(lfn_getcwd(buf), "getcwd nested"); + checkstr(buf, "Long Directory Name\\Nested Folder", "nested long cwd"); + check(lfn_chdir(".."), "chdir .."); +} + +static void t_files(void) +{ + int h, n; + + out("files (716C/714E/7160)\n"); + check(create_file("My Document With A Long Name.txt", "first file\n"), + "create long file name"); + check(create_file("My Document With A Long Name 2.txt", "second file\n"), + "create second, same prefix"); + check(create_file("readme.txt", "case\n"), "create lower case 8.3 name"); + + h = lfn_findfirst("My Document With A Long Name.txt", 0); + check(h >= 0, "findfirst exact long name"); + checkstr(FD_LONG, "My Document With A Long Name.txt", "long name"); + checkstr(FD_SHORT, "MYDOCU~1.TXT", "generated short name"); + if (h >= 0) + lfn_findclose(h); + + h = lfn_findfirst("*name 2.TXT", 0); + check(h >= 0, "findfirst wildcard on long name"); + checkstr(FD_SHORT, "MYDOCU~2.TXT", "numeric tail increments"); + if (h >= 0) + lfn_findclose(h); + + h = lfn_findfirst("readme.txt", 0); + check(h >= 0, "findfirst lower case name"); + checkstr(FD_LONG, "readme.txt", "case preserved"); + if (h >= 0) + lfn_findclose(h); + + n = count_matches("*.txt", 0); + check(n == 3, "714E/714F enumerate 3 files"); + n = count_matches("*", 0x10); + check(n == 6, "'*' with directories: . .. Nested + 3 files"); + + check(read_file("my document with a long name.txt", buf, sizeof(buf)) > 0, + "open existing long name"); + checkstr(buf, "first file\n", "read back"); + check(read_file("MYDOCU~2.TXT", buf, sizeof(buf)) > 0, "open by short alias"); + checkstr(buf, "second file\n", "alias reaches same file"); + + check(lfn_truename("My Document With A Long Name.txt", buf, 1), + "7160 CL=1 short path"); + checkstr(buf, "A:\\LONGDI~1\\MYDOCU~1.TXT", "short path"); + check(lfn_truename("A:\\LONGDI~1\\MYDOCU~1.TXT", buf, 2), + "7160 CL=2 long path"); + checkstr(buf, "A:\\Long Directory Name\\My Document With A Long Name.txt", + "long path"); + check(lfn_truename("Not There Yet.dat", buf, 0), "7160 CL=0 missing file"); + checkstr(buf, "A:\\Long Directory Name\\Not There Yet.dat", + "canonical name keeps missing component"); + + /* classic 8.3 API sees the aliases */ + r.h.ah = 0x1a; /* set DTA */ + ds_dx(buf2); + dos(); + r.h.ah = 0x4e; + r.x.cx = 0; + ds_dx("MYDOCU~1.TXT"); + check(dos(), "classic 4Eh finds short alias"); +} + +static void t_rename_attr(void) +{ + int h; + + out("rename and attributes (7156/7143)\n"); + check(lfn_rename("readme.txt", "Read Me Please.txt"), "rename to long name"); + check(lfn_findfirst("readme.txt", 0) < 0, "old name gone"); + h = lfn_findfirst("read me please.txt", 0); + check(h >= 0, "new name found"); + if (h >= 0) + lfn_findclose(h); + + check(lfn_rename("Read Me Please.txt", "READ ME PLEASE.TXT"), + "case-only rename"); + h = lfn_findfirst("read me please.txt", 0); + checkstr(h >= 0 ? FD_LONG : "", "READ ME PLEASE.TXT", "new case stored"); + if (h >= 0) + lfn_findclose(h); + + check(lfn_rename("READ ME PLEASE.TXT", "Nested Folder\\Moved File.txt"), + "move into subdirectory with new long name"); + check(read_file("Nested Folder\\Moved File.txt", buf, sizeof(buf)) > 0, + "moved file readable"); + + r.x.ax = 0x7143; + r.h.bl = 0; + ds_dx("My Document With A Long Name.txt"); + check(dos() && (r.x.cx & 0x20), "7143 get attributes (archive)"); + r.x.ax = 0x7143; + r.h.bl = 1; + r.x.cx = 0x21; + ds_dx("My Document With A Long Name.txt"); + check(dos(), "7143 set read-only"); + check(!lfn_delete("My Document With A Long Name.txt", 0), + "read-only file cannot be deleted"); + r.x.ax = 0x7143; + r.h.bl = 1; + r.x.cx = 0x20; + ds_dx("My Document With A Long Name.txt"); + check(dos(), "7143 clear read-only"); + r.x.ax = 0x7143; + r.h.bl = 4; + ds_dx("My Document With A Long Name.txt"); + check(dos() && r.x.di != 0, "7143 get last write date"); +} + +static void t_many(void) +{ + static char name[] = "Lots Of Files With Quite Long Names 00.txt"; + int i, ok = 1; + + out("directory growth with many long names\n"); + check(lfn_mkdir("Many") && lfn_chdir("Many"), "mkdir and chdir"); + for (i = 0; i < 60 && ok; i++) + { + name[36] = '0' + i / 10; + name[37] = '0' + i % 10; + ok = create_file(name, "x"); + } + check(ok, "create 60 files with 4 LFN entries each"); + check(count_matches("Lots Of Files*", 0) == 60, "all 60 enumerate"); + check(count_matches("LOTSO*.TXT", 0) == 60, "short aliases match too"); + { + int h = lfn_findfirst("Lots Of Files With Quite Long Names 09.txt", 0); + checkstr(h >= 0 ? FD_SHORT : "", "LOTSO~10.TXT", + "10th alias shortens base for 2-digit tail"); + if (h >= 0) + lfn_findclose(h); + } + check(lfn_delete("Lots Of Files*", 1), "wildcard delete"); + check(count_matches("*", 0) == 0, "directory empty again"); + check(lfn_chdir(".."), "chdir .."); + check(lfn_rmdir("Many"), "rmdir"); +} + +static void t_misc(void) +{ + static unsigned char ft[8]; + unsigned date = (46 << 9) | (11 << 5) | 21; /* 2026-11-21 */ + unsigned time = (13 << 11) | (37 << 5) | 21; /* 13:37:42 */ + + out("conversions (71A7/71A8)\n"); + r.x.ax = 0x71a7; + r.h.bl = 1; + r.x.cx = time; + r.x.dx = date; + r.h.bh = 50; + segread(&sr); + sr.es = sr.ds; + r.x.di = FP_OFF(ft); + check(dos(), "DOS -> FILETIME"); + r.x.ax = 0x71a7; + r.h.bl = 0; + segread(&sr); + r.x.si = FP_OFF(ft); + check(dos() && r.x.cx == time && r.x.dx == date && r.h.bh == 50, + "FILETIME -> DOS round trip"); + + r.x.ax = 0x71a8; + r.x.dx = 0x0100; /* DH=1: ASCIZ */ + segread(&sr); + sr.es = sr.ds; + r.x.si = FP_OFF("My Long File.text"); + r.x.di = FP_OFF(buf); + check(dos(), "71A8 generate short name"); + checkstr(buf, "MYLONGFI.TEX", "basis name"); + + r.x.ax = 0x7100 | 0x99; /* unknown subfunction */ + check(!dos() && r.x.ax == 0x7100, "unknown 71xx -> AX=7100h, CF"); +} + +/* files left on the disk for the Linux side of the test */ +static void t_keep(void) +{ + out("files kept for host verification\n"); + check(create_file("A:\\Long Directory Name\\Keep This File.txt", + "written by modernDOS\n"), "create kept file"); + check(lfn_delete("My Document With A Long Name 2.txt", 0), "delete by long name"); +} + +/* run A:\DJTEST.EXE (DJGPP libc test) if present, expect exit code 0 */ +static void t_djgpp(void) +{ + static char prog[] = "A:\\DJTEST.EXE", tail[] = "\0\r"; + static unsigned pb[7]; + unsigned psp, ds; + + r.x.ax = 0x4300; /* present? */ + ds_dx(prog); + if (!dos()) + { + out("DJGPP test not on disk, skipped\n"); + return; + } + out("running DJGPP libc test (EXEC)\n"); + + /* small model: give back everything above DS:FFFF so EXEC has memory */ + r.h.ah = 0x62; + dos(); + psp = r.x.bx; + segread(&sr); + ds = sr.ds; + r.h.ah = 0x4a; + r.x.bx = (ds - psp) + 0x1000; + sr.es = psp; + dos(); + + pb[0] = 0; /* inherit environment */ + pb[1] = FP_OFF(tail); + pb[2] = ds; + pb[3] = pb[5] = 0xffff; /* no FCBs */ + pb[4] = pb[6] = 0xffff; + r.x.ax = 0x4b00; + segread(&sr); + sr.es = sr.ds; + r.x.bx = FP_OFF(pb); + r.x.dx = FP_OFF(prog); + check(dos(), "EXEC DJTEST.EXE"); + r.h.ah = 0x4d; + dos(); + check(r.h.al == 0, "DJGPP test reported no failures"); +} + +static void finish(void) +{ + static const char ok_[] = "success", bad[] = "failure"; + int h; + + out(failures ? "RESULT: FAILED " : "RESULT: PASSED "); + outhex(failures); + out(" failures / "); + outhex(checks); + out(" checks\n"); + + r.h.ah = 0x3c; /* classic create, root */ + r.x.cx = 0; + ds_dx("A:\\RESULT.TXT"); + if (dos()) + { + h = r.x.ax; + dos_write(h, failures ? bad : ok_, failures ? sizeof(bad) - 1 : sizeof(ok_) - 1); + dos_close(h); + } + r.x.ax = 0x0d00; /* flush */ + dos(); + + /* APM power off */ + r.x.ax = 0x5301; r.x.bx = 0; int86(0x15, &r, &r); + r.x.ax = 0x530e; r.x.bx = 0; r.x.cx = 0x0102; int86(0x15, &r, &r); + r.x.ax = 0x5307; r.x.bx = 1; r.x.cx = 3; int86(0x15, &r, &r); + for (;;) + ; +} + +/* LFNTEST run as the shell: also run DJTEST, write RESULT.TXT, power off + LFNTEST /T run as a normal program: exit code 0 = passed */ +int main(int argc, char **argv) +{ + int program = argc > 1 && (argv[1][1] == 'T' || argv[1][1] == 't'); + + out("\nmodernDOS LFN test\n"); + t_volume(); + t_linux_file(); + t_dirs(); + t_files(); + t_rename_attr(); + t_many(); + t_misc(); + t_keep(); + lfn_chdir("A:\\"); + if (program) + { + out(failures ? "RESULT: FAILED " : "RESULT: PASSED "); + outhex(failures); + out(" failures / "); + outhex(checks); + out(" checks\n"); + return failures ? 1 : 0; + } + t_djgpp(); + finish(); + return 0; +} diff --git a/tests/lfn/run.sh b/tests/lfn/run.sh new file mode 100755 index 00000000..3a848edb --- /dev/null +++ b/tests/lfn/run.sh @@ -0,0 +1,90 @@ +#!/bin/bash +# modernDOS LFN integration test (runs inside the build container). +# +# 1. builds tests/lfn/lfntest.exe (ia16-gcc + libi86) +# 2. builds a bootable FAT12 floppy with the kernel (same boot sector +# and image tools as test/test.sh), SHELL=LFNTEST.EXE and a long +# named file written by mtools +# 3. boots it in QEMU; the test logs to the debug console (port E9h) +# 4. checks RESULT.TXT, verifies the long names from the host side with +# mtools and runs fsck.fat on the image +# +# Usage: tests/lfn/run.sh [kernel.sys] + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +KERNEL=$(realpath "${1:-$ROOT/_output/gcc/kgc8632.sys}") +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +TEST="$ROOT/test" +. "$TEST/cfg.sh" + +echo "== building lfntest.exe" +ia16-elf-gcc -mcmodel=small -Os -o "$WORK/lfntest.exe" "$HERE/lfntest.c" -li86 + +DJGPP=/opt/djgpp/bin/i586-pc-msdosdjgpp-gcc +if [ -x "$DJGPP" ]; then + echo "== building djtest.exe (DJGPP)" + "$DJGPP" -O2 -o "$WORK/djtest.exe" "$HERE/djtest.c" +fi + +echo "== building boot floppy" +cd "$WORK" +printf 'failure\r\n' > result.txt +printf 'shell=a:\\lfntest.exe\r\n' > fdconfig.sys +cp "$WORK/lfntest.exe" test.com # placeholder payload name +"$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_LBA=0 -D_USE_PART_INFO=0 -D_QUERY_GEOMETRY=0 \ + -D_FAT12 -D_UNIT=00h -o boot.bin +"$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,fdconfig.sys,result.txt" \ + -D_BOOTPATCHFILE="'boot.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR_PART_TYPE=ptFAT12 -D_BPE=12 -D_SPC=1 -D_SPI=2880 \ + -D_SPF=9 -D_NUMROOT=224 -D_UNIT=00h -o disk.img + +export MTOOLS_SKIP_CHECK=1 +mcopy -i disk.img lfntest.exe ::LFNTEST.EXE +if [ -f djtest.exe ]; then + mcopy -i disk.img djtest.exe ::DJTEST.EXE + mcopy -i disk.img "$(find /opt/cwsdpmi -iname cwsdpmi.exe | head -1)" ::CWSDPMI.EXE +fi +printf 'hello from linux\n' > linux.txt +mcopy -i disk.img linux.txt "::Created On Linux.txt" + +echo "== booting in QEMU" +timeout --foreground 120 "$QEMU" -drive file=disk.img,format=raw,if=floppy -display none \ + -debugcon stdio -no-reboot /dev/null || true) +[ "$result" = success ] || { echo "RESULT.TXT says: '$result'"; fail=1; } + +expect() { # expect + got=$(mtype -i disk.img "$1" 2>/dev/null || echo "") + if [ "$got" = "$2" ]; then echo " ok $1"; else + echo " FAIL $1: got '$got'"; fail=1; fi +} +absent() { + if mtype -i disk.img "$1" >/dev/null 2>&1; then + echo " FAIL $1 should not exist"; fail=1; else echo " ok $1 absent"; fi +} +expect "::/Long Directory Name/Keep This File.txt" "written by modernDOS" +expect "::/Long Directory Name/My Document With A Long Name.txt" "first file" +expect "::/Long Directory Name/Nested Folder/Moved File.txt" "case" +absent "::/Long Directory Name/My Document With A Long Name 2.txt" +absent "::/Long Directory Name/Many" +echo " directory listing as seen by Linux:" +mdir -i disk.img "::/Long Directory Name" | sed 's/^/ /' + +if command -v fsck.fat >/dev/null; then + echo "== fsck.fat" + if fsck.fat -n -V disk.img; then echo " ok file system clean"; else + echo " FAIL fsck.fat reported problems"; fail=1; fi +fi + +if [ $fail = 0 ]; then echo "LFN TEST: success"; else echo "LFN TEST: failure"; fi +exit $fail diff --git a/tests/mdvmm/dpmitest.c b/tests/mdvmm/dpmitest.c new file mode 100644 index 00000000..03481e08 --- /dev/null +++ b/tests/mdvmm/dpmitest.c @@ -0,0 +1,203 @@ +/* + * MDVMM DPMI host test (DJGPP, 32-bit client). + * + * Exercises the host through DJGPP's libc: large memory blocks, exceptions + * delivered as signals, a protected mode timer interrupt handler, a real + * mode callback, DOS memory and LDT descriptors. Logs to port E9h; the + * exit code is the number of failures. + * + * Build: i586-pc-msdosdjgpp-gcc -O2 -o dpmitest.exe dpmitest.c + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int failures, checks; + +static void out(const char *s) +{ + for (; *s; s++) + { + if (*s == '\n') + outportb(0xe9, '\r'); + outportb(0xe9, *s); + } +} + +static void check(int ok, const char *what) +{ + checks++; + if (!ok) + failures++; + out(ok ? " ok " : " FAIL "); + out(what); + out("\n"); +} + +static jmp_buf jb; +static void on_signal(int sig) +{ + longjmp(jb, sig); +} + +static volatile int ticks; +static void timer_handler(void) +{ + ticks++; +} + +static volatile int callback_hits; +static _go32_dpmi_registers cb_regs; +static void rm_callback(_go32_dpmi_registers *r) +{ + callback_hits++; + r->x.ax = 0x1234; +} + +static void t_version(void) +{ + __dpmi_version_ret v; + + check(__dpmi_get_version(&v) == 0, "0400h get version"); + check(v.major == 0 && v.minor == 90, "DPMI 0.90"); + check(v.flags & 1, "32 bit host"); +} + +static void t_memory(void) +{ + const size_t size = 24u << 20; + char *p = malloc(size); + size_t i; + int ok = 1; + + check(p != NULL, "malloc 24 MB"); + if (!p) + return; + for (i = 0; i < size; i += 4096) + p[i] = (char)(i >> 12); + for (i = 0; i < size && ok; i += 4096) + ok = p[i] == (char)(i >> 12); + check(ok, "touch and verify every page"); + free(p); +} + +static void t_exceptions(void) +{ + volatile int zero = 0, num = 7, r = 0; + int sig; + + signal(SIGSEGV, on_signal); + if ((sig = setjmp(jb)) == 0) + { + *(volatile char *)0xfffffff0u = 1; /* wraps to monitor memory: #PF */ + check(0, "SIGSEGV raised"); + } + else + check(sig == SIGSEGV, "invalid access delivered as SIGSEGV"); + signal(SIGSEGV, SIG_DFL); + + signal(SIGFPE, on_signal); + if ((sig = setjmp(jb)) == 0) + { + r = num / zero; /* (1 / x is compiled without DIV) */ + check(0, "SIGFPE raised"); + } + else + check(sig == SIGFPE, "divide error delivered as SIGFPE"); + signal(SIGFPE, SIG_DFL); + (void)r; +} + +static void t_timer(void) +{ + _go32_dpmi_seginfo old, h; + unsigned long t0, n; + __dpmi_regs regs; + + _go32_dpmi_get_protected_mode_interrupt_vector(8, &old); + h.pm_offset = (unsigned long)timer_handler; + h.pm_selector = _go32_my_cs(); + check(_go32_dpmi_chain_protected_mode_interrupt_vector(8, &h) == 0, + "install PM IRQ0 handler (chained)"); + + /* wait for 6 BIOS ticks, mixing pure PM time and real mode DOS calls */ + t0 = _farpeekl(_dos_ds, 0x46c); + for (n = 0; n < 20000000ul && _farpeekl(_dos_ds, 0x46c) - t0 < 6; n++) + if (n % 4096 == 0) + { + regs.h.ah = 0x2c; /* DOS get time */ + __dpmi_int(0x21, ®s); + } + check(_farpeekl(_dos_ds, 0x46c) - t0 >= 6, "BIOS ticks advance (chained to RM)"); + check(ticks >= 5, "PM handler saw the timer interrupts"); + if (_farpeekl(_dos_ds, 0x46c) - t0 < 6 || ticks < 5) + { + /* the monitor's state into its log (INT 2Fh AX=DE13h) */ + printf(" %lu rounds, %lu BIOS ticks, %d in the handler\n", n, _farpeekl(_dos_ds, 0x46c) - t0, (int)ticks); + regs.x.ax = 0xde13; + __dpmi_int(0x2f, ®s); + } + _go32_dpmi_set_protected_mode_interrupt_vector(8, &old); +} + +static void t_callback(void) +{ + _go32_dpmi_seginfo cb; + __dpmi_regs r; + + cb.pm_offset = (unsigned long)rm_callback; + check(_go32_dpmi_allocate_real_mode_callback_retf(&cb, &cb_regs) == 0, + "0303h allocate real mode callback"); + memset(&r, 0, sizeof(r)); + r.x.cs = cb.rm_segment; + r.x.ip = cb.rm_offset; + check(__dpmi_simulate_real_mode_procedure_retf(&r) == 0, + "0301h call it from real mode"); + check(callback_hits == 1 && r.x.ax == 0x1234, "callback ran in PM, result back"); + _go32_dpmi_free_real_mode_callback(&cb); +} + +static void t_dosmem_ldt(void) +{ + int sel, seg, ldt; + unsigned long base; + + seg = __dpmi_allocate_dos_memory(16, &sel); + check(seg > 0, "0100h allocate DOS memory"); + if (seg > 0) + { + _farpokeb(sel, 5, 0x5a); + check(_farpeekb(_dos_ds, seg * 16 + 5) == 0x5a, "selector maps the DOS block"); + check(__dpmi_free_dos_memory(sel) == 0, "0101h free DOS memory"); + } + + ldt = __dpmi_allocate_ldt_descriptors(1); + check(ldt > 0, "0000h allocate descriptor"); + check(__dpmi_set_segment_base_address(ldt, 0xb8000) == 0 && + __dpmi_get_segment_base_address(ldt, &base) == 0 && base == 0xb8000, + "0007h/0006h base round trip"); + check(__dpmi_set_segment_limit(ldt, 0xffff) == 0, "0008h set limit"); + check(__dpmi_free_ldt_descriptor(ldt) == 0, "0001h free descriptor"); +} + +int main(void) +{ + char buf[80]; + + out("\nDPMI host test\n"); + t_version(); + t_memory(); + t_exceptions(); + t_timer(); + t_callback(); + t_dosmem_ldt(); + sprintf(buf, "DPMI: %d failures / %d checks\n", failures, checks); + out(buf); + return failures; +} diff --git a/tests/mdvmm/netchk.asm b/tests/mdvmm/netchk.asm new file mode 100644 index 00000000..1d2fb95d --- /dev/null +++ b/tests/mdvmm/netchk.asm @@ -0,0 +1,210 @@ +; NETCHK.COM - network test through the packet driver (no TCP/IP stack) +; +; Finds the packet driver at INT 60h, reads the MAC, registers a receiver +; for ARP (type 0806h), sends an ARP request for 10.0.2.2 (QEMU's user +; network gateway) from 10.0.2.15 and waits up to 3 s for the reply. +; Logs through the MDVMM monitor (INT 2Fh AX=DE01h); exit code 0 if the +; gateway answered. + + cpu 386 + org 100h + +PKT_INT equ 60h + +start: + ; a packet driver at INT 60h? + xor ax, ax + mov es, ax + les di, [es:PKT_INT * 4] + add di, 3 + mov si, sig + mov cx, 8 + cld + repe cmpsb + jne no_driver + + mov ax, 01ffh ; driver_info + push ds + int PKT_INT + pop ds + jc fail_info + + push cs + pop es + mov di, my_mac ; get_address + mov cx, 6 + mov ah, 6 + int PKT_INT + jc fail_info + + mov ax, 0201h ; access_type, class 1 + mov bx, 0ffffh + mov dl, 0 + mov si, arp_type + mov cx, 2 + push cs + pop es + mov di, receiver + int PKT_INT + jc fail_access + mov [handle], ax + + ; the ARP request + mov si, my_mac + mov di, frame + 6 ; source MAC + mov cx, 6 + rep movsb + mov si, my_mac + mov di, frame + 22 ; sender hardware address + mov cx, 6 + rep movsb + mov si, frame + mov cx, 42 + mov ah, 4 ; send_pkt + int PKT_INT + jc fail_send + + ; wait for the answer (3 s) + xor ax, ax + mov es, ax + mov ebx, [es:46ch] +.wait: cmp byte [got], 0 + jne .answered + sti + hlt + mov eax, [es:46ch] + sub eax, ebx + cmp eax, 55 + jb .wait + mov dx, msg_noreply + jmp done_fail +.answered: + ; "netchk: ARP reply from 10.0.2.2, MAC xx:xx:xx:xx:xx:xx" + mov si, reply_mac + mov di, msg_mac + mov cx, 6 +.mac: lodsb + call hex2 + inc di + loop .mac + mov dx, msg_ok + call log + call release + mov ax, 4c00h + int 21h + +no_driver: + mov dx, msg_nodrv + jmp done_fail +fail_info: + mov dx, msg_info + jmp done_fail +fail_access: + mov dx, msg_access + jmp done_fail +fail_send: + mov dx, msg_send +done_fail: + call log + call release + mov ax, 4c01h + int 21h + +release: + mov bx, [handle] + test bx, bx + jz .r + mov ah, 3 + int PKT_INT +.r: ret + +log: push dx ; to the monitor log and the screen + mov ax, 0de01h + int 2fh + pop dx + mov si, dx ; print the ASCIZ string with INT 21h/02h +.p: lodsb + test al, al + jz .e + mov dl, al + mov ah, 2 + int 21h + jmp .p +.e: ret + +hex2: push ax + shr al, 4 + call .d + pop ax + and al, 0fh +.d: add al, '0' + cmp al, '9' + jbe .s + add al, 'A' - '9' - 1 +.s: mov [di], al + inc di + ret + +; packet driver receiver: AX=0 -> ES:DI buffer (CX bytes), AX=1 -> filled +receiver: + test ax, ax + jnz .filled + cmp cx, 128 + ja .drop + push cs + pop es + mov di, rxbuf + retf +.drop: xor di, di + mov es, di + retf +.filled: ; DS:SI = rxbuf + cmp word [cs:rxbuf + 20], 0200h ; ARP reply (opcode 2, big endian) + jne .ret + cmp dword [cs:rxbuf + 28], 0202000ah ; sender 10.0.2.2 + jne .ret + push si + push di + push ds + push es + push cs + pop ds + push cs + pop es + mov si, rxbuf + 22 + mov di, reply_mac + mov cx, 6 + cld + rep movsb + mov byte [got], 1 + pop es + pop ds + pop di + pop si +.ret: retf + +sig db 'PKT DRVR' +arp_type db 08h, 06h +handle dw 0 +got db 0 +my_mac times 6 db 0 +reply_mac times 6 db 0 + +frame: db 0ffh, 0ffh, 0ffh, 0ffh, 0ffh, 0ffh ; to everyone + times 6 db 0 ; from + db 08h, 06h ; ARP + db 0, 1, 08h, 0, 6, 4, 0, 1 ; Ethernet, IPv4, request + times 6 db 0 ; sender MAC + db 10, 0, 2, 15 ; sender IP + times 6 db 0 ; target MAC + db 10, 0, 2, 2 ; target IP + +msg_ok db 'netchk: ARP reply from 10.0.2.2, MAC ' +msg_mac db '00:00:00:00:00:00', 13, 10, 0 +msg_noreply db 'netchk: no ARP reply from 10.0.2.2', 13, 10, 0 +msg_nodrv db 'netchk: no packet driver at INT 60h', 13, 10, 0 +msg_info db 'netchk: packet driver does not answer', 13, 10, 0 +msg_access db 'netchk: access_type failed', 13, 10, 0 +msg_send db 'netchk: send_pkt failed', 13, 10, 0 + +rxbuf times 128 db 0 diff --git a/tests/mdvmm/poweroff.asm b/tests/mdvmm/poweroff.asm new file mode 100644 index 00000000..e627862e --- /dev/null +++ b/tests/mdvmm/poweroff.asm @@ -0,0 +1,22 @@ +; POWEROFF.COM - switch the (virtual) machine off: APM, then ACPI ports + cpu 386 + org 100h + mov ax, 5301h ; APM real mode connect + xor bx, bx + int 15h + mov ax, 530eh ; APM driver version 1.2 + xor bx, bx + mov cx, 0102h + int 15h + mov ax, 5307h ; set power state: off + mov bx, 1 + mov cx, 3 + int 15h + mov dx, 604h ; QEMU PIIX4 PM1a_CNT: SLP_EN + mov ax, 2000h + out dx, ax + mov dx, 0b004h ; older QEMU / Bochs + out dx, ax +.hang: cli + hlt + jmp .hang diff --git a/tests/mdvmm/run.sh b/tests/mdvmm/run.sh new file mode 100755 index 00000000..b80b01fc --- /dev/null +++ b/tests/mdvmm/run.sh @@ -0,0 +1,201 @@ +#!/bin/bash +# MDVMM integration test (runs inside the build container). +# +# Boots a floppy with HIMEMX (DOS=HIGH) and FreeCOM; AUTOEXEC.BAT loads +# MDVMM and then runs, inside the virtual machine: +# V86CHK - CPU is in V86 mode and the MDVMM API answers +# XMSTEST - XMS moves work (monitor emulates INT 15h AH=87h) +# LFNTEST - the full long filename suite (heavy INT 21h, timer, disk) +# DJTEST - DJGPP libc long filename test, using MDVMM as DPMI host +# DPMITEST - DPMI host test: memory, exceptions, IRQ0, callbacks, ... +# MDVMM NEW BG.BAT + SESSTEST /FG - a second DOS session runs a background +# job while session 0 checks preemption, hotkeys and results +# There is no CWSDPMI on the disk: DJGPP programs must use MDVMM. +# MDVMM and the tests log to the QEMU debug console. +# +# Usage: tests/mdvmm/run.sh [kernel.sys] + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +KERNEL=$(realpath "${1:-$ROOT/_output/gcc/kgc8632.sys}") +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +TEST="$ROOT/test" +. "$TEST/cfg.sh" + +echo "== building MDVMM and test programs" +make -s -C "$ROOT/mdvmm" +make -s -C "$ROOT/gui" +for p in v86chk poweroff xmstest netchk; do + "$NASM" -f bin -o "$WORK/$p.com" "$HERE/$p.asm" +done +ia16-elf-gcc -mcmodel=small -Os -o "$WORK/lfntest.exe" "$ROOT/tests/lfn/lfntest.c" -li86 +ia16-elf-gcc -mcmodel=small -Os -o "$WORK/sesstest.exe" "$HERE/sesstest.c" -li86 +DJGPP=/opt/djgpp/bin/i586-pc-msdosdjgpp-gcc +"$DJGPP" -O2 -s -o "$WORK/djtest.exe" "$ROOT/tests/lfn/djtest.c" +"$DJGPP" -O2 -s -o "$WORK/dpmitest.exe" "$HERE/dpmitest.c" +"$DJGPP" -O2 -s -I"$ROOT/gui/lib" -o "$WORK/gfxtest.exe" "$ROOT/tests/gui/gfxtest.c" "$ROOT/gui/build/mdgui.o" +"$DJGPP" -O2 -s -I"$ROOT/gui/lib" -o "$WORK/mousetest.exe" "$ROOT/tests/gui/mousetest.c" "$ROOT/gui/build/mdgui.o" +"$DJGPP" -O2 -s -I"$ROOT/gui/lib" -o "$WORK/wmtest.exe" "$ROOT/tests/gui/wmtest.c" "$ROOT/gui/build/mdgui.o" +"$DJGPP" -O2 -s -I"$ROOT/gui/lib" -o "$WORK/uitest.exe" "$ROOT/tests/gui/uitest.c" "$ROOT/gui/build/mdgui.o" + +echo "== building boot floppy" +cd "$WORK" +printf 'failure\r\n' > result.txt +printf 'DEVICE=A:\\HIMEMX.EXE\r\nDOS=HIGH\r\nSHELL=A:\\COMMAND.COM A:\\ /E:512 /P\r\n' > fdconfig.sys +cat > autoexec.bat <<'EOF' +@ECHO OFF +ECHO failure>A:\RESULT.TXT +A:\CTMOUSE.EXE +A:\MDVMM.COM +IF ERRORLEVEL 1 GOTO END +A:\V86CHK.COM +IF ERRORLEVEL 1 GOTO END +A:\PKTDRV.COM +IF ERRORLEVEL 1 GOTO END +A:\NETCHK.COM +IF ERRORLEVEL 1 GOTO END +A:\XMSTEST.COM +IF ERRORLEVEL 1 GOTO END +A:\LFNTEST.EXE /T +IF ERRORLEVEL 1 GOTO END +A:\DJTEST.EXE +IF ERRORLEVEL 1 GOTO END +A:\DPMITEST.EXE +IF ERRORLEVEL 1 GOTO END +A:\MDVMM.COM NEW A:\BG.BAT +IF ERRORLEVEL 1 GOTO END +A:\SESSTEST.EXE /FG +IF ERRORLEVEL 1 GOTO END +A:\GFXTEST.EXE +IF ERRORLEVEL 1 GOTO END +A:\MOUSETEST.EXE +IF ERRORLEVEL 1 GOTO END +A:\WMTEST.EXE +IF ERRORLEVEL 1 GOTO END +A:\UITEST.EXE +IF ERRORLEVEL 1 GOTO END +A:\SSHSLOT.COM 2 +A:\MDDESK.EXE /TEST +IF ERRORLEVEL 1 GOTO END +A:\MDDESK.EXE /TEST /EXIT +IF ERRORLEVEL 1 GOTO END +ECHO success>A:\RESULT.TXT +:END +A:\POWEROFF.COM +EOF +sed -i 's/$/\r/' autoexec.bat +printf '@ECHO OFF\r\nA:\\SESSTEST.EXE /BG\r\nECHO done>A:\\BGDONE.TXT\r\n' > bg.bat + +"$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_LBA=0 -D_USE_PART_INFO=0 -D_QUERY_GEOMETRY=0 \ + -D_FAT12 -D_UNIT=00h -D_CHS_SECTORS=36 -D_CHS_HEADS=2 -o boot.bin +"$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,fdconfig.sys,result.txt" \ + -D_BOOTPATCHFILE="'boot.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR_PART_TYPE=ptFAT12 -D_BPE=12 -D_SPC=2 -D_SPI=5760 \ + -D_SPF=9 -D_NUMROOT=224 -D_CHS_SECTORS=36 -D_CHS_HEADS=2 -D_UNIT=00h -o disk.img + +export MTOOLS_SKIP_CHECK=1 +mcopy -i disk.img /opt/fdos/bin/command.com ::COMMAND.COM +mcopy -i disk.img /opt/fdos/bin/himemx.exe ::HIMEMX.EXE +mcopy -i disk.img autoexec.bat ::AUTOEXEC.BAT +mcopy -i disk.img "$ROOT/mdvmm/build/MDVMM.COM" ::MDVMM.COM +mcopy -i disk.img v86chk.com ::V86CHK.COM +mcopy -i disk.img "$ROOT/mdvmm/build/PKTDRV.COM" ::PKTDRV.COM +mcopy -i disk.img netchk.com ::NETCHK.COM +mcopy -i disk.img xmstest.com ::XMSTEST.COM +mcopy -i disk.img poweroff.com ::POWEROFF.COM +mcopy -i disk.img lfntest.exe ::LFNTEST.EXE +mcopy -i disk.img djtest.exe ::DJTEST.EXE # note: no CWSDPMI on this disk +mcopy -i disk.img dpmitest.exe ::DPMITEST.EXE +mcopy -i disk.img sesstest.exe ::SESSTEST.EXE +mcopy -i disk.img gfxtest.exe ::GFXTEST.EXE +mcopy -i disk.img mousetest.exe ::MOUSETEST.EXE +mcopy -i disk.img wmtest.exe ::WMTEST.EXE +mcopy -i disk.img uitest.exe ::UITEST.EXE +mcopy -i disk.img "$ROOT/gui/build/MDDESK.EXE" ::MDDESK.EXE +mcopy -i disk.img "$ROOT/mdvmm/build/SSHSLOT.COM" ::SSHSLOT.COM +mcopy -i disk.img /opt/fdos/bin/ctmouse.exe ::CTMOUSE.EXE +mcopy -i disk.img bg.bat ::BG.BAT +printf 'hello from linux\n' > linux.txt +mcopy -i disk.img linux.txt "::Created On Linux.txt" + +echo "== booting in QEMU" +# session hotkeys: once the sessions test runs, press Ctrl+Alt+F2 and +# Ctrl+Alt+F1 alternately through the QEMU monitor +python3 - "$WORK" <<'PY' & +import os, socket, sys, time +work = sys.argv[1] +log, sock = os.path.join(work, "debug.log"), os.path.join(work, "mon.sock") +def text(): + try: + return open(log, "rb").read() + except OSError: + return b"" +deadline = time.time() + 290 +while time.time() < deadline and b"sessions test" not in text(): + time.sleep(0.2) +keys = ["ctrl-alt-f2", "ctrl-alt-f1"] +i = 0 +while time.time() < deadline and b"SESSIONS:" not in text(): + try: + s = socket.socket(socket.AF_UNIX) + s.connect(sock) + s.sendall(("sendkey %s\n" % keys[i % 2]).encode()) + time.sleep(0.2) + s.close() + except OSError: + break + i += 1 + time.sleep(1.5) +PY +keys_pid=$! +python3 "$ROOT/tests/gui/gfxshot.py" debug.log mon.sock gfx.ppm & +shot_gfx=$! +python3 "$ROOT/tests/gui/mousedrive.py" debug.log mon.sock mouse.ppm & +mouse_drv=$! +(cd "$ROOT/tests/gui" && PYTHONDONTWRITEBYTECODE=1 exec python3 wmdrive.py "$WORK/debug.log" "$WORK/mon.sock" "$WORK/wm.ppm") & +wm_drv=$! +(cd "$ROOT/tests/gui" && PYTHONDONTWRITEBYTECODE=1 exec python3 uidrive.py "$WORK/debug.log" "$WORK/mon.sock" "$WORK/ui.ppm") & +ui_drv=$! +(cd "$ROOT/tests/gui" && PYTHONDONTWRITEBYTECODE=1 exec python3 deskdrive.py "$WORK/debug.log" "$WORK/mon.sock" "$WORK/desk.ppm") & +desk_drv=$! +timeout --foreground 300 "$QEMU" -m 64 -nic user,model=e1000 \ + -drive file=disk.img,format=raw,if=floppy -display none \ + -debugcon file:debug.log -no-reboot \ + -monitor unix:mon.sock,server,nowait $QEMU_EXTRA /dev/null || true +kill $keys_pid 2>/dev/null || true +sed 's/\r$//' debug.log + +echo "== checks" +fail=0 +result=$(mtype -i disk.img ::RESULT.TXT 2>/dev/null | tr -d '\r\n' || true) +[ "$result" = success ] || { echo " FAIL RESULT.TXT says '$result'"; fail=1; } +for marker in "MDVMM core:" "v86: entering VM1" "v86chk: protected mode bit set" \ + "xmstest: 4K round trip" "RESULT: PASSED" "dpmi: 32 bit client" \ + "DJGPP: 0 failures" "DPMI: 0 failures" "vm: sessions enabled" \ + "vm: session 1 started" "vm: focus session 1" "vm: session 1 ended" \ + "SESSIONS: 0 failures" "nic: 82540em (iPXE)" "Packet driver at INT 60h" "netchk: ARP reply from 10.0.2.2" "GFXTEST: text mode again"; do + if grep -q "$marker" debug.log; then echo " ok log: $marker"; else + echo " FAIL log missing: $marker"; fail=1; fi +done +if grep -q "MDVMM PANIC" debug.log; then echo " FAIL monitor panic"; fail=1; fi +if fsck.fat -n disk.img >/dev/null; then echo " ok file system clean"; else + echo " FAIL fsck.fat"; fail=1; fi + +python3 "$ROOT/tests/gui/gfxcheck.py" gfx.ppm debug.log || fail=1 +python3 "$ROOT/tests/gui/mousecheck.py" debug.log mouse.ppm loose || fail=1 # CTMOUSE accelerates +python3 "$ROOT/tests/gui/wmcheck.py" debug.log wm.ppm || fail=1 +PYTHONDONTWRITEBYTECODE=1 python3 "$ROOT/tests/gui/uicheck.py" debug.log ui.ppm || fail=1 +TERMINAL=1 PYTHONDONTWRITEBYTECODE=1 python3 "$ROOT/tests/gui/deskcheck.py" debug.log desk.ppm || fail=1 +[ -n "$SHOTS" ] && cp ./*.ppm "$SHOTS"/ 2>/dev/null || true # keep the screenshots +# the desktop's editor changed this file (DOS boot: the disk is kept) +if [ "$(mtype -i disk.img "::Created On Linux.txt" 2>/dev/null | od -An -c | tr -d ' \n')" = \ + "hellofromlinux-editedinmodernDOS\r\nsecondline\r\n" ]; then + echo " ok editor's file on the disk"; else echo " FAIL editor's file on the disk"; fail=1; fi +if [ $fail = 0 ]; then echo "MDVMM TEST: success"; else echo "MDVMM TEST: failure"; fi +exit $fail diff --git a/tests/mdvmm/sesstest.c b/tests/mdvmm/sesstest.c new file mode 100644 index 00000000..d94fa5af --- /dev/null +++ b/tests/mdvmm/sesstest.c @@ -0,0 +1,241 @@ +/* + * MDVMM DOS sessions test (ia16). + * + * SESSTEST /BG background job: appends 300 numbered lines to A:\BG.TXT, + * slowly (runs in a session started with MDVMM NEW), then + * waits until it has been focused and unfocused + * SESSTEST /FG foreground checks (session 0): + * - two sessions exist + * - BG.TXT grows while this program never yields (preemption) + * - focus moves to session 1 and back (Ctrl+Alt+F2/F1 sent + * by the test harness through the QEMU monitor) + * - the background session finishes and ends + * - BG.TXT holds all 300 lines in order, FG.TXT 50 lines + * Logs to port E9h, exit code = number of failures. + */ +#include +#include +#include +#include +#include + +static union REGS r; +static struct SREGS sr; +static int failures, checks; +static char buf[400]; + +static void out(const char *s) +{ + for (; *s; s++) + { + if (*s == '\n') + outp(0xe9, '\r'); + outp(0xe9, *s); + } +} + +static void check(int ok, const char *what) +{ + checks++; + if (!ok) + failures++; + out(ok ? " ok " : " FAIL "); + out(what); + out("\n"); +} + +static unsigned long ticks(void) +{ + return *(volatile unsigned long __far *)MK_FP(0x40, 0x6c); +} + +static int dos(void) +{ + r.x.cflag = 1; + intdosx(&r, &r, &sr); + return !r.x.cflag; +} + +/* INT 2Fh AX=DE06h: running session, focus, number of sessions */ +static void sessions(unsigned *running, unsigned *focus, unsigned *count) +{ + r.x.ax = 0xde06; + int86(0x2f, &r, &r); + *running = r.x.ax; + *focus = r.x.bx; + *count = r.x.cx; +} + +static int open_file(const char *name, int create) +{ + segread(&sr); + r.x.dx = FP_OFF(name); + r.x.ax = 0x3d02; + if (dos()) + return r.x.ax; + if (!create) + return -1; + r.h.ah = 0x3c; + r.x.cx = 0; + r.x.dx = FP_OFF(name); + return dos() ? (int)r.x.ax : -1; +} + +static void close_file(int h) +{ + r.h.ah = 0x3e; + r.x.bx = h; + dos(); +} + +static long file_size(const char *name) +{ + long size; + int h = open_file(name, 0); + + if (h < 0) + return -1; + r.x.ax = 0x4202; + r.x.bx = h; + r.x.cx = r.x.dx = 0; + dos(); + size = (long)r.x.dx << 16 | r.x.ax; + close_file(h); + return size; +} + +static int append(const char *name, const char *text) +{ + int h = open_file(name, 1); + + if (h < 0) + return 0; + r.x.ax = 0x4202; + r.x.bx = h; + r.x.cx = r.x.dx = 0; + dos(); + r.h.ah = 0x40; + r.x.bx = h; + r.x.cx = strlen(text); + segread(&sr); + r.x.dx = FP_OFF(text); + dos(); + close_file(h); + return 1; +} + +static int background(void) +{ + int i, seen1 = 0, seen0 = 0; + unsigned running, focus, count; + unsigned long t; + + for (i = 0; i < 300; i++) + { + sprintf(buf, "bg %03d\r\n", i); + if (!append("A:\\BG.TXT", buf)) + return 1; + if (i % 20 == 19) /* stretch the job over ~2 s */ + for (t = ticks(); ticks() - t < 2;) + ; + } + /* stay alive until the foreground has moved the focus here and back + (Ctrl+Alt+F2, Ctrl+Alt+F1), so the hotkey checks have a session 1 */ + for (t = ticks(); ticks() - t < 18 * 60 && !(seen1 && seen0);) + { + sessions(&running, &focus, &count); + if (focus == 1) + seen1 = 1; + if (seen1 && focus == 0) + seen0 = 1; + } + return 0; +} + +/* hotkeys from the harness may come at any time: watch the focus go to + session 1 and back to 0 during the whole foreground test */ +static int seen_focus1, seen_focus0; + +static void watch_focus(void) +{ + unsigned running, focus, count; + + sessions(&running, &focus, &count); + if (focus == 1) + seen_focus1 = 1; + if (seen_focus1 && focus == 0) + seen_focus0 = 1; +} + +static int foreground(void) +{ + unsigned running, focus, count, i; + unsigned long t; + long s0, s1; + int ok, h, n; + + out("\nsessions test\n"); + sessions(&running, &focus, &count); + check(count == 2 && running == 0, "two sessions, session 0 running"); + + /* preemption: busy work without ever yielding, BG.TXT must grow */ + s0 = file_size("A:\\BG.TXT"); + for (i = 0; i < 50; i++) + { + sprintf(buf, "fg %03u\r\n", i); + append("A:\\FG.TXT", buf); + for (t = ticks(); ticks() - t < 1;) + watch_focus(); /* spin, no INT 28h / HLT */ + } + s1 = file_size("A:\\BG.TXT"); + sprintf(buf, " BG.TXT %ld -> %ld bytes while busy\n", s0, s1); + out(buf); + check(s1 > s0 && s1 > 0, "background session ran while foreground was busy"); + + /* hotkeys from the harness: focus 1, then back to 0 */ + for (t = ticks(); ticks() - t < 18 * 40 && !(seen_focus1 && seen_focus0);) + watch_focus(); + check(seen_focus1, "Ctrl+Alt+F2 focused session 1"); + check(seen_focus0, "Ctrl+Alt+F1 focused session 0 again"); + + /* wait for the background job and its session to finish */ + for (t = ticks(); ticks() - t < 18 * 60; ) + { + sessions(&running, &focus, &count); + if (count == 1 && file_size("A:\\BGDONE.TXT") >= 0) + break; + } + check(file_size("A:\\BGDONE.TXT") >= 0, "background job completed"); + check(count == 1, "background session ended"); + + /* contents */ + ok = 1; + h = open_file("A:\\BG.TXT", 0); + for (i = 0; ok && h >= 0 && i < 300; i++) + { + char want[16]; + sprintf(want, "bg %03u\r\n", i); + r.h.ah = 0x3f; + r.x.bx = h; + r.x.cx = 8; + segread(&sr); + r.x.dx = FP_OFF(buf); + ok = dos() && r.x.ax == 8 && memcmp(buf, want, 8) == 0; + } + if (h >= 0) + close_file(h); + check(h >= 0 && ok && file_size("A:\\BG.TXT") == 300 * 8L, "BG.TXT: 300 lines in order"); + n = (int)(file_size("A:\\FG.TXT") / 8); + check(n == 50, "FG.TXT: 50 lines"); + + sprintf(buf, "SESSIONS: %d failures / %d checks\n", failures, checks); + out(buf); + return failures; +} + +int main(int argc, char **argv) +{ + if (argc > 1 && (argv[1][1] == 'B' || argv[1][1] == 'b')) + return background(); + return foreground(); +} diff --git a/tests/mdvmm/v86chk.asm b/tests/mdvmm/v86chk.asm new file mode 100644 index 00000000..0ef1a4b7 --- /dev/null +++ b/tests/mdvmm/v86chk.asm @@ -0,0 +1,20 @@ +; V86CHK.COM - exit 0 if running in V86 mode under MDVMM + cpu 386 + org 100h + smsw ax + test al, 1 + jz .real + mov ax, 0de00h ; MDVMM installation check + int 2fh + cmp bx, 4d44h + jne .noapi + mov ax, 0de01h ; log through the monitor + mov dx, msg_ok + int 2fh + mov ax, 4c00h + int 21h +.real: mov ax, 4c01h + int 21h +.noapi: mov ax, 4c02h + int 21h +msg_ok db 'v86chk: protected mode bit set, MDVMM API answers', 10, 0 diff --git a/tests/mdvmm/xmstest.asm b/tests/mdvmm/xmstest.asm new file mode 100644 index 00000000..04de7412 --- /dev/null +++ b/tests/mdvmm/xmstest.asm @@ -0,0 +1,81 @@ +; XMSTEST.COM - XMS round trip: under MDVMM the XMS driver's moves go +; through the monitor's INT 15h AH=87h emulation. Exit 0 on success. + cpu 386 + org 100h +SIZE equ 4096 + mov ax, 4300h + int 2fh + cmp al, 80h + jne fail + mov ax, 4310h + int 2fh + mov [xms], bx + mov [xms + 2], es + push cs + pop es + mov ah, 09h ; allocate 64K + mov dx, 64 + call far [xms] + test ax, ax + jz fail + mov [handle], dx + ; pattern + mov di, buf + mov cx, SIZE + xor ax, ax +.fill: mov [di], al + add al, 7 + inc di + loop .fill + ; conventional -> EMB offset 8000h + mov word [mv + 4], 0 + mov word [mv + 6], buf + mov [mv + 8], cs + mov ax, [handle] + mov [mv + 10], ax + mov dword [mv + 12], 8000h + call move + ; clear buffer + mov di, buf + mov cx, SIZE + xor al, al + rep stosb + ; EMB -> conventional + mov ax, [handle] + mov [mv + 4], ax + mov dword [mv + 6], 8000h + mov word [mv + 10], 0 + mov word [mv + 12], buf + mov [mv + 14], cs + call move + ; verify + mov si, buf + mov cx, SIZE + xor al, al +.chk: cmp [si], al + jne fail + add al, 7 + inc si + loop .chk + mov ah, 0ah ; free + mov dx, [handle] + call far [xms] + mov ax, 0de01h ; log (ignored without MDVMM) + mov dx, msg_ok + int 2fh + mov ax, 4c00h + int 21h +move: mov dword [mv], SIZE + mov si, mv + mov ah, 0bh + call far [xms] + test ax, ax + jz fail + ret +fail: mov ax, 4c01h + int 21h +msg_ok db 'xmstest: 4K round trip through XMS ok', 10, 0 +xms dd 0 +handle dw 0 +mv times 16 db 0 +buf: diff --git a/tests/net/contest.c b/tests/net/contest.c new file mode 100644 index 00000000..bf1881d0 --- /dev/null +++ b/tests/net/contest.c @@ -0,0 +1,175 @@ +/* + * CONTEST - remote console check (DJGPP, a DPMI client in session 0). + * + * Needs SSHSLOT.COM job slots. Checks that the other sessions keep running + * while this DPMI program runs, and the monitor's remote console calls: + * - an interactive shell job: type "ECHO REMOTE-OK" + Enter, find the + * output on its screen (DE08h), type EXIT, the job ends (DE0Dh) + * - a command job: "/C" with a failing command reports its exit code + * Logs to port E9h ("CONTEST: ..."), exit code = number of failures. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +static int failures; + +static void out(const char *fmt, ...) +{ + char buf[300], *p; + va_list ap; + + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + for (p = buf; *p; p++) + { + if (*p == '\n') + outportb(0xe9, '\r'); + outportb(0xe9, *p); + } +} + +static void check(int ok, const char *what) +{ + if (!ok) + failures++; + out("CONTEST: %s %s\n", ok ? "ok " : "FAIL", what); +} + +static int api(__dpmi_regs *r, int al) +{ + r->h.ah = 0xde; + r->h.al = (unsigned char)al; + __dpmi_int(0x2f, r); + return !(r->x.flags & 1); +} + +static int job_start(const char *cmd) +{ + __dpmi_regs r; + + memset(&r, 0, sizeof(r)); + dosmemput(cmd, strlen(cmd) + 1, __tb); + r.x.ds = __tb >> 4; + r.x.si = __tb & 15; + return api(&r, 0x0c) ? r.x.ax : -1; +} + +static int job_state(int n, int *code) +{ + __dpmi_regs r; + + memset(&r, 0, sizeof(r)); + r.h.bl = (unsigned char)n; + api(&r, 0x0d); + *code = r.x.bx; + return (short)r.x.ax; +} + +/* the screen of session n as text lines */ +static int screen(int n, char text[25][81]) +{ + static unsigned char cells[80 * 25 * 2]; + __dpmi_regs r; + int y, x; + + memset(&r, 0, sizeof(r)); + r.h.bl = (unsigned char)n; + r.x.es = __tb >> 4; + r.x.di = __tb & 15; + r.x.cx = sizeof(cells); + if (!api(&r, 0x08)) + return 0; + dosmemget(__tb, sizeof(cells), cells); + for (y = 0; y < 25; y++) + { + for (x = 0; x < 80; x++) + text[y][x] = cells[(y * 80 + x) * 2] ? cells[(y * 80 + x) * 2] : ' '; + text[y][80] = 0; + } + return 1; +} + +static int type(int n, const char *s) +{ + unsigned short keys[128]; + __dpmi_regs r; + int i, len = (int)strlen(s); + + for (i = 0; i < len; i++) + keys[i] = s[i] == '\r' ? 0x1c0d : (unsigned char)s[i]; + memset(&r, 0, sizeof(r)); + dosmemput(keys, len * 2, __tb); + r.h.bl = (unsigned char)n; + r.x.ds = __tb >> 4; + r.x.si = __tb & 15; + r.x.cx = (unsigned short)len; + api(&r, 0x09); + return r.x.cx == len; +} + +/* wait (up to secs) for text on session n's screen */ +static int wait_text(int n, const char *what, int secs) +{ + char text[25][81]; + clock_t end = clock() + secs * CLOCKS_PER_SEC; + int y; + + while (clock() < end) + { + if (screen(n, text)) + for (y = 0; y < 25; y++) + if (strstr(text[y], what)) + return 1; + __dpmi_yield(); + } + return 0; +} + +static int wait_done(int n, int *code, int secs) +{ + clock_t end = clock() + secs * CLOCKS_PER_SEC; + + while (clock() < end) + { + if (job_state(n, code) == 3) + return 1; + __dpmi_yield(); + } + return 0; +} + +int main(void) +{ + int n, code = -1; + + out("CONTEST: start\n"); + n = job_start(""); + check(n > 0, "interactive job started in a slot"); + if (n > 0) + { + check(wait_text(n, ">", 20), "the shell prompt shows on the slot's screen"); + check(type(n, "ECHO REMOTE-OK\r"), "keys typed into the slot"); + check(wait_text(n, "REMOTE-OK", 20), "the command's output on the slot's screen"); + type(n, "EXIT\r"); + check(wait_done(n, &code, 20), "the shell job ended after EXIT"); + } + n = job_start("A:\\NOSUCH.EXE"); + check(n > 0, "command job started"); + if (n > 0) + { + check(wait_done(n, &code, 20), "the command job ended"); + out("CONTEST: exit code %d\n", code); + } + n = job_start("ECHO X > A:\\JOB.TXT"); + check(n > 0 && wait_done(n, &code, 20), "a second command job ran"); + check(fopen("A:\\JOB.TXT", "r") != NULL, "the job's output file exists"); + out("CONTEST: %d failures\n", failures); + return failures; +} diff --git a/tests/net/nettest.c b/tests/net/nettest.c new file mode 100644 index 00000000..2d59454c --- /dev/null +++ b/tests/net/nettest.c @@ -0,0 +1,83 @@ +/* + * NETTEST - TCP/IP on modernDOS (DJGPP + Watt-32, through PKTDRV). + * + * NETTEST host port + * + * Configures the network (WATTCP.CFG: DHCP), connects to host:port with + * a BSD socket, sends "hello from modernDOS\n", reads a line back. + * Logs to port E9h ("NETTEST: ..."); exit code 0 if the reply arrived. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void out(const char *fmt, ...) +{ + char buf[300], *p; + va_list ap; + + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + for (p = buf; *p; p++) + { + if (*p == '\n') + outportb(0xe9, '\r'); + outportb(0xe9, *p); + } + fputs(buf, stdout); +} + +int main(int argc, char **argv) +{ + struct sockaddr_in sa; + char ip[20], reply[200]; + int s, n, total = 0; + + if (argc < 3) + { + printf("usage: NETTEST host port\n"); + return 2; + } + if (sock_init()) + { + out("NETTEST: network setup failed\n"); + return 1; + } + out("NETTEST: my address %s\n", _inet_ntoa(ip, my_ip_addr)); + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons((unsigned short)atoi(argv[2])); + sa.sin_addr.s_addr = inet_addr(argv[1]); + s = socket(AF_INET, SOCK_STREAM, 0); + if (s < 0 || connect(s, (struct sockaddr *)&sa, sizeof(sa)) < 0) + { + out("NETTEST: cannot connect to %s:%s\n", argv[1], argv[2]); + return 1; + } + out("NETTEST: connected to %s:%s\n", argv[1], argv[2]); + send(s, "hello from modernDOS\n", 21, 0); + while (total < (int)sizeof(reply) - 1 && (n = recv(s, reply + total, sizeof(reply) - 1 - total, 0)) > 0) + { + total += n; + if (memchr(reply, '\n', total)) + break; + } + reply[total] = 0; + closesocket(s); + if (total <= 0) + { + out("NETTEST: no reply\n"); + return 1; + } + reply[strcspn(reply, "\r\n")] = 0; + out("NETTEST: reply: %s\n", reply); + return 0; +} diff --git a/tests/net/run.sh b/tests/net/run.sh new file mode 100755 index 00000000..74279db2 --- /dev/null +++ b/tests/net/run.sh @@ -0,0 +1,159 @@ +#!/bin/bash +# Network test (runs inside the build container). +# +# One boot floppy, booted twice: from DOS (SeaBIOS) and from UEFI (OVMF, +# BOOTX64.EFI). QEMU gives an e1000 on its user network (DHCP, gateway +# 10.0.2.2 = the container). AUTOEXEC.BAT loads HIMEMX, MDVMM and PKTDRV +# (the packet driver on MDVMM's network card drivers: iPXE's e1000 +# driver on DOS boots, iPXE's drivers on UEFI boots), then runs +# NETCHK - ARP through the packet driver (no TCP/IP stack) +# NETTEST - Watt-32 (DJGPP): DHCP, then a TCP connection to a server +# the harness runs here, a line out and a line back +# +# Usage: tests/net/run.sh [kernel.sys] + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +KERNEL=$(realpath "${1:-$ROOT/_output/gcc/kgc8632.sys}") +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +TEST="$ROOT/test" +. "$TEST/cfg.sh" +OVMF=/usr/share/ovmf/OVMF.fd +PORT=2323 +export MTOOLS_SKIP_CHECK=1 + +echo "== building" +make -s -C "$ROOT/mdvmm" +for p in netchk poweroff; do + "$NASM" -f bin -o "$WORK/$p.com" "$ROOT/tests/mdvmm/$p.asm" +done +/opt/djgpp/bin/i586-pc-msdosdjgpp-gcc -O2 -s -I/opt/watt32/inc -o "$WORK/nettest.exe" \ + "$HERE/nettest.c" -L/opt/watt32/lib -lwatt +/opt/djgpp/bin/i586-pc-msdosdjgpp-gcc -O2 -s -o "$WORK/contest.exe" "$HERE/contest.c" + +cd "$WORK" +printf 'DEVICE=A:\\HIMEMX.EXE\r\nDOS=HIGH\r\nSHELL=A:\\COMMAND.COM A:\\ /E:1024 /P\r\n' > fdconfig.sys +cat > autoexec.bat < wattcp.cfg + +"$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_LBA=0 -D_USE_PART_INFO=0 -D_QUERY_GEOMETRY=0 \ + -D_FAT12 -D_UNIT=00h -o boot.bin +"$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,fdconfig.sys" \ + -D_BOOTPATCHFILE="'boot.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR_PART_TYPE=ptFAT12 -D_BPE=12 -D_SPC=1 -D_SPI=2880 \ + -D_SPF=9 -D_NUMROOT=224 -D_UNIT=00h -o disk.img +mcopy -i disk.img /opt/fdos/bin/command.com ::COMMAND.COM +mcopy -i disk.img /opt/fdos/bin/himemx.exe ::HIMEMX.EXE +mcopy -i disk.img autoexec.bat ::AUTOEXEC.BAT +mcopy -i disk.img wattcp.cfg ::WATTCP.CFG +mcopy -i disk.img "$ROOT/mdvmm/build/MDVMM.COM" ::MDVMM.COM +mcopy -i disk.img "$ROOT/mdvmm/build/PKTDRV.COM" ::PKTDRV.COM +mcopy -i disk.img netchk.com ::NETCHK.COM +mcopy -i disk.img nettest.exe ::NETTEST.EXE +mcopy -i disk.img contest.exe ::CONTEST.EXE +mcopy -i disk.img "$ROOT/mdvmm/build/SSHSLOT.COM" ::SSHSLOT.COM +mcopy -i disk.img /opt/cwsdpmi/bin/CWSDPMI.EXE ::CWSDPMI.EXE +mcopy -i disk.img poweroff.com ::POWEROFF.COM + +# the UEFI boot: the same floppy as \MDOS\BOOT.IMG on an ESP +dd if=/dev/zero of=esp.img bs=1M count=16 status=none +mformat -i esp.img -h 64 -s 32 -t 16 :: +mmd -i esp.img ::/EFI ::/EFI/BOOT ::/MDOS +mcopy -i esp.img "$ROOT/mdvmm/build/BOOTX64.EFI" ::/EFI/BOOT/BOOTX64.EFI +mcopy -i esp.img disk.img ::/MDOS/BOOT.IMG + +# the server NETTEST talks to (10.0.2.2:PORT from inside QEMU) +python3 - $PORT <<'PY' & +import socket, sys +srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +srv.bind(("127.0.0.1", int(sys.argv[1]))) +srv.listen(4) +srv.settimeout(600) +while True: + try: + c, _ = srv.accept() + except OSError: + break + c.settimeout(20) + data = b"" + try: + while b"\n" not in data: + d = c.recv(256) + if not d: + break + data += d + c.sendall(b"hello from the host, you said: " + data.strip() + b"\n") + except OSError: + pass + c.close() +PY +server=$! + +fail=0 +run() { # run name -- qemu args + local name=$1; shift + rm -f debug.log + if [ -n "$SHOTS" ]; then # SHOTS=dir: screenshots every 5 s + mkdir -p "$SHOTS" + ( for i in $(seq 1 40); do sleep 5 + python3 -c 'import socket,sys,time; s=socket.socket(socket.AF_UNIX); s.connect("mon.sock"); s.sendall(("screendump %s\n" % sys.argv[1]).encode()); time.sleep(0.5)' \ + "$SHOTS/${name// /_}-$i.ppm" 2>/dev/null || true + done ) & + fi + timeout --foreground 240 "$@" -m 128 -display none -no-reboot \ + -monitor unix:mon.sock,server,nowait \ + -nic user,model=${MODEL:-e1000} -debugcon file:debug.log /dev/null || true +if [ $fail = 0 ]; then echo "NET TEST: success"; else echo "NET TEST: failure"; exit 1; fi diff --git a/tests/pkg/host.sh b/tests/pkg/host.sh new file mode 100755 index 00000000..15fb3af6 --- /dev/null +++ b/tests/pkg/host.sh @@ -0,0 +1,59 @@ +#!/bin/bash +# Package manager test on Linux (runs inside the build container): the +# PKG code against a repository made with net/pkg/mkrepo.sh and served by +# a local web server: update, list, install, remove; a tampered package +# list, a tampered package and a wrong key must be refused. +# +# Usage: tests/pkg/host.sh + +set -e +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +WORK=$(mktemp -d) +trap 'kill $WEB 2>/dev/null || true; rm -rf "$WORK"' EXIT +make -s -C "$ROOT/net/pkg" host +cd "$WORK" +mkdir -p src/hello/root/APPS/HELLO src/tools/root/BIN inst +printf 'version=1.2\ndescription=Says hello\n' > src/hello/PKGINFO +printf '@ECHO OFF\r\nECHO Hello from a package\r\n' > src/hello/root/APPS/HELLO/HELLO.BAT +head -c 70000 /dev/urandom > src/hello/root/APPS/HELLO/DATA.BIN +printf 'version=0.9\ndescription=Two small tools\n' > src/tools/PKGINFO +echo one > src/tools/root/BIN/ONE.TXT +echo two > src/tools/root/BIN/TWO.TXT +"$ROOT/net/pkg/mkrepo.sh" src repo repo.key > mkrepo.log +KEY=$(sed -n 's/^public key.*: //p' mkrepo.log) +python3 -m http.server 8377 --bind 127.0.0.1 -d repo > /dev/null 2>&1 & +WEB=$! +sleep 1 +cp "$ROOT/net/pkg/build/pkg-host" inst/pkg +printf 'repo = http://127.0.0.1:8377\nkey = %s\nroot = %s/inst/\n' "$KEY" "$WORK" > inst/PKG.CFG +PKG="$WORK/inst/pkg" + +fail=0 +check() { local what=$1; shift; if "$@" > out.txt 2>&1; then echo " ok $what"; else + echo " FAIL $what"; sed 's/^/ /' out.txt | head -10; fail=1; fi; } + +check "update: signed package list accepted" bash -c "$PKG UPDATE | grep -q '2 packages (signature good)'" +check "list: both packages, none installed" bash -c "$PKG LIST | grep -c '^\[ \]' | grep -qx 2" +check "install hello" bash -c "$PKG INSTALL hello | grep -q 'Installed hello 1.2: 2 files'" +check "the files are there, unchanged" bash -c "cmp src/hello/root/APPS/HELLO/DATA.BIN inst/APPS/HELLO/DATA.BIN && cmp src/hello/root/APPS/HELLO/HELLO.BAT inst/APPS/HELLO/HELLO.BAT" +check "list: hello is installed" bash -c "$PKG LIST | grep -q '^\[\*\] hello'" +check "remove hello" bash -c "$PKG REMOVE hello | grep -q 'Removed hello: 2 files' && test ! -e inst/APPS/HELLO/DATA.BIN" +# tampering +cp repo/TOOLS.TAR tools.good +printf 'evil' | dd of=repo/TOOLS.TAR bs=1 seek=600 conv=notrunc status=none +check "a changed package is refused" bash -c "! $PKG INSTALL tools > o 2>&1 && grep -q 'does NOT match' o && test ! -e inst/BIN/ONE.TXT" +cp tools.good repo/TOOLS.TAR +check "the good package installs" bash -c "$PKG INSTALL tools | grep -q '2 files'" +sed -i 's/Says hello/Says hello!/' repo/INDEX.TXT +check "a changed package list is refused" bash -c "! $PKG UPDATE > o 2>&1 && grep -q 'signature does NOT fit' o" +"$ROOT/net/pkg/mkrepo.sh" src repo other.key > /dev/null +check "a list signed with another key is refused" bash -c "! $PKG UPDATE > o 2>&1 && grep -q 'signature does NOT fit' o" +mkdir -p src/evil/root; printf 'version=1\ndescription=escapes\n' > src/evil/PKGINFO; echo x > src/evil/root/ok.txt +"$ROOT/net/pkg/mkrepo.sh" src repo repo.key > /dev/null +tar --format=ustar -P -cf repo/EVIL.TAR --transform 's|^|../|' -C src/evil/root ok.txt 2>/dev/null +sed -i "s#^evil|.*#evil|1|EVIL.TAR|$(stat -c %s repo/EVIL.TAR)|$(sha256sum repo/EVIL.TAR | cut -d' ' -f1)|escapes#" repo/INDEX.TXT +"$ROOT/net/pkg/build/pkgsign" sign repo.key repo/INDEX.TXT > repo/INDEX.SIG +$PKG UPDATE > /dev/null +check "a package cannot write outside the install root" bash -c "$PKG INSTALL evil > o 2>&1; test ! -e $WORK/ok.txt && grep -q '0 files' o" + +if [ $fail = 0 ]; then echo "PKG HOST TEST: success"; exit 0; else echo "PKG HOST TEST: failure"; exit 1; fi diff --git a/tests/pkg/internet.sh b/tests/pkg/internet.sh new file mode 100755 index 00000000..a0c88c42 --- /dev/null +++ b/tests/pkg/internet.sh @@ -0,0 +1,68 @@ +#!/bin/bash +# HTTPS from modernDOS to real sites on the internet (runs inside the build +# container; needs internet access, so it is not part of mdtest.sh). +# +# A UEFI boot (OVMF, iPXE's e1000 driver, PKTDRV, Watt-32) runs HTTPGET +# (HTTP client + BearSSL) against a few sites: pages must arrive, and +# servers with a wrong certificate must be refused. +# +# Usage: tests/pkg/internet.sh [kernel.sys] + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +KERNEL=$(realpath "${1:-$ROOT/_output/gcc/kgc8632.sys}") +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +TEST="$ROOT/test" +. "$TEST/cfg.sh" +OVMF=/usr/share/ovmf/OVMF.fd +export MTOOLS_SKIP_CHECK=1 + +echo "== building" +make -s -C "$ROOT/mdvmm" +make -s -C "$ROOT/net/pkg" all +"$NASM" -f bin -o "$WORK/poweroff.com" "$ROOT/tests/mdvmm/poweroff.asm" +cd "$WORK" +printf 'SHELL=A:\\COMMAND.COM A:\\ /E:512 /P\r\n' > fdconfig.sys +printf '%s\r\n' '@ECHO OFF' 'SET WATTCP.CFG=A:\' 'A:\PKTDRV.COM' \ + 'A:\HTTPGET.EXE https://example.com/ A:\EX.HTM' \ + 'A:\HTTPGET.EXE https://en.wikipedia.org/wiki/DOS' 'A:\HTTPGET.EXE https://lite.duckduckgo.com/lite/' \ + 'A:\HTTPGET.EXE https://github.com/' 'A:\HTTPGET.EXE http://neverssl.com/' \ + 'A:\HTTPGET.EXE https://expired.badssl.com/' 'A:\HTTPGET.EXE https://wrong.host.badssl.com/' \ + 'A:\HTTPGET.EXE https://self-signed.badssl.com/' \ + 'ECHO NET TEST DONE' 'A:\POWEROFF.COM' > autoexec.bat +printf 'my_ip = dhcp\r\n' > wattcp.cfg +"$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_LBA=0 -D_USE_PART_INFO=0 -D_QUERY_GEOMETRY=0 \ + -D_FAT12 -D_UNIT=00h -D_CHS_SECTORS=36 -D_CHS_HEADS=2 -o boot.bin +"$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,fdconfig.sys" \ + -D_BOOTPATCHFILE="'boot.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR_PART_TYPE=ptFAT12 -D_BPE=12 -D_SPC=2 -D_SPI=5760 \ + -D_SPF=9 -D_NUMROOT=224 -D_CHS_SECTORS=36 -D_CHS_HEADS=2 -D_UNIT=00h -o boot.img +for f in /opt/fdos/bin/command.com autoexec.bat wattcp.cfg poweroff.com \ + "$ROOT/mdvmm/build/PKTDRV.COM"; do + mcopy -i boot.img "$f" "::$(basename "$f" | tr a-z A-Z)" +done +mcopy -i boot.img "$ROOT/net/pkg/build/httpget.exe" ::HTTPGET.EXE +dd if=/dev/zero of=esp.img bs=1M count=16 status=none +mformat -i esp.img -h 64 -s 32 -t 16 :: +mmd -i esp.img ::/EFI ::/EFI/BOOT ::/MDOS +mcopy -i esp.img "$ROOT/mdvmm/build/BOOTX64.EFI" ::/EFI/BOOT/BOOTX64.EFI +mcopy -i esp.img boot.img ::/MDOS/BOOT.IMG + +echo "== booting" +timeout --foreground 400 qemu-system-x86_64 -m 256 -bios "$OVMF" -display none \ + -drive file=esp.img,format=raw,if=ide -nic user,model=e1000 \ + -debugcon file:debug.log -serial file:serial.log -no-reboot screen.txt +grep -a "HTTPGET\|Example\|DONE\|EX.HTM" screen.txt | sed 's/^/ /' +fail=0 +[ "$(grep -ac "HTTPGET: ok" screen.txt)" = 5 ] || { echo " FAIL not all 5 pages arrived"; fail=1; } +for marker in "certificate is expired" "certificate is for another name" \ + "not from a known authority" "NET TEST DONE"; do + if grep -aq "$marker" screen.txt; then echo " ok $marker"; else echo " FAIL missing: $marker"; fail=1; fi +done +if [ $fail = 0 ]; then echo "INTERNET TEST: success"; exit 0; else echo "INTERNET TEST: failure"; exit 1; fi diff --git a/tests/pkg/run.sh b/tests/pkg/run.sh new file mode 100755 index 00000000..093fe814 --- /dev/null +++ b/tests/pkg/run.sh @@ -0,0 +1,75 @@ +#!/bin/bash +# Package manager test on modernDOS (runs inside the build container). +# +# A UEFI boot (OVMF, iPXE's e1000 driver, PKTDRV, Watt-32) with PKG.EXE and +# a repository made here and served on 10.0.2.2:8377: PKG UPDATE (signed +# list), PKG INSTALL (SHA-256 checked, unpacked on A:), the installed batch +# file runs, PKG LIST, PKG REMOVE. The screen comes back over the serial +# mirror of the console. +# +# Usage: tests/pkg/run.sh [kernel.sys] + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +KERNEL=$(realpath "${1:-$ROOT/_output/gcc/kgc8632.sys}") +WORK=$(mktemp -d) +trap 'kill $WEB 2>/dev/null || true; rm -rf "$WORK"' EXIT +TEST="$ROOT/test" +. "$TEST/cfg.sh" +OVMF=/usr/share/ovmf/OVMF.fd +export MTOOLS_SKIP_CHECK=1 + +echo "== building" +make -s -C "$ROOT/mdvmm" +make -s -C "$ROOT/net/pkg" all host +"$NASM" -f bin -o "$WORK/poweroff.com" "$ROOT/tests/mdvmm/poweroff.asm" +cd "$WORK" +mkdir -p src/hello/root/APPS/HELLO +printf 'version=1.2\ndescription=Says hello\n' > src/hello/PKGINFO +printf '@ECHO OFF\r\nECHO Hello from a package\r\n' > src/hello/root/APPS/HELLO/HELLO.BAT +head -c 150000 /dev/urandom > src/hello/root/APPS/HELLO/DATA.BIN +"$ROOT/net/pkg/mkrepo.sh" src repo repo.key > mkrepo.log +KEY=$(sed -n 's/^public key.*: //p' mkrepo.log) +python3 -m http.server 8377 --bind 127.0.0.1 -d repo > /dev/null 2>&1 & +WEB=$! + +printf 'SHELL=A:\\COMMAND.COM A:\\ /E:512 /P\r\n' > fdconfig.sys +printf '%s\r\n' '@ECHO OFF' 'SET WATTCP.CFG=A:\' 'A:\PKTDRV.COM' 'A:\PKG.EXE UPDATE' \ + 'A:\PKG.EXE INSTALL hello' 'CALL A:\APPS\HELLO\HELLO.BAT' 'A:\PKG.EXE LIST' \ + 'A:\PKG.EXE REMOVE hello' 'IF NOT EXIST A:\APPS\HELLO\DATA.BIN ECHO files are gone' \ + 'ECHO PKG TEST DONE' 'A:\POWEROFF.COM' > autoexec.bat +printf 'my_ip = dhcp\r\n' > wattcp.cfg +printf 'repo = http://10.0.2.2:8377\r\nkey = %s\r\nroot = A:\\\r\n' "$KEY" > pkg.cfg +"$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_LBA=0 -D_USE_PART_INFO=0 -D_QUERY_GEOMETRY=0 \ + -D_FAT12 -D_UNIT=00h -D_CHS_SECTORS=36 -D_CHS_HEADS=2 -o boot.bin +"$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,fdconfig.sys" \ + -D_BOOTPATCHFILE="'boot.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR_PART_TYPE=ptFAT12 -D_BPE=12 -D_SPC=2 -D_SPI=5760 \ + -D_SPF=9 -D_NUMROOT=224 -D_CHS_SECTORS=36 -D_CHS_HEADS=2 -D_UNIT=00h -o boot.img +for f in /opt/fdos/bin/command.com autoexec.bat wattcp.cfg pkg.cfg poweroff.com \ + "$ROOT/mdvmm/build/PKTDRV.COM"; do + mcopy -i boot.img "$f" "::$(basename "$f" | tr a-z A-Z)" +done +mcopy -i boot.img "$ROOT/net/pkg/build/pkg.exe" ::PKG.EXE +dd if=/dev/zero of=esp.img bs=1M count=16 status=none +mformat -i esp.img -h 64 -s 32 -t 16 :: +mmd -i esp.img ::/EFI ::/EFI/BOOT ::/MDOS +mcopy -i esp.img "$ROOT/mdvmm/build/BOOTX64.EFI" ::/EFI/BOOT/BOOTX64.EFI +mcopy -i esp.img boot.img ::/MDOS/BOOT.IMG + +echo "== booting" +timeout --foreground 240 qemu-system-x86_64 -m 256 -bios "$OVMF" -display none \ + -drive file=esp.img,format=raw,if=ide -nic user,model=e1000 \ + -debugcon file:debug.log -serial file:serial.log -no-reboot screen.txt +sed -n '/Package list\|PKG:/,$p' screen.txt | head -30 | sed 's/^/ /' +fail=0 +for marker in "Package list updated: 1 packages (signature good)" "Installed hello 1.2: 2 files" \ + "^Hello from a package" "^\[\*\] hello" "Removed hello: 2 files" "^files are gone" "PKG TEST DONE"; do + if grep -aq "$marker" screen.txt; then echo " ok $marker"; else echo " FAIL missing: $marker"; fail=1; fi +done +if [ $fail = 0 ]; then echo "PKG TEST: success"; exit 0; else echo "PKG TEST: failure"; exit 1; fi diff --git a/tests/ssh/host.sh b/tests/ssh/host.sh new file mode 100755 index 00000000..c9f66eb2 --- /dev/null +++ b/tests/ssh/host.sh @@ -0,0 +1,117 @@ +#!/bin/bash +# SSH protocol test on Linux (runs inside the build container): the SSHD +# protocol code (net/ssh, built with plat_host.c) against OpenSSH's ssh, +# sftp and scp. Exec jobs run with /bin/sh; SFTP's /C is a scratch dir. +# +# Usage: tests/ssh/host.sh + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +WORK=$(mktemp -d) +PORT=2222 +trap 'kill $SSHD $OSSHD 2>/dev/null || true; rm -rf "$WORK"' EXIT + +make -s -C "$ROOT/net/ssh" host +mkdir -p "$WORK/srv" "$WORK/root" "$WORK/home" +cp "$ROOT/net/ssh/build/sshd-host" "$WORK/srv/sshd" +ssh-keygen -q -t ed25519 -N "" -C test@host -f "$WORK/home/id" +ssh-keygen -q -t ed25519 -N "" -C other -f "$WORK/home/other" +{ echo "# authorized keys"; cat "$WORK/home/id.pub"; } > "$WORK/srv/AUTHKEYS.TXT" +printf 'correct horse\ncorrect horse\n' | "$WORK/srv/sshd" /PASSWD > /dev/null + +SSHD_ROOT="$WORK/root" "$WORK/srv/sshd" /P $PORT < /dev/null 2> "$WORK/sshd.log" & +SSHD=$! +sleep 1 + +OPTS=(-o StrictHostKeyChecking=no -o UserKnownHostsFile="$WORK/home/known" -o LogLevel=ERROR + -o BatchMode=yes -o IdentitiesOnly=yes -o ConnectTimeout=10) +fail=0 +check() { # check "what" command... + local what=$1; shift + if "$@" > "$WORK/out" 2>&1; then echo " ok $what"; else + echo " FAIL $what"; sed 's/^/ /' "$WORK/out" | head -20; fail=1; fi +} + +echo "== exec" +check "exec: echo" bash -c "ssh ${OPTS[*]} -i $WORK/home/id -p $PORT dos@127.0.0.1 'echo hello world' | grep -qx 'hello world'" +check "exec: exit status" bash -c "ssh ${OPTS[*]} -i $WORK/home/id -p $PORT dos@127.0.0.1 'exit 3'; test \$? = 3" +check "exec: 1 MB of output" bash -c "test \$(ssh ${OPTS[*]} -i $WORK/home/id -p $PORT dos@127.0.0.1 'head -c 1048576 /dev/zero' | wc -c) = 1048576" + +echo "== authentication" +check "unknown key refused" bash -c "! ssh ${OPTS[*]} -i $WORK/home/other -p $PORT dos@127.0.0.1 true" +cat > "$WORK/askpass" <<'EOF' +#!/bin/sh +echo "$PASS" +EOF +chmod +x "$WORK/askpass" +pw_opts="-o StrictHostKeyChecking=no -o UserKnownHostsFile=$WORK/home/known -o LogLevel=ERROR -o PubkeyAuthentication=no -o PreferredAuthentications=password -o NumberOfPasswordPrompts=1" +check "password login" bash -c "PASS='correct horse' SSH_ASKPASS=$WORK/askpass SSH_ASKPASS_REQUIRE=force DISPLAY=x setsid ssh $pw_opts -p $PORT dos@127.0.0.1 'echo pw-ok' < /dev/null | grep -qx pw-ok" +check "wrong password refused" bash -c "! PASS='wrong horse' SSH_ASKPASS=$WORK/askpass SSH_ASKPASS_REQUIRE=force DISPLAY=x setsid ssh $pw_opts -p $PORT dos@127.0.0.1 true < /dev/null" +check "host key fingerprint matches the log" bash -c "grep -q \"\$(ssh-keygen -l -F '[127.0.0.1]:$PORT' -f $WORK/home/known | awk '/ED25519/ {print \$3}')\" $WORK/sshd.log" + +echo "== sftp / scp" +head -c 300000 /dev/urandom > "$WORK/home/blob" +cat > "$WORK/batch" < "$WORK/batch2" < $WORK/cli/pub.txt && grep -q '^ssh-ed25519 ' $WORK/cli/pub.txt && ssh-keygen -l -f $WORK/cli/ID.KEY" +cat "$WORK/cli/pub.txt" >> "$WORK/srv/AUTHKEYS.TXT" +check "client -> SSHD: exec" bash -c "$WORK/cli/ssh /P $PORT /Y dos@127.0.0.1 'echo client-ok' < /dev/null 2>&1 | grep -qx client-ok" +check "client: host key remembered" grep -q "^127.0.0.1 $PORT ssh-ed25519 " "$WORK/cli/KNOWNHST.TXT" + +ssh-keygen -q -t ed25519 -N "" -f "$WORK/osshd/hostkey" +cp "$WORK/cli/pub.txt" "$WORK/osshd/authorized_keys" +cat > "$WORK/osshd/config" </dev/null || true +/usr/sbin/sshd -D -e -f "$WORK/osshd/config" 2> "$WORK/osshd/log" & +OSSHD=$! +sleep 1 +me=$(id -un) +check "client -> OpenSSH: exec, exit code" bash -c "$WORK/cli/ssh /P 2224 /Y $me@127.0.0.1 'echo openssh-ok; exit 4' < /dev/null > $WORK/o.txt 2>&1; rc=\$?; grep -qx openssh-ok $WORK/o.txt && test \$rc = 4 || { cat $WORK/o.txt $WORK/osshd/log; false; }" +check "client -> OpenSSH: 1 MB" bash -c "test \$($WORK/cli/ssh /P 2224 $me@127.0.0.1 'head -c 1048576 /dev/zero' < /dev/null 2>/dev/null | wc -c) = 1048576" +check "client -> OpenSSH: terminal (pty) screen" bash -c "SSHDUMP=1 $WORK/cli/ssh /P 2224 /T $me@127.0.0.1 'printf \"\\033[2J\\033[3;5HPTY-\\033[1;32mOK\\033[0m\\r\\n\"' < /dev/null 2>&1 | grep -q '^screen: PTY-OK'" +check "client: OpenSSH key file (/I)" bash -c "cp $WORK/home/id.pub $WORK/osshd/authorized_keys && $WORK/cli/ssh /P 2224 /I $WORK/home/id $me@127.0.0.1 'echo idkey-ok' < /dev/null 2>&1 | grep -qx idkey-ok" +sed -i 's/ssh-ed25519 AAAA/ssh-ed25519 BAAA/' "$WORK/cli/KNOWNHST.TXT" +check "client: changed host key refused" bash -c "! $WORK/cli/ssh /P 2224 /I $WORK/home/id $me@127.0.0.1 true < /dev/null > $WORK/o.txt 2>&1 && grep -q 'HAS CHANGED' $WORK/o.txt" +kill $OSSHD 2>/dev/null || true + +kill $SSHD 2>/dev/null || true +echo "-- server log" +sed 's/^/ /' "$WORK/sshd.log" | tail -25 +if [ $fail = 0 ]; then echo "SSH HOST TEST: success"; exit 0; else echo "SSH HOST TEST: failure"; exit 1; fi diff --git a/tests/ssh/run.sh b/tests/ssh/run.sh new file mode 100755 index 00000000..b73426fd --- /dev/null +++ b/tests/ssh/run.sh @@ -0,0 +1,220 @@ +#!/bin/bash +# SSH server test on modernDOS (runs inside the build container). +# +# A boot floppy with MDVMM, SSHSLOT (job slots), PKTDRV and SSHD, booted +# from DOS (SeaBIOS) and from UEFI (OVMF). QEMU's user network forwards +# 127.0.0.1:2222 to the guest's port 22; OpenSSH here then checks: +# exec (ECHO), an interactive shell (ANSI screen), sftp up and down, +# the host key fingerprint, and finally powers the guest off over SSH. +# +# Usage: tests/ssh/run.sh [kernel.sys] + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +KERNEL=$(realpath "${1:-$ROOT/_output/gcc/kgc8632.sys}") +WORK=$(mktemp -d) +trap 'kill $QPID 2>/dev/null || true; rm -rf "$WORK"' EXIT +TEST="$ROOT/test" +. "$TEST/cfg.sh" +OVMF=/usr/share/ovmf/OVMF.fd +PORT=2222 +export MTOOLS_SKIP_CHECK=1 + +echo "== building" +make -s -C "$ROOT/mdvmm" +make -s -C "$ROOT/net/ssh" +"$NASM" -f bin -o "$WORK/poweroff.com" "$ROOT/tests/mdvmm/poweroff.asm" + +cd "$WORK" +ssh-keygen -q -t ed25519 -N "" -C tester -f id +printf 'DEVICE=A:\\HIMEMX.EXE\r\nDOS=HIGH\r\nSHELL=A:\\COMMAND.COM A:\\ /E:1024 /P\r\n' > fdconfig.sys +cat > autoexec.bat < wattcp.cfg +{ echo "# keys allowed to log in"; cat id.pub; } | sed 's/$/\r/' > authkeys.txt + +"$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_LBA=0 -D_USE_PART_INFO=0 -D_QUERY_GEOMETRY=0 \ + -D_FAT12 -D_UNIT=00h -o boot.bin +"$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,fdconfig.sys" \ + -D_BOOTPATCHFILE="'boot.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR_PART_TYPE=ptFAT12 -D_BPE=12 -D_SPC=1 -D_SPI=2880 \ + -D_SPF=9 -D_NUMROOT=224 -D_UNIT=00h -o disk.img +mcopy -i disk.img /opt/fdos/bin/command.com ::COMMAND.COM +mcopy -i disk.img /opt/fdos/bin/himemx.exe ::HIMEMX.EXE +mcopy -i disk.img autoexec.bat ::AUTOEXEC.BAT +mcopy -i disk.img wattcp.cfg ::WATTCP.CFG +mcopy -i disk.img authkeys.txt ::AUTHKEYS.TXT +mcopy -i disk.img "$ROOT/mdvmm/build/MDVMM.COM" ::MDVMM.COM +mcopy -i disk.img "$ROOT/mdvmm/build/PKTDRV.COM" ::PKTDRV.COM +mcopy -i disk.img "$ROOT/mdvmm/build/SSHSLOT.COM" ::SSHSLOT.COM +mcopy -i disk.img "$ROOT/net/ssh/build/sshd.exe" ::SSHD.EXE +mcopy -i disk.img /opt/cwsdpmi/bin/CWSDPMI.EXE ::CWSDPMI.EXE +mcopy -i disk.img poweroff.com ::POWEROFF.COM +echo "floppy: $(mdir -i disk.img -w :: | wc -w) files, $(mdu -i disk.img -s :: 2>/dev/null | tail -1)" + +dd if=/dev/zero of=esp.img bs=1M count=16 status=none +mformat -i esp.img -h 64 -s 32 -t 16 :: +mmd -i esp.img ::/EFI ::/EFI/BOOT ::/MDOS +mcopy -i esp.img "$ROOT/mdvmm/build/BOOTX64.EFI" ::/EFI/BOOT/BOOTX64.EFI +mcopy -i esp.img disk.img ::/MDOS/BOOT.IMG + +OPTS=(-o StrictHostKeyChecking=no -o UserKnownHostsFile="$WORK/known" -o LogLevel=ERROR + -o BatchMode=yes -o IdentitiesOnly=yes -o ConnectTimeout=20 -i "$WORK/id" -p $PORT) +fail=0 +check() { # check "what" command... + local what=$1; shift + if "$@" > out.txt 2>&1; then echo " ok $name: $what"; else + echo " FAIL $name: $what"; sed 's/^/ /' out.txt | head -20; fail=1; fi +} + +run() { # run name -- qemu args + name=$1; shift + rm -f debug.log known + timeout --foreground 400 "$@" -m 128 -display none -no-reboot \ + -nic user,model=e1000,hostfwd=tcp:127.0.0.1:$PORT-:22 -debugcon file:debug.log /dev/null && break + grep -aq "PANIC" debug.log 2>/dev/null && break + sleep 1 + done + echo "-- $name ($i s to start)" + grep -a "sshd: \|Packet driver\|PANIC" debug.log | sed 's/\r$//; s/^/ /' + + check "exec ECHO" bash -c "ssh ${OPTS[*]} dos@127.0.0.1 'ECHO hello from DOS' | tr -d '\r' | grep -qx 'hello from DOS'" + check "exec DIR shows the files" bash -c "ssh ${OPTS[*]} dos@127.0.0.1 'DIR A:\\' | grep -q 'SSHD EXE'" + + head -c 50000 /dev/urandom > blob + printf 'put blob /A/UP.BIN\nls -l /A\nget /A/UP.BIN back\nrm /A/UP.BIN\nls /\n' > batch + check "sftp put, ls, get, rm" sftp -b batch -P $PORT "${OPTS[@]:0:12}" -i "$WORK/id" dos@127.0.0.1 + check "sftp: file came back unchanged" cmp blob back + + # interactive shell: type a command, read it back from the screen + python3 - "$PORT" > shell.txt 2>&1 <<'PY' && +import subprocess, sys, time, os +p = subprocess.Popen(["ssh", "-tt", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=known", + "-o", "LogLevel=ERROR", "-o", "BatchMode=yes", "-i", "id", "-p", sys.argv[1], + "dos@127.0.0.1"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) +os.set_blocking(p.stdout.fileno(), False) +out = b"" +def wait_for(text, secs): + global out + end = time.time() + secs + while time.time() < end: + try: + d = p.stdout.read() + except BlockingIOError: + d = None + if d: + out += d + if text in out: + return True + time.sleep(0.1) + return False +ok = wait_for(b">", 30) +p.stdin.write(b"ECHO SHELL-%COMSPEC%\r"); p.stdin.flush() +ok = ok and wait_for(b"SHELL-A:\\COMMAND.COM", 30) +p.stdin.write(b"EXIT\r"); p.stdin.flush() +try: + p.wait(timeout=30) +except subprocess.TimeoutExpired: + p.kill(); ok = False +wait_for(b"\x00", 1) +sys.stdout.write(out.decode("utf-8", "replace")) +sys.exit(0 if ok else 1) +PY + { echo " ok $name: shell: typed ECHO, its output came back"; } || { + echo " FAIL $name: shell"; sed 's/\x1b\[[0-9;?]*[a-zA-Z]/ /g' shell.txt | tr -s ' ' | head -c 600; echo; fail=1; } + + fp=$(ssh-keygen -l -F "[127.0.0.1]:$PORT" -f known 2>/dev/null | awk '/ED25519/ {print $3}') + check "host key fingerprint matches the server's log" grep -aq "$fp" debug.log + + ssh "${OPTS[@]}" dos@127.0.0.1 'A:\POWEROFF.COM' > /dev/null 2>&1 || true + for i in $(seq 1 30); do kill -0 $QPID 2>/dev/null || break; sleep 1; done + kill $QPID 2>/dev/null && { echo " FAIL $name: no power off over SSH"; fail=1; } || echo " ok $name: powered off over SSH" + wait $QPID 2>/dev/null || true + echo " server log:" + grep -a "sshd: \|vm: session\|PANIC\|dpmi: " debug.log | sed 's/\r$//; s/^/ /' | tail -40 +} + +echo "== DOS boot" +run "DOS boot" "$QEMU" -drive file=disk.img,format=raw,if=floppy +echo "== UEFI boot" +run "UEFI boot" qemu-system-x86_64 -bios "$OVMF" -drive file=esp.img,format=raw,if=ide + +# ------------------------------------------------------------------ +# the client: SSH.EXE on modernDOS against OpenSSH's sshd here +echo "== client" +me=$(id -un) +mkdir -p osshd +ssh-keygen -q -t ed25519 -N "" -f osshd/hostkey +cp id.pub osshd/authorized_keys +cat > osshd/config </dev/null || true +/usr/sbin/sshd -D -e -f "$WORK/osshd/config" 2> osshd/log & +OSSHD=$! +printf 'printf "\\033[2J\\033[3;5HPTY-\\033[1;32mOK\\033[0m"\n' > pty.sh +cat > client.bat </dev/null || true + +if [ $fail = 0 ]; then echo "SSH TEST: success"; exit 0; else echo "SSH TEST: failure"; exit 1; fi diff --git a/tests/uefi/disktest.c b/tests/uefi/disktest.c new file mode 100644 index 00000000..27a6aec9 --- /dev/null +++ b/tests/uefi/disktest.c @@ -0,0 +1,232 @@ +/* + * DISKTEST - hard disk test for the native disk drivers (ia16). + * + * DISKTEST d: on drive d: + * - BIOS: INT 13h AH=41h extensions, AH=48h parameters for drive 80h + * - reads \HELLO.TXT written by Linux (mtools) + * - writes \DISKTEST\BIG.BIN (1 MB, pattern) in chunks of varying size, + * reads it back in other chunk sizes and compares + * - creates 60 small files, deletes every other one + * - leaves \FROMDOS.TXT for the harness to check from Linux + * Logs to port E9h, exit code = number of failures. + */ +#include +#include +#include +#include +#include + +#define BIG_SIZE (1024L * 1024L) + +static union REGS r; +static struct SREGS sr; +static int failures, checks; +static char buf[24576]; +static char path[80]; +static char drive; + +static void out(const char *s) +{ + for (; *s; s++) + { + if (*s == '\n') + outp(0xe9, '\r'); + outp(0xe9, *s); + } +} + +static void check(int ok, const char *what) +{ + checks++; + if (!ok) + failures++; + out(ok ? " ok " : " FAIL "); + out(what); + out("\n"); +} + +static int dos(void) +{ + r.x.cflag = 1; + segread(&sr); + intdosx(&r, &r, &sr); + return !r.x.cflag; +} + +static const char *p(const char *rest) +{ + sprintf(path, "%c:%s", drive, rest); + return path; +} + +static int fopen_rw(const char *name, int create) +{ + r.x.dx = FP_OFF(name); + if (create) + { + r.h.ah = 0x3c; + r.x.cx = 0; + } + else + r.x.ax = 0x3d02; + return dos() ? (int)r.x.ax : -1; +} + +static void fclose_h(int h) +{ + r.h.ah = 0x3e; + r.x.bx = h; + dos(); +} + +static unsigned frw(int h, unsigned n, int write) +{ + r.h.ah = write ? 0x40 : 0x3f; + r.x.bx = h; + r.x.cx = n; + r.x.dx = FP_OFF(buf); + return dos() ? r.x.ax : 0; +} + +static unsigned char pattern(long off) +{ + return (unsigned char)(off * 7 + (off >> 9) + (off >> 17)); +} + +static void fill(long off, unsigned n) +{ + unsigned i; + for (i = 0; i < n; i++) + buf[i] = pattern(off + i); +} + +static int same(long off, unsigned n) +{ + unsigned i; + for (i = 0; i < n; i++) + if ((unsigned char)buf[i] != pattern(off + i)) + return 0; + return 1; +} + +static void bios_checks(void) +{ + static unsigned char params[0x1e]; + + r.h.ah = 0x41; + r.x.bx = 0x55aa; + r.h.dl = 0x80; + int86(0x13, &r, &r); + check(!r.x.cflag && r.x.bx == 0xaa55 && (r.x.cx & 1), "INT 13h AH=41h: extensions on drive 80h"); + + memset(params, 0, sizeof(params)); + *(unsigned *)params = sizeof(params); + r.h.ah = 0x48; + r.h.dl = 0x80; + r.x.si = FP_OFF(params); + segread(&sr); + int86x(0x13, &r, &r, &sr); + sprintf(buf, " drive 80h: %lu sectors of %u bytes\n", + *(unsigned long *)(params + 16), *(unsigned *)(params + 24)); + out(buf); + check(!r.x.cflag && *(unsigned long *)(params + 16) >= 65536UL && + *(unsigned *)(params + 24) == 512, "INT 13h AH=48h: drive parameters"); +} + +int main(int argc, char **argv) +{ + static const unsigned wsizes[] = { 512, 4096, 1, 24576, 3000, 17000 }; + static const unsigned rsizes[] = { 24576, 777, 8192, 512, 20000 }; + long off; + int h, i, ok, n; + unsigned k; + + drive = argc > 1 ? (char)(argv[1][0] & 0xdf) : 'C'; + sprintf(buf, "\ndisk test on %c:\n", drive); + out(buf); + bios_checks(); + + h = fopen_rw(p("\\HELLO.TXT"), 0); + n = h >= 0 ? (int)frw(h, 100, 0) : 0; + if (h >= 0) + fclose_h(h); + check(n >= 16 && memcmp(buf, "hello from linux", 16) == 0, "read HELLO.TXT written by Linux"); + + r.h.ah = 0x39; + r.x.dx = FP_OFF(p("\\DISKTEST")); + dos(); + + /* write 1 MB in varying chunk sizes */ + h = fopen_rw(p("\\DISKTEST\\BIG.BIN"), 1); + ok = h >= 0; + for (off = 0, i = 0; ok && off < BIG_SIZE; i++) + { + k = wsizes[i % 6]; + if (off + k > BIG_SIZE) + k = (unsigned)(BIG_SIZE - off); + fill(off, k); + ok = frw(h, k, 1) == k; + off += k; + } + if (h >= 0) + fclose_h(h); + check(ok, "write 1 MB BIG.BIN"); + + /* read it back in other chunk sizes */ + h = fopen_rw(p("\\DISKTEST\\BIG.BIN"), 0); + ok = h >= 0; + for (off = 0, i = 0; ok && off < BIG_SIZE; i++) + { + k = rsizes[i % 5]; + if (off + k > BIG_SIZE) + k = (unsigned)(BIG_SIZE - off); + ok = frw(h, k, 0) == k && same(off, k); + off += k; + } + if (h >= 0) + { + ok = ok && frw(h, 10, 0) == 0; /* at end of file */ + fclose_h(h); + } + check(ok, "read back 1 MB and compare"); + + /* many small files, delete every other */ + ok = 1; + for (i = 0; ok && i < 60; i++) + { + sprintf(buf, "%c:\\DISKTEST\\F%02d.TXT", drive, i); + h = fopen_rw(buf, 1); + ok = h >= 0; + if (ok) + { + n = sprintf(buf, "small file %d\r\n", i); + ok = frw(h, n, 1) == (unsigned)n; + fclose_h(h); + } + } + for (i = 0; ok && i < 60; i += 2) + { + sprintf(buf, "%c:\\DISKTEST\\F%02d.TXT", drive, i); + r.h.ah = 0x41; + r.x.dx = FP_OFF(buf); + ok = dos(); + } + check(ok, "create 60 files, delete 30"); + + h = fopen_rw(p("\\FROMDOS.TXT"), 1); + if (h >= 0) + { + sprintf(buf, "written by DOS on %c:\r\n", drive); + frw(h, strlen(buf), 1); + fclose_h(h); + } + check(h >= 0, "write FROMDOS.TXT"); + + /* make sure everything reached the disk */ + r.h.ah = 0x0d; + dos(); + + sprintf(buf, "DISKTEST: %d failures / %d checks\n", failures, checks); + out(buf); + return failures; +} diff --git a/tests/uefi/run.sh b/tests/uefi/run.sh new file mode 100755 index 00000000..4f68818e --- /dev/null +++ b/tests/uefi/run.sh @@ -0,0 +1,361 @@ +#!/bin/bash +# UEFI boot test (runs inside the build container). +# +# OVMF boots \EFI\BOOT\BOOTX64.EFI from a FAT ESP. The loader starts the +# MDVMM core, which provides a PC BIOS (text console on the GOP +# framebuffer, keyboard, timer, INT 13h on \MDOS\BOOT.IMG) and boots +# the modernDOS floppy image in V86 mode. CONFIG.SYS loads HIMEMX on the +# extended memory the virtual BIOS reports (DOS=HIGH). AUTOEXEC.BAT runs: +# MDVMM - no monitor to load: sets up DOS sessions +# V86CHK - V86 mode, MDVMM API +# XMSTEST - XMS moves (INT 15h AH=87h through the extended memory window) +# LFNTEST - long filename suite (heavy INT 21h, timer, disk) +# DJTEST - DJGPP program, MDVMM as DPMI host +# DPMITEST - DPMI host test +# MDVMM NEW BG.BAT + SESSTEST /FG - a second session; the harness presses +# Ctrl+Alt+F2/F1 +# DISKTEST C - the AHCI hard disk (64 MB, MBR, FAT16) as drive C: +# DISKTEST D - the NVMe disk (96 MB, MBR, FAT16) as drive D: +# Afterwards both disk images are checked from Linux: fsck, the 1 MB +# file DISKTEST wrote, FROMDOS.TXT. +# and leaves FreeCOM at its prompt, where the harness types (QEMU sendkey) +# ECHO Typed: aB3!~ ECHO R + x held for 1.5 s (repeat) A:\POWEROFF +# All keys (also the session hotkeys) go to a USB keyboard on an xHCI +# controller: QEMU sends input to the last keyboard that was activated. +# The console is mirrored to COM1 (serial.log); MDVMM and the tests log +# to the QEMU debug console. With SCREEN=file.ppm the GOP screen is saved +# at the end. +# +# Usage: tests/uefi/run.sh [kernel.sys] + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +KERNEL=$(realpath "${1:-$ROOT/_output/gcc/kgc8632.sys}") +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +TEST="$ROOT/test" +. "$TEST/cfg.sh" +OVMF=/usr/share/ovmf/OVMF.fd + +echo "== building MDVMM and test programs" +make -s -C "$ROOT/mdvmm" +make -s -C "$ROOT/gui" +for p in v86chk poweroff xmstest netchk; do + "$NASM" -f bin -o "$WORK/$p.com" "$ROOT/tests/mdvmm/$p.asm" +done +ia16-elf-gcc -mcmodel=small -Os -o "$WORK/lfntest.exe" "$ROOT/tests/lfn/lfntest.c" -li86 +ia16-elf-gcc -mcmodel=small -Os -o "$WORK/sesstest.exe" "$ROOT/tests/mdvmm/sesstest.c" -li86 +ia16-elf-gcc -mcmodel=small -Os -o "$WORK/disktest.exe" "$HERE/disktest.c" -li86 +DJGPP=/opt/djgpp/bin/i586-pc-msdosdjgpp-gcc +"$DJGPP" -O2 -s -o "$WORK/djtest.exe" "$ROOT/tests/lfn/djtest.c" +"$DJGPP" -O2 -s -o "$WORK/dpmitest.exe" "$ROOT/tests/mdvmm/dpmitest.c" +"$DJGPP" -O2 -s -I"$ROOT/gui/lib" -o "$WORK/gfxtest.exe" "$ROOT/tests/gui/gfxtest.c" "$ROOT/gui/build/mdgui.o" +"$DJGPP" -O2 -s -I"$ROOT/gui/lib" -o "$WORK/mousetest.exe" "$ROOT/tests/gui/mousetest.c" "$ROOT/gui/build/mdgui.o" +"$DJGPP" -O2 -s -I"$ROOT/gui/lib" -o "$WORK/wmtest.exe" "$ROOT/tests/gui/wmtest.c" "$ROOT/gui/build/mdgui.o" +"$DJGPP" -O2 -s -I"$ROOT/gui/lib" -o "$WORK/uitest.exe" "$ROOT/tests/gui/uitest.c" "$ROOT/gui/build/mdgui.o" + +echo "== building the DOS boot image" +cd "$WORK" +printf 'DEVICE=A:\\HIMEMX.EXE\r\nDOS=HIGH\r\nSHELL=A:\\COMMAND.COM A:\\ /E:512 /P\r\n' > fdconfig.sys +cat > autoexec.bat <<'EOF' +@ECHO OFF +ECHO Hello from DOS on UEFI +A:\MDVMM.COM +IF ERRORLEVEL 1 GOTO END +A:\V86CHK.COM +IF ERRORLEVEL 1 GOTO END +A:\PKTDRV.COM +IF ERRORLEVEL 1 GOTO END +A:\NETCHK.COM +IF ERRORLEVEL 1 GOTO END +A:\XMSTEST.COM +IF ERRORLEVEL 1 GOTO END +A:\LFNTEST.EXE /T +IF ERRORLEVEL 1 GOTO END +A:\DJTEST.EXE +IF ERRORLEVEL 1 GOTO END +A:\DPMITEST.EXE +IF ERRORLEVEL 1 GOTO END +A:\MDVMM.COM NEW A:\BG.BAT +IF ERRORLEVEL 1 GOTO END +A:\SESSTEST.EXE /FG +IF ERRORLEVEL 1 GOTO END +A:\GFXTEST.EXE +IF ERRORLEVEL 1 GOTO END +A:\MOUSETEST.EXE +IF ERRORLEVEL 1 GOTO END +A:\WMTEST.EXE +IF ERRORLEVEL 1 GOTO END +A:\UITEST.EXE +IF ERRORLEVEL 1 GOTO END +A:\SSHSLOT.COM 2 +A:\MDDESK.EXE /TEST +IF ERRORLEVEL 1 GOTO END +A:\MDDESK.EXE /TEST /EXIT +IF ERRORLEVEL 1 GOTO END +DIR C:\ +A:\DISKTEST.EXE C +IF ERRORLEVEL 1 GOTO END +DIR D:\ +A:\DISKTEST.EXE D +IF ERRORLEVEL 1 GOTO END +DIR A:\ /W +ECHO UEFI BOOT: success +GOTO PROMPT +:END +A:\POWEROFF.COM +:PROMPT +EOF +sed -i 's/$/\r/' autoexec.bat +printf '@ECHO OFF\r\nA:\\SESSTEST.EXE /BG\r\nECHO done>A:\\BGDONE.TXT\r\n' > bg.bat + +"$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_LBA=0 -D_USE_PART_INFO=0 -D_QUERY_GEOMETRY=0 \ + -D_FAT12 -D_UNIT=00h -D_CHS_SECTORS=36 -D_CHS_HEADS=2 -o boot.bin +"$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,fdconfig.sys" \ + -D_BOOTPATCHFILE="'boot.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR_PART_TYPE=ptFAT12 -D_BPE=12 -D_SPC=2 -D_SPI=5760 \ + -D_SPF=9 -D_NUMROOT=224 -D_CHS_SECTORS=36 -D_CHS_HEADS=2 -D_UNIT=00h -o boot.img + +export MTOOLS_SKIP_CHECK=1 +mcopy -i boot.img /opt/fdos/bin/command.com ::COMMAND.COM +mcopy -i boot.img autoexec.bat ::AUTOEXEC.BAT +mcopy -i boot.img v86chk.com ::V86CHK.COM +mcopy -i boot.img "$ROOT/mdvmm/build/PKTDRV.COM" ::PKTDRV.COM +mcopy -i boot.img netchk.com ::NETCHK.COM +mcopy -i boot.img poweroff.com ::POWEROFF.COM +mcopy -i boot.img lfntest.exe ::LFNTEST.EXE +mcopy -i boot.img djtest.exe ::DJTEST.EXE +mcopy -i boot.img /opt/fdos/bin/himemx.exe ::HIMEMX.EXE +mcopy -i boot.img "$ROOT/mdvmm/build/MDVMM.COM" ::MDVMM.COM +mcopy -i boot.img xmstest.com ::XMSTEST.COM +mcopy -i boot.img dpmitest.exe ::DPMITEST.EXE +mcopy -i boot.img sesstest.exe ::SESSTEST.EXE +mcopy -i boot.img gfxtest.exe ::GFXTEST.EXE +mcopy -i boot.img mousetest.exe ::MOUSETEST.EXE +mcopy -i boot.img wmtest.exe ::WMTEST.EXE +mcopy -i boot.img uitest.exe ::UITEST.EXE +mcopy -i boot.img "$ROOT/gui/build/MDDESK.EXE" ::MDDESK.EXE +mcopy -i boot.img "$ROOT/mdvmm/build/SSHSLOT.COM" ::SSHSLOT.COM +mcopy -i boot.img bg.bat ::BG.BAT +mcopy -i boot.img disktest.exe ::DISKTEST.EXE + +echo "== building the hard disks (AHCI, NVMe)" +# make_disk image sectors label: MBR with one FAT16 partition from 1MB on, +# HELLO.TXT written by Linux +make_disk() { + dd if=/dev/zero of="$1" bs=512 count="$2" status=none + python3 - "$1" "$2" <<'PY' +import struct, sys +path, total = sys.argv[1], int(sys.argv[2]) +entry = struct.pack(" hello.txt +make_disk hd.img 131072 AHCIDISK +make_disk nvme.img 196608 NVMEDISK +printf 'hello from linux\n' > linux.txt +mcopy -i boot.img linux.txt "::Created On Linux.txt" # LFNTEST fixture + +echo "== building the EFI system partition" +dd if=/dev/zero of=esp.img bs=1M count=32 status=none +mformat -i esp.img -h 64 -s 32 -t 32 :: +mmd -i esp.img ::/EFI ::/EFI/BOOT ::/MDOS +mcopy -i esp.img "$ROOT/mdvmm/build/BOOTX64.EFI" ::/EFI/BOOT/BOOTX64.EFI +mcopy -i esp.img boot.img ::/MDOS/BOOT.IMG +printf 'hard disks writable\r\n' > diskrw +mcopy -i esp.img diskrw ::/MDOS/DISKRW # else disks are read-only +mcopy -i esp.img diskrw ::/MDOS/FBPROBE # the loader probes the framebuffer too + +echo "== booting OVMF in QEMU" +if [ -n "$SCREEN" ]; then + # save the screen every 2 s until QEMU exits: the last one stays + python3 - "$WORK" "$SCREEN" <<'PY' & +import os, socket, sys, time +work, out = sys.argv[1], sys.argv[2] +sock = os.path.join(work, "mon.sock") +time.sleep(3) +while True: + try: + s = socket.socket(socket.AF_UNIX); s.connect(sock) + s.sendall(("screendump %s.tmp\n" % out).encode()); time.sleep(0.5); s.close() + if os.path.exists(out + ".tmp"): + os.replace(out + ".tmp", out) + except OSError: + break + time.sleep(1.5) +PY + shot_pid=$! +fi +# keyboard: Ctrl+Alt+F2/F1 while the sessions test runs, then (once the +# batch is done) type at the prompt +python3 - "$WORK" <<'PY' & +import os, socket, sys, time +work = sys.argv[1] +serial, sock = os.path.join(work, "serial.log"), os.path.join(work, "mon.sock") +debug = os.path.join(work, "debug.log") +def text(path): + try: + return open(path, "rb").read() + except OSError: + return b"" +def send(cmd): + s = socket.socket(socket.AF_UNIX); s.connect(sock) + s.sendall((cmd + "\n").encode()); time.sleep(0.15); s.close() +deadline = time.time() + 290 +while time.time() < deadline and b"sessions test" not in text(debug): + time.sleep(0.2) +i = 0 +while time.time() < deadline and b"SESSIONS:" not in text(debug): + try: + send("sendkey " + ["ctrl-alt-f2", "ctrl-alt-f1"][i % 2]) + except OSError: + break + i += 1 + time.sleep(1.5) +names = {" ": "spc", ":": "shift-semicolon", "!": "shift-1", "~": "shift-grave_accent", + "\\": "backslash", "\n": "ret"} +def key(c): + if c in names: + return names[c] + return "shift-" + c.lower() if c.isupper() else c +while time.time() < deadline and b"UEFI BOOT: success" not in text(serial): + time.sleep(0.5) +time.sleep(2) +try: + s = socket.socket(socket.AF_UNIX); s.connect(sock) + def type_text(t): + for c in t: + s.sendall(("sendkey %s\n" % key(c)).encode()) + time.sleep(0.15) + type_text("ECHO Typed: aB3!~\nECHO R") + s.sendall(b"sendkey x 1500\n") # held: typematic repeat + time.sleep(2) + type_text("\nA:\\POWEROFF\n") + time.sleep(1); s.close() +except OSError: + pass +PY +keys_pid=$! +python3 "$ROOT/tests/gui/gfxshot.py" debug.log mon.sock gfx.ppm & +shot_gfx=$! +python3 "$ROOT/tests/gui/mousedrive.py" debug.log mon.sock mouse.ppm & +mouse_drv=$! +(cd "$ROOT/tests/gui" && PYTHONDONTWRITEBYTECODE=1 exec python3 wmdrive.py "$WORK/debug.log" "$WORK/mon.sock" "$WORK/wm.ppm") & +wm_drv=$! +(cd "$ROOT/tests/gui" && PYTHONDONTWRITEBYTECODE=1 exec python3 uidrive.py "$WORK/debug.log" "$WORK/mon.sock" "$WORK/ui.ppm") & +ui_drv=$! +# a small web site for the browser (10.0.2.2:8378 in the guest) +mkdir -p site/sub +cat > site/index.html <<'HTML' +Test Page +

modernDOS browser test

+

A paragraph with bold text, an entity & an umlaut: grün, UTF-8: grĂ¼n.

+ +
  preformatted
+    text
+ +

home

+HTML +printf 'Second Page

Second

You followed the link. Back home

' > site/sub/page2.html +python3 -m http.server 8378 --bind 127.0.0.1 -d site > /dev/null 2>&1 & +web_pid=$! +(cd "$ROOT/tests/gui" && BROWSER=8378 PYTHONDONTWRITEBYTECODE=1 exec python3 deskdrive.py "$WORK/debug.log" "$WORK/mon.sock" "$WORK/desk.ppm") & +desk_drv=$! +timeout --foreground 300 qemu-system-x86_64 -m 256 -bios "$OVMF" \ + -drive file=esp.img,format=raw,if=ide -nic user,model=e1000 -display none \ + -device ahci,id=ahci -drive id=hd,file=hd.img,format=raw,if=none \ + -device ide-hd,drive=hd,bus=ahci.0 \ + -drive id=nv,file=nvme.img,format=raw,if=none \ + -device nvme,serial=MDNVME01,drive=nv \ + -device qemu-xhci,id=xhci -device usb-kbd,bus=xhci.0 -device usb-mouse,bus=xhci.0 \ + -debugcon file:debug.log -serial file:serial.log -no-reboot \ + -monitor unix:mon.sock,server,nowait $QEMU_EXTRA /dev/null || true +kill $keys_pid 2>/dev/null || true +[ -n "$SCREEN" ] && wait $shot_pid 2>/dev/null || true +echo "-- debug console" +sed 's/\r$//' debug.log +echo "-- screen (serial mirror)" +sed 's/\r$//; s/\x1b\[[0-9;]*[A-Za-z]//g' serial.log | tr -d '\000' | grep -a -v '^$' | tail -40 + +echo "== checks" +fail=0 +for marker in "MDVMM core:" "bios: disk image" "fbcon:" "apic: virtual wire mode set" \ + "timer: ok - the 8254 ticks and its interrupt reaches the CPU" "v86: entering VM1" \ + "vm: sessions enabled" "v86chk: protected mode bit set" \ + "xmstest: 4K round trip" "RESULT: PASSED" "dpmi: 32 bit client" \ + "DJGPP: 0 failures" "DPMI: 0 failures" "vm: session 1 ended" \ + "SESSIONS: 0 failures" "GFXTEST: text mode again" "ahci: port 0: QEMU HARDDISK" \ + "bios: hard disks are writable" \ + "nvme: namespace 1: 96 MB" "DISKTEST: 0 failures" \ + "disk test on D:" "nic: .* (iPXE)" "Packet driver at INT 60h" "netchk: ARP reply from 10.0.2.2" "xhci: port [0-9]*: keyboard" "xhci: port [0-9]*: mouse" "mouse: first report" "bios: mouse driver installed" \ + "usbkbd: first key report"; do + if grep -q "$marker" debug.log; then echo " ok log: $marker"; else + echo " FAIL log missing: $marker"; fail=1; fi +done +for marker in "modernDOS kernel" "Hello from DOS on UEFI" "UEFI BOOT: success" \ + "^Typed: aB3!~$" "^Rxxxxx"; do + if sed 's/\r//g' serial.log | grep -aq "$marker"; then echo " ok screen: $marker"; else + echo " FAIL screen missing: $marker"; fail=1; fi +done +# the loader's hardware report on the ESP +mtype -i esp.img ::/MDOS/HWINFO.TXT 2>/dev/null | tr -d '\r' > hwinfo.txt || true +echo "-- HWINFO.TXT (start)"; head -12 hwinfo.txt +for marker in "Firmware: " "System: " "CPU: " "GOP: mode" "PCI devices" " 00:00.0 8086:" "Usable memory: " "End of report"; do + if grep -q "$marker" hwinfo.txt; then echo " ok hwinfo: $marker"; else + echo " FAIL hwinfo missing: $marker"; fail=1; fi +done +# the loader's own log, and its framebuffer probe (drawn markers found in +# the display's memory) against what GOP reports +mtype -i esp.img ::/MDOS/BOOTLOG.TXT 2>/dev/null | tr -d '\r' > bootlog.txt || true +echo "-- BOOTLOG.TXT"; sed 's/^/ /' bootlog.txt +for marker in "Hardware report written" "Memory: disk image at" "Graphics (GOP)" "Starting the monitor"; do + if grep -q "$marker" bootlog.txt; then echo " ok bootlog: $marker"; else + echo " FAIL bootlog missing: $marker"; fail=1; fi +done +gop=$(sed -n 's/^Graphics (GOP): //p' bootlog.txt) +for how in scan poke; do + probe=$(sed -n "s/^Framebuffer probe ($how): //p" bootlog.txt) + if [ -n "$gop" ] && [ "$gop" = "$probe" ]; then echo " ok framebuffer probe ($how) agrees with GOP ($probe)"; else + echo " FAIL framebuffer probe ($how): '$probe' but GOP says '$gop'"; fail=1; fi +done + +# the hard disks, from Linux: check_disk image drive name +check_disk() { + dd if="$1" of=part.img bs=512 skip=2048 status=none + if fsck.fat -n part.img >/dev/null; then echo " ok $3: file system clean"; else + echo " FAIL $3: fsck.fat"; fail=1; fi + if mtype -i part.img ::FROMDOS.TXT 2>/dev/null | grep -q "written by DOS on $2:"; then + echo " ok $3: FROMDOS.TXT"; else echo " FAIL $3: FROMDOS.TXT"; fail=1; fi + rm -f big.bin + mcopy -n -i part.img ::DISKTEST/BIG.BIN big.bin 2>/dev/null || true + if python3 - big.bin <<'PY' +import sys +try: + d = open(sys.argv[1], "rb").read() +except OSError: + sys.exit(1) +want = bytes(((o * 7 + (o >> 9) + (o >> 17)) & 0xff) for o in range(1 << 20)) +sys.exit(0 if d == want else 1) +PY + then echo " ok $3: BIG.BIN pattern (1 MB)"; else + echo " FAIL $3: BIG.BIN"; fail=1; fi +} +check_disk hd.img C "AHCI disk" +check_disk nvme.img D "NVMe disk" +python3 "$ROOT/tests/gui/gfxcheck.py" gfx.ppm debug.log || fail=1 +python3 "$ROOT/tests/gui/mousecheck.py" debug.log mouse.ppm || fail=1 +python3 "$ROOT/tests/gui/wmcheck.py" debug.log wm.ppm || fail=1 +PYTHONDONTWRITEBYTECODE=1 python3 "$ROOT/tests/gui/uicheck.py" debug.log ui.ppm || fail=1 +TERMINAL=1 BROWSER=8378 PYTHONDONTWRITEBYTECODE=1 python3 "$ROOT/tests/gui/deskcheck.py" debug.log desk.ppm || fail=1 +[ -n "$SHOTS" ] && cp ./*.ppm "$SHOTS"/ 2>/dev/null || true # keep the screenshots +if [ $fail = 0 ]; then echo "UEFI TEST: success"; else echo "UEFI TEST: failure"; exit 1; fi diff --git a/tests/usb/run.sh b/tests/usb/run.sh new file mode 100755 index 00000000..f0c0251a --- /dev/null +++ b/tests/usb/run.sh @@ -0,0 +1,116 @@ +#!/bin/bash +# USB keyboard test on UHCI controllers (runs inside the build container). +# +# Boots modernDOS from UEFI (OVMF) three times and types at the DOS prompt +# through a USB keyboard (QEMU sendkey); the screen comes back over the +# serial mirror of the console: +# - keyboard and mouse directly on a UHCI controller +# - keyboard and mouse behind a hub +# - like an older Mac: an EHCI controller with UHCI companions, the +# keyboard behind a hub on an EHCI port (the ports must fall back to +# the companions), booted from a stick on that controller, no PS/2 +# controller +# +# Usage: tests/usb/run.sh [kernel.sys] + +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +KERNEL=$(realpath "${1:-$ROOT/_output/gcc/kgc8632.sys}") +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +TEST="$ROOT/test" +. "$TEST/cfg.sh" +OVMF=/usr/share/ovmf/OVMF.fd +export MTOOLS_SKIP_CHECK=1 + +echo "== building" +make -s -C "$ROOT/mdvmm" +"$NASM" -f bin -o "$WORK/poweroff.com" "$ROOT/tests/mdvmm/poweroff.asm" +cd "$WORK" +printf 'SHELL=A:\\COMMAND.COM A:\\ /E:512 /P\r\n' > fdconfig.sys +printf '@ECHO OFF\r\nECHO USB TEST READY\r\n' > autoexec.bat +"$NASM" "$TEST/ldosboot/boot.asm" -w-user -I"$TEST/lmacros/" \ + -D_COMPAT_FREEDOS=1 -D_LBA=0 -D_USE_PART_INFO=0 -D_QUERY_GEOMETRY=0 \ + -D_FAT12 -D_UNIT=00h -o boot.bin +"$NASM" "$TEST/bootimg/bootimg.asm" -I ./ -I"$TEST/bootimg/" -I"$TEST/lmacros/" \ + -D_PAYLOADFILE="::rename,'$KERNEL',KERNEL.SYS,fdconfig.sys" \ + -D_BOOTPATCHFILE="'boot.bin'" \ + -D_WARN_DEFAULT_OFF=1 -D_WARN_TOOMANYFAT=0 -D_WARN_ALIGNDATA=0 \ + -D_MBR_PART_TYPE=ptFAT12 -D_BPE=12 -D_SPC=1 -D_SPI=2880 \ + -D_SPF=9 -D_NUMROOT=224 -D_UNIT=00h -o boot.img +mcopy -i boot.img /opt/fdos/bin/command.com ::COMMAND.COM +mcopy -i boot.img autoexec.bat ::AUTOEXEC.BAT +mcopy -i boot.img poweroff.com ::POWEROFF.COM +dd if=/dev/zero of=esp.img bs=1M count=16 status=none +mformat -i esp.img -h 64 -s 32 -t 16 :: +mmd -i esp.img ::/EFI ::/EFI/BOOT ::/MDOS +mcopy -i esp.img "$ROOT/mdvmm/build/BOOTX64.EFI" ::/EFI/BOOT/BOOTX64.EFI +mcopy -i esp.img boot.img ::/MDOS/BOOT.IMG + +fail=0 +run() { # run name "log markers|..." -- qemu args + local name=$1 markers=$2; shift 2 + rm -f debug.log serial.log mon.sock + python3 - <<'PY' & +import socket, time +def text(path): + try: + return open(path, "rb").read() + except OSError: + return b"" +names = {" ": "spc", ":": "shift-semicolon", "\\": "backslash", "\n": "ret", "-": "minus"} +def key(c): + if c in names: + return names[c] + return "shift-" + c.lower() if c.isupper() else c +end = time.time() + 100 +while time.time() < end and b"USB TEST READY" not in text("serial.log"): + time.sleep(0.5) +time.sleep(2) +try: + s = socket.socket(socket.AF_UNIX); s.connect("mon.sock") + for c in "ECHO Typed: aB3-usb\nA:\\POWEROFF\n": + s.sendall(("sendkey %s\n" % key(c)).encode()) + time.sleep(0.15) + time.sleep(1); s.close() +except OSError: + pass +PY + local typer=$! + timeout --foreground 120 qemu-system-x86_64 -m 256 -bios "$OVMF" -display none -net none \ + "$@" \ + -debugcon file:debug.log -serial file:serial.log -no-reboot \ + -monitor unix:mon.sock,server,nowait /dev/null || true + echo "-- $name" + [ -n "$KEEP" ] && cp debug.log "$KEEP/usb-${name%% *}.log" && cp serial.log "$KEEP/usb-${name%% *}.serial" + grep -a "uhci:\|ehci:\|PANIC" debug.log | sed 's/\r$//; s/^/ /' + local IFS='|' m + for m in $markers; do + if grep -aq "$m" debug.log; then echo " ok $name: $m"; else + echo " FAIL $name: log lacks '$m'"; fail=1; fi + done + if grep -aq "MDVMM core:" debug.log && grep -aq "USB TEST READY" serial.log && + sed 's/\r//g' serial.log | grep -aq "^Typed: aB3-usb$"; then + echo " ok $name: typed text arrived at the DOS prompt"; else + echo " FAIL $name: typed text did not arrive"; fail=1 + sed 's/\r//g' serial.log | tr -d '\000' | grep -av '^$' | tail -4 | cut -c1-120 | sed 's/^/ screen: /' + grep -a "^usbkbd\|^kbd:\|PANIC" debug.log | head -5 | sed 's/^/ monitor: /'; fi +} + +run "UHCI" "uhci: controller 0 port [12]: keyboard|uhci: controller 0 port [12]: mouse" \ + -drive file=esp.img,format=raw,if=ide \ + -device piix3-usb-uhci,id=u -device usb-kbd,bus=u.0,port=1 -device usb-mouse,bus=u.0,port=2 +run "UHCI, hub" "uhci: hub at address 1, 8 ports|uhci: hub 01 port 02: keyboard|uhci: hub 01 port 03: mouse" \ + -drive file=esp.img,format=raw,if=ide \ + -device piix3-usb-uhci,id=u -device usb-hub,bus=u.0,port=1 \ + -device usb-kbd,bus=u.0,port=1.2 -device usb-mouse,bus=u.0,port=1.3 +run "EHCI with companions (Mac-like)" "ehci: controller at .* left to its UHCI companions|uhci: hub at address 1|: keyboard" \ + -machine q35,i8042=off \ + -device ich9-usb-ehci1,id=e -device ich9-usb-uhci1,masterbus=e.0,firstport=0 \ + -device ich9-usb-uhci2,masterbus=e.0,firstport=2 -device ich9-usb-uhci3,masterbus=e.0,firstport=4 \ + -drive if=none,id=stick,format=raw,file=esp.img -device usb-storage,bus=e.0,port=1,drive=stick \ + -device usb-hub,bus=e.0,port=3 -device usb-kbd,bus=e.0,port=3.1 -device usb-mouse,bus=e.0,port=3.4 + +if [ $fail = 0 ]; then echo "USB TEST: success"; exit 0; else echo "USB TEST: failure"; exit 1; fi