diff --git a/.claude/skills/crash-debug/SKILL.md b/.claude/skills/crash-debug/SKILL.md new file mode 100644 index 000000000..8fb50d56d --- /dev/null +++ b/.claude/skills/crash-debug/SKILL.md @@ -0,0 +1,121 @@ +--- +name: crash-debug +description: Symbolicate an Aura OS (Cosmos gen3) kernel crash. Boots the ISO headless in QEMU with a gdb stub, catches the CPU-exception panic / KERNEL PANIC / [FAILFAST] report on serial, dumps the crashed stack via gdb, and resolves the kernel's raw stack trace and every return address against the kernel ELF with nm/addr2line. Also symbolicates an existing serial log (--uart) or pasted addresses (--symbolicate). Use when Aura OS page-faults, panics or fail-fasts in QEMU and you need to know which managed method crashed, or when the user pastes a panic dump that needs symbolication. Never builds. +--- + +# Aura OS crash debug + +Reproduce a boot-time kernel crash and get a fully symbolicated backtrace in +one command: + +```bash +.claude/skills/crash-debug/crash-debug.sh +``` + +The script boots `SRC/Aura_OS/output-x64/Aura_OS.iso` headless (serial to a +temp uart.log, gdb stub on the first free port from 12377, `-m 1024`, a temp +copy of `SRC/Aura_OS/disk.img` on AHCI, e1000e NIC), waits for a fatal report, +and prints: + +- the faulting RIP symbol, +- `[RSP]` (the kernel's `sp0:` line): the direct caller when the fault hit a + frameless leaf runtime helper, +- the kernel's own frame-pointer walk from the panic's + `Stack trace (raw return addresses, symbolicate with nm):` block + (NativeAOT keeps frame pointers, so this is reliable), +- with gdb: a conservative scan of all code addresses near RSP (covers broken + chains), and the RBP chain from the dump when the serial trace has no frames. + +Useful flags: `--timeout N` (default 180s; the crash must occur during boot or +be reachable without input), `--keep` (leave QEMU + gdb stub alive for +interactive digging), `--mem SIZE` (default 1024 MB), `--iso/--elf/--disk PATH` +overrides, `--hang-after PATTERN` (no crash, but stuck: samples RIP twice via +gdb once PATTERN shows up on serial). + +Symbolicate a crash that already happened, no QEMU run. For example, use the +`uart.log` that run-aura tees at the repo root, or a log the user pasted into a +file: + +```bash +.claude/skills/crash-debug/crash-debug.sh --uart uart.log +``` + +To resolve addresses the user pasted: + +```bash +.claude/skills/crash-debug/crash-debug.sh --symbolicate 0xFFFFFFFF8009E2A0 0xFFFFFFFF80088486 +``` + +## Never build + +This skill and its scripts never build. The user runs the builds: `cosmos build +-p SRC/Aura_OS`, or `dotnet publish SRC/Aura_OS/Aura_OS.csproj -c Debug -r +linux-x64 -o SRC/Aura_OS/output-x64`. + +- The backtrace is only valid against the ELF that produced the crash. +- The script warns when a `.cs`/`.csproj` under `SRC/Aura_OS` is newer than the + ELF. +- If the ISO or ELF is missing or stale, stop and ask the user to rebuild. + +## What the serial reports mean + +- **`CPU EXCEPTION: `, then `System halted.`** A hardware fault: #PF, + #GP, #UD, #DE and the like. gen3 never turns these into managed exceptions: + a null dereference or an integer `/0` halts the kernel (GEN3-GAP(null-deref) + in `GEN3-GAPS.md`). +- **`KERNEL PANIC`, then `System halted.`** A kernel-internal `Panic.Halt`, + printed with the method, file and line. +- **`[FAILFAST] `, then the CPU spins.** A managed exception nobody + caught ("Unhandled exception"), or one thrown while another was being + dispatched ("Recursive exception"). The report carries the exception message + and its managed stack trace. +- **`[CRASH] : `.** This is Aura's own crash screen + (`Crash.StopKernel`) for a managed exception it caught. The kernel keeps + running and waits for a key. The script stops on it, prints the `[CRASH]` + line and the last serial output, and exits with code 4: there is no CPU + fault to symbolicate. Read the message and fix the throw site. + +## Environment gotchas (already handled by the script) + +- QEMU is probed in this order: + 1. `~/.cosmos/tools/qemu/bin/qemu-system-x86_64` (newer bundles) + 2. `~/.cosmos/tools/qemu/qemu-system-x86_64` + 3. the system qemu +- `~/.cosmos/tools/bin/qemu-system-x86_64` is a stale symlink to the bundle + wrapper. It execs a nonexistent `bin/*.real` and fails `--version`, so it is + skipped. `cosmos run` is not affected by it. +- `SRC/Aura_OS/disk.img` may be write-locked by the user's own QEMU session + (run-aura or the VS Code extension). The script always runs against a temp + copy. A missing image becomes a blank 512 MB disk, and Aura then boots in + live mode. +- gdb comes from `PATH`, then `~/.cosmos/tools/gdb/bin/gdb`. Without gdb, a CPU + exception still symbolicates from the kernel's serial stack trace. + +## Interpreting the backtrace + +- Symbols are ILC-mangled: `Assembly_Namespace_Class__Method`. Map them back + to the C# source and read the actual method. +- **Page fault with CR2 < 64K = null dereference.** CR2 is the field or element + offset into the null object. gen2/IL2CPU identity-mapped low memory, so + ported gen2 code is full of latent null dereferences that only now fault + (GEN3-GAP(null-deref)). +- **CR2 next to RSP**: the kernel prints `not walking` instead of frames. This + is most likely a stack overflow (deep or infinite recursion). +- If RIP is in a leaf runtime helper, the real bug is in the `[RSP]` frame: + - `RhpAssignRef` / `RhpCheckedAssignRef` (GC write barrier): the caller did + `nullObject.refField = value`; CR2 = the field's offset. + - `memset/memcpy/RhpCopy*`: caller passed a null/bad buffer. +- Frames like `Aura_OS_Aura_Boot_Kernel__BeforeRun`/`__Run`, + `Aura_OS_Aura_OS_Kernel__BeforeRun`/`__Run`, `__managed__Main` and `kmain` + are the normal boot spine. The interesting frames sit above them. + +## After symbolication + +Read the C# source of frames #1–#3. Find which object can be null on that path +with a ref field at the CR2 offset, and fix it at the source (rule C6: explicit +null and divisor checks). + +If the field offsets are ambiguous, count the object-reference fields in class +layout order: base class first, 8 bytes each, after the 8-byte MethodTable +pointer. Or add a targeted `Log.WriteString` and ask the user to rebuild and +rerun. diff --git a/.claude/skills/crash-debug/crash-debug.sh b/.claude/skills/crash-debug/crash-debug.sh new file mode 100755 index 000000000..b32120b3c --- /dev/null +++ b/.claude/skills/crash-debug/crash-debug.sh @@ -0,0 +1,272 @@ +#!/usr/bin/env bash +# Boot the Aura OS ISO headless under QEMU with a gdb stub, wait for a fatal +# report on serial (CPU EXCEPTION / KERNEL PANIC / [FAILFAST]), dump the +# crashed stack via gdb, and print a symbolicated backtrace against the kernel +# ELF. Can also symbolicate an existing serial log (--uart) or raw addresses +# (--symbolicate) without booting anything. +# +# This script NEVER builds. The user runs the builds: when the ISO/ELF is +# missing or older than the sources, ask him to rebuild. +# +# The disk image is COPIED to a temp workdir, so this never fights an +# already-running QEMU for the write lock on disk.img. +set -uo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" +PROJECT_DIR="$REPO_ROOT/SRC/Aura_OS" + +# `cosmos build -p SRC/Aura_OS` (and `dotnet publish ... -o SRC/Aura_OS/output-x64`) +# put the ISO there; PublishISO copies the ELF next to it. +ISO="$PROJECT_DIR/output-x64/Aura_OS.iso" +ELF="$PROJECT_DIR/output-x64/Aura_OS.elf" +# Same image as SRC/Aura_OS/.cosmos/config.json (VS Code extension) and run-aura. +DISK="$PROJECT_DIR/disk.img" +TIMEOUT=180 +PORT_BASE=12377 +KEEP=0 +MEM=1024 +HANG_PATTERN="" +HANG_GRACE=8 +UART_IN="" +SYM_ONLY=() + +REBUILD_HINT="ask the user to rebuild (cosmos build -p SRC/Aura_OS); this skill never builds" + +usage() { + cat </dev/null | head -n 1)" +if [ -n "$NEWER_SRC" ]; then + echo "WARNING: sources changed after the ELF was built (e.g. ${NEWER_SRC#"$REPO_ROOT"/})." + echo " Addresses from a NEW crash need a matching ELF: $REBUILD_HINT." +fi + +if [ ${#SYM_ONLY[@]} -gt 0 ]; then + exec python3 "$SCRIPT_DIR/symbolicate.py" --elf "$ELF" --addrs "${SYM_ONLY[@]}" +fi + +if [ -n "$UART_IN" ]; then + [ -f "$UART_IN" ] || { echo "ERROR: serial log not found: $UART_IN"; exit 1; } + exec python3 "$SCRIPT_DIR/symbolicate.py" --elf "$ELF" --uart "$UART_IN" +fi + +[ -f "$ISO" ] || { echo "ERROR: ISO not found: $ISO ($REBUILD_HINT)"; exit 1; } + +# gdb is needed for the stack dump and for hang mode. HEAD's panic prints its +# own frame-pointer walk, so a CPU-exception crash still symbolicates without it. +GDB="$(command -v gdb || true)" +[ -z "$GDB" ] && [ -x "$HOME/.cosmos/tools/gdb/bin/gdb" ] && GDB="$HOME/.cosmos/tools/gdb/bin/gdb" +if [ -z "$GDB" ]; then + [ -n "$HANG_PATTERN" ] && { echo "ERROR: gdb not installed (needed for --hang-after)"; exit 1; } + echo "WARNING: gdb not installed; using the kernel's serial stack trace only." +fi + +# QEMU: the Cosmos bundle (qemu/bin/ in newer bundles, qemu/ in older ones), +# then the system one. ~/.cosmos/tools/bin/qemu-system-x86_64 (a stale symlink +# to the qemu/ wrapper, first on PATH on the user's machine) fails --version +# and is skipped. +QEMU="" +for q in "$HOME/.cosmos/tools/qemu/bin/qemu-system-x86_64" \ + "$HOME/.cosmos/tools/qemu/qemu-system-x86_64" \ + /usr/bin/qemu-system-x86_64 \ + "$(command -v qemu-system-x86_64 || true)"; do + [ -n "$q" ] || continue + if "$q" --version >/dev/null 2>&1; then QEMU="$q"; break; fi +done +[ -n "$QEMU" ] || { echo "ERROR: no working qemu-system-x86_64 found (try: cosmos install)"; exit 1; } + +PORT="" +for p in $(seq "$PORT_BASE" $((PORT_BASE + 9))); do + if ! (echo >"/dev/tcp/127.0.0.1/$p") 2>/dev/null; then PORT=$p; break; fi +done +[ -n "$PORT" ] || { echo "ERROR: no free gdb port in $PORT_BASE-$((PORT_BASE + 9))"; exit 1; } + +# KVM when the host exposes it: boots and runs the kernel ~10x faster, and +# the gdb usage here (halt, register reads, memory dumps) works fine under it. +KVM_FLAGS=(-cpu max) +[ -w /dev/kvm ] && KVM_FLAGS=(-enable-kvm -cpu host) + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/aura-crash-debug.XXXXXX")" +echo "Workdir: $WORK (uart.log, stack.txt, disk copy)" + +if [ -f "$DISK" ]; then + cp "$DISK" "$WORK/disk.img" +else + # Blank disk: Aura boots in live mode (no FAT volume). + truncate -s 512M "$WORK/disk.img" +fi + +# Same machine as `cosmos run` (q35, CD bootindex=0, AHCI disk, e1000e NIC). +"$QEMU" -M q35 "${KVM_FLAGS[@]}" -m "$MEM" \ + -drive file="$ISO",if=none,id=cosmoscd,format=raw,readonly=on \ + -device ide-cd,drive=cosmoscd,bootindex=0 \ + -boot d -vga std \ + -serial file:"$WORK/uart.log" \ + -device ich9-ahci,id=ahci0 \ + -drive file="$WORK/disk.img",if=none,id=ahcidisk0,format=raw \ + -device ide-hd,drive=ahcidisk0,bus=ahci0.0 \ + -netdev user,id=net0 -device e1000e,netdev=net0 \ + -display none -no-reboot -no-shutdown -gdb "tcp::$PORT" \ + >"$WORK/qemu.err" 2>&1 & +QPID=$! + +cleanup() { + if [ "$KEEP" = 1 ] && kill -0 "$QPID" 2>/dev/null; then + echo "" + echo "QEMU left running (pid $QPID, gdb stub on :$PORT)." + echo " attach: gdb -ex 'target remote :$PORT'" + echo " kill: kill $QPID" + else + kill "$QPID" 2>/dev/null + fi +} +trap cleanup EXIT + +echo "Booting with $QEMU (gdb stub on :$PORT), waiting up to ${TIMEOUT}s for a crash..." +CRASHED=0 +FAILFAST=0 +HUNG=0 +AURA_CRASH=0 +START=$(date +%s) +while :; do + grep -q "System halted" "$WORK/uart.log" 2>/dev/null && { CRASHED=1; break; } + # FailFast spins without "System halted."; give it a moment to finish + # writing the exception message and stack trace. + if grep -qF "[FAILFAST]" "$WORK/uart.log" 2>/dev/null; then + sleep 2; CRASHED=1; FAILFAST=1; break + fi + # Aura's own crash screen (Crash.StopKernel): a managed exception Aura + # caught. The kernel then waits for a key, so stop here instead of timing + # out as "running fine". Drawing the screen can still fault: re-check. + if grep -qF "[CRASH] " "$WORK/uart.log" 2>/dev/null; then + sleep 2 + grep -q "System halted" "$WORK/uart.log" 2>/dev/null && { CRASHED=1; break; } + grep -qF "[FAILFAST]" "$WORK/uart.log" 2>/dev/null && { CRASHED=1; FAILFAST=1; break; } + AURA_CRASH=1 + break + fi + if [ -n "$HANG_PATTERN" ] && grep -qE "$HANG_PATTERN" "$WORK/uart.log" 2>/dev/null; then + echo "Hang pattern '$HANG_PATTERN' seen; waiting ${HANG_GRACE}s grace, then sampling..." + sleep "$HANG_GRACE" + grep -q "System halted" "$WORK/uart.log" 2>/dev/null && { CRASHED=1; break; } + HUNG=1 + break + fi + kill -0 "$QPID" 2>/dev/null || { echo "ERROR: QEMU exited:"; cat "$WORK/qemu.err"; exit 3; } + [ $(( $(date +%s) - START )) -ge "$TIMEOUT" ] && break + sleep 1 +done + +if [ "$HUNG" = 1 ]; then + # Live-sample the (halted-by-gdb) CPU twice: two RIPs inside the same + # function a second apart = stuck loop, not normal progress. + echo "Sampling live registers via gdb (twice, 1s apart)..." + "$GDB" -batch -ex "set pagination off" -ex "target remote :$PORT" \ + -ex "info registers rip rsp rbp" >"$WORK/regs1.txt" 2>"$WORK/gdb.err" + sleep 1 + "$GDB" -batch -ex "set pagination off" -ex "target remote :$PORT" \ + -ex "info registers rip rsp rbp" >"$WORK/regs2.txt" 2>>"$WORK/gdb.err" + + parse_reg() { grep -oE "^$2\s+0x[0-9a-fA-F]+" "$1" | awk '{print $2}'; } + RIP1=$(parse_reg "$WORK/regs1.txt" rip); RIP2=$(parse_reg "$WORK/regs2.txt" rip) + RSP1=$(parse_reg "$WORK/regs1.txt" rsp); RBP1=$(parse_reg "$WORK/regs1.txt" rbp) + [ -n "$RIP1" ] || { echo "ERROR: could not sample registers:"; cat "$WORK/gdb.err"; exit 1; } + + "$GDB" -batch -ex "set pagination off" -ex "target remote :$PORT" \ + -ex "x/512gx $RSP1" \ + -ex "x/512gx $RSP1+4096" \ + >"$WORK/stack.txt" 2>>"$WORK/gdb.err" + + echo "" + echo "Sample 1: RIP=$RIP1 RSP=$RSP1 RBP=$RBP1" + echo "Sample 2: RIP=$RIP2" + python3 "$SCRIPT_DIR/symbolicate.py" --elf "$ELF" --stack "$WORK/stack.txt" \ + --rip "$RIP1" --rsp "$RSP1" --rbp "$RBP1" --rip2 "$RIP2" + exit 0 +fi + +if [ "$AURA_CRASH" = 1 ]; then + echo "Aura crash screen after $(( $(date +%s) - START ))s (Crash.StopKernel: a managed exception Aura caught, no CPU fault):" + grep -F "[CRASH] " "$WORK/uart.log" | tail -n 5 + echo "Nothing to symbolicate: find the throw site from the message. Last serial output:" + tail -15 "$WORK/uart.log" + exit 4 +fi + +if [ "$CRASHED" = 0 ]; then + echo "No crash within ${TIMEOUT}s: the kernel appears to be running fine." + echo "Last serial output:" + tail -15 "$WORK/uart.log" + exit 2 +fi + +echo "Crash caught after $(( $(date +%s) - START ))s." + +# Only a CPU exception has a meaningful RSP to dump (KERNEL PANIC and +# FAILFAST print their own report and halt/spin in the reporting code). +RSP="" +if [ "$FAILFAST" = 0 ] && grep -q "CPU EXCEPTION:" "$WORK/uart.log"; then + RSP=$(grep -oE 'RSP: 0x[0-9A-Fa-f]+' "$WORK/uart.log" | tail -1 | cut -d' ' -f2) +fi + +STACK_ARGS=() +if [ -n "$RSP" ] && [ -n "$GDB" ]; then + echo "Dumping the crashed stack via gdb..." + # Two chunked dumps so a partially unmapped range doesn't lose everything. + "$GDB" -batch -ex "set pagination off" -ex "target remote :$PORT" \ + -ex "x/512gx $RSP" \ + -ex "x/512gx $RSP+4096" \ + >"$WORK/stack.txt" 2>"$WORK/gdb.err" + if grep -q "^0x" "$WORK/stack.txt"; then + STACK_ARGS=(--stack "$WORK/stack.txt") + else + echo "WARNING: gdb stack dump failed; using the serial stack trace only:" + cat "$WORK/gdb.err" + fi +fi + +echo "" +python3 "$SCRIPT_DIR/symbolicate.py" --elf "$ELF" --uart "$WORK/uart.log" "${STACK_ARGS[@]}" diff --git a/.claude/skills/crash-debug/symbolicate.py b/.claude/skills/crash-debug/symbolicate.py new file mode 100755 index 000000000..dcd170e8a --- /dev/null +++ b/.claude/skills/crash-debug/symbolicate.py @@ -0,0 +1,317 @@ +#!/usr/bin/env python3 +"""Symbolicate an Aura OS (Cosmos gen3) kernel crash. + +Inputs: the kernel ELF (for nm/addr2line), the QEMU serial log, and optionally +a gdb stack dump ("x/Ngx " output). + +Cosmos HEAD writes three kinds of fatal report to serial: + +- CPU EXCEPTION (Cosmos.Kernel/Panic.cs). Registers, then the kernel's own + frame-pointer walk: + Stack trace (raw return addresses, symbolicate with nm): + ip: 0x... + sp0: 0x... (return address if ip is a frameless leaf) + [0] 0x... + then "System halted.". The walk is skipped when CR2 is near RSP (likely + stack overflow). +- KERNEL PANIC (Cosmos.Kernel.Core/Panic.cs). A message plus the method, + file and line, then "System halted.". +- [FAILFAST] (ExceptionHelper.FailFast). An unhandled or recursive managed + exception: the message, the exception message and the managed stack trace. + The CPU then spins, so no "System halted." follows. + +The LAST report in the log is symbolicated. For a CPU exception, the kernel's +raw trace is the primary backtrace. The gdb dump, when given, adds the RBP +chain (used only when the raw trace has no frames) and a conservative scan of +code addresses near RSP. +""" + +import argparse +import bisect +import re +import shutil +import subprocess +import sys + +# Link base of the x64 kernel (Cosmos.Build.Templates/Linker/linker.x64.ld). +KERNEL_TEXT_BASE = 0xFFFFFFFF80000000 + +HEX = r"0x[0-9A-Fa-f]+" + + +def find_tool(*names): + for n in names: + path = shutil.which(n) + if path: + return path + return None + + +NM = find_tool("nm", "llvm-nm") +ADDR2LINE = find_tool("addr2line", "llvm-addr2line") + + +def load_symbols(elf): + if not NM: + print("ERROR: neither nm nor llvm-nm is installed.", file=sys.stderr) + sys.exit(1) + out = subprocess.run([NM, elf], capture_output=True, text=True, check=True).stdout + by_addr = {} + for line in out.splitlines(): + parts = line.split() + if len(parts) != 3 or parts[1] not in "tTwW": + continue + addr = int(parts[0], 16) + name = parts[2] + # duplicate names at one address (mangled + exported alias): keep shortest + if addr not in by_addr or len(name) < len(by_addr[addr]): + by_addr[addr] = name + addrs = sorted(by_addr) + return addrs, by_addr + + +def symbolize(addr, addrs, by_addr): + if addr < KERNEL_TEXT_BASE or not addrs or addr < addrs[0] or addr > addrs[-1] + 0x10000: + return None + i = bisect.bisect_right(addrs, addr) - 1 + base = addrs[i] + return f"{by_addr[base]}+0x{addr - base:x}" + + +def addr2line(elf, addr): + if not ADDR2LINE: + return None + try: + out = subprocess.run( + [ADDR2LINE, "-e", elf, "-f", "-C", hex(addr)], + capture_output=True, text=True, timeout=10, + ).stdout.splitlines() + if len(out) >= 2: + src = out[1].strip() + if not src.startswith("??") and not src.endswith("?") and not src.endswith(":0"): + return src + except Exception: + pass + return None + + +def describe(addr, elf, addrs, by_addr, want_src=True): + sym = symbolize(addr, addrs, by_addr) + if not sym: + return None + src = addr2line(elf, addr) if want_src else None + return f"0x{addr:016x} {sym}" + (f" [{src}]" if src else "") + + +def last_report(uart_text): + """Return (kind, block) for the LAST fatal report in the serial log.""" + text = uart_text.replace("\r", "") + markers = { + "cpu": "CPU EXCEPTION:", + "panic": "KERNEL PANIC", + "failfast": "[FAILFAST]", + } + best = None + for kind, marker in markers.items(): + i = text.rfind(marker) + if i >= 0 and (best is None or i > best[1]): + best = (kind, i) + if best is None: + return None, None + kind, i = best + block = text[i:] + end = block.find("System halted.") + if end >= 0: + block = block[:end + len("System halted.")] + return kind, block + + +def parse_cpu_exception(block): + regs = {} + for m in re.finditer(r"\b(RIP|RSP|RBP|CR2|RAX|RDI|RSI)\s*:\s*(" + HEX + ")", block): + regs[m.group(1)] = int(m.group(2), 16) + regs["exception"] = block.splitlines()[0].replace("CPU EXCEPTION:", "").strip() + m = re.search(r"Interrupt Vector:\s*(\d+)", block) + if m: + regs["vector"] = int(m.group(1)) + + trace = {"frames": [], "no_walk": "not walking" in block} + i = block.find("Stack trace (raw return addresses") + if i >= 0: + for line in block[i:].splitlines()[1:]: + line = line.strip() + m = re.match(r"(ip|sp0|lr):\s*(" + HEX + ")", line) + if m: + trace[m.group(1)] = int(m.group(2), 16) + continue + m = re.match(r"\[(\d+)\]\s+(" + HEX + ")", line) + if m: + trace["frames"].append(int(m.group(2), 16)) + return regs, trace + + +def parse_stack_dump(text): + """Parse gdb 'x/Ngx' output into {address: qword}.""" + mem = {} + for m in re.finditer( + r"^(0x[0-9a-fA-F]+):\s+(0x[0-9a-fA-F]+)(?:\s+(0x[0-9a-fA-F]+))?", + text, re.MULTILINE, + ): + addr = int(m.group(1), 16) + mem[addr] = int(m.group(2), 16) + if m.group(3): + mem[addr + 8] = int(m.group(3), 16) + return mem + + +def print_text_report(kind, block, elf, addrs, by_addr): + """KERNEL PANIC / [FAILFAST]: echo the report, resolve any kernel addresses in it.""" + lines = [l for l in block.splitlines() if l.strip() and not set(l.strip()) <= {"="}] + title = "KERNEL PANIC" if kind == "panic" else "FAILFAST (unhandled or recursive managed exception)" + print(f"Report: {title}") + for line in lines[:80]: + print(f" {line.rstrip()}") + if len(lines) > 80: + print(f" ... ({len(lines) - 80} more lines in the serial log)") + + seen = [] + for m in re.finditer(HEX, block): + v = int(m.group(0), 16) + if v >= KERNEL_TEXT_BASE and v not in seen: + seen.append(v) + resolved = [d for d in (describe(v, elf, addrs, by_addr) for v in seen) if d] + if resolved: + print("\n=== Kernel addresses in the report ===") + for d in resolved: + print(f" {d}") + if kind == "failfast": + print("\nHINT: no CPU fault happened; a managed exception escaped (gen3 does not run " + "AppDomain.UnhandledException, GEN3-GAP(unhandled)) or was thrown while another " + "was being dispatched (GEN3-GAP(eh-global)). Find the throw site from the " + "exception message and the stack trace above.") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--elf", required=True) + ap.add_argument("--uart", help="serial log containing the crash report") + ap.add_argument("--stack", help="gdb stack dump (x/Ngx output)") + ap.add_argument("--addrs", nargs="*", help="just symbolicate these addresses") + ap.add_argument("--rip", help="live-sampled RIP (hang mode, no panic block)") + ap.add_argument("--rsp", help="live-sampled RSP (hang mode)") + ap.add_argument("--rbp", help="live-sampled RBP (hang mode)") + ap.add_argument("--rip2", help="second RIP sample to prove a stuck loop") + args = ap.parse_args() + + addrs, by_addr = load_symbols(args.elf) + + if args.addrs: + for a in args.addrs: + v = int(a, 16) + print(describe(v, args.elf, addrs, by_addr) or f"0x{v:016x} ") + return 0 + + trace = {"frames": [], "no_walk": False} + if args.rip: + regs = {"exception": "LIVE SAMPLE (hang mode)", "RIP": int(args.rip, 16)} + if args.rsp: + regs["RSP"] = int(args.rsp, 16) + if args.rbp: + regs["RBP"] = int(args.rbp, 16) + if args.rip2: + rip2 = int(args.rip2, 16) + d = describe(rip2, args.elf, addrs, by_addr) + print(f"Second RIP sample: {d or hex(rip2)}") + else: + if not args.uart: + print("ERROR: give --uart, --rip or --addrs.", file=sys.stderr) + return 1 + with open(args.uart, errors="replace") as f: + uart_text = f.read() + kind, block = last_report(uart_text) + if kind is None: + print("No 'CPU EXCEPTION', 'KERNEL PANIC' or '[FAILFAST]' report found in the serial log.", + file=sys.stderr) + # Aura's own crash screen (Crash.StopKernel) for a caught managed exception. + crash = [l.strip() for l in uart_text.replace("\r", "").splitlines() if "[CRASH] " in l] + if crash: + print("Aura crash screen (a managed exception Aura caught, no CPU fault):", file=sys.stderr) + for l in crash[-5:]: + print(f" {l}", file=sys.stderr) + return 1 + if kind != "cpu": + print_text_report(kind, block, args.elf, addrs, by_addr) + return 0 + regs, trace = parse_cpu_exception(block) + + print(f"Exception: {regs.get('exception', '?')}") + if "vector" in regs: + print(f" vector: {regs['vector']}") + for r in ("RIP", "RSP", "RBP", "CR2"): + if r in regs: + print(f" {r}: 0x{regs[r]:x}") + + cr2 = regs.get("CR2") + if cr2 is not None and "Page Fault" in regs.get("exception", "") and cr2 < 0x10000: + print(f"\nHINT: CR2=0x{cr2:x} (< 64K) => null dereference; " + f"0x{cr2:x} is the field/element offset into a null object.") + if trace["no_walk"]: + print("\nHINT: the kernel did not walk the stack because CR2 is next to RSP: " + "most likely a stack overflow (deep or infinite recursion).") + + print("\n=== Backtrace ===") + rip = regs.get("RIP", trace.get("ip")) + n = 0 + if rip is not None: + print(f"#{n} {describe(rip, args.elf, addrs, by_addr) or hex(rip)} <- faulting RIP") + n += 1 + + mem = parse_stack_dump(open(args.stack).read()) if args.stack else {} + rsp, rbp = regs.get("RSP"), regs.get("RBP") + + # Top of stack: the return address if the fault hit a frameless leaf + # helper (e.g. RhpAssignRef, memcpy) before it set up a frame. + top = trace.get("sp0") + if top is None and rsp in mem: + top = mem[rsp] + if top is not None: + d = describe(top, args.elf, addrs, by_addr) + if d: + print(f"#{n} {d} <- [RSP] (caller, if RIP is in a frameless leaf helper)") + n += 1 + + if trace["frames"]: + # The kernel's own frame-pointer walk (NativeAOT keeps frame pointers). + for ret in trace["frames"]: + d = describe(ret, args.elf, addrs, by_addr) + print(f"#{n} {d or hex(ret)}") + n += 1 + elif mem: + # No raw trace on serial: walk the RBP chain in the gdb dump. + frame, seen = rbp, set() + while frame and frame in mem and frame not in seen and n < 64: + seen.add(frame) + ret = mem.get(frame + 8) + if ret is None: + break + d = describe(ret, args.elf, addrs, by_addr) + print(f"#{n} {d or hex(ret)}") + n += 1 + frame = mem[frame] + if frame and frame not in mem and frame not in seen: + print(f"(frame 0x{frame:x} outside dumped stack range — increase dump size)") + else: + print("(no raw stack trace on serial and no gdb stack dump — RIP only)") + + # Conservative scan: any code-looking qwords near RSP the chain missed. + if mem and rsp is not None: + print("\n=== Other code addresses on stack (conservative scan) ===") + for a in sorted(k for k in mem if rsp <= k < rsp + 64 * 8): + d = describe(mem[a], args.elf, addrs, by_addr, want_src=False) + if d: + print(f" [rsp+0x{a - rsp:03x}] {d}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.claude/skills/run-aura/SKILL.md b/.claude/skills/run-aura/SKILL.md new file mode 100644 index 000000000..b7b8355b9 --- /dev/null +++ b/.claude/skills/run-aura/SKILL.md @@ -0,0 +1,62 @@ +--- +name: run-aura +description: Boot an already-built Aura OS ISO in a visible QEMU window through `cosmos run` (1 GB, AHCI disk.img, e1000e, FTP port forwards, serial tee'd to uart.log). Never builds. Use when the user asks to run/start/launch Aura OS, boot the ISO, or open the QEMU window. For headless crash symbolication use crash-debug instead. +--- + +# Run Aura OS (QEMU window) + +Boot the existing ISO with a visible QEMU display: + +```bash +.claude/skills/run-aura/run-aura.sh +``` + +It is a thin wrapper over: + +```bash +cosmos run -p SRC/Aura_OS -m 1024 --disk SRC/Aura_OS/disk.img --nic e1000e \ + --hostfwd tcp::2121-:21 --hostfwd tcp::50000-:50000 ... --hostfwd tcp::50009-:50009 \ + | tee uart.log +``` + +QEMU stays in the foreground until the window is closed. Launch it with +`run_in_background: true` so the session isn't blocked, then watch boot +progress in `uart.log` at the repo root. It is a fresh file each boot, and its +first lines are `cosmos run`'s own banner. + +**No build step.** The user runs the builds (`cosmos build -p SRC/Aura_OS`). +If `SRC/Aura_OS/output-x64/Aura_OS.iso` is missing or older than the change +you want to see, stop and ask the user to rebuild. + +Flags: + +- `--temp-disk`: boot a throwaway copy of `disk.img`. This keeps the real one + untouched and avoids the write-lock conflict when another QEMU is running. + The copy is deleted on exit. +- `--gdb PORT`: also expose a gdb stub (passed as `cosmos run -- -gdb + tcp::PORT`). Combine it with the crash-debug skill's `--symbolicate` mode for + manual digging. +- `--headless`: no window, serial only. +- `--mem MB`: guest memory, 1024 by default. +- `--nic MODEL`: network card, `e1000e` by default. gen3 drives only e1000e and + virtio-net. +- `--iso/--disk/--uart PATH`: path overrides. + +Notes: + +- `cosmos run` picks QEMU itself: the Cosmos bundle, or the system QEMU if its + version passes. It also adds q35, KVM with `-cpu host` when `/dev/kvm` is + usable, `-vga std`, the CD at `bootindex=0`, and `-no-reboot -no-shutdown`. +- The disk is `SRC/Aura_OS/disk.img` on AHCI, the same image the VS Code + extension uses (`SRC/Aura_OS/.cosmos/config.json`). + - A missing image is created blank at 512M. Aura then boots in live mode + until Setup or `vol` formats it. + - gen3 has no IDE driver, so disks must be on AHCI or NVMe. +- FTP from the host: `ftp localhost 2121`. Passive data ports 50000–50009 are + forwarded. +- If the boot panics (`CPU EXCEPTION` ... `System halted.`, `KERNEL PANIC`, or + `[FAILFAST]` in `uart.log`), symbolicate that log: + `.claude/skills/crash-debug/crash-debug.sh --uart uart.log`. +- To stop it from the CLI: `pkill -f '[q]emu-system-x86_64.*Aura_OS.iso'`. + The `[q]` keeps the pattern from matching your own shell. Stopping the + `cosmos run` process also takes QEMU down. diff --git a/.claude/skills/run-aura/run-aura.sh b/.claude/skills/run-aura/run-aura.sh new file mode 100755 index 000000000..ed38f613d --- /dev/null +++ b/.claude/skills/run-aura/run-aura.sh @@ -0,0 +1,120 @@ +#!/usr/bin/env bash +# Boot Aura OS in a visible QEMU window through `cosmos run`, teeing the serial +# console to uart.log. Thin wrapper: `cosmos run` builds the QEMU command line +# (q35, KVM + -cpu host when available, CD bootindex=0, AHCI disk, NIC, port +# forwards, -no-reboot -no-shutdown) and finds a working QEMU (bundle or system). +# +# This script NEVER builds. The user runs the builds: when the ISO is missing +# or stale, ask him to rebuild. +set -uo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" +PROJECT_DIR="$REPO_ROOT/SRC/Aura_OS" + +ISO="" # default: cosmos run picks SRC/Aura_OS/output-x64/*.iso +DEFAULT_ISO="$PROJECT_DIR/output-x64/Aura_OS.iso" +DISK="$PROJECT_DIR/disk.img" # same image as SRC/Aura_OS/.cosmos/config.json (VS Code extension) +UART="$REPO_ROOT/uart.log" +MEM=1024 +NIC=e1000e +TEMP_DISK=0 +HEADLESS=0 +GDB_PORT="" + +usage() { + cat < $UART). Close the window or Ctrl+C to stop." +# Serial goes to stdio with `cosmos run`; tee it to uart.log (fresh file each boot). +"$COSMOS" run -p "$PROJECT_DIR" "${ISO_ARGS[@]}" -m "$MEM" \ + --disk "$DISK" --nic "$NIC" "${FWD_ARGS[@]}" "${EXTRA_ARGS[@]}" 2>&1 \ + | tee "$UART" | { + # Surface the classic failure mode with a helpful message. + while IFS= read -r line; do + echo "$line" + case "$line" in + *'Failed to get "write" lock'*) + echo "HINT: $DISK is in use by another QEMU instance (run-aura, crash-debug --keep" + echo " or the VS Code extension). Close it, or rerun with --temp-disk." ;; + esac + done + } diff --git a/.github/workflows/dotnet-core.yml b/.github/workflows/dotnet-core.yml index 8a426892f..24622c9d6 100644 --- a/.github/workflows/dotnet-core.yml +++ b/.github/workflows/dotnet-core.yml @@ -1,121 +1,95 @@ name: .NET Core +# Builds the Aura OS ISO on Cosmos gen3 (NativeAOT). +# +# The Cosmos 3.0.89 dev packages Aura pins in global.json are not on nuget.org, +# so this job: +# 1. checks out CosmosOS/Cosmos at a pinned commit, +# 2. builds its local package feed with `make setup`, +# 3. points Aura at it. NuGet.Config expects the sibling ../Cosmos checkout. +# `make setup` stamps the packages with today's date (.), so +# Aura's global.json Cosmos.Sdk literal is rewritten to that stamp before the +# build. Directory.Build.props derives every other Cosmos version from it. on: - push: - branches: [ master ] - pull_request: - branches: [ master ] - workflow_dispatch: {} + workflow_dispatch: + inputs: + cosmos_ref: + description: 'CosmosOS/Cosmos commit SHA (or branch/tag) to build the packages from' + required: true + type: string + default: '6c857b5676596587fcccf164ae6dd680db2104df' jobs: build: - name: Build & test Lamscript on ${{ matrix.os }} with ${{ matrix.compiler }}. - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [windows-latest] - include: - - os: windows-latest - target: Windows + name: Build Aura OS ISO (Cosmos gen3, x64) + runs-on: ubuntu-latest + timeout-minutes: 90 + env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 + DOTNET_NOLOGO: 1 steps: - - uses: actions/checkout@v3 - - name: Setup .NET Core - uses: actions/setup-dotnet@v3 + # actions/checkout only writes under $GITHUB_WORKSPACE, so both repos go + # there side by side: Cosmos is then ../Cosmos from the Aura checkout. + - name: Check out Aura + uses: actions/checkout@v4 with: - dotnet-version: '6.0.x' + path: Aura-Operating-System - - name: Add msbuild to PATH - if: ${{ matrix.os == 'windows-latest' }} - uses: microsoft/setup-msbuild@v1.0.2 - env: - ACTIONS_ALLOW_UNSECURE_COMMANDS: 'true' - - - name: Install Visual C++ 2010 Service Pack 1 Redistributable Update - if: ${{ matrix.os == 'windows-latest' }} - run: choco install vcredist2010 - - - name: Clone Cosmos - if: ${{ matrix.os == 'windows-latest' }} - run: | - mkdir Cosmos - mkdir c:/CosmosRun - cd Cosmos - git clone https://github.com/CosmosOS/Common - git clone https://github.com/CosmosOS/IL2CPU - git clone https://github.com/CosmosOS/Cosmos - git clone https://github.com/CosmosOS/XSharp - - name: Build Cosmos - if: ${{ matrix.os == 'windows-latest' }} - run: | - cd Cosmos/Cosmos - msbuild Build.sln /t:Restore - msbuild Build.sln /maxcpucount /verbosity:normal /t:Build - - name: Build Cosmos - if: ${{ matrix.os == 'ubuntu-20.04' }} - run: | - sudo apt-get install yasm mkisofs make binutils git && \ - cd ~ && \ - mkdir cosmos && \ - cd cosmos && \ - git clone https://github.com/CosmosOS/Cosmos --depth 1 && \ - git clone https://github.com/CosmosOS/IL2CPU --depth 1 && \ - git clone https://github.com/CosmosOS/XSharp --depth 1 && \ - git clone https://github.com/CosmosOS/Common --depth 1 && \ - cd Cosmos && \ - sudo make - - name: Publish IL2CPU - if: ${{ matrix.os == 'windows-latest' }} - run: | - dotnet publish Cosmos\IL2CPU\source\IL2CPU -r win10-x64 -o "c:\CosmosRun\Build\IL2CPU\" - - name: Pack packages - if: ${{ matrix.os == 'windows-latest' }} - run: | - cd Cosmos/Cosmos/source - dotnet pack Cosmos.Build.Tasks/Cosmos.Build.Tasks.csproj -p:PackageVersion=10.0.0 --output c:\packages - dotnet pack Cosmos.Common/Cosmos.Common.csproj -p:PackageVersion=10.0.0 --output c:\packages - dotnet pack Cosmos.Core/Cosmos.Core.csproj -p:PackageVersion=10.0.0 --output c:\packages - dotnet pack Cosmos.Core_Plugs/Cosmos.Core_Plugs.csproj -p:PackageVersion=10.0.0 --output c:\packages - dotnet pack Cosmos.Core_Asm/Cosmos.Core_Asm.csproj -p:PackageVersion=10.0.0 --output c:\packages - dotnet pack Cosmos.HAL2/Cosmos.HAL2.csproj -p:PackageVersion=10.0.0 --output c:\packages - dotnet pack Cosmos.System2/Cosmos.System2.csproj -p:PackageVersion=10.0.0 --output c:\packages - dotnet pack Cosmos.System2_Plugs/Cosmos.System2_Plugs.csproj -p:PackageVersion=10.0.0 --output c:\packages - dotnet pack Cosmos.Plugs/Cosmos.Plugs.csproj -p:PackageVersion=10.0.0 --output c:\packages - dotnet pack Cosmos.Debug.Kernel/Cosmos.Debug.Kernel.csproj -p:PackageVersion=10.0.0 --output c:\packages - dotnet pack Cosmos.Debug.Kernel.Plugs.Asm/Cosmos.Debug.Kernel.Plugs.Asm.csproj -p:PackageVersion=10.0.0 --output c:\packages - dotnet pack Cosmos.Plugs/Cosmos.Plugs.csproj -p:PackageVersion=10.0.0 --output c:\packages - cd ../../IL2CPU/source - dotnet pack IL2CPU.API/IL2CPU.API.csproj -p:PackageVersion=10.0.0 --output c:\packages - - name: Install packages - if: ${{ matrix.os == 'windows-latest' }} - run: | - nuget sources Add -Name "Cosmos Local Package Feed" -Source "c:\packages" - cd "C:\Users\runneradmin\AppData\Roaming\" - mkdir "Cosmos User Kit" - cd "Cosmos User Kit" - mkdir "Build" - mkdir "Kernel" - cd "Build" - mkdir "IL2CPU" - - name: Install files - if: ${{ matrix.os == 'windows-latest' }} + - name: Check out Cosmos + uses: actions/checkout@v4 + with: + repository: CosmosOS/Cosmos + ref: ${{ inputs.cosmos_ref }} + path: Cosmos + submodules: recursive # dotnet/runtime sources + lai (ACPI), as in Cosmos's own CI + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.201' + + # clang (asm/C), ld.lld (link), xorriso (ISO), make + the runner's cc (Limine CLI). + - name: Install native toolchain run: | - copy "Cosmos\IL2CPU\source\IL2CPU\bin\Debug\net6.0\*" "C:\Users\runneradmin\AppData\Roaming\Cosmos User Kit\Build\IL2CPU\" - Copy-Item -Path "Cosmos\Cosmos\source\Cosmos.Common\bin\Debug\net6.0\*" -Destination "C:\Users\runneradmin\AppData\Roaming\Cosmos User Kit\Kernel\" -Force - Copy-Item -Path "Cosmos\Cosmos\source\Cosmos.Core_Asm\bin\Debug\net6.0\*" -Destination "C:\Users\runneradmin\AppData\Roaming\Cosmos User Kit\Kernel\" -Force - Copy-Item -Path "Cosmos\Cosmos\source\Cosmos.Core_Plugs\bin\Debug\net6.0\*" -Destination "C:\Users\runneradmin\AppData\Roaming\Cosmos User Kit\Kernel\" -Force - Copy-Item -Path "Cosmos\Cosmos\source\Cosmos.Core\bin\Debug\net6.0\*" -Destination "C:\Users\runneradmin\AppData\Roaming\Cosmos User Kit\Kernel\" -Force - Copy-Item -Path "Cosmos\Cosmos\source\Cosmos.System2\bin\Debug\net6.0\*" -Destination "C:\Users\runneradmin\AppData\Roaming\Cosmos User Kit\Kernel\" -Force - Copy-Item -Path "Cosmos\Cosmos\source\Cosmos.HAL2\bin\Debug\net6.0\*" -Destination "C:\Users\runneradmin\AppData\Roaming\Cosmos User Kit\Kernel\" -Force - Copy-Item -Path "Cosmos\Cosmos\source\Cosmos.System2_Plugs\bin\Debug\net6.0\*" -Destination "C:\Users\runneradmin\AppData\Roaming\Cosmos User Kit\Kernel\" -Force - Copy-Item -Path "Cosmos\Cosmos\source\Cosmos.Plugs\bin\Debug\net6.0\*" -Destination "C:\Users\runneradmin\AppData\Roaming\Cosmos User Kit\Kernel\" -Force - Copy-Item -Path "Cosmos\Cosmos\source\Cosmos.Debug.Kernel\bin\Debug\netstandard2.0\*" -Destination "C:\Users\runneradmin\AppData\Roaming\Cosmos User Kit\Kernel\" -Force - Copy-Item -Path "Cosmos\Cosmos\source\Cosmos.Debug.Kernel.Plugs.Asm\bin\Debug\netstandard2.0\*" -Destination "C:\Users\runneradmin\AppData\Roaming\Cosmos User Kit\Kernel\" -Force - - name: Restore dependancies + sudo apt-get update + sudo apt-get install -y clang lld xorriso make + echo "$HOME/.dotnet/tools" >> "$GITHUB_PATH" + + - name: Build the Cosmos packages (make setup) + working-directory: Cosmos + run: make setup + + - name: Pin Aura to the stamped Cosmos version + id: cosmos + working-directory: Aura-Operating-System run: | - cd "SRC" - dotnet restore - - name: Build Aura Operating System + # postCreateCommand.sh rewrites Cosmos's own global.json to the version it stamped. + VERSION=$(sed -nE 's/.*"Cosmos\.Sdk"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' ../Cosmos/global.json | head -n1) + if [ -z "$VERSION" ] || [ ! -f "../Cosmos/artifacts/package/release/Cosmos.Sdk.$VERSION.nupkg" ]; then + echo "::error::Could not determine the stamped Cosmos version (got '$VERSION')" + ls ../Cosmos/artifacts/package/release/ || true + exit 1 + fi + echo "Cosmos packages: $VERSION" + sed -i -E "s|(\"Cosmos\.Sdk\"[[:space:]]*:[[:space:]]*\")[^\"]+(\")|\1${VERSION}\2|" global.json + cat global.json + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + + - name: Install Cosmos.Patcher + working-directory: Aura-Operating-System run: | - cd "SRC" - dotnet build + dotnet tool uninstall -g Cosmos.Patcher 2>/dev/null || true + dotnet tool install -g Cosmos.Patcher --add-source ../Cosmos/artifacts/package/release --version "${{ steps.cosmos.outputs.version }}" + + - name: Publish Aura OS + working-directory: Aura-Operating-System + run: dotnet publish SRC/Aura_OS/Aura_OS.csproj -c Release -r linux-x64 -o out + + - name: Upload ISO + uses: actions/upload-artifact@v4 + with: + name: Aura_OS-iso + path: Aura-Operating-System/out/Aura_OS.iso + if-no-files-found: error diff --git a/.gitignore b/.gitignore index 25e2abb2c..5a3ce734e 100644 --- a/.gitignore +++ b/.gitignore @@ -287,3 +287,9 @@ __pycache__/ *.btm.cs *.odx.cs *.xsd.cs + +# Cosmos gen3 build output (cosmos build / dotnet publish -o output-), QEMU disk images and serial logs +output-x64/ +output-arm64/ +*.img +uart.log diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 000000000..5c70393e0 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,11 @@ + + + <_AuraGlobalJson>$(MSBuildThisFileDirectory)global.json + + $([System.Text.RegularExpressions.Regex]::Match($([System.IO.File]::ReadAllText('$(_AuraGlobalJson)')), '"Cosmos\.Sdk"\s*:\s*"([^"]+)"').Groups[1].Value) + 2.0.0 + 1.0.0 + + linux-x64 + + diff --git a/GEN3-GAPS.md b/GEN3-GAPS.md new file mode 100644 index 000000000..ca06105f3 --- /dev/null +++ b/GEN3-GAPS.md @@ -0,0 +1,825 @@ +# Cosmos gen3 gaps found while porting AuraOS + +These are the upstream-issue candidates found while porting AuraOS from gen2 +(IL2CPU) to Cosmos gen3 (NativeAOT). + +- Checked against **Cosmos HEAD `6c857b567`** (2026-10-02), with the local + package feed **3.0.89.20261001** built by `make setup`. The `v3.0.89` tag + packages were not used. +- Each entry is written to be liftable into a GitHub issue. +- This list replaces the one from the previous port attempt (origin/gen3 on + 3.0.77). The section at the end says which of those items HEAD has fixed. + +**Finding the workarounds in the code.** Every Aura workaround site carries a +`// GEN3-GAP(): ...` comment. The tag is the one in each heading below. + +```bash +grep -rn "GEN3-GAP(" SRC/ # every workaround site +grep -rn "GEN3-GAP(dhcp)" SRC/ # the sites of one gap +``` + +When a gap is fixed upstream, remove its workaround and its comments, then +delete the entry here. + +**Severity** is the impact on Aura with the workaround applied: +- **major**: a visible feature loss or a real crash risk. +- **minor**: cosmetic, performance or edge cases. +- **(phase 2)**: it becomes major once Aura runs work on several threads. Phase + 1 is single-threaded except for the FTP server. + +**Source** names the section of the porting notes that documents the gap: +- 01 build/boot/plugs, 02 core system, 03 filesystem/storage, 04 graphics +- 05 input, 06 network, 07 BCL/packages/Lua +- 08 lessons from the 3.0.77 port (origin/gen3) + +The "rule Cn" references in the workarounds are the porting conventions from +the same notes. Examples: C6 explicit null checks, C7 no `finally` on the +exception path, C8 dispose everything. + +## Summary + +| Area | Major | Minor | +|---|---|---| +| Build / tooling | `iso-files` | `resources`, `resources-perf`, `update-pins`, `prop-trap`, `defines`, `compile-only`, `iso-path`, `dev-stamp`, `bytes-only` | +| Core runtime | `cpu-exception`, `null-deref`, `unhandled`, `finally`, `eh-global`, `finalizers`, `gc-trigger`, `gc-conservative`, `idle-thread` | `run-spam`, `log-sink`, `meminfo`, `cpuinfo`, `pci`, `tz-rtc`, `env`, `pc-speaker`, `encoding` | +| Console / graphics | `console-input` | `kernelconsole`, `console-global`, `present`, `display-mode`, `blit`, `psf`, `hw-cursor`, `bmp`, `canvas3d` | +| Input | `keyboard-altgr`, `ps2-sync` | `key-release`, `key-repeat`, `e0`, `sessions`, `mouse`, `key-docs` | +| Filesystem / storage | `ide`, `fat-names`, `vfs-threads` (phase 2) | `driveinfo`, `fat-label`, `fat-time`, `mounts`, `tmp`, `cwd`, `mbr`, `ext2` | +| Network | `http-tls`, `tcp-receive`, `ipaddress`, `net-threads` (phase 2), `nic-drivers`, `tcp-robust` | `socket-misc`, `dhcp`, `tcp-primary`, `nic-names`, `net-misc` | +| BCL / packages | | `deflate`, `crypto`, `lua-host` | +| Aura-side (not Cosmos) | `backend` | | + +--- + +## Build / tooling + +### `resources`: no supported embedded-resource API (minor) +- **Gap:** `Cosmos.Kernel.Core.Runtime.ResourceManager` has been internal since + `a1835bac0` ("Internalize Cosmos.Kernel.Core outside the ring"), and + `PCScreenFont` still reads through it. + - `Assembly.GetManifestResourceStream` / `GetManifestResourceNames` **do + work** at HEAD. This was verified on 3.0.89.20261001 by booting a test + kernel: the LogicalNames are listed, and a 300 KB resource streamed + correctly. + - But that path is untested and undocumented upstream, and + `accessing-internals.md` says the kernel cannot use reflection. +- **Aura workaround:** `Files.cs` alone reads assets, through + `typeof(Aura_OS.Kernel).Assembly.GetManifestResourceStream(name)`. It reads in + a loop until the buffer is full, disposes explicitly (no `finally`, see + `finally`) and caches the bytes. +- **Upstream ask:** add a test and a doc for `GetManifestResourceStream` under + NativeAOT. Alternatively, add a ring facade + `Cosmos.Kernel.System.Resources.TryGet(string, out ReadOnlySpan)` / + `Open(string) -> Stream` / `Names`. +- **Source:** 01, 08, orchestrator amendment A1. + +### `resources-perf`: ResourceManager re-parses and logs on every lookup (minor) +- **Gap:** the internal `ResourceManager` re-parses the whole resource index on + each lookup and serial-logs every entry (`Found resource: ...`). + - The `s_resourceInfos` cache is commented out. + - Names are decoded as ASCII only. + - This hits every `PCScreenFont` default-font load. Aura sets + `CosmosDefaultFont` to its own `zap-ext-light16.psf`. +- **Aura workaround:** + - Read each asset once: lazy `Files.*` properties and a single + `LoadFiles`/`LoadImages` pass. + - Use ASCII LogicalNames only. + - Aura's own reads no longer go through ResourceManager (see `resources`). +- **Upstream ask:** cache the index and drop the per-entry log. +- **Source:** 01, 08. + +### `iso-files`: the ISO cannot carry or expose extra files (major) +- **Gap:** the kernel has no way to read files from the boot medium. + - `_BuildIsoCore` wipes `iso_root/` and stages only the ELF, `limine.conf` + and the Limine binaries. There is no `CosmosIsoFile` item, and a + pre-fill target is wiped by the same target. + - Even with extra files, the kernel cannot read the CD: there is no ISO9660 + filesystem, and AHCI refuses SATAPI. + - `Cosmos.Kernel.Boot.Limine` implements no module request. Limine 10.8.5 + supports `module_path:`. +- **Aura workaround:** embed every asset (`SRC/Aura_OS/Resources/**`, about + 20 MiB, read through `Files.Get`). gen2's "files on the CD" feature is gone, + and so is `HelloWorld.gb`. +- **Upstream ask:** either + - an `@(CosmosIsoFile)` item plus a read-only ISO9660 driver (and SATAPI), + or + - a Limine module request on the ring (an initrd/tar). +- **Source:** 01, 03, 08. + +### `update-pins`: `cosmos update` rewrites third-party `Cosmos.*` pins (minor) +- **Gap:** `ProjectPinUpdater.s_packagePin` matches any + `PackageReference`/`PackageVersion` whose `Include` starts with `Cosmos.`. + - It would therefore bump `Cosmos.Network.Ftp` (2.0.0) and + `Cosmos.Executable.Lua` (1.0.0) to the kernel version. + - Values containing `$(` or `@` are skipped. +- **Aura workaround:** keep those versions in `$(AuraFtpVersion)` / + `$(AuraLuaVersion)`, defined in `Directory.Build.props`. The Cosmos version + itself lives only in `global.json`. +- **Upstream ask:** restrict the updater to the package IDs Cosmos publishes. +- **Source:** 01, 08. + +### `prop-trap`: `CosmosPackageVersion` adds both-arch references (minor) +- **Gap:** `Cosmos.Architecture.props` adds `PackageReference`s to both the + X64 and the ARM64 HAL when `$(CosmosPackageVersion)` is set, and to both + Native packages when `$(CosmosNativePackageVersion)` is set. + - This happens in a targets file, after restore. + - A user who centralizes the version under that natural name gets + unrestored, build-time-only ARM64 references. +- **Aura workaround:** name the property `AuraCosmosVersion`. +- **Upstream ask:** rename the trigger properties, or document them. +- **Source:** 01. + +### `defines`: `cosmos build` passes `DefineConstants` globally (minor) +- **Gap:** `cosmos build` and the Cosmos `Makefile` pass + `-p:DefineConstants=ARCH_X64` as a global property. + - That discards every `DefineConstants` a kernel sets. + - A project that replaces instead of appending loses `ARCH_X64`, and with it + `--root:Cosmos.Kernel.HAL.X64`. +- **Aura workaround:** no custom defines; only ever append + (`$(DefineConstants);X`). +- **Upstream ask:** pass only `-p:CosmosArch=...` and let + `Cosmos.ArchitecturePicker.props` append `ARCH_*`. +- **Source:** 01. + +### `compile-only`: no compile-only build switch (minor) +- **Gap:** patch, ILC, link and ISO all hang off `AfterTargets="Build"`, with + no opt-out property. + - `-p:EnablePatching=false` skips only the patcher. + - `-t:Compile` alone fails with CS0016 on the source-generator output + directory. +- **Aura workaround:** the central compile check is + `dotnet build SRC/Aura_OS/Aura_OS.csproj -t:Compile -p:EmitCompilerGeneratedFiles=false -v:q -nologo`. +- **Upstream ask:** a `CosmosCompileOnly` / `CosmosSkipNative` property, and a + `-t:Compile` that works without the extra property. +- **Source:** 01, orchestrator amendment A3. + +### `iso-path`: the ISO lands relative to the caller's working directory (minor) +- **Gap:** `Cosmos.Build.Common.targets` sets + `CosmosOutputPath = NormalizePath('$(OutputPath)', 'cosmos')`. `OutputPath` + is relative (`bin/Debug/net10.0/linux-x64/`), and `NormalizePath` resolves it + against the process working directory, not `$(MSBuildProjectDirectory)`. + - So `dotnet build SRC/Aura_OS/Aura_OS.csproj` run from the repo root writes + `/bin/Debug/net10.0/linux-x64/cosmos/Aura_OS.iso`. + - The ELF still lands in the project's own `bin/`. +- **Aura workaround:** build from `SRC/Aura_OS` (or use `cosmos build -p`, + which runs in the project directory). +- **Upstream ask:** base the path on `$(MSBuildProjectDirectory)`, for example + `NormalizePath('$(MSBuildProjectDirectory)', '$(OutputPath)', 'cosmos')`. +- **Source:** first full build of the port (2026-10-02). + +### `dev-stamp`: dev package versions are date-stamped (minor) +- **Gap:** `make setup` (`.devcontainer/postCreateCommand.sh`) stamps the + current date (`.`) and rewrites Cosmos's own `global.json`. + - It also wipes `artifacts/` and `~/.nuget/packages/cosmos.*`. + - So after a `make setup` on a later day, Aura's pinned version exists + neither in the feed nor in the cache. +- **Aura workaround:** after `make setup`, bump the `Cosmos.Sdk` literal in + Aura's `global.json`. `Directory.Build.props` derives the rest. + - CI (`.github/workflows/dotnet-core.yml`) does this with `sed`. + - After a hand-run `dotnet pack`, also run `rm -rf ~/.nuget/packages/cosmos.*` + and `dotnet tool update -g Cosmos.Patcher`. +- **Upstream ask:** a per-build counter or a fixed dev version, so consumers + need not re-pin daily. +- **Source:** 01. + +### `bytes-only`: `Bitmap`/`PCScreenFont.LoadFont` take only `byte[]` (minor) +- **Gap:** embedded data already in the read-only image must be copied to the + heap first. That is about 20 MiB of assets for Aura. +- **Aura workaround:** copy once and cache. +- **Upstream ask:** `ReadOnlySpan` overloads. +- **Source:** 01. + +## Core runtime + +### `cpu-exception`: no CPU-exception / panic hook (major) +- **Gap:** gen2's `INTs.HandleException` plug has no replacement. + - `Panic.CpuException`, `IRQContext`, `InterruptManager.SetHandler` and its + `IrqDelegate` are all internal, so neither a plug nor an `[UnsafeAccessor]` + can register a handler. +- **Aura workaround:** the Aura crash screen covers managed exceptions only. + For faults, read the serial panic (registers plus a raw stack trace) and + symbolicate it with `.claude/skills/crash-debug`. +- **Upstream ask:** a public `OnPanic(in PanicInfo)` seam: allocation-restricted, + with the vector, RIP and CR2. +- **Source:** 01, 02, 08. + +### `null-deref`: hardware faults are not managed exceptions (major) +- **Gap:** #PF, #DE and stack overflow are not translated into + `NullReferenceException` / `DivideByZeroException`. A null dereference or an + integer `/0` halts the kernel. + - gen2 identity-mapped low memory, so ported code is full of latent null + dereferences. +- **Aura workaround:** init-order fixes, plus explicit null and divisor checks + on user-driven and optional-data paths (rule C6). +- **Upstream ask:** a null-page #PF raises an NRE, and #DE raises + `DivideByZeroException`, as in CoreCLR. +- **Source:** 02, 05, 08. + +### `unhandled`: unhandled exceptions are unobservable (major) +- **Gap:** `AppDomain.UnhandledException` never fires. An escaped exception + ends in `ExceptionHelper.FailFast`, which prints `[FAILFAST]` on serial and + spins. +- **Aura workaround:** try/catch in `BeforeRun`, `Run` and every thread body, + routed to `Crash.StopKernel`. +- **Upstream ask:** wire `OnUnhandledException` / `AppDomain.UnhandledException`. +- **Source:** 02. + +### `finally`: `finally` / `using` / `lock` release do not run during unwinding (major) +- **Gap:** fault and finally funclets are skipped when an exception unwinds + through them. A `using` stream stays open, and a `lock` stays held. +- **Aura workaround:** catch inside the scope, then `Dispose()` / close + explicitly after the `try/catch` (rule C7). Writers installed with + `Console.SetOut` never throw. +- **Upstream ask:** run fault/finally funclets during the second pass. +- **Source:** 07. + +### `eh-global`: the exception-dispatch guard is a single static (major) +- **Gap:** `ExceptionHelper.s_isHandlingException` is global, not per thread. + - Two threads throwing concurrently end in a "Recursive exception" FailFast. + - After an unhandled exception the flag stays set, so any later throw also + FailFasts. +- **Aura workaround:** single-threaded phase 1. Only the FTP server runs + concurrently. +- **Upstream ask:** a per-thread guard. +- **Source:** 02. + +### `finalizers`: no finalizers; fixed descriptor tables (major) +- **Gap:** finalizers never run (`RhSuppressFinalize` is a no-op). The fd table + is fixed at 64 files and 32 directory streams. + - Cosmos.Kernel.Core does not export `RhWaitForPendingFinalizers`. The stub + is left commented out in `src/Cosmos.Kernel.Core/Runtime/Stdllib.cs`, and + without the `int allowReentrantWait` parameter that NativeAOT's + `RuntimeImports` p/invoke declares. + - So any reachable `GC.WaitForPendingFinalizers` or `GC.GetTotalMemory(bool)` + fails at ld.lld with `undefined symbol: RhWaitForPendingFinalizers` + (referenced from `GC.NativeAot.cs:732`, in `GC.GetTotalMemory`). + - The `false` overload fails too, because the method body still references + the symbol. +- **Aura workaround:** + - Dispose every `FileStream`, `ZipStorer` and `LuaInterpreter` (rule C8). + `File.Create(p)` used as a statement becomes `File.Create(p).Dispose()`. + - The kernel-assembly plug `SRC/Aura_OS/Plugs/GCImpl.cs` + (`[Plug(typeof(GC))]`) turns `GC.WaitForPendingFinalizers()` into an + immediate return. That is correct because there is no finalizer queue, so + there is never anything to wait for. +- **Upstream ask:** + - an fd-exhaustion diagnostic and/or a bigger or growable table; + - export `RhWaitForPendingFinalizers(int allowReentrantWait)` as a no-op from + Cosmos.Kernel.Core, for example in `Runtime/GC.cs` next to + `RhGetGcTotalMemory`. Aura's `GCImpl` plug can then be deleted. +- **Source:** 03, 07, 08, and the first full build (link error). + +### `run-spam`: `Kernel.Start()` logs on every `Run()` iteration (minor) +- **Gap:** two serial lines are written per `Run()` call. +- **Aura workaround:** loop inside `Aura_Boot.Kernel.Run()`, so it is called + once. +- **Upstream ask:** log once, or behind a verbose flag. +- **Source:** 02. + +### `log-sink`: no kernel log sink or history (minor) +- **Gap:** `Log.WriteString` goes straight to the internal serial port. Nothing + can subscribe or read it back. gen2's `Debugger` plug fed `logs /k`. +- **Aura workaround:** Aura logs only its own messages (`Logs.DoOSLog` / + `DoKernelLog`, mirrored to serial). Cosmos-internal messages stay serial-only. +- **Upstream ask:** `Log.Subscribe(Action)` or a ring-buffer + `Log.History`. +- **Source:** 01, 02. + +### `gc-trigger`: GC collects only on page-allocator exhaustion (major) +- **Gap:** OrionGC collects only when the page allocator is exhausted. The + collection is stop-the-world with interrupts off. +- **Aura workaround:** a rate-limited `MemoryInfo.Collect()` from + `Aura_OS.Kernel.Run`: 1 Hz, or 10 Hz under memory pressure. +- **Upstream ask:** an allocation-budget trigger. +- **Source:** 02, 08. + +### `meminfo`: memory figures describe one region / the last GC (minor) +- **Gap:** `MemoryInfo.RamSizeBytes` / `TotalPages` cover only the largest + Limine region. `GCMemoryInfo` is a snapshot from the last GC. +- **Aura workaround:** label the figure "memory pool". Use + `GC.GetTotalMemory(false)` for the live heap. That call links only because of + the `GCImpl` plug (see `finalizers`). +- **Upstream ask:** `InstalledRamBytes`, a live heap figure, and a fix to the + doc. +- **Source:** 02. + +### `cpuinfo`: no CPU information API (minor) +- **Gap:** there is no CPU info API. Also, `g_cpuFeatures = 0` (`kmain.c`), so + opportunistic ISA checks (`Avx2.IsSupported`, ...) are false at runtime. +- **Aura workaround:** `X86Base.CpuId` and `Stopwatch.Frequency`; scalar or + `Vector128` blend loops. +- **Upstream ask:** a `CpuInfo` on the ring, and cpuid feature detection at + boot. +- **Source:** 01, 02. + +### `pci`: no typed PCI enumeration nor name tables (minor) +- **Gap:** the PCI view offers only `DeviceNodeInfo` strings. +- **Aura workaround:** parse `Path` / `Description`; Aura keeps its own + `PciNames` copy. +- **Upstream ask:** a numeric identity (vendor, device, class) plus public name + tables. +- **Source:** 02. + +### `idle-thread`: the UI loop is the scheduler's idle thread (major, phase 2) +- **Gap:** the kernel `Run()` loop is the scheduler's idle thread. + - It must never block: only `Mutex` and `InterruptEvent` guard idle-thread + blocking, not `ConditionVariable` (reached by `Thread.Sleep` and contended + `lock`). + - It is excluded from `SchedulerInfo.BusyCpuTimeNs`. + - It gets the same 100 tickets as every worker. +- **Aura workaround:** + - Never block the UI thread (rule C9); use `TimerManager.Wait` for short + waits. + - Phase 2: a ticket boost through the COSMOS0001 scheduler seam. +- **Verified at HEAD (2026-10-02):** starvation is real without any GC. + - With 2 workers looping on `Thread.Sleep(10)`, the main loop managed fewer than 100 iterations in 60 s. + - With 1 worker it managed about 4500 in 20 s. + - So Aura's UI slows down while the FTP server thread runs. +- **Upstream ask:** a dedicated idle thread, so `Run()` becomes an ordinary + thread, and a ring priority API, or the earlier `MainThreadTickets` boost for + the idle thread. +- **Source:** 02, 08; kernel investigation 2026-10-02. + +### `gc-conservative`: the GC corrupts objects behind interior pointers on other threads' stacks (major) +- **Gap:** found at HEAD, root-caused and patched in this port. It crashes Aura's `ftp` command within seconds. + - **Primary defect.** `GarbageCollector.Mark.cs` `ScanMemoryRange` and the saved-register scan of switched-out threads pass every word that falls in the heap to `TryMarkRoot` as an object start. `TryMarkRoot` then ORs the mark bit into whatever word sits there. + - **Effect on Aura.** CoreLib's `ThreadWaitInfo.Wait` keeps `r12 = &_waitMonitor` (an interior byref) across `LowLevelMonitor_TimedWait`. A collection on the UI thread marks `_nativeMonitor`, the `GCHandle` IntPtr, so it becomes `…E059`. + - **Symptom.** `LowLevelMonitor_Release` reads the handle one byte off and takes a #GP at `+0x27` (FTP thread: `FtpServer.Listen` → `Thread.Sleep`). Depending on the address bits, the GC hangs in `EnumerateReferences` instead. + - **Second consequence.** Objects reachable only through interior pointers (byrefs, spans) on another thread's stack are not kept alive. + - **B, same file.** A suspended boot/idle thread, which is Aura's UI thread, is never stack-scanned when another thread collects. + - **C, `Runtime/Memory.cs`.** The allocation helpers store the MethodTable after `AllocObject` has re-enabled interrupts. A preempting collection sweeps the zero-header object, and the next allocation overlaps it. +- **Aura workaround:** none possible. The `ftp` command stays as designed. It needs the kernel fix. +- **Upstream fix (validated):** `gc-gp.patch` (Cosmos.Kernel.Core, 4 files). + - A: `TryMarkConservativeRoot` resolves through `GetParentObject`. + - B: scan the suspended idle thread from its saved SP to `BootStack.Top`. + - C: stamp the header inside `AllocObject`'s interrupts-off scope. + - Results: + - Repro kernels (sleep/lock/alloc/gcworker variants): unpatched faults in 2.5–35 s; patched runs 150 s × 8 variants with 0 faults. + - Aura FTP soak: 65/65. + - GarbageCollector suite 50/50; Threading suite 0 failures. + - Upstream should also add GC-suite cases for a waiter blocked in `Thread.Sleep`/`Monitor.Wait` while another thread collects. +- **Also open:** the `LowLevelMonitor_*` plug serial-logs every op, and `Thread.Yield` is a no-op. +- **Source:** 02, 06, 07, 08; kernel investigation 2026-10-02. + +### `tz-rtc`: no time zone, no RTC write (minor) +- **Gap:** there is no time zone and no way to set the RTC. The SDK does not + set `InvariantTimezone`. +- **Aura workaround:** `true`. Times are + the firmware clock. +- **Upstream ask:** a settable offset, an RTC write, and an SDK default. +- **Source:** 02, 07. + +### `env`: environment variables unusable (minor) +- **Gap:** `Environment.Get*` returns null, and `Set*` fails to link. +- **Aura workaround:** `Kernel.EnvironmentVariables`, plus an `os.getenv` + override in Lua. +- **Upstream ask:** an in-memory environment block. +- **Source:** 02, 07. + +### `pc-speaker`: no PC speaker (minor) +- **Gap:** there is no PC speaker driver, and port I/O (`Native.IO`) is + internal. +- **Aura workaround:** the `beep` command is dropped. +- **Upstream ask:** a PIT channel 2 driver or a `Console.Beep` plug. +- **Source:** 02, 08. + +### `encoding`: no CP437; encoding setters swap the console pipeline (minor) +- **Gap:** there is no CP437 provider. Any `Console.*Encoding` assignment swaps + the keyboard reader for a `StreamReader` over `ConsoleStream`. +- **Aura workaround:** the encoding lines are deleted. +- **Upstream ask:** compare by CodePage before swapping, and document it. +- **Source:** 02, 07. + +## Console / graphics + +### `kernelconsole`: the KernelConsole cannot be detached or hidden (minor) +- **Gap:** there is no public way to detach or hide the boot `KernelConsole`. + `Console` APIs paint the shared canvas. +- **Aura workaround:** + - Right after acquiring the canvas, call `Console.SetOut(Kernel.GuiSink)` + and `Console.SetError(Kernel.GuiSink)` (a serial writer). + - GUI code never calls the Console input or `Clear` APIs (rule C10). + - KernelConsole paints only on writes and cursor operations; it has no blink + timer. + - No `[UnsafeAccessor]` hatch is used. +- **Upstream ask:** a public `IsVisible` / `Suspend()`. +- **Source:** 04, 07, orchestrator amendment A2. + +### `console-input`: Console input APIs drain the keyboard queue (major) +- **Gap:** `Console.ReadKey` / `ReadLine` / `KeyAvailable` / `Console.In` drain + `KeyboardManager`'s queue into tty1. +- **Aura workaround:** + - The GUI uses only `KeyboardManager` (rules C10/C11). + - Lua runs with `Input = TextReader.Null`. +- **Upstream ask:** an unrouted `TryReadKey` should also drain the tty1 buffer. +- **Source:** 05, 07. + +### `console-global`: `Console.SetOut` is process-global (minor) +- **Gap:** the writer is wrapped in one global `SyncTextWriter`. +- **Aura workaround:** the Terminal swaps its writer in on focus and restores + `Kernel.GuiSink` when it loses focus. +- **Upstream ask:** a headless `ConsoleSession` or a per-thread hook. +- **Source:** 07. + +### `present`: no partial present (minor) +- **Gap:** there is no `Canvas.Display(rect)`, so every present copies the full + 8 MB frame. +- **Aura workaround:** present once per frame (`Kernel.Present()`), and throttle + terminal presents. +- **Upstream ask:** `Display(x, y, w, h)`. +- **Source:** 04. + +### `display-mode`: resolution fixed at boot on GOP / virtio-gpu (minor) +- **Gap:** the resolution is fixed at boot on GOP and virtio-gpu, and the depth + is 32 bpp only. +- **Aura workaround:** `limine.conf` `resolution:`; read `Canvas.Width/Height`; + scale assets. +- **Upstream ask:** a documented resolution property, and depth conversion. +- **Source:** 04, 08. + +### `blit`: no public memory ops or blend (minor) +- **Gap:** + - There are no public memory ops. + - `Canvas.DrawImageAlpha` blends per pixel and forces opaque. + - There is no image scaling: `DrawImage(img, x, y, w, h)` rescales and + allocates on every call. + - An `Image` cannot wrap an existing buffer. +- **Aura workaround:** the Aura DirectBitmap C# blend, Span/Array ops, and + `ImageUtils.ScaleTo` once. +- **Upstream ask:** a Span blend with opacity, `Image.Resize`, and a no-copy + `Bitmap` constructor. +- **Source:** 04, 08. + +### `psf`: PSF2 parsing gaps (minor) +- **Gap:** + - The PSF2 Unicode table is ignored. + - The 32-byte header is hard-coded. + - `(byte)charDataSize` overflows. + - `DefaultFont` is now 16×32. +- **Aura workaround:** zap 6×12 through `Kernel.font`; `DrawChar` handles + bytesPerRow. +- **Upstream ask:** a correct PSF2 parse and a glyph-index API. +- **Source:** 04. + +### `hw-cursor`: hardware cursor experimental and VMware-only (minor) +- **Gap:** `IHardwareCursor` is experimental (COSMOS0003), and + `TryDefine` returns false on QEMU. +- **Aura workaround:** a software cursor. Phase 2: the facet. +- **Upstream ask:** a virtio-gpu cursor, and promote the facet. +- **Source:** 04, 05, 08. + +### `bmp`: BMP loader limits; `Bitmap.Save` corrupt (minor) +- **Gap:** the BMP loader has no top-down images, no bitfield masks and nothing + below 24 bpp. `Bitmap.Save` writes zero-length copies. +- **Aura workaround:** catch around loads in `pic` and `ApplicationManager`. +- **Upstream ask:** harden the loader and fix `Save`. +- **Source:** 04, 08. + +### `canvas3d`: `Canvas3D` is full-screen and VMware SVGA3D only (minor) +- **Aura workaround:** CubeApp stays software-rendered. +- **Upstream ask:** an off-screen or software `Canvas3D`. +- **Source:** 04. + +## Input + +### `keyboard-altgr`: layout map defects (major) +- **Gap:** + - The FR/GB maps lack AltGr. + - FR/DE/ES lack the ISO 0x56 key. + - DE/ES/TR lose AltGr under Caps Lock (7-character `KeyMapping`). +- **Aura workaround:** `AuraFRStandardLayout`, built with the 8-character + constructor, 0x60 = AltGr, and 0x56. +- **Upstream ask:** fix the bundled maps. +- **Source:** 05. + +### `key-release`: only key presses are queued (minor) +- **Gap:** there is no held-key query. +- **Aura workaround:** GameBoy pulse model (fixed release). +- **Upstream ask:** opt-in Break events or a pressed-key bitmap. +- **Source:** 05, 08. + +### `key-repeat`: no USB typematic repeat; incomplete virtio keymap (minor) +- **Gap:** there is no typematic repeat for USB keyboards. The virtio-keyboard + keymap misses Del, Home, End, F11, F12, LWin, the keypad and more. +- **Aura workaround:** PS/2 keyboard in VM configs. +- **Upstream ask:** a repeat timer and a complete keymap. +- **Source:** 05. + +### `e0`: E0 prefix dropped (minor) +- **Gap:** with NumLock on, the arrows, Home and End arrive as keypad keys. +- **Aura workaround:** leave NumLock off. +- **Upstream ask:** keep an extended bit. +- **Source:** 05. + +### `sessions`: a second console session swallows Alt+F1..F12 (minor) +- **Gap:** once a second console session exists (a virtual console or Telnet), + the key router swallows Alt+F1..F12 and Alt+arrows, including Alt+F4. +- **Aura workaround:** never open sessions or Telnet (rule C11). +- **Upstream ask:** an opt-out, or a GUI owner for tty1. +- **Source:** 05, 08. + +### `mouse`: mouse model limits (minor) +- **Gap:** + - Buttons are level-only. + - There is no absolute or USB pointer. + - The wheel sign likely differs between PS/2 and virtio. + - `Sensitivity` truncates. +- **Aura workaround:** edge detection, PS/2 mouse, `Sensitivity` 1.0. +- **Upstream ask:** press counters, a tablet/USB mouse, and a documented sign. +- **Source:** 05. + +### `ps2-sync`: the PS/2 drivers never resynchronise (major on real hardware) +- **Gap:** found at HEAD and patched in this port. + - `HAL.X64/Devices/Input/PS2Mouse.cs` checks byte-0 bit 3 only after a whole packet has arrived, and keeps the alignment. One extra or lost byte (an ACK, a stray 00, a lost byte) freezes an IntelliMouse until reboot, after one phantom jump or click. + - Both IRQ handlers read port 0x60 without checking OBF or AUX. + - The config byte is read back (0x20) while IRQ1 is live. That causes the phantom `F7` key press on every boot. + - An edge that arrives on a masked I/O APIC pin is lost at unmask, which freezes keyboard and mouse together. + - The keyboard driver passes ACK/resend bytes, E0 fake shifts and the E1 Pause sequence through as keys. +- **Aura workaround:** none. QEMU's natural input does not trigger the desync. QMP automation must send at most ±127 per rel event: QEMU queues up to 4 packets per sync and keeps the rest, which looks like a drifting or frozen cursor. +- **Upstream fix (validated):** `ps2-mouse.patch` (HAL.X64, 3 files). + - Sync byte 0 on arrival with the 0xC8/0x08 mask, and drop a partial packet after 100 ms of silence (TSC). + - A single status-checked `HandleOutputBuffer` routes bytes by AUX. + - Service the buffer after unmasking; cache the config byte. + - Filter keyboard control bytes. + - Results: fault-injection repro 14/14 (stock 10/14, then a dead mouse); 60-round soak clean; no phantom F7. +- **Source:** kernel investigation 2026-10-02. + +### `key-docs`: `KeyEvent.Key` is layout-dependent (minor) +- **Gap:** the docs say `KeyEvent.Key` is the physical key, but it depends on + the layout. `Menu` is unmapped in all layouts. +- **Aura workaround:** per-layout bindings where needed. +- **Upstream ask:** fix the docs and the maps. +- **Source:** 05. + +## Filesystem / storage + +### `ide`: no IDE / PATA / ATAPI driver (major) +- **Gap:** only AHCI, NVMe and USB mass storage are supported. +- **Aura workaround:** VMs must use SATA/AHCI or NVMe disks. + `.cosmos/config.json`, run-aura and crash-debug all attach `disk.img` on + AHCI. +- **Upstream ask:** an IDE driver. +- **Source:** 03. + +### `fat-names`: the FAT driver accepts any character in long names (major) +- **Gap:** a missed gen2 drive-letter path literal (volume 0, backslash + separators) silently writes junk directory entries. +- **Aura workaround:** convert every path literal to the `/N/...` form, and + validate user input with `AuraPath.IsValidName`. +- **Upstream ask:** validate names. +- **Source:** 03. + +### `driveinfo`: `DriveInfo` not wired (minor) +- **Aura workaround:** `VfsManager.TryStatFs` through `Volumes.TryGetSpace`. + The result is cached, because each call is a full FAT sweep. +- **Upstream ask:** plug statfs / mount enumeration, and use the FSInfo free + count as a shortcut. +- **Source:** 03, 08. + +### `fat-label`: no API to read or set a FAT volume label (minor) +- **Aura workaround:** parse the BPB bytes at 0x2B / 0x47. +- **Upstream ask:** a label API. +- **Source:** 03. + +### `fat-time`: FAT timestamps always 0 (minor) +- **Gap:** timestamps are always 0 (1970), and `SetLastWriteTime` is a no-op. +- **Aura workaround:** clamp in ZipStorer; don't sort by date. +- **Upstream ask:** implement timestamps. +- **Source:** 03, 08. + +### `mounts`: mount-table rough edges (minor) +- **Gap:** + - No parent is synthesized for nested mount points. + - The format and mount guards compare by reference. + - `TryMount` allows duplicates. + - `MountFlags` (ReadOnly) are not enforced. + - There is no hot-plug event. +- **Aura workaround:** + - Top-level `/N` mount points only. + - Host plus StartSector checks (`Volumes.IsMounted`). + - `Volumes.PollHotplug()` from `Run`. +- **Upstream ask:** fix the guards, enforce the flags, and add a hot-plug + callback. +- **Source:** 03. + +### `vfs-threads`: VFS and PAL fd table not thread-safe (major, phase 2) +- **Aura workaround:** single-threaded phase 1. The FTP server is the only + concurrent VFS user. +- **Upstream ask:** locking. +- **Source:** 03. + +### `tmp`: no temp files (minor) +- **Gap:** `Path.GetTempFileName` is unplugged and there is no `/tmp`, so Lua's + `os.tmpname` fails. +- **Aura workaround:** `.tmp` files on the same volume. +- **Upstream ask:** a `MksTemps` plug or a tmpfs. +- **Source:** 03. + +### `cwd`: the current directory is kernel-global (minor) +- **Gap:** the current directory is kernel-global, and + `VfsManager.CurrentDirectory` is internal. +- **Aura workaround:** the `Kernel.CurrentDirectory` property setter syncs + `Directory.SetCurrentDirectory`. +- **Upstream ask:** a per-thread current directory. +- **Source:** 03. + +### `mbr`: `Mbr.IsMbr` checks only 0x55AA (minor) +- **Gap:** it is therefore true on superfloppies. +- **Aura workaround:** check GPT first; treat a superfloppy as one partition at + LBA 0. +- **Upstream ask:** real MBR validation. +- **Source:** 03. + +### `ext2`: Ext2 driver public but experimental and undocumented (minor) +- **Aura workaround:** FAT only. +- **Upstream ask:** document its status. +- **Source:** 03. + +## Network + +### `http-tls`: no HttpClient, no TLS (major) +- **Aura workaround:** an Aura HTTP/1.1 GET client over `Socket`; `https` is + refused. +- **Upstream ask:** an HTTP handler or package, and a TLS roadmap. +- **Source:** 06, 08. + +### `tcp-receive`: TCP receive returns 0 while open; span paths broken (major) +- **Gap:** + - `Receive` / `Read` return 0 while the connection is open (a spin-count + timeout). + - `Receive(Span)` drops data. + - `NetworkStream.Read(Span)` is unplugged. +- **Aura workaround:** the `Available`/`Poll` idiom with a deadline; receive + into `byte[]` only (rule C15). +- **Upstream ask:** a blocking receive, and fix the span paths. +- **Source:** 06, 08. + +### `ipaddress`: `IPAddress` plug defects (major) +- **Gap:** + - `Parse` returns null. + - `Equals` is always true. + - The hash is constant. + - String interpolation prints 0.0.0.0. +- **Aura workaround:** explicit `.ToString()`, compare `GetAddressBytes()`, + `TryParse` (rule C15). +- **Upstream ask:** store the address in the BCL field. +- **Source:** 06. + +### `socket-misc`: socket API rough edges (minor) +- **Gap:** + - The host-name overloads don't resolve DNS. + - Errors are bare `Exception`s. + - UDP `Available` counts datagrams. + - `Poll` ignores its timeout. +- **Aura workaround:** resolve first (`NetworkHelper.Resolve`); catch + `Exception`. +- **Upstream ask:** `SocketException`, and byte counts. +- **Source:** 06. + +### `dhcp`: DHCP client defects (minor) +- **Gap:** + - The ACK is applied to the first device only. + - There is no renewal. + - A NAK is applied as success. + - It throws with two or more NICs. + - Release throws when unconfigured. + - A 0.0.0.0 config is left behind. +- **Aura workaround:** `NetworkHelper` checks, `RemoveAllConfigIP`, try/catch. +- **Upstream ask:** fix the client, and add an `IsConfigured` API. +- **Source:** 06. + +### `tcp-primary`: TCP always sources from `NetworkManager.Primary` (minor) +- **Aura workaround:** make the configured NIC primary. +- **Upstream ask:** route-based source selection. +- **Source:** 06. + +### `nic-names`: no interface names or types (minor) +- **Aura workaround:** `eth{Index}` aliases (`NetworkHelper.AliasOf`). +- **Upstream ask:** stable names. +- **Source:** 06. + +### `net-threads`: network stack has no locks (major, phase 2) +- **Gap:** for example, the DNS port 53 registry is shared. +- **Aura workaround:** single-threaded phase 1; avoid DNS while FTP is busy. +- **Upstream ask:** locking. +- **Source:** 06. + +### `nic-drivers`: only E1000E and virtio-net (major) +- **Gap:** there are no drivers for e1000 82540/82545, PCnet or RTL. +- **Aura workaround:** VM configs use `e1000e` or `virtio-net`. +- **Upstream ask:** more drivers. +- **Source:** 06. + +### `tcp-robust`: minimal TCP (major) +- **Gap:** + - There is no retransmission. + - `WaitAck` spins. + - MSS is 536 and the window is fixed. + - Close takes 5 s. +- **Aura workaround:** timeouts on the Aura side. +- **Upstream ask:** TCP hardening. +- **Source:** 06. + +### `net-misc`: miscellaneous network gaps (minor) +- **Gap:** + - There is no `System.Net.NetworkInformation`. + - `IcmpClient` doesn't match the id/seq. + - `Dns` uses only `Nameservers[0]` and A records. + - The Cosmos `UdpClient.Send(byte[], Address, int)` doesn't pump. + - `FtpServer` can't detect a port clash. + - There is serial spam on every socket call. +- **Aura workaround:** use the Cosmos clients; run a single FTP server. +- **Upstream ask:** various, per item. +- **Source:** 06. + +## BCL / packages + +### `deflate`: no public DEFLATE (minor) +- **Gap:** BCL compression is native, and the vendored SharpZipLib `Inflater` + is internal. +- **Aura workaround:** `Zlib.Portable` (Ionic.Zlib). +- **Upstream ask:** plug `System.IO.Compression`, or make the inflater public. +- **Source:** 07, 08. + +### `crypto`: BCL crypto routes to OpenSSL; weak "secure" RNG (minor) +- **Gap:** BCL hashes and RNG route to OpenSSL, and the "secure" RNG is + xorshift. +- **Aura workaround:** Aura's own Sha256/MD5, plus `acryptohashnet`. +- **Upstream ask:** a managed hash plug, and RDRAND. +- **Source:** 07, 08. + +### `lua-host`: Cosmos.Executable.Lua 1.0.0 host hooks (minor) +- **Gap:** + - There is no virtual-file loader. + - Callbacks can't see host settings. + - `os.getenv` is hard-wired. + - There is no cancellation hook. + - The next version (Lua 5.3) breaks `ILuaState`. +- **Aura workaround:** `package.preload`, closures, an `os.getenv` override. +- **Upstream ask:** a loader hook, a host accessor, an env `Func`, and + `SetHook`. +- **Source:** 07. + +## Aura-side (not Cosmos) + +### `backend`: update and package endpoints unreachable (major) +- **Gap:** `http://aura.valentin.bzh/os.json` and `/repository.json` answer + 301 to https, which then answers 404. gen3 has no TLS anyway. +- **Workaround:** callers catch the error and report it. The endpoints need + plain-HTTP hosting (decision D3). + +--- + +## Other upstream findings (no Aura workaround site) + +- **The Stride scheduler's interactive wake boost is dead code.** + `ReadyThread` sets `Ready` before `OnThreadReady` tests `wasBlocked`, so no + thread is ever classified as interactive. Ask: test the previous state, + captured before the write. (08) + +## Items from the 3.0.77 list (origin/gen3) re-checked at HEAD + +**Fixed at HEAD.** These can be closed upstream: + +| Old § | Item | Status at HEAD | +|---|---|---| +| 1.1 | libm `fmod/cosh/sinh/tanh` missing | fixed (`Runtime/Math.cs`) | +| 1.2 | `RhCpuIdEx` stub missing | fixed (`CpuOps.s`) | +| 1.3 | `MemSet` tail corruption | fixed; `MemoryOp` is internal now | +| 1.4 | `CosmosDefaultFont` key | fixed (`Sdk.props`) | +| 1.5 | `ResetScrollDelta` | fixed (public) | +| 1.6 | DarkMagenta palette | fixed | +| 1.7 / 1.8 | RIP + stack trace in the panic | fixed (`Cosmos.Kernel/Panic.cs`) | +| 1.9 | `Canvas.Mode` reported a wrong resolution | fixed (the canvas re-reads the display) | +| 1.10 / 1.11 | GC hang / mark stack out of bounds | fixed | +| 2.1 | ICMP | fixed (`IcmpClient`) | +| 2.4 | US layout only, no E0, LEDs TODO | fixed: 7 layouts, E0 handled, PS/2 LEDs. Remaining: `keyboard-altgr`, `e0` (NumLock case), `key-release`. | +| 2.7 | `Accept()` returned the listener | fixed (`9d1dd320e`) | +| 2.9 | `System.Net.Dns` not plugged | fixed (`NameResolutionPalPlug`) | +| 3.6 | `Console.ReadKey` didn't block | changed: blocks through the session | +| 3.7 | MSB4011, restore trap, NAOT0007 noise, plugs.md | fixed. The broken `~/.cosmos/tools/bin` qemu wrapper is a stale local install, not an upstream issue. | + +**Still open, or partly fixed,** under the tags above: + +| Old § | Tag | +|---|---| +| 2.2 | `iso-files` | +| 2.3 | `display-mode` (partly fixed: honest API, switchable on SVGA II) | +| 2.5 | `cpu-exception` | +| 2.6 | `null-deref` | +| 2.8 | `tcp-receive` | +| 2.10 | `http-tls` | +| 2.11 | `deflate` (worse: the inflater is internal now) | +| 2.12 | `crypto` | +| 2.13 | `finalizers` | +| 2.14 | `driveinfo` (partly fixed: `TryStatFs`) | +| 2.15 | `fat-time` | +| 2.16 | `mounts` | +| 2.17 | `pc-speaker` | +| 2.18 | `cpuinfo` | +| 3.1 | `blit` | +| 3.2 | `bmp` | +| 3.3 | `resources-perf` | +| 3.4 | `log-sink`, `gc-conservative` (the old #GP, now root-caused) | +| 3.5 | `kernelconsole` | +| 3.8 | `tz-rtc`. `GetFiles` returning full paths is standard BCL behaviour, not a gap. | diff --git a/LICENSES/LICENSES.md b/LICENSES/LICENSES.md index 4396946af..f18fe2dba 100644 --- a/LICENSES/LICENSES.md +++ b/LICENSES/LICENSES.md @@ -38,8 +38,15 @@ Open source project used in Aura Operating System: - Location: [Aura Operating System/Aura OS/System/Network/SimpleHttpServer/] - License file: [LICENSE.MD](https://github.com/aura-systems/Aura-Operating-System/blob/master/LICENSES/SimpleHttpServer/LICENSE.md) -### UniLua -- Description: Lua 2.5 interpreter. -- Project: [github.com/xebecnan/UniLua](https://github.com/xebecnan/UniLua) -- Location: [SRC/Aura_OS/System/Interpreter/UniLua] -- License file: [LICENSE.MD](https://github.com/aura-systems/Aura-Operating-System/blob/master/LICENSES/UniLua/LICENSE.txt) +### Cosmos.Executable.Lua +- Description: Lua 5.2 interpreter for Cosmos gen3 kernels, based on UniLua. Replaces the in-tree UniLua copy. +- Project: [github.com/CosmosOS/Cosmos.Executable.Lua](https://github.com/CosmosOS/Cosmos.Executable.Lua) +- Package: NuGet `Cosmos.Executable.Lua` (referenced by SRC/Aura_OS/Aura_OS.csproj) +- License: BSD 3-Clause, Copyright (c) 2021, CosmosOS, COSMOS Project (LICENSE.txt in the package). +- Includes: [UniLua](https://github.com/xebecnan/UniLua), MIT License, Copyright (C) 2013 Sheng Lunan (THIRD-PARTY-NOTICES.txt in the package). + +### Cosmos.Network.Ftp +- Description: FTP server for Cosmos gen3 kernels, used by the ftp command. +- Project: [github.com/CosmosOS/CosmosFtp](https://github.com/CosmosOS/CosmosFtp) +- Package: NuGet `Cosmos.Network.Ftp` (referenced by SRC/Aura_OS/Aura_OS.csproj) +- License: BSD 3-Clause, Copyright (c) 2021, CosmosOS, COSMOS Project (LICENSE.txt in the package). diff --git a/LICENSES/UniLua/LICENSE.txt b/LICENSES/UniLua/LICENSE.txt deleted file mode 100644 index 5434d53c5..000000000 --- a/LICENSES/UniLua/LICENSE.txt +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (C) 2013 Sheng Lunan - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/NuGet.Config b/NuGet.Config new file mode 100644 index 000000000..e4d7a615d --- /dev/null +++ b/NuGet.Config @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/SRC/Aura_Boot/Aura_Boot.csproj b/SRC/Aura_Boot/Aura_Boot.csproj deleted file mode 100644 index 481cc12c7..000000000 --- a/SRC/Aura_Boot/Aura_Boot.csproj +++ /dev/null @@ -1,54 +0,0 @@ - - - - net6.0 - True - VMware - ELF - False - MethodFooters - ISO - False - Source - False - bin\Debug\net6.0\Aura_Boot.iso - False - False - VMware - Pipe: Cosmos\Serial - Serial: COM1 - Workstation - False - False - 1920x1080x32 - 3 - 0 - True - Gzip - False - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/SRC/Aura_Boot/Kernel.cs b/SRC/Aura_Boot/Kernel.cs deleted file mode 100644 index aabf7003e..000000000 --- a/SRC/Aura_Boot/Kernel.cs +++ /dev/null @@ -1,41 +0,0 @@ -/* -* PROJECT: Aura Operating System Development -* CONTENT: Main entry point for AuraOS. -* PROGRAMMER(S): Valentin Charbonnier -*/ - -using Sys = Cosmos.System; - -namespace Aura_Boot -{ - /// - /// Represents the main kernel of AuraOS, extending the Cosmos.System.Kernel. - /// This class serves as the entry point for the operating system, handling the initial setup - /// before the operating system's main loop begins and managing the main loop itself. - /// - public class Kernel : Sys.Kernel - { - /// - /// Performs initialization tasks before the main AuraOS loop starts. - /// This method calls the BeforeRun method of the Aura_OS.Kernel to perform - /// any necessary pre-run initialization tasks. - /// - protected override void BeforeRun() - { - Aura_OS.Kernel.BeforeRun(); - } - - /// - /// The main loop of AuraOS. This method checks if the Aura_OS.Kernel - /// indicates that the system should continue running. If not, it stops the kernel. - /// Otherwise, it calls the Run method of the Aura_OS.Kernel to perform the main - /// operating system tasks. - /// - protected override void Run() - { - if (!Aura_OS.Kernel.Running) - Stop(); - Aura_OS.Kernel.Run(); - } - } -} diff --git a/SRC/Aura_Boot/isoFiles/HelloWorld.gb b/SRC/Aura_Boot/isoFiles/HelloWorld.gb deleted file mode 100644 index 7a2af7d09..000000000 Binary files a/SRC/Aura_Boot/isoFiles/HelloWorld.gb and /dev/null differ diff --git a/SRC/Aura_Boot/isoFiles/Tetris.gb b/SRC/Aura_Boot/isoFiles/Tetris.gb deleted file mode 100644 index fbcef426f..000000000 Binary files a/SRC/Aura_Boot/isoFiles/Tetris.gb and /dev/null differ diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/AuraLogoWhite.jpg b/SRC/Aura_Boot/isoFiles/UI/Images/AuraLogoWhite.jpg deleted file mode 100644 index d23379d68..000000000 Binary files a/SRC/Aura_Boot/isoFiles/UI/Images/AuraLogoWhite.jpg and /dev/null differ diff --git a/SRC/Aura_OS.sln b/SRC/Aura_OS.sln index e204caea8..017306b1f 100644 --- a/SRC/Aura_OS.sln +++ b/SRC/Aura_OS.sln @@ -3,13 +3,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30225.117 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Aura_Boot", "Aura_Boot\Aura_Boot.csproj", "{7C0C2F6D-6BCE-470C-A9EE-E466876F51F8}" - ProjectSection(ProjectDependencies) = postProject - {69D204BF-F5A6-48CE-A053-0406685A4CA1} = {69D204BF-F5A6-48CE-A053-0406685A4CA1} - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Aura_Plugs", "Aura_Plugs\Aura_Plugs.csproj", "{69D204BF-F5A6-48CE-A053-0406685A4CA1}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aura_OS", "Aura_OS\Aura_OS.csproj", "{5B4F664C-AA8F-4BC5-9951-77A05DC03652}" EndProject Global @@ -18,14 +11,6 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {7C0C2F6D-6BCE-470C-A9EE-E466876F51F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7C0C2F6D-6BCE-470C-A9EE-E466876F51F8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7C0C2F6D-6BCE-470C-A9EE-E466876F51F8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7C0C2F6D-6BCE-470C-A9EE-E466876F51F8}.Release|Any CPU.Build.0 = Release|Any CPU - {69D204BF-F5A6-48CE-A053-0406685A4CA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {69D204BF-F5A6-48CE-A053-0406685A4CA1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {69D204BF-F5A6-48CE-A053-0406685A4CA1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {69D204BF-F5A6-48CE-A053-0406685A4CA1}.Release|Any CPU.Build.0 = Release|Any CPU {5B4F664C-AA8F-4BC5-9951-77A05DC03652}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5B4F664C-AA8F-4BC5-9951-77A05DC03652}.Debug|Any CPU.Build.0 = Debug|Any CPU {5B4F664C-AA8F-4BC5-9951-77A05DC03652}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/SRC/Aura_OS/.cosmos/config.json b/SRC/Aura_OS/.cosmos/config.json new file mode 100644 index 000000000..fdb368938 --- /dev/null +++ b/SRC/Aura_OS/.cosmos/config.json @@ -0,0 +1,36 @@ +{ + "targetArch": "x64", + "qemu": { + "memory": "1024M", + "machineType": "q35", + "cpuModel": "max", + "serialMode": "stdio", + "networkCard": "e1000e", + "portForwards": [ + "tcp::2121-:21", + "tcp::50000-:50000", + "tcp::50001-:50001", + "tcp::50002-:50002", + "tcp::50003-:50003", + "tcp::50004-:50004", + "tcp::50005-:50005", + "tcp::50006-:50006", + "tcp::50007-:50007", + "tcp::50008-:50008", + "tcp::50009-:50009" + ], + "keyboard": "ps2", + "mouse": "ps2", + "audio": "none", + "enableNetwork": false, + "networkPorts": "5555", + "extraArgs": "", + "disks": [ + { + "path": "disk.img", + "type": "ahci", + "size": "512M" + } + ] + } +} diff --git a/SRC/Aura_OS/Aura_OS.csproj b/SRC/Aura_OS/Aura_OS.csproj index 00a2748f0..2119ec330 100644 --- a/SRC/Aura_OS/Aura_OS.csproj +++ b/SRC/Aura_OS/Aura_OS.csproj @@ -1,48 +1,65 @@ - + - - net6.0 - TRACE;NOASYNC - + + Exe + net10.0 + Aura_OS + + Aura_Boot.Kernel + disable + disable + true + Aura_OS/UI/Fonts/zap-ext-light16.psf + + + - - $([System.DateTime]::Now.ToString("yyyy")) - $([System.DateTime]::Now.ToString("MM")) - $([System.DateTime]::Now.ToString("dd")) - - - - - True - + + + + + + + + + - - - - - - - + + + + Aura_OS/$([System.String]::Copy('%(RecursiveDir)').Replace('\', '/'))%(Filename)%(Extension) + + - - - - - - - - + + + $([System.DateTime]::Now.ToString("ddMMyyyyHHmm")) + $([System.DateTime]::Now.ToString("ddMMyyyy"))0000 + - - - + + + + <_AuraVersionInfoFile>$(IntermediateOutputPath)VersionInfo.g.cs + + + <_AuraVersionInfoLine Include="// <auto-generated/>" /> + <_AuraVersionInfoLine Include="namespace Aura_OS" /> + <_AuraVersionInfoLine Include="{" /> + <_AuraVersionInfoLine Include=" public class VersionInfo" /> + <_AuraVersionInfoLine Include=" {" /> + <_AuraVersionInfoLine Include=" public static string revision = "$(AuraRevision)"%3B" /> + <_AuraVersionInfoLine Include=" }" /> + <_AuraVersionInfoLine Include="}" /> + + + + + + + + diff --git a/SRC/Aura_OS/Boot/Kernel.cs b/SRC/Aura_OS/Boot/Kernel.cs new file mode 100644 index 000000000..21f887deb --- /dev/null +++ b/SRC/Aura_OS/Boot/Kernel.cs @@ -0,0 +1,68 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: Main entry point for AuraOS. +* PROGRAMMER(S): Valentin Charbonnier +*/ + +using System; +using Aura_OS.System; +using Sys = Cosmos.Kernel.System; + +namespace Aura_Boot +{ + /// + /// Represents the main kernel of AuraOS, extending Cosmos.Kernel.System.Kernel. + /// This class serves as the entry point for the operating system (selected by + /// CosmosKernelClass in Aura_OS.csproj), handling the initial setup before the + /// operating system's main loop begins and managing the main loop itself. + /// + public class Kernel : Sys.Kernel + { + /// + /// Called once during boot, with interrupts enabled and the drivers started. + /// base.OnBoot() brings up the KernelConsole, which makes Console.* draw. + /// Prints the boot banner the gen2 Global plug used to print. + /// + protected override void OnBoot() + { + base.OnBoot(); + + CustomConsole.WriteLineInfo("Starting Aura Operating System v" + Aura_OS.Kernel.Version + "-" + Aura_OS.Kernel.Revision); + CustomConsole.WriteLineInfo("Cosmos gen3 " + VersionString); + } + + /// + /// Performs initialization tasks before the main AuraOS loop starts. + /// This method calls the BeforeRun method of the Aura_OS.Kernel to perform + /// any necessary pre-run initialization tasks. + /// + protected override void BeforeRun() + { + try + { + Aura_OS.Kernel.BeforeRun(); + } + catch (Exception ex) + { + // gen3: an exception escaping BeforeRun is not caught by Cosmos.Kernel.System.Kernel.Start(). + // StopKernel falls back to text when the canvas/assets do not exist yet. + Crash.StopKernel("Boot failed", ex.Message, "", "0"); + } + } + + /// + /// The main loop of AuraOS. Loops here while Aura_OS.Kernel indicates that the + /// system should continue running (Cosmos.Kernel.System.Kernel.Start() logs two + /// serial lines around every Run() call), then stops the kernel. + /// + protected override void Run() + { + while (Aura_OS.Kernel.Running && !Stopped) + { + Aura_OS.Kernel.Run(); + } + + Stop(); + } + } +} diff --git a/SRC/Aura_OS/Bootloader/limine.conf b/SRC/Aura_OS/Bootloader/limine.conf new file mode 100644 index 000000000..474308790 --- /dev/null +++ b/SRC/Aura_OS/Bootloader/limine.conf @@ -0,0 +1,6 @@ +timeout: 0 + +/Aura Operating System + protocol: limine + path: boot():/boot/Aura_OS.elf + resolution: 1920x1080x32 diff --git a/SRC/Aura_OS/Core/CpuInfo.cs b/SRC/Aura_OS/Core/CpuInfo.cs new file mode 100644 index 000000000..7eb41f3fc --- /dev/null +++ b/SRC/Aura_OS/Core/CpuInfo.cs @@ -0,0 +1,108 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: CPU Informations +* PROGRAMMER(S): Valentin Charbonnier +*/ + +using System; +using System.Buffers.Binary; +using System.Diagnostics; +using System.Runtime.Intrinsics.X86; +using System.Text; + +namespace Aura_OS.Core +{ + /// + /// CPU vendor, brand string, TSC frequency, cycle counter and uptime. + /// GEN3-GAP(cpuinfo): Cosmos has no CPU information API; this reads CPUID through the BCL + /// (X86Base.CpuId, backed by RhCpuIdEx) and the TSC through the plugged Stopwatch. + /// + public static class CpuInfo + { + /// + /// CPUID leaf 0 vendor id (e.g. "GenuineIntel"), or "Unknown" off x86. + /// + public static string GetVendor() + { + if (!X86Base.IsSupported) + { + return "Unknown"; + } + + var leaf = X86Base.CpuId(0, 0); + + Span bytes = stackalloc byte[12]; + BinaryPrimitives.WriteInt32LittleEndian(bytes, leaf.Ebx); + BinaryPrimitives.WriteInt32LittleEndian(bytes.Slice(4), leaf.Edx); + BinaryPrimitives.WriteInt32LittleEndian(bytes.Slice(8), leaf.Ecx); + + return Encoding.ASCII.GetString(bytes); + } + + /// + /// CPUID leaves 0x80000002..0x80000004 brand string, or the vendor id when the CPU has no brand string. + /// + public static string GetBrandString() + { + if (!X86Base.IsSupported) + { + return "Unknown"; + } + + var extended = X86Base.CpuId(unchecked((int)0x80000000), 0); + if ((uint)extended.Eax < 0x80000004) + { + return GetVendor(); + } + + Span bytes = stackalloc byte[48]; + for (int i = 0; i < 3; i++) + { + var leaf = X86Base.CpuId(unchecked((int)(0x80000002u + (uint)i)), 0); + Span slice = bytes.Slice(i * 16); + BinaryPrimitives.WriteInt32LittleEndian(slice, leaf.Eax); + BinaryPrimitives.WriteInt32LittleEndian(slice.Slice(4), leaf.Ebx); + BinaryPrimitives.WriteInt32LittleEndian(slice.Slice(8), leaf.Ecx); + BinaryPrimitives.WriteInt32LittleEndian(slice.Slice(12), leaf.Edx); + } + + int length = bytes.IndexOf((byte)0); + string brand = Encoding.ASCII.GetString(length < 0 ? bytes : bytes.Slice(0, length)).Trim(); + + return brand.Length == 0 ? GetVendor() : brand; + } + + /// + /// Calibrated TSC frequency in MHz (x64). + /// + public static long FrequencyMHz + { + get + { + return Stopwatch.Frequency / 1000000; + } + } + + /// + /// Raw TSC value (RDTSC on x64). + /// + public static long Cycles + { + get + { + return Stopwatch.GetTimestamp(); + } + } + + /// + /// Time since boot. + /// + public static TimeSpan Uptime + { + get + { + return TimeSpan.FromMilliseconds(Environment.TickCount64); + } + } + } +} diff --git a/SRC/Aura_OS/Core/Memory.cs b/SRC/Aura_OS/Core/Memory.cs index 6240b2237..6d2b42b14 100644 --- a/SRC/Aura_OS/Core/Memory.cs +++ b/SRC/Aura_OS/Core/Memory.cs @@ -5,45 +5,49 @@ * Valentin Charbonnier */ -using Cosmos.Core; +using Cosmos.Kernel.System.Diagnostics; namespace Aura_OS.Core { public class Memory { - public static uint TotalMemory = CPU.GetAmountOfRAM(); - public uint FreePercentage; - public uint UsedPercentage = (GetUsedMemory() * 100) / TotalMemory; - public uint FreeMemory = TotalMemory - GetUsedMemory(); - private const uint div = 1048576; + // GEN3-GAP(meminfo): MemoryInfo.TotalPages/RamSizeBytes only cover the largest usable + // Limine memory-map region (the page allocator's pool), so the total reads below the + // machine's installed RAM. All figures are in MB. - public Memory() + public static uint TotalMemory { - this.Monitor(); + get + { + return (uint)((MemoryInfo.TotalPages * MemoryInfo.PageSizeBytes) >> 20); + } } - public static void GetTotalMemory() + public uint FreePercentage; + public uint UsedPercentage; + public uint FreeMemory; + + public Memory() { - TotalMemory = CPU.GetAmountOfRAM() + 1; + this.Monitor(); } public void Monitor() { - GetTotalMemory(); - FreeMemory = TotalMemory - GetUsedMemory(); - UsedPercentage = (GetUsedMemory() * 100) / TotalMemory; + uint total = TotalMemory; + FreeMemory = GetFreeMemory(); + UsedPercentage = total == 0 ? 0 : (GetUsedMemory() * 100) / total; FreePercentage = 100 - UsedPercentage; } public static uint GetFreeMemory() { - return TotalMemory - GetUsedMemory(); + return (uint)((MemoryInfo.FreePages * MemoryInfo.PageSizeBytes) >> 20); } public static uint GetUsedMemory() { - uint UsedRAM = CPU.GetEndOfKernel() + 1024; - return UsedRAM / div; + return (uint)(((MemoryInfo.TotalPages - MemoryInfo.FreePages) * MemoryInfo.PageSizeBytes) >> 20); } } } \ No newline at end of file diff --git a/SRC/Aura_OS/Files.cs b/SRC/Aura_OS/Files.cs index 34c3bd923..9c97544e0 100644 --- a/SRC/Aura_OS/Files.cs +++ b/SRC/Aura_OS/Files.cs @@ -1,119 +1,332 @@ -using Aura_OS.System; -using Cosmos.System.Graphics.Fonts; -using Cosmos.System.Graphics; -using IL2CPU.API.Attribs; +using System; using System.IO; +using System.Text; +using Aura_OS.System; +using Cosmos.Kernel.System.Graphics.Fonts; +using Cosmos.Kernel.System.Graphics; namespace Aura_OS { - public class Files + /// + /// Embedded assets. gen3 has no ISO volume: every file under Resources/ is an embedded resource + /// named "Aura_OS/<path relative to Resources>" (see Aura_OS.csproj), read with Get("UI/..."). + /// + public static class Files { + /// + /// Sentinel path prefix for an asset that is not on disk ("embedded:UI/Themes/Suave.skin.xml"). + /// Read such paths with ReadAllBytes/ReadAllText. + /// + public const string EmbeddedScheme = "embedded:"; + + private const string ResourcePrefix = "Aura_OS/"; + + private static byte[] _errorImage; + private static byte[] _tetrisRom; + private static byte[] _wallpaper; + private static byte[] _wallpaper2; + private static byte[] _auralogoWhite; + //200x178 .bmp - [ManifestResourceStream(ResourceName = "Aura_OS.Resources.error.bmp")] - public static byte[] ErrorImage; + public static byte[] ErrorImage + { + get + { + if (_errorImage == null) + { + _errorImage = Get("error.bmp"); + } + + return _errorImage; + } + } //.gb - [ManifestResourceStream(ResourceName = "Aura_OS.Resources.Tetris.gb")] - public static byte[] TetrisRom; + public static byte[] TetrisRom + { + get + { + if (_tetrisRom == null) + { + _tetrisRom = Get("Tetris.gb"); + } + + return _tetrisRom; + } + } + + public static byte[] Wallpaper + { + get + { + if (_wallpaper == null) + { + _wallpaper = Get("wallpaper-1.bmp"); + } + + return _wallpaper; + } + } + + public static byte[] Wallpaper2 + { + get + { + if (_wallpaper2 == null) + { + _wallpaper2 = Get("wallpaper-2.bmp"); + } + + return _wallpaper2; + } + } + + public static byte[] auralogo_white + { + get + { + if (_auralogoWhite == null) + { + _auralogoWhite = Get("auralogo_white.bmp"); + } + + return _auralogoWhite; + } + } - [ManifestResourceStream(ResourceName = "Aura_OS.Resources.wallpaper-1.bmp")] - public static byte[] Wallpaper; + /// + /// Embedded asset by its path relative to Resources/ ("UI/Themes/Suave.skin.xml", "error.bmp"; + /// '\' is accepted). Returns a fresh copy on every call: read each asset once and cache it. + /// + /// No such embedded resource. + public static byte[] Get(string relPath) + { + if (relPath == null) + { + throw new ArgumentNullException(nameof(relPath)); + } - [ManifestResourceStream(ResourceName = "Aura_OS.Resources.wallpaper-2.bmp")] - public static byte[] Wallpaper2; + return ReadResource(relPath); + } - [ManifestResourceStream(ResourceName = "Aura_OS.Resources.auralogo_white.bmp")] - public static byte[] auralogo_white; + /// + /// Embedded asset, or false (data = null) when it does not exist or cannot be read. + /// + public static bool TryGet(string relPath, out byte[] data) + { + data = null; - public static string IsoVolume; + if (string.IsNullOrEmpty(relPath)) + { + return false; + } - public static void LoadFiles() + try + { + data = ReadStream(ResourceName(relPath)); + } + catch (Exception) + { + data = null; + } + + return data != null; + } + + /// + /// Embedded text asset, UTF-8 with the BOM stripped (gen2's File.ReadAllText did that; + /// Suave.skin.xml has one and NanoXML rejects it). + /// + /// No such embedded resource. + public static string GetText(string relPath) + { + byte[] bytes = Get(relPath); + int skip = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0; + return Encoding.UTF8.GetString(bytes, skip, bytes.Length - skip); + } + + /// + /// True for an "embedded:..." sentinel path. + /// + public static bool IsEmbeddedPath(string path) + { + return path != null && path.StartsWith(EmbeddedScheme, StringComparison.Ordinal); + } + + /// + /// "embedded:X" -> Get(X); any other path -> File.ReadAllBytes(path). + /// + public static byte[] ReadAllBytes(string pathOrEmbedded) + { + if (IsEmbeddedPath(pathOrEmbedded)) + { + return Get(pathOrEmbedded.Substring(EmbeddedScheme.Length)); + } + + return File.ReadAllBytes(pathOrEmbedded); + } + + /// + /// "embedded:X" -> GetText(X); any other path -> File.ReadAllText(path). + /// + public static string ReadAllText(string pathOrEmbedded) + { + if (IsEmbeddedPath(pathOrEmbedded)) + { + return GetText(pathOrEmbedded.Substring(EmbeddedScheme.Length)); + } + + return File.ReadAllText(pathOrEmbedded); + } + + private static string ResourceName(string relPath) + { + return ResourcePrefix + relPath.Replace('\\', '/'); + } + + private static byte[] ReadResource(string relPath) + { + string name = ResourceName(relPath); + byte[] data = ReadStream(name); + + if (data == null) + { + throw new FileNotFoundException("Embedded resource not found: " + name, name); + } + + return data; + } + + /// + /// Whole manifest resource, or null when it does not exist. + /// + private static byte[] ReadStream(string name) { - CustomConsole.WriteLineInfo("Checking for ISO9660 volume..."); + // GEN3-GAP(resources): GetManifestResourceStream works but is untested and undocumented upstream; + // the internal ResourceManager is what PCScreenFont uses. Only Files.cs reads resources. + Stream stream = typeof(Aura_OS.Kernel).Assembly.GetManifestResourceStream(name); - var vols = Kernel.VirtualFileSystem.GetVolumes(); - IsoVolume = Kernel.CurrentVolume; + if (stream == null) + { + return null; + } + + byte[] data = null; + Exception error = null; - foreach (var vol in vols) + try { - if (Kernel.VirtualFileSystem.GetFileSystemType(vol.mName).Equals("ISO9660")) + data = new byte[stream.Length]; + + // Read may return short counts. + int offset = 0; + while (offset < data.Length) { - IsoVolume = vol.mName; + int read = stream.Read(data, offset, data.Length - offset); + if (read <= 0) + { + break; + } - CustomConsole.WriteLineOK("Volume is " + IsoVolume); + offset += read; + } + + if (offset != data.Length) + { + error = new EndOfStreamException("Embedded resource truncated: " + name); } } + catch (Exception ex) + { + error = ex; + } + // gen3: finally/using do not run on the exception path, dispose explicitly. + stream.Dispose(); + + if (error != null) + { + throw new IOException("Cannot read embedded resource " + name + ": " + error.Message, error); + } + + return data; + } + + public static void LoadFiles() + { // Files - Kernel.errorLogo = new Bitmap(Files.ErrorImage); + Kernel.errorLogo = new Bitmap(ErrorImage); CustomConsole.WriteLineOK("error.bmp image loaded."); // Wallpapers - Kernel.wallpaper1 = new Bitmap(Files.Wallpaper); + Kernel.wallpaper1 = new Bitmap(Wallpaper); CustomConsole.WriteLineOK("wallpaper-1.bmp wallpaper loaded."); - Kernel.wallpaper2 = new Bitmap(Files.Wallpaper2); + Kernel.wallpaper2 = new Bitmap(Wallpaper2); CustomConsole.WriteLineOK("wallpaper-2.bmp wallpaper loaded."); // Logo - Kernel.auralogo_white = new Bitmap(Files.auralogo_white); + Kernel.auralogo_white = new Bitmap(auralogo_white); CustomConsole.WriteLineOK("auralogo_white.bmp wallpaper loaded."); // Images - Kernel.AuraLogo = new Bitmap(File.ReadAllBytes(IsoVolume + "UI\\Images\\AuraLogo.bmp")); + Kernel.AuraLogo = new Bitmap(Get("UI/Images/AuraLogo.bmp")); CustomConsole.WriteLineOK("AuraLogo.bmp image loaded."); - Kernel.AuraLogoWhite = new Bitmap(File.ReadAllBytes(IsoVolume + "UI\\Images\\AuraLogoWhite.bmp")); + Kernel.AuraLogoWhite = new Bitmap(Get("UI/Images/AuraLogoWhite.bmp")); CustomConsole.WriteLineOK("AuraLogoWhite.bmp image loaded."); - Kernel.AuraLogo2 = new Bitmap(File.ReadAllBytes(IsoVolume + "UI\\Images\\aura.bmp")); + Kernel.AuraLogo2 = new Bitmap(Get("UI/Images/aura.bmp")); CustomConsole.WriteLineOK("aura.bmp image loaded."); - Kernel.CosmosLogo = new Bitmap(File.ReadAllBytes(IsoVolume + "UI\\Images\\CosmosLogo.bmp")); + Kernel.CosmosLogo = new Bitmap(Get("UI/Images/CosmosLogo.bmp")); CustomConsole.WriteLineOK("CosmosLogo.bmp image loaded."); // Fonts - Kernel.font = PCScreenFont.LoadFont(File.ReadAllBytes(IsoVolume + "UI\\Fonts\\zap-ext-light16.psf")); + Kernel.font = PCScreenFont.LoadFont(Get("UI/Fonts/zap-ext-light16.psf")); CustomConsole.WriteLineOK("zap-ext-light16.psf font loaded."); } public static void LoadImages() { // Icons - LoadImage(IsoVolume + "UI\\Images\\Icons\\16\\up.bmp", "16"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\16\\close.bmp", "16"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\16\\minimize.bmp", "16"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\16\\explorer.bmp", "16"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\16\\network-idle.bmp", "16"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\16\\network-offline.bmp", "16"); - //LoadImage(isoVol + "UI\\Images\\Icons\\16\\network-transmit.bmp", "16"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\16\\program.bmp", "16"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\16\\terminal.bmp", "16"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\16\\drive.bmp", "16"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\16\\drive-readonly.bmp", "16"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\16\\settings.bmp", "16"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\24\\program.bmp", "24"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\24\\reboot.bmp", "24"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\24\\logout.bmp", "24"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\24\\settings.bmp", "24"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\24\\shutdown.bmp", "24"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\24\\terminal.bmp", "24"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\24\\explorer.bmp", "24"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\32\\file.bmp", "32"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\32\\folder.bmp", "32"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\32\\dialog-information.bmp", "32"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\32\\dialog-error.bmp", "32"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\cursor.bmp", "00"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\grab.bmp", "00"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\resize-horizontal.bmp", "00"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\resize-vertical.bmp", "00"); - LoadImage(IsoVolume + "UI\\Images\\Icons\\start.bmp", "00"); - } - - public static void LoadImage(string path, string type) - { - string fileName = Path.GetFileName(path); - Bitmap bitmap = new(File.ReadAllBytes(path)); + LoadImage("UI/Images/Icons/16/up.bmp", "16"); + LoadImage("UI/Images/Icons/16/close.bmp", "16"); + LoadImage("UI/Images/Icons/16/minimize.bmp", "16"); + LoadImage("UI/Images/Icons/16/explorer.bmp", "16"); + LoadImage("UI/Images/Icons/16/network-idle.bmp", "16"); + LoadImage("UI/Images/Icons/16/network-offline.bmp", "16"); + //LoadImage("UI/Images/Icons/16/network-transmit.bmp", "16"); + LoadImage("UI/Images/Icons/16/program.bmp", "16"); + LoadImage("UI/Images/Icons/16/terminal.bmp", "16"); + LoadImage("UI/Images/Icons/16/drive.bmp", "16"); + LoadImage("UI/Images/Icons/16/drive-readonly.bmp", "16"); + LoadImage("UI/Images/Icons/16/settings.bmp", "16"); + LoadImage("UI/Images/Icons/24/program.bmp", "24"); + LoadImage("UI/Images/Icons/24/reboot.bmp", "24"); + LoadImage("UI/Images/Icons/24/logout.bmp", "24"); + LoadImage("UI/Images/Icons/24/settings.bmp", "24"); + LoadImage("UI/Images/Icons/24/shutdown.bmp", "24"); + LoadImage("UI/Images/Icons/24/terminal.bmp", "24"); + LoadImage("UI/Images/Icons/24/explorer.bmp", "24"); + LoadImage("UI/Images/Icons/32/file.bmp", "32"); + LoadImage("UI/Images/Icons/32/folder.bmp", "32"); + LoadImage("UI/Images/Icons/32/dialog-information.bmp", "32"); + LoadImage("UI/Images/Icons/32/dialog-error.bmp", "32"); + LoadImage("UI/Images/Icons/cursor.bmp", "00"); + LoadImage("UI/Images/Icons/grab.bmp", "00"); + LoadImage("UI/Images/Icons/resize-horizontal.bmp", "00"); + LoadImage("UI/Images/Icons/resize-vertical.bmp", "00"); + LoadImage("UI/Images/Icons/start.bmp", "00"); + } + + /// + /// Loads an embedded icon ("UI/Images/Icons/16/up.bmp") into the ResourceManager as type + "-" + file name. + /// + public static void LoadImage(string relPath, string type) + { + string fileName = Path.GetFileName(relPath.Replace('\\', '/')); + Bitmap bitmap = new(Get(relPath)); Kernel.ResourceManager.AddIcon(type + "-" + fileName, bitmap); CustomConsole.WriteLineOK(fileName + " icon loaded."); } diff --git a/SRC/Aura_OS/Kernel.cs b/SRC/Aura_OS/Kernel.cs index b38e214ff..cc6868068 100644 --- a/SRC/Aura_OS/Kernel.cs +++ b/SRC/Aura_OS/Kernel.cs @@ -6,17 +6,12 @@ using System; using System.Collections.Generic; -using System.Text; using System.Drawing; using System.IO; -using Cosmos.Core.Memory; -using Cosmos.HAL; -using Cosmos.System; -using Cosmos.System.ExtendedASCII; -using Cosmos.System.FileSystem; -using Cosmos.System.FileSystem.VFS; -using Cosmos.System.Graphics; -using Cosmos.System.Graphics.Fonts; +using Cosmos.Kernel.System.Diagnostics; +using Cosmos.Kernel.System.Graphics; +using Cosmos.Kernel.System.Graphics.Fonts; +using Cosmos.Kernel.System.Vfs; using Aura_OS.System; using Aura_OS.Processing; using Aura_OS.System.Processing; @@ -24,6 +19,7 @@ using Aura_OS.System.Processing.Interpreter; using Aura_OS.System.Processing.Processes; using Aura_OS.System.Graphics.UI.GUI.Skin; +using Aura_OS.System.Filesystem; using Aura_OS.System.Utils; namespace Aura_OS @@ -45,8 +41,38 @@ public class Kernel public static string Clipboard { get; internal set; } public static string UserDirectory { get; internal set; } - public static string CurrentVolume = @"0:\"; - public static string CurrentDirectory = @"0:\"; + /// + /// Current volume: "/N/" (the N-th FAT volume), or "/" when no volume is mounted. Always ends with '/'. + /// + public static string CurrentVolume = "/"; + + private static string _currentDirectory = "/"; + + /// + /// Current directory, always ending with '/'. The setter also moves the BCL current directory + /// (Lua, FTP, relative System.IO paths). + /// + public static string CurrentDirectory + { + get + { + return _currentDirectory; + } + set + { + _currentDirectory = value; + + try + { + // GEN3-GAP(cwd): the current directory is kernel-global (VfsManager.CurrentDirectory is internal). + Directory.SetCurrentDirectory(value); + } + catch (Exception) + { + // DirectoryNotFoundException when the volume is gone: keep Aura's own value. + } + } + } private static bool _networkConnected = false; public static bool NetworkConnected @@ -97,6 +123,13 @@ public static bool NetworkConnected public static Canvas Canvas; + /// + /// Console.Out/Error once the canvas is acquired: keeps Console output (serial) off Aura's frame, + /// because the KernelConsole draws on the same canvas. The Terminal swaps in its own writer + /// while focused and must restore this one, never the original console writer. + /// + public static TextWriter GuiSink; + public static Color WhiteColor = Color.FromArgb(0xff, 0xff, 0xff, 0xff); public static int WhiteColorInt = WhiteColor.ToArgb(); public static Color BlackColor = Color.FromArgb(0xff, 0x00, 0x00, 0x00); @@ -119,17 +152,12 @@ public static bool NetworkConnected public static ThemeManager ThemeManager; public static Explorer Explorer; - // Textmode Console - public static System.Graphics.UI.CUI.Console TextmodeConsole; - public static int FreeCount = 0; - private static int _frameCount = 0; private static int _frames = 0; private static int _fps = 0; - private static int _deltaT = 0; - - public static CosmosVFS VirtualFileSystem; + private static long _lastFpsTick = 0; + private static long _lastCollectTick = 0; public static string CommandOutput = ""; public static bool Redirect = false; @@ -137,18 +165,31 @@ public static bool NetworkConnected public static void BeforeRun() { EnvironmentVariables = new Dictionary(); - VirtualFileSystem = new CosmosVFS(); //Start Filesystem - VFSManager.RegisterVFS(VirtualFileSystem); + CustomConsole.WriteLineInfo("Mounting volumes..."); + Volumes.Initialize(); + + CurrentVolume = AuraPaths.SystemVolume ?? "/"; + CurrentDirectory = CurrentVolume; - if (File.Exists(@"0:\System\settings.ini")) + if (AuraPaths.SystemVolume != null && File.Exists(AuraPaths.SettingsIni)) { Installed = true; - Settings config = new Settings(@"0:\System\settings.ini"); - ScreenWidth = uint.Parse(config.GetValue("screenWidth")); - ScreenHeight = uint.Parse(config.GetValue("screenHeight")); + Settings config = new Settings(AuraPaths.SettingsIni); + + uint width; + if (uint.TryParse(config.GetValue("screenWidth"), out width) && width > 0) + { + ScreenWidth = width; + } + + uint height; + if (uint.TryParse(config.GetValue("screenHeight"), out height) && height > 0) + { + ScreenHeight = height; + } } ProcessManager = new ProcessManager(); @@ -161,36 +202,51 @@ public static void BeforeRun() Files.LoadFiles(); CustomConsole.WriteLineInfo("Checking for boot.bat script..."); - for (int i = 0; i <= 5; i++) + IReadOnlyList mounts = VfsManager.Mounts; // immutable snapshot + for (int i = 0; i < mounts.Count; i++) { - string volumePath = i + @":\"; - if (Directory.Exists(volumePath)) + string volumePath = AuraPath.AsDirectory(mounts[i].MountPoint); + CustomConsole.WriteLineInfo($"Checking for boot.bat on volume {volumePath}..."); + if (File.Exists(volumePath + "boot.bat")) { - CustomConsole.WriteLineInfo($"Checking for boot.bat on volume {volumePath}..."); - if (File.Exists(volumePath + "boot.bat")) - { - CustomConsole.WriteLineOK($"Detected boot.bat on {volumePath}, executing script..."); - Batch.Execute(volumePath + "boot.bat"); - CurrentVolume = volumePath; - break; - } + CustomConsole.WriteLineOK($"Detected boot.bat on {volumePath}, executing script..."); + Batch.Execute(volumePath + "boot.bat"); + CurrentVolume = volumePath; + break; } } - global::System.Console.ReadKey(); - CustomConsole.WriteLineInfo("Starting Canvas..."); //START GRAPHICS - Canvas = FullScreenCanvas.GetFullScreenCanvas(new Mode(ScreenWidth, ScreenHeight, ColorDepth.ColorDepth32)); - Canvas.DrawImage(AuraLogoWhite, (int)((ScreenWidth / 2) - (AuraLogoWhite.Width / 2)), (int)((ScreenHeight / 2) - (AuraLogoWhite.Height / 2))); - Canvas.Display(); + try + { + // Display that can switch modes (VMware SVGA II): switches. Firmware framebuffer / virtio-gpu: + // ignored, the resolution is the one limine.conf asked for. + Canvas = Canvas.GetFullScreen(new Mode((int)ScreenWidth, (int)ScreenHeight, ColorDepth.ColorDepth32)); + } + catch (ArgumentOutOfRangeException) + { + // Mode refused by the display (screenWidth/screenHeight come from a user-editable settings.ini). + Canvas = Canvas.GetFullScreen(); + } + + // GEN3-GAP(display-mode): the real framebuffer size from here on. + ScreenWidth = (uint)Canvas.Width; + ScreenHeight = (uint)Canvas.Height; + + // GEN3-GAP(kernelconsole): no public way to detach or hide the KernelConsole, which draws on this + // same canvas; redirecting Console.Out/Error keeps it from painting over the GUI. + GuiSink = new SerialTextWriter(); + global::System.Console.SetOut(GuiSink); + global::System.Console.SetError(GuiSink); + + Canvas.DrawImage(AuraLogoWhite, (Canvas.Width - AuraLogoWhite.Width) / 2, (Canvas.Height - AuraLogoWhite.Height) / 2); + Present(); CustomConsole.BootConsole = new(0, 0, (int)ScreenWidth, (int)ScreenHeight); CustomConsole.BootConsole.DrawBackground = false; - TextmodeConsole = null; - ResourceManager = new ResourceManager(); ResourceManager.Initialize(); @@ -200,31 +256,34 @@ public static void BeforeRun() ApplicationManager = new ApplicationManager(); ApplicationManager.Initialize(); + // The Explorer constructor (LoginScreen.Hide()) writes MouseManager.FocusedComponent: + // construct the input managers first (a null dereference is a fatal #PF in gen3). + MouseManager = new System.Input.MouseManager(); + KeyboardManager = new System.Input.KeyboardManager(); + Explorer = new Explorer(); Explorer.Initialize(); - MouseManager = new System.Input.MouseManager(); + // Process order stays Explorer -> Mouse (cursor drawn on top) -> Keyboard. MouseManager.Initialize(); - - KeyboardManager = new System.Input.KeyboardManager(); KeyboardManager.Initialize(); - //Load Localization - CustomConsole.WriteLineInfo("Initializing localization..."); - Encoding.RegisterProvider(CosmosEncodingProvider.Instance); - - CustomConsole.WriteLineInfo("Initializing ASCII encoding..."); - global::System.Console.InputEncoding = Encoding.ASCII; - global::System.Console.OutputEncoding = Encoding.ASCII; + if (!string.IsNullOrEmpty(ComputerName)) + { + Cosmos.Kernel.System.Network.Config.DnsConfig.HostName = ComputerName; + } CustomConsole.WriteLineInfo("Try cleaning memory..."); - FreeCount = Heap.Collect(); + FreeCount = MemoryInfo.Collect(); CustomConsole.WriteLineInfo("Cosmos Memory Manager works."); BootTime = Time.MonthString() + "/" + Time.DayString() + "/" + Time.YearString() + ", " + Time.TimeString(true, true, true); CustomConsole.WriteLineOK("Aura Operating System boot sequence done."); + _lastFpsTick = Environment.TickCount64; + _lastCollectTick = _lastFpsTick; + Running = true; } @@ -234,20 +293,27 @@ public static void Run() { try { - if (_deltaT != RTC.Second) + long now = Environment.TickCount64; + + if (now - _lastFpsTick >= 1000) { _fps = _frames; _frames = 0; - _deltaT = RTC.Second; + _lastFpsTick = now; + + // GEN3-GAP(mounts): no hot-plug event, poll once per second. + Volumes.PollHotplug(); } _frames++; - _frameCount++; - if (_frameCount == 4) + // GEN3-GAP(gc-trigger): OrionGC only collects on page-allocator exhaustion. + // 1 Hz, 10 Hz under memory pressure (rate-limited: a collection is stop-the-world). + bool lowMemory = MemoryInfo.FreePages < MemoryInfo.TotalPages / 4; + if (now - _lastCollectTick >= (lowMemory ? 100 : 1000)) { - FreeCount = Heap.Collect(); - _frameCount = 0; + FreeCount = MemoryInfo.Collect(); + _lastCollectTick = now; } ProcessManager.Update(); @@ -260,20 +326,39 @@ public static void Run() Explorer.Screen.DrawString(Debug, font, WhiteColorInt, 2, font.Height * 2); } - Canvas.DrawImage(Explorer.Screen.Bitmap, 0, 0); - Canvas.Display(); + Present(); } catch (Exception ex) { if (ex.InnerException != null) { - Crash.StopKernel(ex.Message, ex.InnerException.Message, "0x00000000", "0"); + Crash.StopKernel(ex.Message, ex.InnerException.Message, "", "0"); } else { - Crash.StopKernel("Fatal dotnet exception occured.", ex.Message, "0x00000000", "0"); + Crash.StopKernel("Fatal dotnet exception occured.", ex.Message, "", "0"); } } } + + /// + /// Shows the frame. Explorer.Screen aliases the canvas back buffer, so this is a single + /// Canvas.Display(); a separate screen bitmap (if any) is blitted first. + /// + public static void Present() + { + if (Canvas == null) + { + // Before BeforeRun acquired the screen (a null dereference is a fatal #PF in gen3). + return; + } + + if (Explorer != null && Explorer.Screen != null && Explorer.Screen.Bitmap != null) + { + Canvas.DrawImage(Explorer.Screen.Bitmap, 0, 0); + } + + Canvas.Display(); + } } } diff --git a/SRC/Aura_OS/Plugs/GCImpl.cs b/SRC/Aura_OS/Plugs/GCImpl.cs new file mode 100644 index 000000000..50ad8f68a --- /dev/null +++ b/SRC/Aura_OS/Plugs/GCImpl.cs @@ -0,0 +1,26 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: System.GC plug (gen3 runtime without a finalizer queue). +* PROGRAMMER(S): Valentin Charbonnier +*/ + +using System; +using Cosmos.Build.API.Attributes; + +namespace Aura_OS.Plugs +{ + // GEN3-GAP(finalizers): Cosmos runs no finalizers (RhSuppressFinalize/RhReRegisterForFinalize are + // no-ops) and Cosmos.Kernel.Core does not export RhWaitForPendingFinalizers (left commented out in + // Runtime/Stdllib.cs). GC.GetTotalMemory, the only public live-heap reading (MemoryInfoApp, + // GEN3-GAP(meminfo)), calls GC.WaitForPendingFinalizers in its body, so the kernel failed to link with + // "undefined symbol: RhWaitForPendingFinalizers". With no finalizer queue there is never anything to + // wait for, so the wait returns at once. Remove this plug once Cosmos exports the symbol. + [Plug(typeof(GC))] + public static class GCImpl + { + [PlugMember] + public static void WaitForPendingFinalizers() + { + } + } +} diff --git a/SRC/Aura_OS/Properties/VersionInfo.cs b/SRC/Aura_OS/Properties/VersionInfo.cs deleted file mode 100644 index 63547c4c4..000000000 --- a/SRC/Aura_OS/Properties/VersionInfo.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Aura_OS -{ - public class VersionInfo - { - public static string revision = "291120241912"; - } -} diff --git a/SRC/Aura_Boot/isoFiles/UI/Fonts/zap-ext-light16.psf b/SRC/Aura_OS/Resources/UI/Fonts/zap-ext-light16.psf similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Fonts/zap-ext-light16.psf rename to SRC/Aura_OS/Resources/UI/Fonts/zap-ext-light16.psf diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/AuraLogo.bmp b/SRC/Aura_OS/Resources/UI/Images/AuraLogo.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/AuraLogo.bmp rename to SRC/Aura_OS/Resources/UI/Images/AuraLogo.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/AuraLogoWhite.bmp b/SRC/Aura_OS/Resources/UI/Images/AuraLogoWhite.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/AuraLogoWhite.bmp rename to SRC/Aura_OS/Resources/UI/Images/AuraLogoWhite.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/CosmosLogo.bmp b/SRC/Aura_OS/Resources/UI/Images/CosmosLogo.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/CosmosLogo.bmp rename to SRC/Aura_OS/Resources/UI/Images/CosmosLogo.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/close.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/16/close.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/close.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/16/close.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/drive-readonly.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/16/drive-readonly.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/drive-readonly.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/16/drive-readonly.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/drive.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/16/drive.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/drive.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/16/drive.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/explorer.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/16/explorer.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/explorer.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/16/explorer.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/minimize.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/16/minimize.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/minimize.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/16/minimize.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/network-idle.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/16/network-idle.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/network-idle.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/16/network-idle.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/network-offline.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/16/network-offline.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/network-offline.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/16/network-offline.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/network-transmit.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/16/network-transmit.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/network-transmit.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/16/network-transmit.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/program.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/16/program.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/program.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/16/program.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/settings.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/16/settings.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/settings.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/16/settings.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/terminal.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/16/terminal.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/terminal.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/16/terminal.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/up.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/16/up.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/16/up.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/16/up.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/explorer.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/24/explorer.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/explorer.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/24/explorer.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/logout.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/24/logout.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/logout.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/24/logout.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/program.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/24/program.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/program.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/24/program.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/reboot.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/24/reboot.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/reboot.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/24/reboot.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/settings.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/24/settings.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/settings.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/24/settings.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/shutdown.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/24/shutdown.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/shutdown.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/24/shutdown.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/terminal.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/24/terminal.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/24/terminal.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/24/terminal.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/32/dialog-error.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/32/dialog-error.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/32/dialog-error.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/32/dialog-error.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/32/dialog-information.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/32/dialog-information.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/32/dialog-information.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/32/dialog-information.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/32/file.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/32/file.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/32/file.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/32/file.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/32/folder.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/32/folder.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/32/folder.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/32/folder.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/cursor.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/cursor.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/cursor.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/cursor.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/grab.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/grab.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/grab.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/grab.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/resize-horizontal.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/resize-horizontal.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/resize-horizontal.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/resize-horizontal.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/resize-vertical.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/resize-vertical.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/resize-vertical.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/resize-vertical.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/Icons/start.bmp b/SRC/Aura_OS/Resources/UI/Images/Icons/start.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/Icons/start.bmp rename to SRC/Aura_OS/Resources/UI/Images/Icons/start.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Images/aura.bmp b/SRC/Aura_OS/Resources/UI/Images/aura.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Images/aura.bmp rename to SRC/Aura_OS/Resources/UI/Images/aura.bmp diff --git a/SRC/Aura_Boot/isoFiles/UI/Themes/Suave.skin.xml b/SRC/Aura_OS/Resources/UI/Themes/Suave.skin.xml similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Themes/Suave.skin.xml rename to SRC/Aura_OS/Resources/UI/Themes/Suave.skin.xml diff --git a/SRC/Aura_Boot/isoFiles/UI/Themes/SuaveSheet.bmp b/SRC/Aura_OS/Resources/UI/Themes/SuaveSheet.bmp similarity index 100% rename from SRC/Aura_Boot/isoFiles/UI/Themes/SuaveSheet.bmp rename to SRC/Aura_OS/Resources/UI/Themes/SuaveSheet.bmp diff --git a/SRC/Aura_OS/System/Compression/ZipStorer.cs b/SRC/Aura_OS/System/Compression/ZipStorer.cs index 1fc8a19a1..396bd823a 100644 --- a/SRC/Aura_OS/System/Compression/ZipStorer.cs +++ b/SRC/Aura_OS/System/Compression/ZipStorer.cs @@ -1,12 +1,15 @@ // ZipStorer, by Jaime Olivares // Website: http://github.com/jaime-olivares/zipstorer +// Inside `namespace Aura_OS.System.*` the bare identifier `System` binds to `Aura_OS.System`: +// never write `System.X` in the body, use these usings. using Ionic.Zlib; using System; using System.Collections.Generic; +using System.IO; using System.Text; -namespace System.IO.Compression +namespace Aura_OS.System.Compression { /// /// Unique class for compression/decompression file. Represents a Zip file. @@ -213,7 +216,7 @@ public static ZipStorer Open(Stream _stream, FileAccess _access, bool _leaveOpen if (!_leaveOpen) zip.Close(); - throw new System.IO.InvalidDataException(); + throw new InvalidDataException(); } /// @@ -228,10 +231,34 @@ public ZipFileEntry AddFile(Compression _method, string _pathname, string _filen if (Access == FileAccess.Read) throw new InvalidOperationException("Writing is not alowed"); - using (var stream = new FileStream(_pathname, FileMode.Open, FileAccess.Read)) + // GEN3-GAP(fat-time): FAT timestamps are always 0 (1970) and a DOS date cannot hold a year + // before 1980, so fall back to the current time. + DateTime modTime = File.GetLastWriteTime(_pathname); + if (modTime.Year < 1980) + modTime = DateTime.Now; + if (modTime.Year < 1980) + modTime = new DateTime(1980, 1, 1); + + // GEN3-GAP(finally): `using` does not dispose when an exception unwinds, close explicitly. + var stream = new FileStream(_pathname, FileMode.Open, FileAccess.Read); + ZipFileEntry entry = null; + Exception error = null; + + try + { + entry = this.AddStream(_method, _filenameInZip, stream, modTime, _comment); + } + catch (Exception e) { - return this.AddStream(_method, _filenameInZip, stream, File.GetLastWriteTime(_pathname), _comment); + error = e; } + + stream.Dispose(); + + if (error != null) + throw error; + + return entry; } /// @@ -332,33 +359,61 @@ public void AddDirectory(Compression _method, string _pathname, string _pathname /// This is a required step, unless automatic dispose is used public void Close() { - if (this.Access != FileAccess.Read) - { - uint centralOffset = (uint)this.ZipFileStream.Position; - uint centralSize = 0; + // Already closed: a null dereference halts the gen3 kernel. + if (this.ZipFileStream == null) + return; - if (this.CentralDirImage != null) - this.ZipFileStream.Write(CentralDirImage, 0, CentralDirImage.Length); + Exception error = null; - for (int i = 0; i < Files.Count; i++) + try + { + if (this.Access != FileAccess.Read) { - long pos = this.ZipFileStream.Position; - this.WriteCentralDirRecord(Files[i]); - centralSize += (uint)(this.ZipFileStream.Position - pos); + uint centralOffset = (uint)this.ZipFileStream.Position; + uint centralSize = 0; + + if (this.CentralDirImage != null) + this.ZipFileStream.Write(CentralDirImage, 0, CentralDirImage.Length); + + for (int i = 0; i < Files.Count; i++) + { + long pos = this.ZipFileStream.Position; + this.WriteCentralDirRecord(Files[i]); + centralSize += (uint)(this.ZipFileStream.Position - pos); + } + + if (this.CentralDirImage != null) + this.WriteEndRecord(centralSize + (uint)CentralDirImage.Length, centralOffset); + else + this.WriteEndRecord(centralSize, centralOffset); } - if (this.CentralDirImage != null) - this.WriteEndRecord(centralSize + (uint)CentralDirImage.Length, centralOffset); - else - this.WriteEndRecord(centralSize, centralOffset); + if (!this.leaveOpen) + this.ZipFileStream.Flush(); + } + catch (Exception e) + { + error = e; } - if (this.ZipFileStream != null && !this.leaveOpen) + // GEN3-GAP(finally)/GEN3-GAP(finalizers): release the file descriptor on every path. + if (!this.leaveOpen) { - this.ZipFileStream.Flush(); - this.ZipFileStream.Dispose(); + try + { + this.ZipFileStream.Dispose(); + } + catch (Exception e) + { + if (error == null) + error = e; + } + this.ZipFileStream = null; } + + if (error != null) + throw error; } /// @@ -442,11 +497,34 @@ public bool ExtractFile(ZipFileEntry _zfe, string _filename) if (Directory.Exists(_filename)) return true; - bool result; - using (var output = new FileStream(_filename, FileMode.Create, FileAccess.Write)) + // GEN3-GAP(finally): `using` does not dispose when an exception unwinds, close explicitly. + // bufferSize 1 disables the FileStream buffer, so Dispose has nothing left to flush and + // always releases the descriptor (a failing flush inside Dispose would skip its finally). + bool result = false; + Exception error = null; + var output = new FileStream(_filename, FileMode.Create, FileAccess.Write, FileShare.Read, 1); + + try { result = this.ExtractFile(_zfe, output); } + catch (Exception e) + { + error = e; + } + + try + { + output.Dispose(); + } + catch (Exception e) + { + if (error == null) + error = e; + } + + if (error != null) + throw error; return result; } @@ -499,6 +577,16 @@ private bool ExtractFileAsync(ZipFileEntry _zfe, Stream _stream) while (bytesPending > 0) { int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length)); + + // Truncated or corrupt archive: stop instead of spinning forever on the UI thread. + if (bytesRead <= 0) + { + if (_zfe.Method == Compression.Deflate) + inStream.Dispose(); + + return false; + } + _stream.Write(buffer, 0, bytesRead); bytesPending -= (uint)bytesRead; @@ -544,19 +632,23 @@ public bool ExtractFile(ZipFileEntry _zfe, out byte[] _file) /// This method only works for storage of type FileStream public static bool RemoveEntries(ref ZipStorer _zip, List _zfes) { - if (!(_zip.ZipFileStream is FileStream)) + if (!(_zip.ZipFileStream is FileStream) || string.IsNullOrEmpty(_zip.FileName)) throw new InvalidOperationException("RemoveEntries is allowed just over streams of type FileStream"); //Get full list of entries var fullList = _zip.ReadCentralDir(); //In order to delete we need to create a copy of the zip file excluding the selected items - var tempZipName = Path.GetTempFileName(); - var tempEntryName = Path.GetTempFileName(); + // GEN3-GAP(tmp): Path.GetTempFileName is unplugged and there is no /tmp, so the temporary + // files sit next to the archive, on the same volume. + var tempZipName = _zip.FileName + ".tmp"; + var tempEntryName = _zip.FileName + ".entry.tmp"; + ZipStorer tempZip = null; + bool result = true; try { - var tempZip = ZipStorer.Create(tempZipName, string.Empty); + tempZip = ZipStorer.Create(tempZipName, string.Empty); foreach (ZipFileEntry zfe in fullList) { @@ -571,6 +663,7 @@ public static bool RemoveEntries(ref ZipStorer _zip, List _zfes) _zip.Close(); tempZip.Close(); + tempZip = null; File.Delete(_zip.FileName); File.Move(tempZipName, _zip.FileName); @@ -579,16 +672,34 @@ public static bool RemoveEntries(ref ZipStorer _zip, List _zfes) } catch { - return false; + result = false; } - finally + + // GEN3-GAP(finally): this cleanup used to sit in a finally block, which gen3 skips when an + // exception unwinds. + if (tempZip != null) + { + try + { + tempZip.Close(); + } + catch (Exception) + { + } + } + + try { if (File.Exists(tempZipName)) File.Delete(tempZipName); if (File.Exists(tempEntryName)) File.Delete(tempEntryName); } - return true; + catch (Exception) + { + } + + return result; } #endregion diff --git a/SRC/Aura_OS/System/Filesystem/AuraPath.cs b/SRC/Aura_OS/System/Filesystem/AuraPath.cs new file mode 100644 index 000000000..2c3f4931a --- /dev/null +++ b/SRC/Aura_OS/System/Filesystem/AuraPath.cs @@ -0,0 +1,154 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: Path helpers: gen3 Unix paths (/N/...), gen2 DOS input (N:\...), system paths +* PROGRAMMERS: Valentin Charbonnier +*/ + +using System; +using System.IO; + +namespace Aura_OS.System.Filesystem +{ + /// + /// Path helpers. The N-th FAT volume is mounted at /N, so gen2 "N:\a\b" is gen3 "/N/a/b"; + /// "/" is the virtual root listing the volumes. + /// + public static class AuraPath + { + public const char Separator = '/'; + + /// + /// gen2 "0:\a\b" -> AuraPaths.SystemVolume (or "/0/") + "a/b"; "N:\x" -> "/N/x"; any '\' -> '/'. + /// For settings.ini values written by gen2 installs and for DOS-style user input. null/"" unchanged. + /// + public static string FromLegacy(string path) + { + if (string.IsNullOrEmpty(path)) + { + return path; + } + + int colon = path.IndexOf(':'); + if (colon > 0 && IsDigits(path, colon)) + { + string drive = path.Substring(0, colon); + string rest = path.Substring(colon + 1).TrimStart('\\', '/'); + + // gen2 0:\ was by construction the volume holding System\settings.ini. + string root = drive == "0" ? (AuraPaths.SystemVolume ?? "/0/") : "/" + drive + "/"; + + path = root + rest; + } + + return path.Replace('\\', Separator); + } + + /// + /// Absolute, normalised path for any user/argument input: legacy conversion, then anchored at + /// Kernel.CurrentDirectory when relative, then Path.GetFullPath ("." and ".." collapsed). + /// "" or null -> Kernel.CurrentDirectory. + /// + public static string Resolve(string input) + { + string current = AsDirectory(Kernel.CurrentDirectory); + string path = FromLegacy(input ?? string.Empty); + + if (path.Length == 0) + { + return current; + } + + if (path[0] != Separator) + { + path = current + path; + } + + try + { + return Path.GetFullPath(path); // rooted input: pure string operation + } + catch (Exception) + { + return path; + } + } + + /// + /// Ensures a trailing '/' ("/0/Users" -> "/0/Users/"). null or "" -> "/". + /// + public static string AsDirectory(string path) + { + if (string.IsNullOrEmpty(path)) + { + return "/"; + } + + return path[path.Length - 1] == Separator ? path : path + Separator; + } + + /// + /// False for an empty name or one containing / \ : * ? " < > | + /// GEN3-GAP(fat-names): the FAT driver accepts any character in long names. + /// + public static bool IsValidName(string name) + { + if (string.IsNullOrEmpty(name)) + { + return false; + } + + for (int i = 0; i < name.Length; i++) + { + switch (name[i]) + { + case '/': + case '\\': + case ':': + case '*': + case '?': + case '"': + case '<': + case '>': + case '|': + return false; + } + } + + return true; + } + + private static bool IsDigits(string s, int end) + { + for (int i = 0; i < end; i++) + { + if (!char.IsDigit(s[i])) + { + return false; + } + } + + return true; + } + } + + /// + /// System paths. Always end with '/' for directories. + /// + public static class AuraPaths + { + /// + /// "/N/" holding System/settings.ini, else "/0/" if mounted, else null (live mode). Set by Volumes. + /// + public static string SystemVolume { get; internal set; } + + public static string SystemDir => (SystemVolume ?? "/0/") + "System/"; + public static string SettingsIni => SystemDir + "settings.ini"; + public static string Passwd => SystemDir + "passwd"; + public static string ProgramsDir => SystemDir + "Programs/"; + public static string ThemesDir => SystemDir + "Themes/"; + public static string WallpapersDir => SystemDir + "Wallpapers/"; + public static string UsersDir => (SystemVolume ?? "/0/") + "Users/"; + + public static string NetworkIni(string alias) => SystemDir + alias + ".ini"; + } +} diff --git a/SRC/Aura_OS/System/Filesystem/CurrentPath.cs b/SRC/Aura_OS/System/Filesystem/CurrentPath.cs index ae09d3a16..8c1329c55 100644 --- a/SRC/Aura_OS/System/Filesystem/CurrentPath.cs +++ b/SRC/Aura_OS/System/Filesystem/CurrentPath.cs @@ -4,59 +4,54 @@ * PROGRAMMERS: Valentin Charbonnier */ +using Cosmos.Kernel.System.Vfs; using System.IO; namespace Aura_OS.System.Filesystem { public class CurrentPath { + /// + /// Changes Kernel.CurrentDirectory (and Kernel.CurrentVolume to the volume holding it). + /// Accepts "~", relative paths, "..", absolute paths ("/1/Docs") and gen2 input ("1:\Docs"). + /// ".." at a volume root goes to "/", the volume list. + /// public static bool Set(string dir, out string error) { - if (dir == "..") - { - Directory.SetCurrentDirectory(Kernel.CurrentDirectory); - - var root = Kernel.VirtualFileSystem.GetDirectory(Kernel.CurrentDirectory); + string target; - if (Kernel.CurrentDirectory != Kernel.CurrentVolume) - { - Kernel.CurrentDirectory = root.mParent.mFullPath; - } - } - else if (dir == "~") + if (dir == "~") { - if (Directory.Exists(Kernel.UserDirectory)) - { - Directory.SetCurrentDirectory(Kernel.CurrentDirectory); - Kernel.CurrentDirectory = Kernel.UserDirectory; - } - else + if (string.IsNullOrEmpty(Kernel.UserDirectory) || !Directory.Exists(Kernel.UserDirectory)) { error = "No user directory found."; return false; } + + target = Kernel.UserDirectory; } - else if (dir == Kernel.CurrentVolume) + else { - Kernel.CurrentDirectory = Kernel.CurrentVolume; + target = AuraPath.Resolve(dir); + } + + if (Directory.Exists(target)) + { + // The Kernel.CurrentDirectory setter also syncs Directory.SetCurrentDirectory. + Kernel.CurrentDirectory = AuraPath.AsDirectory(target); + + VfsManager.VfsMount mount = Volumes.MountOf(target); + Kernel.CurrentVolume = AuraPath.AsDirectory(mount != null ? mount.MountPoint : "/"); + } + else if (File.Exists(target)) + { + error = "This is a file."; + return false; } else { - if (Directory.Exists(Kernel.CurrentDirectory + dir)) - { - Directory.SetCurrentDirectory(Kernel.CurrentDirectory); - Kernel.CurrentDirectory = Kernel.CurrentDirectory + dir + @"\"; - } - else if (File.Exists(Kernel.CurrentDirectory + dir)) - { - error = "This is a file."; - return false; - } - else - { - error = "This directory doesn't exist!"; - return false; - } + error = "This directory doesn't exist!"; + return false; } error = "none"; diff --git a/SRC/Aura_OS/System/Filesystem/Entries.cs b/SRC/Aura_OS/System/Filesystem/Entries.cs index c021c8023..2f25bcbad 100644 --- a/SRC/Aura_OS/System/Filesystem/Entries.cs +++ b/SRC/Aura_OS/System/Filesystem/Entries.cs @@ -5,6 +5,7 @@ */ using Aura_OS.System.Processing.Interpreter.Commands; +using Cosmos.Kernel.System.Vfs; using System; using System.IO; @@ -14,6 +15,13 @@ public class Entries { public static bool ForceRemove(string fullPath) { + // Never delete a volume (/N) or the volume list (/): a recursive delete would empty it. + if (IsMountPoint(fullPath)) + { + Console.WriteLine("Cannot remove a volume!"); + return false; + } + if (File.Exists(fullPath)) { File.Delete(fullPath); @@ -35,11 +43,35 @@ public static bool ForceCopy(string sourcePath, string destPath) { if (File.Exists(sourcePath)) { - File.Copy(sourcePath, destPath, overwrite: true); + // A folder as destination (cp a.txt /0/Docs, Explorer "Paste"): copy into it. + if (Directory.Exists(destPath)) + { + destPath = Path.Combine(destPath, Path.GetFileName(sourcePath)); + } + + if (IsSamePath(sourcePath, destPath)) + { + Console.WriteLine("Source and destination are the same file!"); + return false; + } + + CopyFileContent(sourcePath, destPath); return true; } else if (Directory.Exists(sourcePath)) { + if (Directory.Exists(destPath)) + { + destPath = Path.Combine(destPath, Path.GetFileName(sourcePath.TrimEnd('/'))); + } + + // Copying a folder into itself would recurse forever. + if (IsSamePath(sourcePath, destPath) || IsUnder(destPath, sourcePath)) + { + Console.WriteLine("Cannot copy a directory into itself!"); + return false; + } + Entries.CopyDirectory(sourcePath, destPath); return true; } @@ -52,14 +84,38 @@ public static bool ForceCopy(string sourcePath, string destPath) public static void SaveFile(string sourcePath, byte[] file) { - File.WriteAllBytes(sourcePath, file); + if (file == null) + { + throw new ArgumentNullException(nameof(file)); + } + + // GEN3-GAP(finally): the stream is disposed explicitly on every path (see CopyFileContent). + FileStream stream = null; + Exception error = null; + + try + { + stream = new FileStream(sourcePath, FileMode.Create, FileAccess.Write, FileShare.Read, UnbufferedSize); + stream.Write(file, 0, file.Length); + } + catch (Exception ex) + { + error = ex; + } + + CloseStream(stream, ref error); + + if (error != null) + { + throw error; + } } public static void CopyFile(string sourcePath, string destPath) { - if (File.Exists(sourcePath)) + if (File.Exists(sourcePath) && !IsSamePath(sourcePath, destPath)) { - File.Copy(sourcePath, destPath, overwrite: true); + CopyFileContent(sourcePath, destPath); } } @@ -67,10 +123,18 @@ public static void CopyDirectory(string sourceDir, string destDir) { Directory.CreateDirectory(destDir); + // gen3 returns full paths: keep only the names. foreach (var file in Directory.GetFiles(sourceDir)) { string dest = Path.Combine(destDir, Path.GetFileName(file)); - File.Copy(file, dest); + + // Same as the gen2 File.Copy(file, dest) without overwrite. + if (File.Exists(dest)) + { + throw new IOException("The file '" + dest + "' already exists."); + } + + CopyFileContent(file, dest); } foreach (var directory in Directory.GetDirectories(sourceDir)) @@ -79,5 +143,109 @@ public static void CopyDirectory(string sourceDir, string destDir) CopyDirectory(directory, dest); } } + + // bufferSize 1 disables the FileStream buffer: every Write goes straight to the file, so + // Dispose has nothing left to flush and always releases the descriptor. + private const int UnbufferedSize = 1; + + /// + /// Overwriting file copy. GEN3-GAP(finally): `using`/`finally` do not run when an exception + /// unwinds, and GEN3-GAP(finalizers): there are no finalizers and only 64 descriptors, so the + /// streams are opened and disposed here explicitly, on every path, then the error is rethrown. + /// + private static void CopyFileContent(string sourcePath, string destPath) + { + FileStream source = null; + FileStream dest = null; + Exception error = null; + + try + { + source = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read, UnbufferedSize); + dest = new FileStream(destPath, FileMode.Create, FileAccess.Write, FileShare.Read, UnbufferedSize); + + byte[] buffer = new byte[16384]; + int read; + + while ((read = source.Read(buffer, 0, buffer.Length)) > 0) + { + dest.Write(buffer, 0, read); + } + } + catch (Exception ex) + { + error = ex; + } + + CloseStream(dest, ref error); + CloseStream(source, ref error); + + if (error != null) + { + throw error; + } + } + + private static void CloseStream(FileStream stream, ref Exception error) + { + if (stream == null) + { + return; + } + + try + { + stream.Dispose(); + } + catch (Exception ex) + { + if (error == null) + { + error = ex; + } + } + } + + private static string Normalize(string path) + { + if (string.IsNullOrEmpty(path)) + { + return string.Empty; + } + + try + { + path = Path.GetFullPath(path); + } + catch (Exception) + { + } + + return path.Length > 1 ? path.TrimEnd('/') : path; + } + + private static bool IsMountPoint(string path) + { + string normalized = Normalize(path); + if (normalized == "/") + { + return true; + } + + VfsManager.VfsMount mount; + return normalized.Length > 0 && VfsManager.TryGetMount(normalized, out mount); + } + + // FAT names are case-insensitive, so compare paths the same way. + private static bool IsSamePath(string a, string b) + { + return string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase); + } + + private static bool IsUnder(string path, string directory) + { + string parent = AuraPath.AsDirectory(Normalize(directory)); + return AuraPath.AsDirectory(Normalize(path)).StartsWith(parent, StringComparison.OrdinalIgnoreCase); + } } } diff --git a/SRC/Aura_OS/System/Filesystem/Utils.cs b/SRC/Aura_OS/System/Filesystem/Utils.cs index 35e39724f..e9ab8acd7 100644 --- a/SRC/Aura_OS/System/Filesystem/Utils.cs +++ b/SRC/Aura_OS/System/Filesystem/Utils.cs @@ -4,48 +4,101 @@ * PROGRAMMERS: Valentin Charbonnier */ +using Cosmos.Kernel.System.Vfs; +using System; using System.IO; namespace Aura_OS.System.Filesystem { public class Utils { + /// + /// Parent directory, always ending with '/': "/0/Users/bob/" -> "/0/Users/", "/0/" -> "/" (volume list), + /// "/" -> "/". + /// public static string GetParentPath(string path) { if (string.IsNullOrEmpty(path)) { return path; } - if (path.EndsWith(Path.DirectorySeparatorChar.ToString())) + + string trimmed = path.TrimEnd(AuraPath.Separator); + if (trimmed.Length == 0) { - path = path.TrimEnd(Path.DirectorySeparatorChar); + return "/"; } - int lastSeparatorIndex = path.LastIndexOf(Path.DirectorySeparatorChar); - if (lastSeparatorIndex <= 0) + string parent = Path.GetDirectoryName(trimmed); + if (parent == null) { - return path + "\\"; + return "/"; } - if (lastSeparatorIndex == 2 && path[1] == ':') + if (parent.Length == 0) { - return path.Substring(0, lastSeparatorIndex + 1); + return trimmed + AuraPath.Separator; } - return path.Substring(0, lastSeparatorIndex) + "\\"; + return AuraPath.AsDirectory(parent); } public static string GetFreeSpace() { - var available_space = Kernel.VirtualFileSystem.GetAvailableFreeSpace(Kernel.CurrentVolume); - return ConvertSize(available_space); + ulong freeBytes, totalBytes; + TryGetCurrentVolumeSpace(out freeBytes, out totalBytes); + return ConvertSize(freeBytes); } public static string GetCapacity() { - var total_size = Kernel.VirtualFileSystem.GetTotalSize(Kernel.CurrentVolume); - return ConvertSize(total_size); + ulong freeBytes, totalBytes; + TryGetCurrentVolumeSpace(out freeBytes, out totalBytes); + return ConvertSize(totalBytes); + } + + // GEN3-GAP(driveinfo): TryStatFs sweeps the whole FAT on every call, so the result is cached + // per mount point for a few seconds. + private const long SpaceCacheMs = 5000; + private static string _spaceMountPoint; + private static long _spaceTick; + private static ulong _spaceFree; + private static ulong _spaceTotal; + + private static bool TryGetCurrentVolumeSpace(out ulong freeBytes, out ulong totalBytes) + { + freeBytes = 0; + totalBytes = 0; + + // null in live mode (no FAT volume, Kernel.CurrentVolume == "/"). + VfsManager.VfsMount mount = Volumes.MountOf(Kernel.CurrentVolume); + if (mount == null) + { + return false; + } + + string mountPoint = mount.MountPoint; + long now = Environment.TickCount64; + + if (_spaceMountPoint != null && _spaceMountPoint == mountPoint && now - _spaceTick < SpaceCacheMs) + { + freeBytes = _spaceFree; + totalBytes = _spaceTotal; + return true; + } + + if (!Volumes.TryGetSpace(mountPoint, out freeBytes, out totalBytes)) + { + _spaceMountPoint = null; + return false; + } + + _spaceMountPoint = mountPoint; + _spaceTick = now; + _spaceFree = freeBytes; + _spaceTotal = totalBytes; + return true; } - public static string ConvertSize(long bytes) + public static string ConvertSize(ulong bytes) { string suffix = " Bytes"; double size = bytes; diff --git a/SRC/Aura_OS/System/Filesystem/Volumes.cs b/SRC/Aura_OS/System/Filesystem/Volumes.cs new file mode 100644 index 000000000..1dec960b0 --- /dev/null +++ b/SRC/Aura_OS/System/Filesystem/Volumes.cs @@ -0,0 +1,330 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: Volumes: FAT driver registration, /N mounts, hot-plug, free space +* PROGRAMMERS: Valentin Charbonnier +*/ + +// File-scope usings resolve from the global namespace. Inside `namespace Aura_OS.System.*` the bare +// identifier `System` binds to `Aura_OS.System`, so never write `System.IO.X` in the body. +using System; +using System.Collections.Generic; +using System.IO; +using Cosmos.Kernel.HAL.Vfs; +using Cosmos.Kernel.System; +using Cosmos.Kernel.System.Diagnostics; +using Cosmos.Kernel.System.Filesystems.Fat; +using Cosmos.Kernel.System.Storage; +using Cosmos.Kernel.System.Vfs; + +namespace Aura_OS.System.Filesystem +{ + /// + /// Mounts every FAT partition at /0, /1, ... (gen2 "0:\", "1:\"). Nothing is mounted at "/": + /// the root lists the mount points. + /// + public static class Volumes + { + public const string FatDriver = "fat"; + + // static readonly, NOT const: a const of an enum type from another assembly makes + // Mono.Cecil resolve that assembly while the patcher rewrites this one. + private static readonly MountFlags s_flags = MountFlags.None; + + // Last StorageManager.Partitions snapshot seen by MountAll (replaced whole on every change). + private static IReadOnlyList s_lastPartitions; + + /// + /// Registers the FAT driver and mounts every FAT partition. Picks AuraPaths.SystemVolume. + /// + public static void Initialize() + { + if (!KernelFeatures.Fat) + { + Log.WriteString("[Aura] FAT support compiled out, no volume mounted\n"); + RefreshSystemVolume(); + return; + } + + if (!VfsManager.RegisterFilesystem(FatDriver, new FatFilesystemType())) + { + Log.WriteString("[Aura] FAT driver already registered or invalid\n"); + } + + MountAll(); + } + + /// + /// Mounts every FAT partition not mounted yet at the next free /N (gen2 numbering). + /// Returns the number of new mounts. Recomputes AuraPaths.SystemVolume. + /// + public static int MountAll() + { + int mounted = 0; + + IReadOnlyList partitions = StorageManager.Partitions; // snapshot; USB can change it + s_lastPartitions = partitions; + + for (int i = 0; i < partitions.Count; i++) + { + Partition partition = partitions[i]; + if (partition == null || IsMounted(partition)) + { + continue; + } + + // TryMount returns false when the partition is not FAT, but the BPB probe's ReadBlock + // can THROW on a device error (e.g. an NVMe timeout), so guard it. + try + { + string mountPoint = NextFreeMountPoint(); + if (VfsManager.TryMount(FatDriver, partition, s_flags, mountPoint, out _)) + { + mounted++; + Log.WriteString("[Aura] FAT volume " + partition.Name + " mounted at " + mountPoint + "\n"); + } + } + catch (Exception) + { + Log.WriteString("[Aura] cannot mount partition " + partition.Name + "\n"); + } + } + + RefreshSystemVolume(); + + return mounted; + } + + /// + /// By location (Host + StartSector), never by reference: RescanPartitions creates new Partition objects. + /// + public static bool IsMounted(Partition partition) + { + if (partition == null) + { + return false; + } + + IReadOnlyList mounts = VfsManager.Mounts; + for (int i = 0; i < mounts.Count; i++) + { + Partition p = mounts[i].Partition; + if (p != null && ReferenceEquals(p.Host, partition.Host) && p.StartSector == partition.StartSector) + { + return true; + } + } + + return false; + } + + /// + /// Longest-prefix mount covering an absolute path ("/0/Users/" -> the /0 mount), null if none + /// (live mode, or "/"). + /// + public static VfsManager.VfsMount MountOf(string fullPath) + { + if (string.IsNullOrEmpty(fullPath)) + { + return null; + } + + VfsManager.VfsMount best = null; + IReadOnlyList mounts = VfsManager.Mounts; + for (int i = 0; i < mounts.Count; i++) + { + VfsManager.VfsMount m = mounts[i]; + string mp = m.MountPoint; + bool covers = mp == "/" || (fullPath.StartsWith(mp, StringComparison.Ordinal) + && (fullPath.Length == mp.Length || fullPath[mp.Length] == '/')); + if (covers && (best == null || mp.Length > best.MountPoint.Length)) + { + best = m; + } + } + + return best; + } + + /// + /// Free and total bytes of the volume mounted at mountPoint ("/0" or "/0/"). + /// GEN3-GAP(driveinfo): TryStatFs sweeps the whole FAT on every call, callers must cache the result. + /// + public static bool TryGetSpace(string mountPoint, out ulong freeBytes, out ulong totalBytes) + { + freeBytes = 0; + totalBytes = 0; + + if (string.IsNullOrEmpty(mountPoint)) + { + return false; + } + + try + { + VfsStatFs stats; + if (!VfsManager.TryStatFs(mountPoint, out stats)) + { + return false; + } + + freeBytes = stats.Bavail * stats.BlockSize; + totalBytes = stats.Blocks * stats.BlockSize; + return true; + } + catch (Exception) + { + freeBytes = 0; + totalBytes = 0; + return false; + } + } + + /// + /// Flushes and detaches every mount (AuraPower calls it before reboot/shutdown). + /// + public static void UnmountAll() + { + IReadOnlyList mounts = VfsManager.Mounts; // snapshot, safe to mutate + for (int i = 0; i < mounts.Count; i++) + { + try + { + VfsManager.TryUnmount(mounts[i].MountPoint); + } + catch (Exception) + { + // The flush failed; the mount is already removed from the table. + } + } + + RefreshSystemVolume(); + } + + /// + /// Call from the UI loop (about once per second). GEN3-GAP(mounts): there is no hot-plug event. + /// When the StorageManager.Partitions snapshot changed, mounts the new FAT partitions (MountAll). + /// Resets Kernel.CurrentVolume/CurrentDirectory when their mount vanished (a pulled USB stick is + /// detached by the VFS). Returns true when something changed. Never throws. + /// + public static bool PollHotplug() + { + bool changed = false; + + try + { + if (!ReferenceEquals(StorageManager.Partitions, s_lastPartitions)) + { + MountAll(); + changed = true; + } + + string volume = Kernel.CurrentVolume; + if (volume != null && volume != "/" && MountOf(volume) == null) + { + RefreshSystemVolume(); + Kernel.CurrentVolume = AuraPaths.SystemVolume ?? "/"; + Kernel.CurrentDirectory = Kernel.CurrentVolume; + changed = true; + } + else + { + string directory = Kernel.CurrentDirectory; + if (directory != null && directory != "/" && MountOf(directory) == null) + { + Kernel.CurrentDirectory = Kernel.CurrentVolume ?? "/"; + changed = true; + } + } + } + catch (Exception) + { + // Never let the UI loop crash on a storage change. + } + + return changed; + } + + /// + /// Recomputes AuraPaths.SystemVolume: the lowest /N holding System/settings.ini, else "/0/" if + /// mounted, else null (live mode). + /// + public static void RefreshSystemVolume() + { + string system = null; + int systemNumber = int.MaxValue; + bool zeroMounted = false; + + IReadOnlyList mounts = VfsManager.Mounts; + for (int i = 0; i < mounts.Count; i++) + { + string volume = AuraPath.AsDirectory(mounts[i].MountPoint); + int number = MountNumber(volume); + + if (volume == "/0/") + { + zeroMounted = true; + } + + if (number >= systemNumber) + { + continue; + } + + try + { + if (File.Exists(volume + "System/settings.ini")) + { + system = volume; + systemNumber = number; + } + } + catch (Exception) + { + // Unreadable volume: not the system volume. + } + } + + if (system == null && zeroMounted) + { + system = "/0/"; + } + + AuraPaths.SystemVolume = system; + } + + private static string NextFreeMountPoint() + { + for (int n = 0; ; n++) + { + string mountPoint = "/" + n.ToString(); + if (!VfsManager.TryGetMount(mountPoint, out _)) // TryMount itself does not check + { + return mountPoint; + } + } + } + + /// + /// N of "/N/", int.MaxValue - 1 for any other mount point. + /// + private static int MountNumber(string volume) + { + int number = 0; + int digits = 0; + + for (int i = 1; i < volume.Length - 1; i++) + { + char c = volume[i]; + if (c < '0' || c > '9' || digits >= 9) + { + return int.MaxValue - 1; + } + + number = number * 10 + (c - '0'); + digits++; + } + + return digits == 0 ? int.MaxValue - 1 : number; + } + } +} diff --git a/SRC/Aura_OS/System/Graphics/ResourceManager.cs b/SRC/Aura_OS/System/Graphics/ResourceManager.cs index 4fa89adec..c3e37aadc 100644 --- a/SRC/Aura_OS/System/Graphics/ResourceManager.cs +++ b/SRC/Aura_OS/System/Graphics/ResourceManager.cs @@ -4,7 +4,7 @@ * PROGRAMMERS: Valentin Charbonnier */ -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; using System.Collections.Generic; namespace Aura_OS.System.Graphics @@ -50,16 +50,15 @@ public void AddIcon(string name, Bitmap icon) /// Thrown when the icon is not found. public Bitmap GetIcon(string key) { - try + Bitmap bitmap; + + if (key != null && _icons != null && _icons.TryGetValue(key, out bitmap)) { - Bitmap bitmap = _icons[key]; return bitmap; } - catch - { - Crash.StopKernel(key + " not found", "Error while getting resource file.", "0x00000000", "0"); - throw; - } + + Crash.StopKernel(key + " not found", "Error while getting resource file.", "0x00000000", "0"); + throw new KeyNotFoundException(key + " not found"); } /// diff --git a/SRC/Aura_OS/System/Graphics/UI/CUI/Console.cs b/SRC/Aura_OS/System/Graphics/UI/CUI/Console.cs deleted file mode 100644 index da5b95948..000000000 --- a/SRC/Aura_OS/System/Graphics/UI/CUI/Console.cs +++ /dev/null @@ -1,214 +0,0 @@ -/* -* PROJECT: Aura Operating System Development -* CONTENT: VGA Console -* PROGRAMMERS: Valentin Charbonnier -* https://github.com/CosmosOS/Cosmos/blob/master/source/Cosmos.System2/Console.cs -*/ - -using System; -using System.Runtime.CompilerServices; -using Aura_OS.System.Graphics.UI; -using Cosmos.HAL; -using Cosmos.System.Graphics; - -namespace Aura_OS.System.Graphics.UI.CUI -{ - - public class Console : UI.Console - { - protected int mX = 0; - public override int X - { - get { return mX; } - set - { - mX = value; - UpdateCursor(); - } - } - - protected int mY = 0; - public override int Y - { - get { return mY; } - set - { - mY = value; - UpdateCursor(); - } - } - - public override int Cols - { - get { return mText.Cols; } - } - - public override int Rows - { - get { return mText.Rows; } - } - - protected TextScreenBase mText; - - public Console(TextScreenBase textScreen) - { - Name = "VGA Textmode"; - Type = ConsoleType.Text; - - //Global.debugger.Send("VGA Textmode Class"); - if (textScreen == null) - { - mText = new TextScreen(); - } - else - { - mText = textScreen; - } - } - - public override void Clear() - { - mText.Clear(); - mX = 0; - mY = 0; - UpdateCursor(); - } - - public override void Clear(uint color) - { - mText.Clear(); - mX = 0; - mY = 0; - UpdateCursor(); - } - - //TODO: This is slow, batch it and only do it at end of updates - public override void UpdateCursor() - { - mText.SetCursorPos(mX, mY); - } - - private void DoLineFeed() - { - mY++; - mX = 0; - if (mY == mText.Rows) - { - mText.ScrollUp(); - mY--; - } - UpdateCursor(); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void DoCarriageReturn() - { - mX = 0; - UpdateCursor(); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void DoTab() - { - Write((byte)Space); - Write((byte)Space); - Write((byte)Space); - Write((byte)Space); - } - - public void Write(byte aChar) - { - mText[mX, mY] = aChar; - mX++; - if (mX == mText.Cols) - { - DoLineFeed(); - } - UpdateCursor(); - } - - public override void Write(char[] aText) - { - //throw new NotImplementedException(); - } - - //TODO: Optimize this - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override void Write(byte[] aText) - { - if (aText == null) - { - return; - } - - for (int i = 0; i < aText.Length; i++) - { - switch (aText[i]) - { - case (byte)LineFeed: - DoLineFeed(); - break; - - case (byte)CarriageReturn: - DoCarriageReturn(); - break; - - case (byte)Tab: - DoTab(); - break; - - /* Normal characters, simply write them */ - default: - Write(aText[i]); - break; - } - } - } - - public override void DrawImage(ushort X, ushort Y, Bitmap image) - { - // Do nothing - } - - public override ConsoleColor Foreground - { - get { return (ConsoleColor)(mText.GetColor() ^ (byte)((byte)Background << 4)); } - set { mText.SetColors(value, Background); } - } - public override ConsoleColor Background - { - get { return (ConsoleColor)(mText.GetColor() >> 4); } - set { mText.SetColors(Foreground, value); } - } - - public override int CursorSize - { - get { return mText.GetCursorSize(); } - set - { - // Value should be a percentage from [1, 100]. - if (value < 1 || value > 100) - throw new ArgumentOutOfRangeException("value", value, "CursorSize value " + value + " out of range (1 - 100)"); - - mText.SetCursorSize(value); - } - } - - public override bool CursorVisible - { - get { return mText.GetCursorVisible(); } - set { mText.SetCursorVisible(value); } - } - - public override int Width - { - get { return 80; } - } - - public override int Height - { - get { return 25; } - } - - } -} \ No newline at end of file diff --git a/SRC/Aura_OS/System/Graphics/UI/Console.cs b/SRC/Aura_OS/System/Graphics/UI/Console.cs deleted file mode 100644 index b51e1f9ad..000000000 --- a/SRC/Aura_OS/System/Graphics/UI/Console.cs +++ /dev/null @@ -1,67 +0,0 @@ -/* -* PROJECT: Aura Operating System Development -* CONTENT: Consoles -* PROGRAMMERS: Valentin Charbonnier -*/ - -using System; -using Cosmos.System.Graphics; - -namespace Aura_OS.System.Graphics.UI -{ - public abstract class Console - { - internal const char LineFeed = '\n'; - internal const char CarriageReturn = '\r'; - internal const char Tab = '\t'; - internal const char Space = ' '; - - public Console() - { - - } - - public bool writecommand = false; - public int commandindex = -1; - public string cmd; - - public string Name; - - public ConsoleType Type; - - public abstract int X { get; set; } - public abstract int Y { get; set; } - - public abstract int Width { get; } - public abstract int Height { get; } - - public abstract int Cols { get; } - public abstract int Rows { get; } - - public abstract void Clear(); - - public abstract void Clear(uint color); - - public abstract void Write(char[] aText); - - public abstract void Write(byte[] aText); - - public abstract void UpdateCursor(); - - public abstract ConsoleColor Foreground { get; set; } - - public abstract ConsoleColor Background { get; set; } - - public abstract int CursorSize { get; set; } - - public abstract bool CursorVisible { get; set; } - - public abstract void DrawImage(ushort X, ushort Y, Bitmap image); - } - - public enum ConsoleType - { - Text, - Graphical - } -} \ No newline at end of file diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Application.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Application.cs index c0bc31e82..0d87fdc39 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Application.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Application.cs @@ -7,7 +7,7 @@ Valentin Charbonnier using System; using System.Drawing; -using Cosmos.System; +using Cosmos.Kernel.System.Mouse; using Aura_OS.Processing; using Aura_OS.System.Graphics.UI.GUI.Components; using Aura_OS.System.Processing.Processes; @@ -465,12 +465,12 @@ public void DrawString(string str, int x, int y) Window.DrawString(str, x + 4, y + Window.TopBar.Height + 6); } - public void DrawString(string str, Cosmos.System.Graphics.Fonts.Font font, Color color, int x, int y) + public void DrawString(string str, Cosmos.Kernel.System.Graphics.Fonts.Font font, Color color, int x, int y) { Window.DrawString(str, font, color, x + 4, y + Window.TopBar.Height + 6); } - public void DrawImage(Cosmos.System.Graphics.Bitmap image, int x, int y) + public void DrawImage(Cosmos.Kernel.System.Graphics.Bitmap image, int x, int y) { Window.DrawImage(image, x + 4, y + Window.TopBar.Height + 6); } diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Button.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Button.cs index 44b48c67c..bc20fecb6 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Button.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Button.cs @@ -4,7 +4,7 @@ * PROGRAMMERS: Valentin Charbonnier */ -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; using System; using System.Drawing; @@ -81,7 +81,7 @@ public override void HandleLeftClick() { if (Click != null) { - if (IsInside((int)Cosmos.System.MouseManager.X, (int)Cosmos.System.MouseManager.Y)) + if (IsInside((int)Cosmos.Kernel.System.Mouse.MouseManager.X, (int)Cosmos.Kernel.System.Mouse.MouseManager.Y)) { Click(); } diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Checkbox.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Checkbox.cs index 6b252a0f8..14b3843ca 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Checkbox.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Checkbox.cs @@ -4,7 +4,7 @@ * PROGRAMMERS: Valentin Charbonnier */ -using Cosmos.System.Graphics.Fonts; +using Cosmos.Kernel.System.Graphics.Fonts; using System; using System.Drawing; diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Component.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Component.cs index 6ea109da8..bdc0aa6df 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Component.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Component.cs @@ -6,9 +6,9 @@ using System.Collections.Generic; using System.Drawing; -using Cosmos.System; -using Cosmos.System.Graphics; -using Cosmos.System.Graphics.Fonts; +using Cosmos.Kernel.System.Mouse; +using Cosmos.Kernel.System.Graphics; +using Cosmos.Kernel.System.Graphics.Fonts; using Aura_OS.System.Graphics.UI.GUI.Skin; using Aura_OS.System.Processing.Processes; using System; @@ -295,7 +295,11 @@ public virtual void HandleLeftClick() { if (entry.IsInside((int)MouseManager.X, (int)MouseManager.Y)) { - entry.Click(); + // GEN3-GAP(null-deref): invoking a null delegate halts the kernel. + if (entry.Click != null) + { + entry.Click(); + } return; } } @@ -533,7 +537,7 @@ public void DrawLine(Color color, int xStart, int yStart, int width, int height) _buffer.DrawLine(color.ToArgb(), xStart, yStart, width, height); } - public void DrawImage(Bitmap image, int x, int y) + public void DrawImage(Image image, int x, int y) { _buffer.DrawImageAlpha(image, x, y); } diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Console.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Console.cs index 36ff0f876..02e9fdcce 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Console.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Console.cs @@ -4,7 +4,6 @@ * PROGRAMMERS: Valentin Charbonnier */ -using Cosmos.System.Graphics; using System; using System.Collections.Generic; using System.Drawing; diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Filesystem.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Filesystem.cs index a9715c13c..2f6119d7a 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Filesystem.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Filesystem.cs @@ -8,8 +8,8 @@ using Aura_OS.System.Processing.Applications; using Aura_OS.System.Processing.Applications.Terminal; using Aura_OS.System.Processing.Processes; -using Cosmos.System; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; +using Cosmos.Kernel.System.Mouse; using System; using System.Collections.Generic; using System.Drawing; @@ -39,16 +39,27 @@ public FilesystemPanel(string path, Color textcolor, int x, int y, int width, in RightClickEntry entry = new("Open in Terminal", RightClick.Width, RightClick); entry.Click = new Action(() => { - Kernel.CurrentDirectory = CurrentPath; + Kernel.CurrentDirectory = AuraPath.AsDirectory(CurrentPath); Kernel.ApplicationManager.StartApplication(typeof(TerminalApp)); }); RightClickEntry entry2 = new("Paste", RightClick.Width, RightClick); entry2.Click = new Action(() => { - if (Kernel.Clipboard != null) + // Nothing can be created in the volume list ("/" is read-only). + if (Kernel.Clipboard != null && !IsVolumeList()) { - Entries.ForceCopy(Kernel.Clipboard, CurrentPath); + // Copies into the folder. ForceCopy throws on I/O errors, and a GUI click must not + // reach the crash screen. + try + { + Entries.ForceCopy(Kernel.Clipboard, CurrentPath); + } + catch (Exception ex) + { + Logs.DoOSLog("[Error] Cannot paste " + Kernel.Clipboard + ": " + ex.Message); + } + RefreshFilesystem(); Kernel.Clipboard = null; } @@ -100,22 +111,49 @@ public void UpdateCurrentFolder() int currentX = startX; int currentY = startY; - string[] directories = Directory.GetDirectories(CurrentPath); - string[] files = Directory.GetFiles(CurrentPath); + // At "/" the entries are the mounted volumes ("/0", "/1"), which cannot be deleted. + bool volumeList = IsVolumeList(); + + string[] directories; + string[] files; + + // GEN3-GAP(mounts): gen2 always had drive 0 mounted. In gen3 the path may be unmounted (no FAT + // disk, live mode, a pulled USB stick): show an empty folder instead of faulting at boot. + if (!string.IsNullOrEmpty(CurrentPath) && Directory.Exists(CurrentPath)) + { + try + { + directories = Directory.GetDirectories(CurrentPath); + files = Directory.GetFiles(CurrentPath); + } + catch (Exception) + { + directories = Array.Empty(); + files = Array.Empty(); + } + } + else + { + directories = Array.Empty(); + files = Array.Empty(); + } _buttons.Clear(); Children.Clear(); foreach (string directory in directories) { + // GetDirectories returns full paths. string folderName = Path.GetFileName(directory); - var button = new FileButton(folderName, _textColor, Kernel.ResourceManager.GetIcon("32-folder.bmp"), 0 + startX + currentX, 0 + currentY, 70, 70); + Bitmap folderIcon = volumeList ? Kernel.ResourceManager.GetIcon("16-drive.bmp") : Kernel.ResourceManager.GetIcon("32-folder.bmp"); + var button = new FileButton(folderName, _textColor, folderIcon, 0 + startX + currentX, 0 + currentY, 70, 70); button.Click = new Action(() => { OpenFolder(folderName); UpdateCurrentFolder(); }); - button.RightClick = new RightClick((int)MouseManager.X, (int)MouseManager.Y, 200, 3 * RightClickEntry.ConstHeight); + int entryCount = volumeList ? 2 : 3; + button.RightClick = new RightClick((int)MouseManager.X, (int)MouseManager.Y, 200, entryCount * RightClickEntry.ConstHeight); RightClickEntry entry = new("Open", button.RightClick.Width, button.RightClick); entry.Click = new Action(() => @@ -126,20 +164,24 @@ public void UpdateCurrentFolder() RightClickEntry entry2 = new("Copy", button.RightClick.Width, button.RightClick); entry2.Click = new Action(() => { - string path = CurrentPath + folderName; + string path = Path.Combine(CurrentPath, folderName); Kernel.Clipboard = path; }); - RightClickEntry entry3 = new("Delete", button.RightClick.Width, button.RightClick); - entry3.Click = new Action(() => - { - Entries.ForceRemove(CurrentPath + folderName); - RefreshFilesystem(); - }); - button.RightClick.AddEntry(entry); button.RightClick.AddEntry(entry2); - button.RightClick.AddEntry(entry3); + + // A volume is never deleted from here. + if (!volumeList) + { + RightClickEntry entry3 = new("Delete", button.RightClick.Width, button.RightClick); + entry3.Click = new Action(() => + { + Delete(Path.Combine(CurrentPath, folderName)); + }); + + button.RightClick.AddEntry(entry3); + } _buttons.Add(button); AddChild(button); @@ -172,15 +214,14 @@ public void UpdateCurrentFolder() RightClickEntry entry2 = new("Copy", button.RightClick.Width, button.RightClick); entry2.Click = new Action(() => { - string path = CurrentPath + fileName; + string path = Path.Combine(CurrentPath, fileName); Kernel.Clipboard = path; }); RightClickEntry entry3 = new("Delete", button.RightClick.Width, button.RightClick); entry3.Click = new Action(() => { - Entries.ForceRemove(CurrentPath + fileName); - RefreshFilesystem(); + Delete(Path.Combine(CurrentPath, fileName)); }); button.RightClick.AddEntry(entry); @@ -204,7 +245,7 @@ public void OpenFolder(string folderName) if (OpenNewWindow) { /* - ExplorerApp app = new(CurrentPath + folderName + "\\", 500, 400, 40, 40); + ExplorerApp app = new(AuraPath.AsDirectory(Path.Combine(CurrentPath, folderName)), 500, 400, 40, 40); app.Initialize(); app.MarkFocused(); app.Visible = true; @@ -217,8 +258,32 @@ public void OpenFolder(string folderName) } else { - CurrentPath = CurrentPath + folderName + "\\"; + CurrentPath = AuraPath.AsDirectory(Path.Combine(CurrentPath, folderName)); + } + } + + /// + /// True when this panel shows the virtual root "/", whose entries are the mounted volumes. + /// + private bool IsVolumeList() + { + return CurrentPath == "/"; + } + + private void Delete(string path) + { + // ForceRemove refuses volumes and throws on I/O errors; a GUI click must not reach the + // crash screen. + try + { + Entries.ForceRemove(path); + } + catch (Exception ex) + { + Logs.DoOSLog("[Error] Cannot delete " + path + ": " + ex.Message); } + + RefreshFilesystem(); } public void RefreshFilesystem() diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/KeyboardLayoutButton.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/KeyboardLayoutButton.cs new file mode 100644 index 000000000..e7dd664f6 --- /dev/null +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/KeyboardLayoutButton.cs @@ -0,0 +1,82 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: Keyboard layout switcher button (taskbar + login screen) +* PROGRAMMER(S): Valentin Charbonnier +*/ + +using System; +using Aura_OS.System.Input; + +namespace Aura_OS.System.Graphics.UI.GUI.Components +{ + /// + /// Keyboard layout switcher: the button face is the active layout code + /// ("US", "FR", ...) and both mouse buttons open a menu listing every layout + /// of KeyboardLayouts. Picking one activates it and saves it in settings.ini. + /// Shared by the taskbar and the login screen; the host adds it to its + /// children and calls Update/Draw like any Button. + /// + public class KeyboardLayoutButton : Button + { + public KeyboardLayoutButton(int x, int y, int width, int height) : base(KeyboardLayouts.CurrentCode, x, y, width, height) + { + // Position is set by HandleRightClick when the menu opens. + RightClick = new RightClick(0, 0, 240, KeyboardLayouts.Codes.Length * RightClickEntry.ConstHeight); + + foreach (string code in KeyboardLayouts.Codes) + { + string layoutCode = code; + + RightClickEntry entry = new(layoutCode + " - " + KeyboardLayouts.GetDisplayName(layoutCode), RightClick.Width, RightClick); + entry.Click = new Action(() => + { + if (KeyboardLayouts.Set(layoutCode)) + { + KeyboardLayouts.Persist(); + SyncText(); + } + }); + RightClick.AddEntry(entry); + } + + // A layout switcher is expected to react to a plain left click too, + // so both buttons open the same menu. + Click = new Action(() => + { + HandleRightClick(); + }); + } + + /// + /// Refreshes the face when the layout was changed elsewhere (setkeyboardmap). + /// + public override void Update() + { + base.Update(); + + if (Text != KeyboardLayouts.CurrentCode) + { + SyncText(); + } + } + + public override void Draw() + { + // Stays in sync when the layout is changed elsewhere (setkeyboardmap). + Text = KeyboardLayouts.CurrentCode; + + base.Draw(); + } + + private void SyncText() + { + Text = KeyboardLayouts.CurrentCode; + MarkDirty(); + + if (Parent != null) + { + Parent.MarkDirty(); + } + } + } +} diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Label.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Label.cs index f05411d63..1e2d62dc5 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Label.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Label.cs @@ -4,7 +4,7 @@ * PROGRAMMERS: Valentin Charbonnier */ -using Cosmos.System.Graphics.Fonts; +using Cosmos.Kernel.System.Graphics.Fonts; using System.Drawing; namespace Aura_OS.System.Graphics.UI.GUI.Components diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Panel.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Panel.cs index 801bd34f2..e1dc3f324 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Panel.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Panel.cs @@ -4,7 +4,7 @@ * PROGRAMMERS: Valentin Charbonnier */ -using Cosmos.System.Graphics.Fonts; +using Cosmos.Kernel.System.Graphics.Fonts; using System.Drawing; namespace Aura_OS.System.Graphics.UI.GUI.Components @@ -52,7 +52,8 @@ public override void Draw() if (Text != "") { - DrawString(Text, PCScreenFont.Default, Kernel.WhiteColor, 5, 3); + // GEN3-GAP(psf): PCScreenFont.Default is internal and DefaultFont is now 16x32; use Aura's zap font. + DrawString(Text, Kernel.font, Kernel.WhiteColor, 5, 3); } } } diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Slider.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Slider.cs index d02f8a769..a38b98de3 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Slider.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Slider.cs @@ -4,8 +4,7 @@ * PROGRAMMERS: Valentin Charbonnier */ -using Cosmos.System; -using UniLua; +using Cosmos.Kernel.System.Mouse; namespace Aura_OS.System.Graphics.UI.GUI.Components { @@ -83,7 +82,12 @@ public override void Update() _slide.MarkDirty(); MarkDirty(); - Value = (currentX * 255) / (Width - _slide.Width); + // GEN3-GAP(null-deref): an integer /0 halts the kernel, so guard the rail length. + int range = Width - _slide.Width; + if (range > 0) + { + Value = (currentX * 255) / range; + } } _slide.Update(); diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/TextBox.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/TextBox.cs index 0d2469c66..d15215a9e 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/TextBox.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/TextBox.cs @@ -4,7 +4,8 @@ * PROGRAMMERS: Valentin Charbonnier */ -using Cosmos.System; +using Cosmos.Kernel.System.Keyboard; +using Cosmos.Kernel.System.Mouse; using System; using System.Collections.Generic; using System.Linq; diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Window.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Window.cs index ca8f990ae..a6c6fa391 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Window.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Components/Window.cs @@ -5,7 +5,7 @@ */ using System.Drawing; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; using Aura_OS.System.Graphics.UI.GUI.Skin; namespace Aura_OS.System.Graphics.UI.GUI.Components diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Desktop.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Desktop.cs index 9a1ba61ad..c6309f380 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Desktop.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Desktop.cs @@ -4,9 +4,11 @@ * PROGRAMMERS: Valentin Charbonnier */ +using System; using System.Drawing; using System.IO; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; +using Aura_OS.System.Filesystem; using Aura_OS.System.Graphics.UI.GUI.Components; using Aura_OS.System.Utils; @@ -16,21 +18,34 @@ public class Desktop : Component { public FilesystemPanel MainPanel; private string _wallpaperPath; - private Bitmap _wallpaper; - private Color? _color = null; + private Image _wallpaper; public Desktop(int x, int y, int width, int height) : base(x, y, width, height) { if (Kernel.Installed) { - CustomConsole.WriteLineInfo("Retrieving wallpaper from 0:\\."); - Settings config = new Settings(@"0:\System\settings.ini"); - SetWallpaper(config.GetValue("wallpaperPath")); + CustomConsole.WriteLineInfo("Retrieving wallpaper from " + AuraPaths.SettingsIni + "."); + Settings config = new Settings(AuraPaths.SettingsIni); + string wallpaperPath = config.GetValue("wallpaperPath"); + + try + { + SetWallpaper(wallpaperPath); + } + catch (Exception ex) + { + // GEN3-GAP(bmp): a wallpaper the gen3 BMP loader rejects must not stop the boot. + CustomConsole.WriteLineWarning("Cannot load wallpaper " + wallpaperPath + ": " + ex.Message); + _wallpaperPath = string.IsNullOrEmpty(wallpaperPath) ? "Embedded" : AuraPath.FromLegacy(wallpaperPath); + _wallpaper = ImageUtils.ScaleToScreen(Kernel.wallpaper1); + MarkDirty(); + } } else { _wallpaperPath = "Embedded"; - _wallpaper = new Bitmap(Files.Wallpaper); + // Kernel.wallpaper1 is Files.Wallpaper, already decoded at boot (Files.LoadFiles). + _wallpaper = ImageUtils.ScaleToScreen(Kernel.wallpaper1); MarkDirty(); } @@ -48,14 +63,7 @@ public override void Draw() { base.Draw(); - if (_color != null) - { - Clear((Color)_color); - } - else - { - DrawImage(_wallpaper, X, Y); - } + DrawImage(_wallpaper, X, Y); MainPanel.UpdateCurrentFolder(); MainPanel.Draw(this); @@ -66,15 +74,30 @@ public string GetWallpaperPath() return _wallpaperPath; } + /// + /// Loads and shows a wallpaper. A missing file falls back to the embedded wallpaper; + /// a BMP the loader rejects throws (SettingsApp reports it) and keeps the current one. + /// public void SetWallpaper(string path) { - _wallpaperPath = path; - _wallpaper = new Bitmap(File.ReadAllBytes(path)); + // gen2-installed disks store DOS-style paths (drive 0, backslashes): convert them. + path = AuraPath.FromLegacy(path); - if (_wallpaper.Width != Kernel.ScreenWidth && _wallpaper.Height != Kernel.ScreenHeight) + Image wallpaper; + + if (!string.IsNullOrEmpty(path) && File.Exists(path)) { - _color = Color.Black; + wallpaper = new Bitmap(File.ReadAllBytes(path)); } + else + { + wallpaper = Kernel.wallpaper1; + } + + // gen2 blanked to black when the wallpaper did not match the screen; gen3 runs at the + // real framebuffer size (GEN3-GAP(display-mode)), so scale once here, never per frame. + _wallpaper = ImageUtils.ScaleToScreen(wallpaper); + _wallpaperPath = string.IsNullOrEmpty(path) ? "Embedded" : path; MarkDirty(); } diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Dialog.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Dialog.cs index 6597ef5a8..fb5f1f898 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Dialog.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Dialog.cs @@ -6,7 +6,7 @@ using System; using System.Collections.Generic; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; using Aura_OS.System.Graphics.UI.GUI.Components; namespace Aura_OS.System.Graphics.UI.GUI diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/DirectBitmap.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/DirectBitmap.cs index 29c5a276c..50d7b4f6f 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/DirectBitmap.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/DirectBitmap.cs @@ -7,12 +7,18 @@ using System; using System.Drawing; using System.Runtime.CompilerServices; -using Cosmos.Core; -using Cosmos.System.Graphics; -using Cosmos.System.Graphics.Fonts; +using Cosmos.Kernel.System.Graphics; +using Cosmos.Kernel.System.Graphics.Fonts; namespace Aura_OS.System.Graphics.UI.GUI { + /// + /// Aura's compositor surface: raw ARGB ints, either owned by a Bitmap or aliasing the canvas + /// back buffer. Every operation clips to the surface, never throws for off-screen coordinates + /// (windows and the cursor go off-screen) and never allocates (except ExtractImage). + /// GEN3-GAP(blit): Canvas.DrawImageAlpha is per-pixel and forces opaque output, and the BCL + /// replaces the gen2 kernel memory helpers, so blending and copies are done here in plain C#. + /// public unsafe class DirectBitmap { /// @@ -25,22 +31,59 @@ public unsafe class DirectBitmap /// internal int Pitch; + /// + /// Raw ARGB pixels, row-major, Width * Height. This is Bitmap.RawData (same array, no copy), + /// or the canvas back buffer for a canvas-backed DirectBitmap. + /// + public readonly int[] Pixels; + + /// + /// Backing bitmap. Null only when this DirectBitmap aliases the canvas back buffer. + /// public Bitmap Bitmap { get; private set; } public int Height = 144; public int Width = 160; public DirectBitmap() { - Bitmap = new Bitmap((uint)Width, (uint)Height, ColorDepth.ColorDepth32); + Bitmap = new Bitmap(Width, Height, ColorDepth.ColorDepth32); + Pixels = Bitmap.RawData; Stride = (int)32 / 8; Pitch = (int)Width * Stride; } public DirectBitmap(int width, int height) { - Width = width; - Height = height; - Bitmap = new Bitmap((uint)Width, (uint)Height, ColorDepth.ColorDepth32); + Width = Math.Max(0, width); + Height = Math.Max(0, height); + Bitmap = new Bitmap(Width, Height, ColorDepth.ColorDepth32); + Pixels = Bitmap.RawData; + Stride = (int)32 / 8; + Pitch = (int)Width * Stride; + } + + /// + /// Zero-copy surface over the canvas back buffer: whatever is drawn here is shown by the + /// next Canvas.Display(). Bitmap stays null. The canvas reallocates its buffer on a mode + /// change, so create a new DirectBitmap after any Canvas.GetFullScreen(mode). + /// + public DirectBitmap(Canvas canvas) + { + int[] buffer = canvas != null ? canvas.GetBuffer() : null; + + if (buffer != null) + { + Width = canvas.Width; + Height = canvas.Height; + Pixels = buffer; + } + else + { + Width = 0; + Height = 0; + Pixels = Array.Empty(); + } + Stride = (int)32 / 8; Pitch = (int)Width * Stride; } @@ -48,51 +91,61 @@ public DirectBitmap(int width, int height) [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetPixel(int x, int y, int colour) { - int index = x + y * Width; - Bitmap.RawData[index] = colour | (0xFF << 24); + if ((uint)x < (uint)Width && (uint)y < (uint)Height) + { + Pixels[x + y * Width] = colour | (0xFF << 24); + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetPixelAlpha(int x, int y, int colour) { + if ((uint)x >= (uint)Width || (uint)y >= (uint)Height) + { + return; + } + int index = x + y * Width; - if (index < Bitmap.RawData.Length) + if (((uint)colour >> 24) == 0xFF) { - if ((colour >> 24) == 0xFF) - { - Bitmap.RawData[index] = colour; - return; - } + Pixels[index] = colour; + return; + } - int bgColour = Bitmap.RawData[index]; - int alpha = (colour >> 24) & 0xff; - int invAlpha = 255 - alpha; - int newRed = (((colour >> 16) & 0xff) * alpha + ((bgColour >> 16) & 0xff) * invAlpha) >> 8; - int newGreen = (((colour >> 8) & 0xff) * alpha + ((bgColour >> 8) & 0xff) * invAlpha) >> 8; - int newBlue = ((colour & 0xff) * alpha + (bgColour & 0xff) * invAlpha) >> 8; + int bgColour = Pixels[index]; + int alpha = (colour >> 24) & 0xff; + int invAlpha = 255 - alpha; + int newRed = (((colour >> 16) & 0xff) * alpha + ((bgColour >> 16) & 0xff) * invAlpha) >> 8; + int newGreen = (((colour >> 8) & 0xff) * alpha + ((bgColour >> 8) & 0xff) * invAlpha) >> 8; + int newBlue = ((colour & 0xff) * alpha + (bgColour & 0xff) * invAlpha) >> 8; - Bitmap.RawData[index] = (alpha << 24) | (newRed << 16) | (newGreen << 8) | newBlue; - } + Pixels[index] = (alpha << 24) | (newRed << 16) | (newGreen << 8) | newBlue; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetPixel(int x, int y) { - int index = x + y * Width; - return Bitmap.RawData[index]; + if ((uint)x < (uint)Width && (uint)y < (uint)Height) + { + return Pixels[x + y * Width]; + } + + return 0; } public void Clear(int colour) { - fixed (int* destPtr = Bitmap.RawData) - { - MemoryOperations.Fill(destPtr, colour, Bitmap.RawData.Length); - } + Pixels.AsSpan().Fill(colour); } public void DrawString(string str, Font font, int color, int x, int y) { + if (str == null || font == null) + { + return; + } + int length = str.Length; byte width = font.Width; for (int i = 0; i < length; i++) @@ -104,17 +157,43 @@ public void DrawString(string str, Font font, int color, int x, int y) public void DrawChar(char c, Font font, int color, int x, int y) { - byte height = font.Height; - byte width = font.Width; + if (font == null) + { + return; + } + + int height = font.Height; + int width = font.Width; byte[] data = font.Data; - int num = height * (byte)c; - for (int i = 0; i < height; i++) + + // PSF glyph rows are (Width + 7) / 8 bytes wide (zap is 6 px = 1 byte, DefaultFont 16 px = 2 bytes). + int bytesPerRow = (width + 7) / 8; + int p = height * bytesPerRow * (byte)c; + + if (data == null || p + height * bytesPerRow > data.Length) { - for (byte b = 0; b < width; b = (byte)(b + 1)) + return; + } + + if (x >= Width || y >= Height || x + width <= 0 || y + height <= 0) + { + return; + } + + for (int cy = 0; cy < height; cy++) + { + int py = y + cy; + if ((uint)py >= (uint)Height) + { + continue; + } + + int row = p + cy * bytesPerRow; + for (int cx = 0; cx < width; cx++) { - if (font.ConvertByteToBitAddress(data[num + i], b + 1)) + if (font.ConvertByteToBitAddress(data[row + cx / 8], (cx % 8) + 1)) { - SetPixelAlpha((ushort)(x + b), (ushort)(y + i), color); + SetPixelAlpha(x + cx, py, color); } } } @@ -339,95 +418,279 @@ protected void TrimLine(ref int x1, ref int y1, ref int x2, ref int y2) y2 = (int)num4; } - public void DrawImage(Bitmap image, int x, int y) + /// + /// Clips a width x height rectangle placed at (x, y) against this bitmap. + /// On success (x, y) is the first visible destination pixel, (srcX, srcY) the matching + /// offset inside the rectangle and w x h the visible size. + /// + private bool ClipRect(ref int x, ref int y, int width, int height, out int srcX, out int srcY, out int w, out int h) { - for (int yi = 0; yi < image.Height; yi++) + srcX = 0; + srcY = 0; + w = width; + h = height; + + if (width <= 0 || height <= 0 || x >= Width || y >= Height || x <= -width || y <= -height) { - int destOffset = ((y + yi) * (int)Bitmap.Width + x); - int srcOffset = yi * (int)image.Width; - int count = (int)image.Width; + return false; + } - MemoryOperations.Copy(Bitmap.RawData, destOffset, image.RawData, srcOffset, count); + if (x < 0) + { + srcX = -x; + w += x; + x = 0; + } + + if (y < 0) + { + srcY = -y; + h += y; + y = 0; + } + + if (w > Width - x) + { + w = Width - x; + } + + if (h > Height - y) + { + h = Height - y; + } + + return w > 0 && h > 0; + } + + /// + /// Validates an image and clips it against this bitmap (see ClipRect). + /// + private bool ClipImage(Image image, ref int x, ref int y, out int[] src, out int srcX, out int srcY, out int w, out int h) + { + src = image != null ? image.RawData : null; + + if (src == null || src.Length < image.Width * image.Height) + { + srcX = 0; + srcY = 0; + w = 0; + h = 0; + return false; + } + + return ClipRect(ref x, ref y, image.Width, image.Height, out srcX, out srcY, out w, out h); + } + + public void DrawImage(Image image, int x, int y) + { + int[] src; + int srcX, srcY, w, h; + + if (!ClipImage(image, ref x, ref y, out src, out srcX, out srcY, out w, out h)) + { + return; + } + + int srcWidth = image.Width; + + for (int yi = 0; yi < h; yi++) + { + int destOffset = (y + yi) * Width + x; + int srcOffset = (srcY + yi) * srcWidth + srcX; + + // The gen2 copy helper took the destination first; Span.CopyTo is source.CopyTo(destination). + src.AsSpan(srcOffset, w).CopyTo(Pixels.AsSpan(destOffset, w)); } } public Bitmap ExtractImage(int srcX, int srcY, int width, int height) { - Bitmap bmp = new((uint)width, (uint)height, ColorDepth.ColorDepth32); + width = Math.Max(0, width); + height = Math.Max(0, height); + + Bitmap bmp = new(width, height, ColorDepth.ColorDepth32); + + int x = srcX; + int y = srcY; + int offsetX, offsetY, w, h; - for (int yi = 0; yi < height; yi++) + if (ClipRect(ref x, ref y, width, height, out offsetX, out offsetY, out w, out h)) { - int destOffset = yi * width; - int srcOffset = ((srcY + yi) * (int)Bitmap.Width + srcX); - int count = width; + int[] dest = bmp.RawData; + + for (int yi = 0; yi < h; yi++) + { + int destOffset = (offsetY + yi) * width + offsetX; + int srcOffset = (y + yi) * Width + x; - MemoryOperations.Copy(bmp.RawData, destOffset, Bitmap.RawData, srcOffset, count); + Pixels.AsSpan(srcOffset, w).CopyTo(dest.AsSpan(destOffset, w)); + } } return bmp; } + /// + /// Blends straight-alpha ARGB source rows over destination rows, in place + /// (bpl = bytes per line). Formerly the X# SSE2 plug AlphaBltSSE2ASM, now plain C#. + /// public static void AlphaBlendSSE(uint *dest, int dbpl, uint* src, int sbpl, int width, int height) { - // PLUGGED + if (dest == null || src == null || width <= 0 || height <= 0) + { + return; + } + + for (int row = 0; row < height; row++) + { + BlendRow(new Span((byte*)dest + (long)row * dbpl, width), new ReadOnlySpan((byte*)src + (long)row * sbpl, width)); + } } - public static void AlphaBltSSE2(byte* dst, byte* src, int w, int h, int wmul4) + /// + /// Sets the alpha byte of every non fully transparent pixel to a (bpl = bytes per line). + /// Formerly the X# plug BrightnessASM, now plain C#. + /// + public static void OpacitySSE(uint* pixelPtr, int w, int h, int bpl, uint a) { + if (pixelPtr == null || w <= 0 || h <= 0) + { + return; + } + + for (int row = 0; row < h; row++) + { + ApplyOpacity(new Span((byte*)pixelPtr + (long)row * bpl, w), (byte)a); + } } - public static void OpacitySSE(uint* pixelPtr, int w, int h, int bpl, uint a) + /// + /// Blends one row of straight-alpha ARGB source pixels over the destination, in place. + /// a == 255 copies, a == 0 skips, otherwise colour = (src * a + dst * (255 - a)) >> 8 + /// and alpha = min(255, dstA + a * a / 255) (gen2 AlphaBltSSE2ASM alpha word: the result + /// stays opaque over opaque buffers and keeps transparency over Color.Transparent ones). + /// + private static void BlendRow(Span dest, ReadOnlySpan src) + { + int count = Math.Min(dest.Length, src.Length); + + for (int i = 0; i < count; i++) + { + uint sp = (uint)src[i]; + uint a = sp >> 24; + + if (a == 0xFF) + { + dest[i] = (int)sp; + continue; + } + + if (a == 0) + { + continue; + } + + uint dp = (uint)dest[i]; + uint ia = 255 - a; + uint rb = (((sp & 0x00FF00FF) * a + (dp & 0x00FF00FF) * ia) >> 8) & 0x00FF00FF; + uint g = (((sp & 0x0000FF00) * a + (dp & 0x0000FF00) * ia) >> 8) & 0x0000FF00; + uint oa = Math.Min(255u, (dp >> 24) + (a * a + 127) / 255); + + dest[i] = (int)((oa << 24) | rb | g); + } + } + + /// + /// gen2 OpacitySSE semantics: rewrites in place the alpha byte of every pixel whose alpha is not 0. + /// + private static void ApplyOpacity(Span pixels, byte alpha) { - // PLUGGED + int a = alpha << 24; + + for (int i = 0; i < pixels.Length; i++) + { + int p = pixels[i]; + + if (((uint)p >> 24) != 0) + { + pixels[i] = (p & 0x00FFFFFF) | a; + } + } } - public void DrawImageAlpha(Bitmap image, int x, int y, byte alpha = 0xFF) + public void DrawImageAlpha(Image image, int x, int y, byte alpha = 0xFF) { - if (image.RawData.Length > Bitmap.RawData.Length) + int[] src; + int srcX, srcY, w, h; + + if (!ClipImage(image, ref x, ref y, out src, out srcX, out srcY, out w, out h)) { return; } - if ((y + image.Height > Bitmap.Height || y < 0) && (x + image.Width < Bitmap.Width || x > 0)) + if (alpha < 0xFF) { - return; + // As in gen2, this permanently mutates the source image. + ApplyOpacity(src, alpha); } - Bitmap tmp = ExtractImage(x, y, (int)image.Width, (int)image.Height); - if (tmp.Width == 0) return; + int srcWidth = image.Width; - fixed (int* bgBitmap = tmp.RawData) - fixed (int* fgBitmap = image.RawData) + for (int yi = 0; yi < h; yi++) { - if (alpha < 0xFF) - { - OpacitySSE((uint*)fgBitmap, (int)image.Width, (int)image.Height, (int)image.Width * 4, alpha); - } + int destOffset = (y + yi) * Width + x; + int srcOffset = (srcY + yi) * srcWidth + srcX; - // AlphaBltSSE2((byte*)bgBitmap, (byte*)fgBitmap, w, (int)image.Height, wmul4); - AlphaBlendSSE((uint*)bgBitmap, (int)image.Width * 4, (uint*)fgBitmap, (int)image.Width * 4, (int)image.Width, (int)image.Height); + BlendRow(Pixels.AsSpan(destOffset, w), src.AsSpan(srcOffset, w)); } - - DrawImage(tmp, x, y); } - public void DrawImageStretchAlpha(Bitmap image, Rectangle sourceRect, Rectangle destRect) + public void DrawImageStretchAlpha(Image image, Rectangle sourceRect, Rectangle destRect) { + if (image == null || sourceRect == null || destRect == null) + { + return; + } + + int[] src = image.RawData; + int srcWidth = image.Width; + int srcHeight = image.Height; + + if (src == null || src.Length < srcWidth * srcHeight || destRect.Width <= 0 || destRect.Height <= 0) + { + return; + } + float scaleX = (float)sourceRect.Width / destRect.Width; float scaleY = (float)sourceRect.Height / destRect.Height; - for (int xi = 0; xi < destRect.Width; xi++) + // Only walk the destination pixels that land inside this bitmap. + int xStart = Math.Max(0, -destRect.Left); + int xEnd = Math.Min(destRect.Width, Width - destRect.Left); + int yStart = Math.Max(0, -destRect.Top); + int yEnd = Math.Min(destRect.Height, Height - destRect.Top); + + for (int yi = yStart; yi < yEnd; yi++) { - for (int yi = 0; yi < destRect.Height; yi++) + int srcY = (int)(yi * scaleY) + sourceRect.Top; + srcY = Math.Min(srcY, sourceRect.Bottom - 1); + + if ((uint)srcY >= (uint)srcHeight) { - int srcX = (int)(xi * scaleX) + sourceRect.Left; - int srcY = (int)(yi * scaleY) + sourceRect.Top; + continue; + } + int destY = destRect.Top + yi; + + for (int xi = xStart; xi < xEnd; xi++) + { + int srcX = (int)(xi * scaleX) + sourceRect.Left; srcX = Math.Min(srcX, sourceRect.Right - 1); - srcY = Math.Min(srcY, sourceRect.Bottom - 1); - int color = image.RawData[srcX + srcY * image.Width]; - SetPixelAlpha(destRect.Left + xi, destRect.Top + yi, color); + if ((uint)srcX < (uint)srcWidth) + { + SetPixelAlpha(destRect.Left + xi, destY, src[srcX + srcY * srcWidth]); + } } } } @@ -449,7 +712,7 @@ public void DrawFilledCircle(int color, int x0, int y0, int radius) { int drawX = x0 + x; int drawY = y0 + y; - if (drawX >= 0 && drawX < Width && drawY >= 0 && drawY < Height) + if ((uint)drawX < (uint)Width && (uint)drawY < (uint)Height) { SetPixelAlpha(drawX, drawY, color); } diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/LoginScreen.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/LoginScreen.cs index a52b1c5d5..6c4374a2e 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/LoginScreen.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/LoginScreen.cs @@ -6,7 +6,9 @@ using System; using System.Drawing; -using Cosmos.System; +using Cosmos.Kernel.System.Graphics; +using Cosmos.Kernel.System.Keyboard; +using Aura_OS.System.Filesystem; using Aura_OS.System.Graphics.UI.GUI.Components; using Aura_OS.System.Processing.Processes; using Aura_OS.System.Security; @@ -19,8 +21,9 @@ public class LoginScreen : Component private TextBox _username; private TextBox _password; private Button _button; + private KeyboardLayoutButton _keyboardButton; + private Image _wallpaper; private string _error; - private Color? _color = null; public LoginScreen(int x, int y, int width, int height) : base(x, y, width, height) { @@ -45,10 +48,13 @@ public LoginScreen(int x, int y, int width, int height) : base(x, y, width, heig AddChild(_button); - if (Kernel.wallpaper2.Width != Kernel.ScreenWidth && Kernel.wallpaper2.Height != Kernel.ScreenHeight) - { - _color = Color.Black; - } + // Keyboard layout switcher at the bottom-right, so AZERTY users can type their password. + _keyboardButton = new KeyboardLayoutButton(Width - 40 - 8, Height - 23 - 8, 40, 23); + AddChild(_keyboardButton); + + // gen2 blanked to black when the wallpaper did not match the screen; gen3 runs at the + // real framebuffer size (GEN3-GAP(display-mode)), so scale once here, never per frame. + _wallpaper = ImageUtils.ScaleToScreen(Kernel.wallpaper2); } public override void Update() @@ -62,13 +68,15 @@ public override void Update() switch (keyEvent.Key) { case ConsoleKeyEx.Tab: - if (Kernel.MouseManager.FocusedComponent.Equals(_username)) + // GEN3-GAP(null-deref): FocusedComponent is null before any focus, and calling + // Equals on it is a fatal #PF in gen3. + if (ReferenceEquals(Kernel.MouseManager.FocusedComponent, _username)) { Kernel.MouseManager.FocusedComponent = _password; _username.SetSelected(false); _password.SetSelected(true); } - else if (Kernel.MouseManager.FocusedComponent.Equals(_password)) + else if (ReferenceEquals(Kernel.MouseManager.FocusedComponent, _password)) { Kernel.MouseManager.FocusedComponent = _username; _password.SetSelected(false); @@ -93,26 +101,21 @@ public override void Update() _username.UpdateNoGetKey(); _password.UpdateNoGetKey(); _button.Update(); + _keyboardButton.Update(); } public override void Draw() { base.Draw(); - if (_color != null) - { - Clear((Color)_color); - } - else - { - DrawImage(Kernel.wallpaper2, X, Y); - } - + DrawImage(_wallpaper, X, Y); + DrawImage(Kernel.auralogo_white, Width / 2 - (int)Kernel.auralogo_white.Width / 2, _username.Y - (int)Kernel.auralogo_white.Height - 24); _username.Draw(this); _password.Draw(this); _button.Draw(this); + _keyboardButton.Draw(this); if (_error != null) { @@ -128,6 +131,7 @@ public void Hide() _username.Visible = false; _password.Visible = false; _button.Visible = false; + _keyboardButton.Visible = false; Explorer.Taskbar.Visible = true; } @@ -144,6 +148,7 @@ public void Show() _password.Text = ""; _password.Visible = true; _button.Visible = true; + _keyboardButton.Visible = true; _error = null; Explorer.Taskbar.Visible = false; Explorer.StartMenu.Visible = false; @@ -170,15 +175,21 @@ public bool Login(string username, string password) Kernel.LoggedIn = true; Kernel.userLogged = username; - Kernel.UserDirectory = @"0:\Users\" + dirUsername + @"\"; + Kernel.UserDirectory = AuraPaths.UsersDir + dirUsername + "/"; Kernel.CurrentDirectory = Kernel.UserDirectory; Explorer.Desktop.MainPanel.CurrentPath = Kernel.CurrentDirectory; Explorer.Desktop.MainPanel.RefreshFilesystem(); - Settings config = new Settings(@"0:\System\settings.ini"); + Settings config = new Settings(AuraPaths.SettingsIni); Kernel.ComputerName = config.GetValue("hostname"); + if (!string.IsNullOrEmpty(Kernel.ComputerName)) + { + // DNS and FTP report this name. + Cosmos.Kernel.System.Network.Config.DnsConfig.HostName = Kernel.ComputerName; + } + return true; } else diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Rectangle.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Rectangle.cs index f32579b28..b663dec7c 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Rectangle.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Rectangle.cs @@ -111,7 +111,7 @@ public bool Intersects(Rectangle other) return !(Left > other.Right || Right < other.Left || Top > other.Bottom || Bottom < other.Top); } - public static Rectangle? Intersection(Rectangle rect1, Rectangle rect2) + public static Rectangle Intersection(Rectangle rect1, Rectangle rect2) { if (!rect1.Intersects(rect2)) return null; diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/Frame.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/Frame.cs index eab1edeb7..3e79c3bba 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/Frame.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/Frame.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; using System.Drawing; -using System.Linq; using System.Text; -using System.Threading.Tasks; namespace Aura_OS.System.Graphics.UI.GUI.Skin { @@ -55,7 +53,7 @@ public struct Region /// public string Id; /// Texture the picture region is taken from - public Cosmos.System.Graphics.Bitmap Texture; + public Cosmos.Kernel.System.Graphics.Bitmap Texture; /// Area within the texture containing the picture region public Rectangle SourceRegion; @@ -67,7 +65,7 @@ public struct Region public struct Text { /// Font to use for drawing the text - public Cosmos.System.Graphics.Fonts.Font Font; + public Cosmos.Kernel.System.Graphics.Fonts.Font Font; /// Offset of the text relative to its specified placement public Point Offset; /// Horizontal placement of the text within the frame diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/RegionListBuilder.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/RegionListBuilder.cs index 373143b2a..4ad922bdc 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/RegionListBuilder.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/RegionListBuilder.cs @@ -2,9 +2,8 @@ using System.Collections.Generic; using System; using Aura_OS.System.Parser; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; using Aura_OS.System.Graphics.UI.GUI; -using System.Xml.Linq; using Aura_OS.System; public class RegionListBuilder @@ -34,6 +33,18 @@ public static Frame.Region[] Build( return builder.createAndPlaceRegions(frameElement, bitmaps); } + /// Value of an optional XML attribute + /// XML node holding the attribute + /// Name of the attribute + /// The attribute's value, or null if the node has no such attribute + private static string Attr(NanoXMLNode node, string name) + { + // GEN3-GAP(null-deref): GetAttribute returns null for a missing attribute; dereferencing it + // is a fatal #PF on gen3 (gen2 silently read low memory). + NanoXMLAttribute attribute = node.GetAttribute(name); + return attribute == null ? null : attribute.Value; + } + /// Retrieves the sizes of the border regions in a frame /// /// XML node for the frame containing the region @@ -42,28 +53,40 @@ private void retrieveBorderSizes(NanoXMLNode frameElement) { foreach (NanoXMLNode element in frameElement.SubNodes) { - // Left and right border width determination - string hplacement = element.GetAttribute("hplacement").Value; - string w = element.GetAttribute("w").Value; - if (hplacement == "left") + // Only regions have a size ( nodes have no w/h) + if (element.Name != "region") { - this.leftBorderWidth = Math.Max(this.leftBorderWidth, int.Parse(w)); + continue; } - else if (hplacement == "right") + + // Left and right border width determination + string hplacement = Attr(element, "hplacement"); + string w = Attr(element, "w"); + if (hplacement != null && w != null) { - this.rightBorderWidth = Math.Max(this.rightBorderWidth, int.Parse(w)); + if (hplacement == "left") + { + this.leftBorderWidth = Math.Max(this.leftBorderWidth, int.Parse(w)); + } + else if (hplacement == "right") + { + this.rightBorderWidth = Math.Max(this.rightBorderWidth, int.Parse(w)); + } } // Top and bottom border width determination - string vplacement = element.GetAttribute("vplacement").Value; - string h = element.GetAttribute("h").Value; - if (vplacement == "top") - { - this.topBorderWidth = Math.Max(this.topBorderWidth, int.Parse(h)); - } - else if (vplacement == "bottom") + string vplacement = Attr(element, "vplacement"); + string h = Attr(element, "h"); + if (vplacement != null && h != null) { - this.bottomBorderWidth = Math.Max(this.bottomBorderWidth, int.Parse(h)); + if (vplacement == "top") + { + this.topBorderWidth = Math.Max(this.topBorderWidth, int.Parse(h)); + } + else if (vplacement == "bottom") + { + this.bottomBorderWidth = Math.Max(this.bottomBorderWidth, int.Parse(h)); + } } } } @@ -88,15 +111,15 @@ private Frame.Region[] createAndPlaceRegions(NanoXMLNode frameElement, IDictiona if (element.Name == "region") { - string idAttribute = element.GetAttribute("id").Value; - string id = (idAttribute == null) ? null : idAttribute; - string source = element.GetAttribute("source").Value; - string hplacement = element.GetAttribute("hplacement").Value; - string vplacement = element.GetAttribute("vplacement").Value; - string x = element.GetAttribute("x").Value; - string y = element.GetAttribute("y").Value; - string w = element.GetAttribute("w").Value; - string h = element.GetAttribute("h").Value; + // The region id is optional (the cursor frame's region has none) + string id = Attr(element, "id"); + string source = Attr(element, "source"); + string hplacement = Attr(element, "hplacement"); + string vplacement = Attr(element, "vplacement"); + string x = Attr(element, "x"); + string y = Attr(element, "y"); + string w = Attr(element, "w"); + string h = Attr(element, "h"); // Assign the trivial attributes var region = new Frame.Region() diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/SkinParsing.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/SkinParsing.cs index bc450b36d..8b4833580 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/SkinParsing.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/SkinParsing.cs @@ -1,6 +1,7 @@ -using Aura_OS.System.Parser; +using Aura_OS.System.Filesystem; +using Aura_OS.System.Parser; using Aura_OS.System.Utils; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; using System; using System.Collections.Generic; using System.IO; @@ -47,29 +48,45 @@ private void loadResources(NanoXMLNode resourcesNode) { if (node.Name.Equals("bitmap")) { - string bitmapName = node.GetAttribute("name").Value; - _skinName = node.GetAttribute("contentPath").Value; + string bitmapName = Attr(node, "name"); + _skinName = Attr(node, "contentPath"); - string bmpPath; + if (bitmapName == null) + { + CustomConsole.WriteLineError("Skipping skin bitmap without a name."); + continue; + } + + // Installed: the theme bitmap on disk (FromLegacy converts paths stored by gen2 installs). + string bmpPath = null; if (Kernel.Installed) { - Settings config = new Settings(@"0:\System\settings.ini"); - bmpPath = config.GetValue("themeBmpPath"); + Settings config = new Settings(AuraPaths.SettingsIni); + string themeBmpPath = AuraPath.FromLegacy(config.GetValue("themeBmpPath")); - if (!File.Exists(bmpPath)) + if (!string.IsNullOrEmpty(themeBmpPath) && File.Exists(themeBmpPath)) { - bmpPath = Files.IsoVolume + "UI\\Themes\\" + _skinName + ".bmp"; + bmpPath = themeBmpPath; } } - else - { - bmpPath = Files.IsoVolume + "UI\\Themes\\" + _skinName + ".bmp"; - } try { - Bitmap bitmap = new Bitmap(File.ReadAllBytes(bmpPath)); + byte[] bmpData; + + if (bmpPath != null) + { + bmpData = File.ReadAllBytes(bmpPath); + } + else + { + // GEN3-GAP(iso-files): no ISO volume; the default skin bitmap is an embedded resource. + bmpPath = Files.EmbeddedScheme + "UI/Themes/" + _skinName + ".bmp"; + bmpData = Files.Get("UI/Themes/" + _skinName + ".bmp"); + } + + Bitmap bitmap = new Bitmap(bmpData); Kernel.ThemeManager.BmpPath = bmpPath; _bitmaps.Add(bitmapName, bitmap); CustomConsole.WriteLineOK("Bitmap '" + bitmapName + "' added successfully!"); @@ -88,11 +105,11 @@ private void loadFrames(NanoXMLNode framesNode) { if (node.Name.Equals("frame")) { - string name = node.GetAttribute("name").Value; + string name = Attr(node, "name"); - if (name.StartsWith("window") || name.StartsWith("button") || + if (name != null && (name.StartsWith("window") || name.StartsWith("button") || name.StartsWith("slider") || name.StartsWith("rail") || - name.StartsWith("cursor") || name.StartsWith("check") || name.StartsWith("input")) + name.StartsWith("cursor") || name.StartsWith("check") || name.StartsWith("input"))) { Frame.Region[] regions = RegionListBuilder.Build(node, _bitmaps); Frame.Text[] texts = null; @@ -105,6 +122,15 @@ private void loadFrames(NanoXMLNode framesNode) } } + /// Value of an optional XML attribute, or null if the node has no such attribute. + private static string Attr(NanoXMLNode node, string name) + { + // GEN3-GAP(null-deref): GetAttribute returns null for a missing attribute; dereferencing it + // is a fatal #PF on gen3. + NanoXMLAttribute attribute = node.GetAttribute(name); + return attribute == null ? null : attribute.Value; + } + public Frame GetFrame(string name) { return _frames[name]; diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/ThemeManager.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/ThemeManager.cs index d34e25860..cb55d42ff 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/ThemeManager.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Skin/ThemeManager.cs @@ -4,6 +4,7 @@ * PROGRAMMER(S): Valentin Charbonnier */ +using Aura_OS.System.Filesystem; using Aura_OS.System.Utils; using System.IO; @@ -31,22 +32,27 @@ public void Initialize() _skinParser = new SkinParsing(); + XmlPath = null; + if (Kernel.Installed) { - Settings config = new Settings(@"0:\System\settings.ini"); - XmlPath = config.GetValue("themeXmlPath"); + Settings config = new Settings(AuraPaths.SettingsIni); + string themeXmlPath = AuraPath.FromLegacy(config.GetValue("themeXmlPath")); - if (!File.Exists(XmlPath)) + if (!string.IsNullOrEmpty(themeXmlPath) && File.Exists(themeXmlPath)) { - XmlPath = Files.IsoVolume + "UI\\Themes\\Suave.skin.xml"; + XmlPath = themeXmlPath; } } - else + + if (XmlPath == null) { - XmlPath = Files.IsoVolume + "UI\\Themes\\Suave.skin.xml"; + // GEN3-GAP(iso-files): no ISO volume; the default skin is an embedded resource. + XmlPath = Files.EmbeddedScheme + "UI/Themes/Suave.skin.xml"; } - _skinParser.loadSkin(File.ReadAllText(XmlPath)); + // Disk or embedded; the UTF-8 BOM (Suave.skin.xml has one) is stripped on both paths. + _skinParser.loadSkin(Files.ReadAllText(XmlPath)); } /// diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/StartMenu.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/StartMenu.cs index 66471f19b..e7f117aa8 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/StartMenu.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/StartMenu.cs @@ -6,8 +6,7 @@ using System; using System.Collections.Generic; -using Cosmos.System; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; using Aura_OS.System.Graphics.UI.GUI.Components; using Aura_OS.System.Processing.Processes; @@ -30,7 +29,8 @@ public StartMenu(int x, int y, int width, int height) : base(x, y, width, height Shutdown = new Button(Kernel.ResourceManager.GetIcon("24-shutdown.bmp"), "Shut Down.", 3, Height - 35 - 3, Width - 6, 35); Shutdown.Click = new Action(() => { - Power.Shutdown(); + // Flushes the mounted volumes first. + AuraPower.Shutdown(); }); AddChild(Shutdown); @@ -38,7 +38,7 @@ public StartMenu(int x, int y, int width, int height) : base(x, y, width, height Reboot = new Button(Kernel.ResourceManager.GetIcon("24-reboot.bmp"), "Reboot.", 3, Height - 70 - 3, Width - 6, 35); Reboot.Click = new Action(() => { - Power.Reboot(); + AuraPower.Reboot(); }); AddChild(Reboot); diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/Taskbar.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/Taskbar.cs index e01e48215..1b380092a 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/Taskbar.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/Taskbar.cs @@ -5,7 +5,7 @@ */ using System.Collections.Generic; -using Cosmos.System; +using Cosmos.Kernel.System.Mouse; using Aura_OS.System.Graphics.UI.GUI.Components; using Aura_OS.System.Processing.Processes; using System; @@ -38,6 +38,7 @@ public class Taskbar : Panel public Button StartButton; public Button HourButton; public Button NetworkButton; + public KeyboardLayoutButton KeyboardButton; public bool Clicked = false; @@ -78,13 +79,29 @@ public Taskbar() : base(Kernel.Gray, 0, (int)Kernel.ScreenHeight - taskbarHeight RightClickEntry entry = new("ipconfig /ask", NetworkButton.RightClick.Width, NetworkButton.RightClick); entry.Click = new Action(() => { - Dhcp.Ask(); + // Phase 1: still synchronous (Ask can block the UI for ~10 s); a GUI click must not + // reach the crash screen. + try + { + Dhcp.Ask(); + } + catch (Exception ex) + { + Logs.DoOSLog("[Error] ipconfig /ask: " + ex.Message); + } }); RightClickEntry entry2 = new("ipconfig /release", NetworkButton.RightClick.Width, NetworkButton.RightClick); entry2.Click = new Action(() => { - Dhcp.Release(); + try + { + Dhcp.Release(); + } + catch (Exception ex) + { + Logs.DoOSLog("[Error] ipconfig /release: " + ex.Message); + } }); NetworkButton.RightClick.AddEntry(entry); @@ -92,6 +109,16 @@ public Taskbar() : base(Kernel.Gray, 0, (int)Kernel.ScreenHeight - taskbarHeight AddChild(NetworkButton); + // Keyboard layout switcher, left of the network icon. Its face is the layout code + // ("US", "FR", ...); a click lists every layout. + int keyboardButtonWidth = 2 * Kernel.font.Width + 6; + int keyboardButtonHeight = 16; + int keyboardButtonX = netoworkButtonX - keyboardButtonWidth - 6; + int keyboardButtonY = (taskbarHeight / 2) - (keyboardButtonHeight / 2); + KeyboardButton = new KeyboardLayoutButton(keyboardButtonX, keyboardButtonY, keyboardButtonWidth, keyboardButtonHeight); + KeyboardButton.NoBackground = true; + AddChild(KeyboardButton); + Buttons = new Dictionary(); } @@ -143,6 +170,7 @@ public void UpdateApplicationButtons() public override void Update() { StartButton.Update(); + KeyboardButton.Update(); foreach (var button in Buttons) { @@ -150,7 +178,8 @@ public override void Update() Button btn = button.Value; Application application = Kernel.ApplicationManager.GetApplicationByPid(pid); - if (application.Focused) + // GEN3-GAP(null-deref): the process may be gone before the buttons are rebuilt. + if (application != null && application.Focused) { btn.State = State.Highlighted; btn.UpdateFrame(); @@ -187,7 +216,7 @@ private void DrawApplications() Button btn = button.Value; Application application = Kernel.ApplicationManager.GetApplicationByPid(pid); - if (application.Focused) + if (application != null && application.Focused) { btn.Frame = Kernel.ThemeManager.GetFrame("button.highlighted"); } @@ -219,6 +248,8 @@ public void DrawNotifications() } NetworkButton.Draw(this); + + KeyboardButton.Draw(this); } public override void MarkDirty() diff --git a/SRC/Aura_OS/System/Graphics/UI/GUI/WindowManager.cs b/SRC/Aura_OS/System/Graphics/UI/GUI/WindowManager.cs index d8f300232..afc9dd3f0 100644 --- a/SRC/Aura_OS/System/Graphics/UI/GUI/WindowManager.cs +++ b/SRC/Aura_OS/System/Graphics/UI/GUI/WindowManager.cs @@ -13,6 +13,7 @@ using Rectangle = Aura_OS.System.Graphics.UI.GUI.Rectangle; using Component = Aura_OS.System.Graphics.UI.GUI.Components.Component; using Aura_OS.System.Utils; +using Aura_OS.System.Filesystem; namespace Aura_OS { @@ -51,9 +52,18 @@ public void Initialize() if (Kernel.Installed) { - Settings config = new Settings(@"0:\System\settings.ini"); - byte windowsTransparency = byte.Parse(config.GetValue("windowsTransparency")); - byte taskbarTransparency = byte.Parse(config.GetValue("taskbarTransparency")); + Settings config = new Settings(AuraPaths.SettingsIni); + // C6: a missing key reads as "null"; fall back to opaque instead of failing the boot. + byte windowsTransparency; + if (!byte.TryParse(config.GetValue("windowsTransparency"), out windowsTransparency)) + { + windowsTransparency = 0xFF; + } + byte taskbarTransparency; + if (!byte.TryParse(config.GetValue("taskbarTransparency"), out taskbarTransparency)) + { + taskbarTransparency = 0xFF; + } WindowsTransparency = windowsTransparency; TaskbarTransparency = taskbarTransparency; } diff --git a/SRC/Aura_OS/System/Input/AuraFRStandardLayout.cs b/SRC/Aura_OS/System/Input/AuraFRStandardLayout.cs new file mode 100644 index 000000000..3067c928f --- /dev/null +++ b/SRC/Aura_OS/System/Input/AuraFRStandardLayout.cs @@ -0,0 +1,143 @@ +// This code is licensed under the BSD 3-Clause license (see LICENSE for details) +// Derived from Cosmos gen3 src/Cosmos.Kernel.System/Keyboard/ScanMaps/FRStandardLayout.cs (Cosmos project, BSD 3-Clause) + +/* +* PROJECT: Aura Operating System Development +* CONTENT: French AZERTY layout with an AltGr level and the ISO 102nd key. +* Copy of Cosmos gen3 src/Cosmos.Kernel.System/Keyboard/ScanMaps/FRStandardLayout.cs +* (sealed upstream, so it cannot be subclassed). +* PROGRAMMER(S): Valentin Charbonnier +*/ + +using Cosmos.Kernel.System.Keyboard; + +namespace Aura_OS.System.Input +{ + /// + /// Represents the standard French (FR) keyboard layout, plus the AltGr characters + /// (~ # { [ | ` \ ^ @ ] } €) and the ISO <> key. + /// GEN3-GAP(keyboard-altgr): the bundled FRStandardLayout has no AltGr level and no 0x56 key, + /// so on AZERTY \ @ # { } [ ] | ~ ` ^ < > cannot be typed. Upstream this map, then drop this class. + /// + public sealed class AuraFRStandardLayout : ScanMapBase + { + /// + protected override void InitializeKeys() + { + #region Keys + // The lookup takes the first matching scan code, so the AltGr rows REPLACE the upstream ones. + // AltGr rows use the 8-char ctor (ctrlAlt + ctrlAltShift): ConvertScanCode picks + // (shift ^ capsLock) ? ControlAltShift : ControlAlt, so AltGr keeps working under Caps Lock. + /* Scan Norm Shift Num Caps ShCaps ShNum CtrlAlt CtrlAltShift ConsoleKeyEx */ + Keys.Add(new KeyMapping(0x00, ConsoleKeyEx.NoName)); + Keys.Add(new KeyMapping(0x01, ConsoleKeyEx.Escape)); + /* 1 -> 9 */ + Keys.Add(new KeyMapping(0x02, '&', '1', '&', '1', '&', '1', ConsoleKeyEx.D1)); + Keys.Add(new KeyMapping(0x03, 'é', '2', 'é', '2', 'é', '2', '~', '~', ConsoleKeyEx.D2)); + Keys.Add(new KeyMapping(0x04, '"', '3', '"', '3', '"', '3', '#', '#', ConsoleKeyEx.D3)); + Keys.Add(new KeyMapping(0x05, '\'', '4', '\'', '4', '\'', '4', '{', '{', ConsoleKeyEx.D4)); + Keys.Add(new KeyMapping(0x06, '(', '5', '(', '5', '(', '5', '[', '[', ConsoleKeyEx.D5)); + Keys.Add(new KeyMapping(0x07, '-', '6', '-', '6', '-', '6', '|', '|', ConsoleKeyEx.D6)); + Keys.Add(new KeyMapping(0x08, 'è', '7', 'è', '7', 'è', '7', '`', '`', ConsoleKeyEx.D7)); + Keys.Add(new KeyMapping(0x09, '_', '8', '_', '8', '_', '8', '\\', '\\', ConsoleKeyEx.D8)); + Keys.Add(new KeyMapping(0x0A, 'ç', '9', 'ç', '9', 'ç', '9', '^', '^', ConsoleKeyEx.D9)); + Keys.Add(new KeyMapping(0x0B, 'à', '0', 'à', '0', 'à', '0', '@', '@', ConsoleKeyEx.D0)); + /* -, =, Bksp, Tab */ + Keys.Add(new KeyMapping(0x0C, ')', '°', ')', '°', ')', '°', ']', ']', ConsoleKeyEx.Minus)); + Keys.Add(new KeyMapping(0x0D, '=', '+', '=', '+', '=', '+', '}', '}', ConsoleKeyEx.Equal)); + Keys.Add(new KeyMapping(0x0E, ConsoleKeyEx.Backspace)); + Keys.Add(new KeyMapping(0x0F, '\t', ConsoleKeyEx.Tab)); + /* QWERTYUIOP[] */ + Keys.Add(new KeyMapping(0x10, 'a', 'A', 'a', 'A', 'a', 'A', ConsoleKeyEx.A)); + Keys.Add(new KeyMapping(0x11, 'z', 'Z', 'z', 'Z', 'z', 'Z', ConsoleKeyEx.Z)); + Keys.Add(new KeyMapping(0x12, 'e', 'E', 'e', 'E', 'e', 'E', '€', '€', ConsoleKeyEx.E)); + Keys.Add(new KeyMapping(0x13, 'r', 'R', 'r', 'R', 'r', 'R', ConsoleKeyEx.R)); + Keys.Add(new KeyMapping(0x14, 't', 'T', 't', 'T', 't', 'T', ConsoleKeyEx.T)); + Keys.Add(new KeyMapping(0x15, 'y', 'Y', 'y', 'Y', 'y', 'Y', ConsoleKeyEx.Y)); + Keys.Add(new KeyMapping(0x16, 'u', 'U', 'u', 'U', 'u', 'U', ConsoleKeyEx.U)); + Keys.Add(new KeyMapping(0x17, 'i', 'I', 'i', 'I', 'i', 'I', ConsoleKeyEx.I)); + Keys.Add(new KeyMapping(0x18, 'o', 'O', 'o', 'O', 'o', 'O', ConsoleKeyEx.O)); + Keys.Add(new KeyMapping(0x19, 'p', 'P', 'p', 'P', 'p', 'P', ConsoleKeyEx.P)); + Keys.Add(new KeyMapping(0x1A, '^', '¨', '^', '¨', '^', '¨', ConsoleKeyEx.LBracket)); + Keys.Add(new KeyMapping(0x1B, '$', '£', '$', '£', '$', '£', ConsoleKeyEx.RBracket)); + /* ENTER, CTRL */ + Keys.Add(new KeyMapping(0x1C, ConsoleKeyEx.Enter)); + Keys.Add(new KeyMapping(0x1D, ConsoleKeyEx.LCtrl)); + /* ASDFGHJKL;'` */ + Keys.Add(new KeyMapping(0x1E, 'q', 'Q', 'q', 'Q', 'q', 'Q', ConsoleKeyEx.Q)); + Keys.Add(new KeyMapping(0x1F, 's', 'S', 's', 'S', 's', 'S', ConsoleKeyEx.S)); + Keys.Add(new KeyMapping(0x20, 'd', 'D', 'd', 'D', 'd', 'D', ConsoleKeyEx.D)); + Keys.Add(new KeyMapping(0x21, 'f', 'F', 'f', 'F', 'f', 'F', ConsoleKeyEx.F)); + Keys.Add(new KeyMapping(0x22, 'g', 'G', 'g', 'G', 'g', 'G', ConsoleKeyEx.G)); + Keys.Add(new KeyMapping(0x23, 'h', 'H', 'h', 'H', 'h', 'H', ConsoleKeyEx.H)); + Keys.Add(new KeyMapping(0x24, 'j', 'J', 'j', 'J', 'j', 'J', ConsoleKeyEx.J)); + Keys.Add(new KeyMapping(0x25, 'k', 'K', 'k', 'K', 'k', 'K', ConsoleKeyEx.K)); + Keys.Add(new KeyMapping(0x26, 'l', 'L', 'l', 'L', 'l', 'L', ConsoleKeyEx.L)); + Keys.Add(new KeyMapping(0x27, 'm', 'M', 'm', 'M', 'm', 'M', ConsoleKeyEx.M)); + Keys.Add(new KeyMapping(0x28, 'ù', '%', 'ù', '%', 'ù', '%', ConsoleKeyEx.Apostrophe)); + Keys.Add(new KeyMapping(0x29, '²', '\0', '²', '²', '\0', '\0', ConsoleKeyEx.Backquote)); + /* Left Shift*/ + Keys.Add(new KeyMapping(0x2A, ConsoleKeyEx.LShift)); + /* \ZXCVBNM,./ */ + Keys.Add(new KeyMapping(0x2B, '*', 'µ', '*', 'µ', '*', 'µ', ConsoleKeyEx.Backslash)); + Keys.Add(new KeyMapping(0x2C, 'w', 'W', 'w', 'W', 'w', 'W', ConsoleKeyEx.W)); + Keys.Add(new KeyMapping(0x2D, 'x', 'X', 'x', 'X', 'x', 'X', ConsoleKeyEx.X)); + Keys.Add(new KeyMapping(0x2E, 'c', 'C', 'c', 'C', 'c', 'C', ConsoleKeyEx.C)); + Keys.Add(new KeyMapping(0x2F, 'v', 'V', 'v', 'V', 'v', 'V', ConsoleKeyEx.V)); + Keys.Add(new KeyMapping(0x30, 'b', 'B', 'b', 'B', 'b', 'B', ConsoleKeyEx.B)); + Keys.Add(new KeyMapping(0x31, 'n', 'N', 'n', 'N', 'n', 'N', ConsoleKeyEx.N)); + Keys.Add(new KeyMapping(0x32, ',', '?', ',', '?', ',', '?', ConsoleKeyEx.Comma)); + Keys.Add(new KeyMapping(0x33, ';', '.', ';', '.', ';', '.', ConsoleKeyEx.Semicolon)); + Keys.Add(new KeyMapping(0x34, ':', '/', ':', '/', ':', '/', ConsoleKeyEx.Colon)); + Keys.Add(new KeyMapping(0x35, '!', '§', '!', '§', '!', '§', ConsoleKeyEx.ExclamationPoint)); // also numpad divide + /* Right Shift */ + Keys.Add(new KeyMapping(0x36, ConsoleKeyEx.RShift)); + /* Print Screen */ + Keys.Add(new KeyMapping(0x37, '*', '*', '*', '*', '*', '*', ConsoleKeyEx.NumMultiply)); // also numpad multiply + /* Alt */ + Keys.Add(new KeyMapping(0x38, ConsoleKeyEx.LAlt)); + /* Right Alt = AltGr (third level). 0x60 is ScanMapBase.RightAltScanCode, which is internal upstream. */ + Keys.Add(new KeyMapping(0x60, ConsoleKeyEx.AltGr)); + /* Space */ + Keys.Add(new KeyMapping(0x39, ' ', ConsoleKeyEx.Spacebar)); + /* Caps */ + Keys.Add(new KeyMapping(0x3A, ConsoleKeyEx.CapsLock)); + /* F1-F12 */ + Keys.Add(new KeyMapping(0x3B, ConsoleKeyEx.F1)); + Keys.Add(new KeyMapping(0x3C, ConsoleKeyEx.F2)); + Keys.Add(new KeyMapping(0x3D, ConsoleKeyEx.F3)); + Keys.Add(new KeyMapping(0x3E, ConsoleKeyEx.F4)); + Keys.Add(new KeyMapping(0x3F, ConsoleKeyEx.F5)); + Keys.Add(new KeyMapping(0x40, ConsoleKeyEx.F6)); + Keys.Add(new KeyMapping(0x41, ConsoleKeyEx.F7)); + Keys.Add(new KeyMapping(0x42, ConsoleKeyEx.F8)); + Keys.Add(new KeyMapping(0x43, ConsoleKeyEx.F9)); + Keys.Add(new KeyMapping(0x44, ConsoleKeyEx.F10)); + Keys.Add(new KeyMapping(0x57, ConsoleKeyEx.F11)); + Keys.Add(new KeyMapping(0x58, ConsoleKeyEx.F12)); + /* Num Lock, Scrl Lock */ + Keys.Add(new KeyMapping(0x45, ConsoleKeyEx.NumLock)); + Keys.Add(new KeyMapping(0x46, ConsoleKeyEx.ScrollLock)); + /* HOME, Up, Pgup, -kpad, left, center, right, +keypad, end, down, pgdn, ins, del */ + Keys.Add(new KeyMapping(0x47, '\0', '\0', '7', '\0', '\0', '\0', ConsoleKeyEx.Home, ConsoleKeyEx.Num7)); + Keys.Add(new KeyMapping(0x48, '\0', '\0', '8', '\0', '\0', '\0', ConsoleKeyEx.UpArrow, ConsoleKeyEx.Num8)); + Keys.Add(new KeyMapping(0x49, '\0', '\0', '9', '\0', '\0', '\0', ConsoleKeyEx.PageUp, ConsoleKeyEx.Num9)); + Keys.Add(new KeyMapping(0x4A, '-', '-', '-', '-', '-', '-', ConsoleKeyEx.NumMinus)); + Keys.Add(new KeyMapping(0x4B, '\0', '\0', '4', '\0', '\0', '\0', ConsoleKeyEx.LeftArrow, ConsoleKeyEx.Num4)); + Keys.Add(new KeyMapping(0x4C, '\0', '\0', '5', '\0', '\0', '\0', ConsoleKeyEx.Num5)); + Keys.Add(new KeyMapping(0x4D, '\0', '\0', '6', '\0', '\0', '\0', ConsoleKeyEx.RightArrow, ConsoleKeyEx.Num6)); + Keys.Add(new KeyMapping(0x4E, '+', '+', '+', '+', '+', '+', ConsoleKeyEx.NumPlus)); + Keys.Add(new KeyMapping(0x4F, '\0', '\0', '1', '\0', '\0', '\0', ConsoleKeyEx.End, ConsoleKeyEx.Num1)); + Keys.Add(new KeyMapping(0x50, '\0', '\0', '2', '\0', '\0', '\0', ConsoleKeyEx.DownArrow, ConsoleKeyEx.Num2)); + Keys.Add(new KeyMapping(0x51, '\0', '\0', '3', '\0', '\0', '\0', ConsoleKeyEx.PageDown, ConsoleKeyEx.Num3)); + Keys.Add(new KeyMapping(0x52, '\0', '\0', '0', '\0', '\0', '\0', ConsoleKeyEx.Insert, ConsoleKeyEx.Num0)); + Keys.Add(new KeyMapping(0x53, '\0', '\0', '.', '\0', '\0', '\0', ConsoleKeyEx.Delete, ConsoleKeyEx.NumPeriod)); + /* ISO 102nd key (< >), missing from the upstream FR map */ + Keys.Add(new KeyMapping(0x56, '<', '>', '<', '<', '>', '>', ConsoleKeyEx.OEM102)); + + Keys.Add(new KeyMapping(0x5b, ConsoleKeyEx.LWin)); + Keys.Add(new KeyMapping(0x5c, ConsoleKeyEx.RWin)); + #endregion + } + } +} diff --git a/SRC/Aura_OS/System/Input/KeyboardLayouts.cs b/SRC/Aura_OS/System/Input/KeyboardLayouts.cs new file mode 100644 index 000000000..eb0b3eca8 --- /dev/null +++ b/SRC/Aura_OS/System/Input/KeyboardLayouts.cs @@ -0,0 +1,175 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: Registry of the gen3 kernel keyboard layouts +* PROGRAMMER(S): Valentin Charbonnier +*/ + +using System; +using System.IO; +using Cosmos.Kernel.System; +using Cosmos.Kernel.System.Keyboard; +using Cosmos.Kernel.System.Keyboard.ScanMaps; +using Aura_OS.System.Filesystem; +using Aura_OS.System.Utils; +using CosmosKeyboard = Cosmos.Kernel.System.Keyboard.KeyboardManager; + +namespace Aura_OS.System.Input +{ + /// + /// Every keyboard scan map Aura can use, keyed by the short code shown in the + /// taskbar. Single source of truth for the taskbar/login layout menu, the + /// setkeyboardmap command and the 'keyboardLayout' entry of settings.ini. + /// + public static class KeyboardLayouts + { + /// Name of the settings.ini entry holding the layout code. + private const string SettingName = "keyboardLayout"; + + /// Code of the active layout (the kernel boots on the US map). + public static string CurrentCode { get; private set; } = "US"; + + /// All selectable layout codes, in menu order. + public static readonly string[] Codes = { "US", "GB", "FR", "DE", "ES", "TR", "DV" }; + + /// Accepted aliases (gen2 kept "azerty"/"qwerty"); see . + public static readonly string[] Aliases = { "azerty", "qwerty", "qwertz", "dvorak" }; + + /// + /// Human-readable name for a layout code (menu label next to the code). + /// + public static string GetDisplayName(string code) + { + // Accept any case and the aliases too ("fr", "azerty"); unknown input is echoed back. + string resolved = ResolveCode(code); + + switch (resolved) + { + case "US": return "English (US, QWERTY)"; + case "GB": return "English (UK, QWERTY)"; + case "FR": return "French (AZERTY)"; + case "DE": return "German (QWERTZ)"; + case "ES": return "Spanish (QWERTY)"; + case "TR": return "Turkish (Q)"; + case "DV": return "English (US, Dvorak)"; + default: return code; + } + } + + /// + /// Maps a code or an alias (case-insensitive) to its layout code. + /// + /// The layout code ("US", "FR", ...), or null when nothing matches. + public static string ResolveCode(string codeOrAlias) + { + if (codeOrAlias == null) + { + return null; + } + + string code = codeOrAlias.Trim().ToUpperInvariant(); + + switch (code) + { + case "AZERTY": return "FR"; + case "QWERTY": return "US"; + case "QWERTZ": return "DE"; + case "DVORAK": return "DV"; + } + + for (int i = 0; i < Codes.Length; i++) + { + if (Codes[i] == code) + { + return code; + } + } + + return null; + } + + private static ScanMapBase Create(string code) + { + switch (code) + { + case "US": return new USStandardLayout(); + case "GB": return new GBStandardLayout(); + case "FR": return new AuraFRStandardLayout(); // AZERTY with an AltGr level (GEN3-GAP(keyboard-altgr)) + case "DE": return new DEStandardLayout(); + case "ES": return new ESStandardLayout(); + case "TR": return new TRStandardLayout(); + case "DV": return new USDvorakLayout(); + default: return null; + } + } + + /// + /// Activates the layout for the given code or alias (case-insensitive). + /// + /// False when the keyboard is compiled out or the code matches no known layout. + public static bool Set(string codeOrAlias) + { + // SetKeyLayout throws when the keyboard support is compiled out. + if (!KernelFeatures.Keyboard) + { + return false; + } + + string code = ResolveCode(codeOrAlias); + if (code == null) + { + return false; + } + + ScanMapBase scanMap = Create(code); + if (scanMap == null) + { + return false; + } + + CosmosKeyboard.SetKeyLayout(scanMap); + CurrentCode = code; + return true; + } + + /// + /// Saves as 'keyboardLayout' in settings.ini (add or edit). + /// Does nothing in live mode (Aura not installed). + /// + public static void Persist() + { + if (!Kernel.Installed) + { + return; + } + + string path = AuraPaths.SettingsIni; + + // Never create settings.ini from here (Setup owns it); gen2 Settings also dereferenced + // null content for a missing file (C6). + if (!File.Exists(path)) + { + return; + } + + try + { + Settings config = new Settings(path); + + if (config.GetValue(SettingName) == "null") + { + config.PutValue(SettingName, CurrentCode); + } + else + { + config.EditValue(SettingName, CurrentCode); + } + + config.PushValues(); + } + catch (Exception ex) + { + Logs.DoOSLog("[Error] Cannot save the keyboard layout: " + ex.Message); + } + } + } +} diff --git a/SRC/Aura_OS/System/Input/KeyboardManager.cs b/SRC/Aura_OS/System/Input/KeyboardManager.cs index ed79fb37a..31e3a83ba 100644 --- a/SRC/Aura_OS/System/Input/KeyboardManager.cs +++ b/SRC/Aura_OS/System/Input/KeyboardManager.cs @@ -4,16 +4,30 @@ * PROGRAMMERS: Valentin Charbonnier */ +using System; using System.Collections.Generic; -using Cosmos.System; +using Cosmos.Kernel.System; +using Cosmos.Kernel.System.Keyboard; using Aura_OS.System.Processing.Processes; using Aura_OS.Processing; +using Aura_OS.System.Filesystem; +using Aura_OS.System.Utils; +using CosmosKeyboard = Cosmos.Kernel.System.Keyboard.KeyboardManager; namespace Aura_OS.System.Input { /// /// Manages keyboard for AuraOS. /// + /// + /// This class is the ONLY caller of CosmosKeyboard.TryReadKey (convention C11). It drains the + /// kernel key queue once per frame on the UI thread, handles the global hotkeys and queues every + /// other key for TryGetKey. Everything else in Aura reads keys through TryGetKey. + /// Never use the Console input APIs (ReadKey, KeyAvailable, ReadLine, In) while the GUI runs: they move the + /// whole kernel queue into tty1's private buffer, where TryReadKey no longer sees it. + /// GEN3-GAP(console-input): Console input APIs drain KeyboardManager's queue into tty1. + /// GEN3-GAP(sessions): never open virtual consoles/sessions, they permanently swallow Alt+F1..F12 (incl. Alt+F4). + /// public class KeyboardManager : Process, IManager { private static Queue keyEvents = new Queue(); @@ -32,36 +46,88 @@ public override void Initialize() CustomConsole.WriteLineInfo("Starting keyboard manager..."); CustomConsole.WriteLineInfo("Starting keyboard..."); - Cosmos.System.KeyboardManager.SetKeyLayout(new Cosmos.System.ScanMaps.USStandardLayout()); + if (KernelFeatures.Keyboard) + { + string code = GetSavedLayoutCode(); + + if (!KeyboardLayouts.Set(code)) + { + CustomConsole.WriteLineWarning("Unknown keyboard layout '" + code + "', using US."); + KeyboardLayouts.Set("US"); + } + + CustomConsole.WriteLineInfo("Keyboard layout: " + KeyboardLayouts.CurrentCode); + } + else + { + CustomConsole.WriteLineWarning("Keyboard support is disabled in this kernel."); + } Kernel.ProcessManager.Register(this); Kernel.ProcessManager.Start(this); } + /// + /// Returns the 'keyboardLayout' value of settings.ini when Aura is installed, else "US". + /// + private static string GetSavedLayoutCode() + { + string code = "US"; + + if (Kernel.Installed) + { + try + { + Settings config = new Settings(AuraPaths.SettingsIni); + string value = config.GetValue("keyboardLayout"); + + if (value != null && value != "null" && value.Trim().Length > 0) + { + code = value.Trim(); + } + } + catch (Exception) + { + code = "US"; + } + } + + return code; + } + /// /// Updates the state of the keyboard, processing keys. /// public override void Update() { - KeyEvent keyEvent; - while (Cosmos.System.KeyboardManager.TryReadKey(out keyEvent)) + // C11: the ONLY call site of CosmosKeyboard.TryReadKey in Aura. Do not add another one. + while (CosmosKeyboard.TryReadKey(out KeyEvent keyEvent)) { - if (Cosmos.System.KeyboardManager.ControlPressed && Cosmos.System.KeyboardManager.AltPressed && keyEvent.Key == ConsoleKeyEx.Delete) + // Physical Ctrl+Alt: AltGr also reports Control|Alt in Modifiers, the globals do not. + if (CosmosKeyboard.ControlPressed && CosmosKeyboard.AltPressed && keyEvent.Key == ConsoleKeyEx.Delete) { - Power.Reboot(); + AuraPower.Reboot(); continue; } - if (Cosmos.System.KeyboardManager.AltPressed && keyEvent.Key == ConsoleKeyEx.F4) + // The event snapshot is more accurate than AltPressed, since keys are drained once per frame. + if ((keyEvent.Modifiers & ConsoleModifiers.Alt) != 0 && keyEvent.Key == ConsoleKeyEx.F4) { - if (Explorer.WindowManager.FocusedApp != null) + var focusedApp = Explorer.WindowManager.FocusedApp; + + if (focusedApp != null && focusedApp.Window != null && focusedApp.Window.Close != null && focusedApp.Window.Close.Click != null) { - Explorer.WindowManager.FocusedApp.Window.Close.Click(); + focusedApp.Window.Close.Click(); } continue; } else if (keyEvent.Key == ConsoleKeyEx.LWin) { - Explorer.ShowStartMenu = !Explorer.ShowStartMenu; + // Only once logged in: DrawWindows/DetermineTopComponent also draw and click a visible + // start menu over the login screen, which would bypass the login. + if (Kernel.LoggedIn) + { + Explorer.ShowStartMenu = !Explorer.ShowStartMenu; + } continue; } diff --git a/SRC/Aura_OS/System/Input/MouseManager.cs b/SRC/Aura_OS/System/Input/MouseManager.cs index 3bcfa16c2..592980110 100644 --- a/SRC/Aura_OS/System/Input/MouseManager.cs +++ b/SRC/Aura_OS/System/Input/MouseManager.cs @@ -7,9 +7,10 @@ using Aura_OS.Processing; using Aura_OS.System.Graphics.UI.GUI.Components; using Aura_OS.System.Processing.Processes; -using Cosmos.System; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System; +using Cosmos.Kernel.System.Graphics; using System; +using CosmosMouse = Cosmos.Kernel.System.Mouse.MouseManager; namespace Aura_OS.System.Input { @@ -99,8 +100,19 @@ public override void Initialize() IsRightButtonDown = false; CustomConsole.WriteLineInfo("Starting mouse..."); - Cosmos.System.MouseManager.ScreenWidth = Kernel.ScreenWidth; - Cosmos.System.MouseManager.ScreenHeight = Kernel.ScreenHeight; + if (KernelFeatures.Mouse) + { + // Kernel.ScreenWidth/Height hold the real canvas size; the kernel default clamp is 1024x768. + int width = (int)Kernel.ScreenWidth; + int height = (int)Kernel.ScreenHeight; + + CosmosMouse.SetScreenSize(width, height); + CosmosMouse.SetPosition(width / 2, height / 2); + } + else + { + CustomConsole.WriteLineWarning("Mouse support is disabled in this kernel."); + } CursorState = CursorState.Normal; @@ -118,7 +130,12 @@ public override void Initialize() /// public override void Update() { - if (Cosmos.System.MouseManager.MouseState == MouseState.Left) + // GEN3-GAP(mouse): buttons are level-only (no press/release events), so sample them once + // per frame and keep Aura's own edge detection below. + bool leftButton = CosmosMouse.LeftButton; + bool rightButton = CosmosMouse.RightButton; + + if (leftButton) { if (!_leftButtonPressed) { @@ -136,7 +153,7 @@ public override void Update() IsLeftButtonDown = false; } - if (Cosmos.System.MouseManager.MouseState == MouseState.Right) + if (rightButton) { if (!_rightButtonPressed) { @@ -156,7 +173,7 @@ public override void Update() HandleScroll(); - DrawCursor(Cosmos.System.MouseManager.X, Cosmos.System.MouseManager.Y); + DrawCursor(CosmosMouse.X, CosmosMouse.Y); } /// @@ -240,9 +257,11 @@ private void HandleRightDoubleClick() /// private void HandleScroll() { - if (Cosmos.System.MouseManager.ScrollDelta != 0) + // The delta accumulates until reset (the driver never clears it). + int d = CosmosMouse.ScrollDelta; + if (d != 0) { - Cosmos.System.MouseManager.ResetScrollDelta(); + CosmosMouse.ResetScrollDelta(); } } @@ -256,7 +275,7 @@ private Component DetermineTopComponent() void CheckComponent(Component component) { - if (component.Visible && component.IsInside((int)Cosmos.System.MouseManager.X, (int)Cosmos.System.MouseManager.Y)) + if (component.Visible && component.IsInside(CosmosMouse.X, CosmosMouse.Y)) { if (component.zIndex > topZIndex) { @@ -281,23 +300,45 @@ void CheckComponent(Component component) return topComponent; } - public void DrawCursor(uint x, uint y) + /// + /// Draws the software cursor into Explorer.Screen (DrawImageAlpha clips at the screen edges). + /// GEN3-GAP(hw-cursor): the IHardwareCursor facet is experimental and VMware-only; software cursor in phase 1. + /// + public void DrawCursor(int x, int y) { + // A null dereference is a fatal #PF on gen3 (C6): skip the frame if the screen or an icon is missing. + if (Explorer.Screen == null) + { + return; + } + if (CursorState == CursorState.Normal) { - Explorer.Screen.DrawImageAlpha(_cursorNormal, (int)x, (int)y); + if (_cursorNormal != null) + { + Explorer.Screen.DrawImageAlpha(_cursorNormal, x, y); + } } else if (CursorState == CursorState.ResizeHorizontal) { - Explorer.Screen.DrawImageAlpha(_cursorResizeHorizontal, (int)x - 23 / 2, (int)y); + if (_cursorResizeHorizontal != null) + { + Explorer.Screen.DrawImageAlpha(_cursorResizeHorizontal, x - 23 / 2, y); + } } else if (CursorState == CursorState.ResizeVertical) { - Explorer.Screen.DrawImageAlpha(_cursorResizeVertical, (int)x, (int)y - 23 / 2); + if (_cursorResizeVertical != null) + { + Explorer.Screen.DrawImageAlpha(_cursorResizeVertical, x, y - 23 / 2); + } } else if (CursorState == CursorState.Grab) { - Explorer.Screen.DrawImageAlpha(_cursorGrap, (int)x, (int)y); + if (_cursorGrap != null) + { + Explorer.Screen.DrawImageAlpha(_cursorGrap, x, y); + } } } diff --git a/SRC/Aura_OS/System/Logs.cs b/SRC/Aura_OS/System/Logs.cs index f8345264d..67bd32320 100644 --- a/SRC/Aura_OS/System/Logs.cs +++ b/SRC/Aura_OS/System/Logs.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Cosmos.Kernel.System.Diagnostics; namespace Aura_OS.System { @@ -26,18 +24,37 @@ public LogEntry(LogLevel level, string log, DateTime dateTime) } } + /// + /// Aura's log window entries, each also mirrored to the serial log. + /// LogLevel.Kernel carries Aura's own kernel-level messages. + /// GEN3-GAP(log-sink): there is no kernel log sink anymore (gen2 fed it from the Cosmos debugger plug). + /// Not thread-safe: a non-UI thread (the FTP server) logs with Cosmos.Kernel.System.Diagnostics.Log only. + /// public static class Logs { public static List LogList = new List(); public static void DoKernelLog(string log) { + Mirror("[Kernel] ", log); LogList.Add(new LogEntry(LogLevel.Kernel, log, DateTime.Now)); } public static void DoOSLog(string log) { + Mirror("", log); LogList.Add(new LogEntry(LogLevel.OS, log, DateTime.Now)); } + + private static void Mirror(string prefix, string log) + { + try + { + Log.WriteString(prefix + log + "\n"); + } + catch (Exception) + { + } + } } } diff --git a/SRC/Aura_OS/System/Network/Dhcp.cs b/SRC/Aura_OS/System/Network/Dhcp.cs index 440059a6a..3a4b42d54 100644 --- a/SRC/Aura_OS/System/Network/Dhcp.cs +++ b/SRC/Aura_OS/System/Network/Dhcp.cs @@ -5,9 +5,8 @@ */ using System; -using Cosmos.System.Network.Config; -using Cosmos.System.Network.IPv4.UDP.DHCP; -using Aura_OS.System.Processing.Processes; +using Cosmos.Kernel.System.Network; +using Cosmos.Kernel.System.Network.IPv4.DHCP; namespace Aura_OS.System.Network { @@ -15,33 +14,84 @@ public static class Dhcp { public static void Release() { - var xClient = new DHCPClient(); - xClient.SendReleasePacket(); - xClient.Close(); + // GEN3-GAP(dhcp): SendReleasePacket throws when nothing is configured (and always on a + // second NIC), so only release a real lease, and never let it escape. + if (NetworkHelper.IsConfigured) + { + DhcpClient xClient = null; + + try + { + xClient = new DhcpClient(); + xClient.SendReleasePacket(); + } + catch (Exception) + { + // No route to the server: nothing to release remotely. + } - NetworkConfiguration.ClearConfigs(); + // gen3: finally/using do not run on the exception path, dispose explicitly. + if (xClient != null) + { + xClient.Dispose(); + } + } - Kernel.NetworkConnected = false; - Explorer.Taskbar.MarkDirty(); + // GEN3-GAP(dhcp): SendReleasePacket leaves a 0.0.0.0 config behind, clear everything. + NetworkStack.RemoveAllConfigIP(); + + Kernel.NetworkConnected = false; // the setter marks the taskbar dirty } public static bool Ask() { - var xClient = new DHCPClient(); - if (xClient.SendDiscoverPacket() != -1) + if (NetworkManager.DeviceCount == 0) + { + Console.WriteLine("No network device found."); + return false; + } + + DhcpClient xClient = null; + int elapsed; + + try { - xClient.Close(); - Console.WriteLine("Configuration applied! Your local IPv4 Address is " + NetworkConfiguration.CurrentAddress + "."); - Kernel.NetworkConnected = true; - return true; + xClient = new DhcpClient(); + elapsed = xClient.SendDiscoverPacket(); } - else + catch (Exception ex) { - NetworkConfiguration.ClearConfigs(); + // GEN3-GAP(dhcp): ArgumentException with 2+ NICs (duplicate 0.0.0.0 in the address map), + // plain Exception when an ACK carries no client address. + Console.WriteLine("DHCP failed: " + ex.Message); + elapsed = -1; + } - xClient.Close(); + if (xClient != null) + { + xClient.Dispose(); + } + + if (elapsed == -1) + { + NetworkStack.RemoveAllConfigIP(); + Kernel.NetworkConnected = false; return false; } + + // GEN3-GAP(dhcp): a DHCPNAK is applied like an ACK (0.0.0.0) and a stray reply returns + // success with nothing applied, so check the address that is really configured. + Address address = NetworkHelper.CurrentAddress; + if (address is null) + { + NetworkStack.RemoveAllConfigIP(); + Kernel.NetworkConnected = false; + return false; + } + + Console.WriteLine("Configuration applied! Your local IPv4 Address is " + address.ToString() + "."); + Kernel.NetworkConnected = true; + return true; } } } diff --git a/SRC/Aura_OS/System/Network/Http.cs b/SRC/Aura_OS/System/Network/Http.cs index 363e3662d..7634913d1 100644 --- a/SRC/Aura_OS/System/Network/Http.cs +++ b/SRC/Aura_OS/System/Network/Http.cs @@ -4,114 +4,376 @@ * PROGRAMMER(S): Valentin Charbonnier */ -using Cosmos.System.Network.Config; -using Cosmos.System.Network.IPv4.UDP.DNS; -using Cosmos.System.Network.IPv4; -using CosmosHttp.Client; +using System; +using System.Diagnostics; +using System.Globalization; +using System.IO; using System.Net; +using System.Net.Sockets; using System.Text; +using Cosmos.Kernel.System.Timer; namespace Aura_OS.System.Network { + /// + /// Error raised by the HTTP client (bad URL, DNS failure, HTTP status, timeout...). + /// + public sealed class HttpException : Exception + { + public int StatusCode { get; } + + public HttpException(string message, int statusCode = 0) : base(message) + { + StatusCode = statusCode; + } + } + + /// + /// Minimal HTTP/1.1 GET client (no TLS: http:// only). + /// GEN3-GAP(http-tls): no HttpClient and no TLS in gen3, and the gen2 HTTP package is gone. + /// public static class Http { + private const int IdleTimeoutMs = 15000; + private const int MaxRedirects = 3; + + public static string DownloadFile(string url) + { + byte[] data = DownloadRawFile(url); + + // Skip a UTF-8 BOM so JSON readers see '{' / '[' first. + int start = data.Length >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF ? 3 : 0; + + return Encoding.UTF8.GetString(data, start, data.Length - start); + } + public static byte[] DownloadRawFile(string url) { - if (url.StartsWith("https://")) + if (string.IsNullOrEmpty(url)) { - throw new WebException("HTTPS currently not supported, please use http://"); + throw new HttpException("No URL given."); } - string path = ExtractPathFromUrl(url); - string domainName = ExtractDomainNameFromUrl(url); + for (int hop = 0; hop <= MaxRedirects; hop++) + { + string host; + int port; + string path; + ParseUrl(url, out host, out port, out path); + + byte[] raw = Get(host, port, path); + + int bodyStart = FindBodyStart(raw, raw.Length); + if (bodyStart < 0) + { + throw new HttpException("Malformed HTTP response."); + } + + string headers = Encoding.ASCII.GetString(raw, 0, bodyStart); + int status = ParseStatus(headers); - var dnsClient = new DnsClient(); + if (status == 301 || status == 302 || status == 303 || status == 307 || status == 308) + { + string location = GetHeader(headers, "Location"); + if (string.IsNullOrEmpty(location)) + { + throw new HttpException("Redirect without Location.", status); + } - dnsClient.Connect(DNSConfig.DNSNameservers[0]); - dnsClient.SendAsk(domainName); - Address address = dnsClient.Receive(); - dnsClient.Close(); + // An https:// Location is rejected by ParseUrl on the next hop. + url = location.StartsWith("/") ? "http://" + host + (port == 80 ? "" : ":" + port.ToString()) + location : location; + continue; + } - HttpRequest request = new(); - request.IP = address.ToString(); - request.Domain = domainName; - request.Path = path; - request.Method = "GET"; - request.Send(); + if (status < 200 || status > 299) + { + throw new HttpException("HTTP error " + status.ToString(), status); + } - return request.Response.GetStream(); + return ExtractBody(raw, headers, bodyStart); + } + + throw new HttpException("Too many redirects."); } - public static string DownloadFile(string url) + private static byte[] Get(string host, int port, string path) { - if (url.StartsWith("https://")) + IPAddress address = Resolve(host); + + TcpClient client = new TcpClient(); + byte[] response = null; + string error = null; + + try { - throw new WebException("HTTPS currently not supported, please use http://"); + // GEN3-GAP(socket-misc): bare Exception after 5 s without SYN-ACK, + // InvalidOperationException without an IPv4 config on the primary adapter. + client.Connect(address, port); + + // GEN3-GAP(tcp-receive): raw Socket + byte[] only (span receives drop data, + // GetStream throws once the server has already answered and closed). + Socket socket = client.Client; + if (socket == null) + { + // gen3: a null dereference halts the kernel, the plug returns null for an unknown client. + throw new InvalidOperationException("Not connected to " + host + "."); + } + + byte[] request = Encoding.ASCII.GetBytes( + "GET " + path + " HTTP/1.1\r\n" + + "Host: " + host + (port == 80 ? "" : ":" + port.ToString()) + "\r\n" + + "User-Agent: AuraOS/" + Kernel.Version + "\r\n" + + "Accept: */*\r\nAccept-Encoding: identity\r\nConnection: close\r\n\r\n"); + + socket.Send(request, 0, request.Length, SocketFlags.None); + response = ReadToEnd(socket); + } + catch (Exception ex) + { + error = ex.Message; } - string path = ExtractPathFromUrl(url); - string domainName = ExtractDomainNameFromUrl(url); + // gen3: finally does not run on the exception path, close explicitly. + try + { + client.Close(); + } + catch (Exception) + { + // FIN timeout: the plug detaches the connection anyway. + } + + // Never hand a null response to the parser (a null dereference halts the kernel). + if (error != null || response == null) + { + throw new HttpException(error ?? "HTTP request to " + host + " failed."); + } - var dnsClient = new DnsClient(); + return response; + } - dnsClient.Connect(DNSConfig.DNSNameservers[0]); - dnsClient.SendAsk(domainName); - Address address = dnsClient.Receive(); - dnsClient.Close(); + private static IPAddress Resolve(string host) + { + IPAddress literal; + if (IPAddress.TryParse(host, out literal)) + { + return literal; + } - HttpRequest request = new(); - request.IP = address.ToString(); - request.Domain = domainName; - request.Path = path; - request.Method = "GET"; - request.Send(); + // GEN3-GAP(socket-misc): TcpClient.Connect(string, int) does not resolve names, resolve first. + try + { + IPAddress[] addresses = Dns.GetHostAddresses(host); // plugged: A records, DnsConfig.Nameservers[0] + if (addresses != null && addresses.Length > 0) + { + return addresses[0]; + } + } + catch (Exception) + { + // SocketException: no nameserver, no route or unknown host. + } - return request.Response.Content; + throw new HttpException("Unable to resolve " + host + " (configure the network / a DNS server first)."); } - private static string ExtractDomainNameFromUrl(string url) + /// + /// Reads until the peer closes (Connection: close), Content-Length is reached, or idle timeout. + /// + private static byte[] ReadToEnd(Socket socket) { - int start; - if (url.Contains("://")) + MemoryStream response = new MemoryStream(); + byte[] buffer = new byte[4096]; + long lastData = Stopwatch.GetTimestamp(); + int bodyStart = -1; + long contentLength = -1; + + while (true) { - start = url.IndexOf("://") + 3; + int available = socket.Available; + if (available > 0) + { + int read = socket.Receive(buffer, 0, Math.Min(available, buffer.Length), SocketFlags.None); + response.Write(buffer, 0, read); + lastData = Stopwatch.GetTimestamp(); + + if (bodyStart < 0) + { + bodyStart = FindBodyStart(response.GetBuffer(), (int)response.Length); + if (bodyStart >= 0) + { + contentLength = GetContentLength(Encoding.ASCII.GetString(response.GetBuffer(), 0, bodyStart)); + } + } + + if (bodyStart >= 0 && contentLength >= 0 && response.Length >= bodyStart + contentLength) + { + break; + } + + continue; + } + + // GEN3-GAP(tcp-receive): Receive returns 0 while the connection is open. + // Readable with nothing to read means the server closed its side. + if (socket.Poll(0, SelectMode.SelectRead) && socket.Available == 0) + { + break; + } + + if (Stopwatch.GetElapsedTime(lastData).TotalMilliseconds > IdleTimeoutMs) + { + throw new HttpException("Timed out waiting for the server."); + } + + TimerManager.Wait(10); // hlt loop: the UI thread must never sleep or block (C9) + } + + return response.ToArray(); + } + + private static void ParseUrl(string url, out string host, out int port, out string path) + { + if (url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + { + throw new NotSupportedException("HTTPS is not supported (no TLS), use http://"); } - else + + string rest = url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? url.Substring(7) : url; + int slash = rest.IndexOf('/'); + string authority = slash < 0 ? rest : rest.Substring(0, slash); + path = slash < 0 ? "/" : rest.Substring(slash); + + port = 80; + int colon = authority.LastIndexOf(':'); + if (colon >= 0) { - start = 0; + if (!int.TryParse(authority.Substring(colon + 1), out port) || port < 1 || port > 65535) + { + throw new HttpException("Invalid port in " + url); + } + + authority = authority.Substring(0, colon); } - int end = url.IndexOf("/", start); - if (end == -1) + if (authority.Length == 0) { - end = url.Length; + throw new HttpException("No host in " + url); } - return url[start..end]; + host = authority; } + private static int ParseStatus(string headers) + { + // "HTTP/1.1 200 OK" + int space = headers.IndexOf(' '); + int status; - private static string ExtractPathFromUrl(string url) + if (!headers.StartsWith("HTTP/") || space < 0 || headers.Length < space + 4 + || !int.TryParse(headers.Substring(space + 1, 3), out status)) + { + throw new HttpException("Malformed HTTP status line."); + } + + return status; + } + + private static string GetHeader(string headers, string name) { - int start; - if (url.Contains("://")) + foreach (string line in headers.Split("\r\n")) { - start = url.IndexOf("://") + 3; + int colon = line.IndexOf(':'); + if (colon > 0 && string.Equals(line.Substring(0, colon).Trim(), name, StringComparison.OrdinalIgnoreCase)) + { + return line.Substring(colon + 1).Trim(); + } } - else + + return null; + } + + private static long GetContentLength(string headers) + { + long length; + return long.TryParse(GetHeader(headers, "Content-Length"), out length) && length >= 0 ? length : -1; + } + + private static int FindBodyStart(byte[] data, int length) + { + for (int i = 0; i + 3 < length; i++) { - start = 0; + if (data[i] == '\r' && data[i + 1] == '\n' && data[i + 2] == '\r' && data[i + 3] == '\n') + { + return i + 4; + } } - int indexOfSlash = url.IndexOf("/", start); - if (indexOfSlash != -1) + return -1; + } + + private static byte[] ExtractBody(byte[] raw, string headers, int bodyStart) + { + if (string.Equals(GetHeader(headers, "Transfer-Encoding"), "chunked", StringComparison.OrdinalIgnoreCase)) { - return url.Substring(indexOfSlash); + return DecodeChunked(raw, bodyStart); } - else + + int available = raw.Length - bodyStart; + long contentLength = GetContentLength(headers); + int length = contentLength >= 0 && contentLength < available ? (int)contentLength : available; + + byte[] body = new byte[length]; + Buffer.BlockCopy(raw, bodyStart, body, 0, length); + return body; + } + + private static byte[] DecodeChunked(byte[] raw, int pos) + { + MemoryStream body = new MemoryStream(); + + while (pos < raw.Length) { - return "/"; + int lineEnd = pos; + while (lineEnd + 1 < raw.Length && !(raw[lineEnd] == '\r' && raw[lineEnd + 1] == '\n')) + { + lineEnd++; + } + + if (lineEnd + 1 >= raw.Length) + { + break; + } + + string sizeText = Encoding.ASCII.GetString(raw, pos, lineEnd - pos); + int semicolon = sizeText.IndexOf(';'); // chunk extensions + if (semicolon >= 0) + { + sizeText = sizeText.Substring(0, semicolon); + } + + int size; + if (!int.TryParse(sizeText.Trim(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out size)) + { + throw new HttpException("Malformed chunk size."); + } + + pos = lineEnd + 2; + if (size == 0) + { + break; // last chunk; trailers ignored + } + + if (pos + size > raw.Length) + { + throw new HttpException("Truncated chunked body."); + } + + body.Write(raw, pos, size); + pos += size + 2; // skip the CRLF after the chunk data } + + return body.ToArray(); } } } diff --git a/SRC/Aura_OS/System/Network/NetworkHelper.cs b/SRC/Aura_OS/System/Network/NetworkHelper.cs new file mode 100644 index 000000000..9035b038e --- /dev/null +++ b/SRC/Aura_OS/System/Network/NetworkHelper.cs @@ -0,0 +1,125 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: Network helpers (gen2 ConfigEmpty / CurrentAddress / NameID / GetDeviceByName / DNS) +* PROGRAMMERS: Valentin Charbonnier +*/ + +using System; +using Cosmos.Kernel.System.Network; +using Cosmos.Kernel.System.Network.Config; +using Cosmos.Kernel.System.Network.DNS; + +namespace Aura_OS.System.Network +{ + public static class NetworkHelper + { + /// + /// gen2 !ConfigEmpty(). A 0.0.0.0 config (left by DHCP timeout/release) counts as none. + /// GEN3-GAP(dhcp) + /// + public static bool IsConfigured + { + get + { + for (int i = 0; i < NetworkManager.DeviceCount; i++) + { + IPConfig config = NetworkManager.GetAdapter(i).IPConfig; + if (config is not null && !config.Address.IsZero) + { + return true; + } + } + + return false; + } + } + + /// + /// gen2 NetworkConfiguration.CurrentAddress: the primary adapter's address, null when unconfigured or 0.0.0.0. + /// + public static Address CurrentAddress + { + get + { + IPConfig config = NetworkManager.Primary.IPConfig; + return config is null || config.Address.IsZero ? null : config.Address; + } + } + + /// + /// gen2 NetworkDevice.NameID. GEN3-GAP(nic-names): gen3 has no stable interface names. + /// + public static string AliasOf(NetworkAdapter adapter) => "eth" + adapter.Index.ToString(); + + /// + /// gen2 NetworkDevice.GetDeviceByName: accepts "eth0", "0" or the driver name. + /// Returns default (IsValid == false) when none matches. + /// + public static NetworkAdapter FindAdapter(string name) + { + if (string.IsNullOrEmpty(name)) + { + return default; + } + + for (int i = 0; i < NetworkManager.DeviceCount; i++) + { + NetworkAdapter adapter = NetworkManager.GetAdapter(i); + if (name == AliasOf(adapter) || name == i.ToString() + || string.Equals(name, adapter.Name, StringComparison.OrdinalIgnoreCase)) + { + return adapter; + } + } + + return default; // IsValid == false + } + + /// + /// IP literal or DNS name -> Cosmos Address (A record). Null on failure (bad name, no reply, + /// no DNS server, or no configured interface reaching it). + /// + public static Address Resolve(string hostOrIp, Address server = null, int timeoutMs = 5000) + { + if (string.IsNullOrEmpty(hostOrIp)) + { + return null; + } + + Address literal = Address.Parse(hostOrIp); + if (literal is not null) + { + return literal; + } + + server ??= DnsConfig.Nameservers.Count > 0 ? DnsConfig.Nameservers[0] : null; + if (server is null) + { + return null; + } + + // gen3: finally/using do not run on the exception path, dispose explicitly. + DnsClient dns = null; + Address result = null; + + try + { + dns = new DnsClient(); + dns.Connect(server); + dns.SendQuery(hostOrIp); // InvalidOperationException: no configured interface reaches the server + result = dns.Receive(timeoutMs); + } + catch (Exception) + { + result = null; + } + + if (dns is not null) + { + dns.Dispose(); + } + + return result; + } + } +} diff --git a/SRC/Aura_OS/System/Network/Version.cs b/SRC/Aura_OS/System/Network/Version.cs index 4ccc53e02..e671713c1 100644 --- a/SRC/Aura_OS/System/Network/Version.cs +++ b/SRC/Aura_OS/System/Network/Version.cs @@ -12,8 +12,13 @@ namespace Aura_OS.System.Network { public static class Version { + /// + /// Latest release info. Throws on any network/HTTP/JSON failure: callers wrap it in try/catch. + /// public static (string, string, string) GetLastVersionInfo() { + // GEN3-GAP(backend): http://aura.valentin.bzh/os.json currently answers 301 -> https, then 404, + // and gen3 has no TLS, so this throws until the file is served over plain HTTP. string json = Http.DownloadFile("http://aura.valentin.bzh/os.json"); JsonReader rdr = new(json); @@ -52,6 +57,12 @@ public static (string, string, string) GetLastVersionInfo() public static int CompareVersions(string version1, string version2) { + // Null-safe: a missing version (failed update check) compares as equal. + if (version1 == null || version2 == null) + { + return 0; + } + var version1Parts = version1.Split('.').Select(v => int.TryParse(v, out int val) ? val : 0).ToArray(); var version2Parts = version2.Split('.').Select(v => int.TryParse(v, out int val) ? val : 0).ToArray(); diff --git a/SRC/Aura_OS/System/Parser/NanoXMLParser.cs b/SRC/Aura_OS/System/Parser/NanoXMLParser.cs index c3e0b7a6d..2ec0a900e 100644 --- a/SRC/Aura_OS/System/Parser/NanoXMLParser.cs +++ b/SRC/Aura_OS/System/Parser/NanoXMLParser.cs @@ -97,6 +97,12 @@ public NanoXMLDocument(string xmlString) { int i = 0; + // Skip a leading BOM (U+FEFF): Encoding.UTF8.GetString keeps it, and it is not a valid token. + if (xmlString != null && xmlString.Length > 0 && xmlString[0] == '\uFEFF') + { + i = 1; + } + while (true) { SkipSpaces(xmlString, ref i); diff --git a/SRC/Aura_OS/System/Processing/ApplicationManager.cs b/SRC/Aura_OS/System/Processing/ApplicationManager.cs index 5b6b1a035..70c2cfd3a 100644 --- a/SRC/Aura_OS/System/Processing/ApplicationManager.cs +++ b/SRC/Aura_OS/System/Processing/ApplicationManager.cs @@ -9,7 +9,7 @@ using Aura_OS.System.Processing.Applications.Emulators.GameBoyEmu; using Aura_OS.System.Processing.Applications.Terminal; using Aura_OS.System.Processing.Processes; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; using System; using System.Collections.Generic; using System.IO; @@ -160,12 +160,32 @@ public Application Instantiate(ApplicationConfig config) public void StartFileApplication(string fileName, string currentPath) { - if (fileName.EndsWith(".bmp")) + // A null dereference halts the kernel on gen3, and Path.Combine throws on a null path. + if (string.IsNullOrEmpty(fileName) || currentPath == null) { - string path = currentPath + fileName; + return; + } + + if (fileName.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase)) + { + string path = Path.Combine(currentPath, fileName); string name = fileName; - byte[] bytes = File.ReadAllBytes(path); - Bitmap bitmap = new Bitmap(bytes); + Bitmap bitmap; + + // GEN3-GAP(bmp): the gen3 BMP loader throws on top-down and < 24 bpp files (BI_BITFIELDS + // masks are ignored). CheckBmpHeader rejects the headers it cannot survive at all. + try + { + byte[] bytes = File.ReadAllBytes(path); + CheckBmpHeader(bytes); + bitmap = new Bitmap(bytes); + } + catch (Exception ex) + { + ReportOpenError(path, ex); + return; + } + int width = name.Length * 8 + 50; if (width < bitmap.Width) @@ -183,13 +203,23 @@ public void StartFileApplication(string fileName, string currentPath) Explorer.Taskbar.UpdateApplicationButtons(); } - else if (fileName.EndsWith(".gb")) + else if (fileName.EndsWith(".gb", StringComparison.OrdinalIgnoreCase)) { - string path = currentPath + fileName; + string path = Path.Combine(currentPath, fileName); string name = fileName; - byte[] bytes = File.ReadAllBytes(path); + GameBoyApp app; + + try + { + byte[] bytes = File.ReadAllBytes(path); + app = new GameBoyApp(bytes, name, 160 + 6, 144 + 26, 40, 40); + } + catch (Exception ex) + { + ReportOpenError(path, ex); + return; + } - var app = new GameBoyApp(bytes, name, 160 + 6, 144 + 26, 40, 40); app.Initialize(); app.MarkFocused(); app.Visible = true; @@ -201,9 +231,19 @@ public void StartFileApplication(string fileName, string currentPath) } else { - string path = currentPath + fileName; + string path = Path.Combine(currentPath, fileName); + EditorApp app; + + try + { + app = new EditorApp(path, 701, 600, 40, 40); + } + catch (Exception ex) + { + ReportOpenError(path, ex); + return; + } - var app = new EditorApp(path, 701, 600, 40, 40); app.Initialize(); app.MarkFocused(); app.Visible = true; @@ -215,6 +255,36 @@ public void StartFileApplication(string fileName, string currentPath) } } + /// + /// Reports a file that could not be opened (unreadable file, unsupported image or ROM). + /// Logged rather than drawn: CustomConsole would paint the full-screen boot console over the desktop. + /// + private static void ReportOpenError(string path, Exception ex) + { + Logs.DoOSLog("[Error] Cannot open '" + path + "': " + ex.Message); + } + + /// + /// Throws for a BMP header the gen3 loader cannot survive: it divides by the height (a #DE + /// halts the kernel) and allocates Width * Height pixels before reading any pixel data. + /// + private static void CheckBmpHeader(byte[] bytes) + { + if (bytes == null || bytes.Length < 54) + { + throw new InvalidDataException("The file is too small to be a BMP image."); + } + + int width = BitConverter.ToInt32(bytes, 18); + int height = BitConverter.ToInt32(bytes, 22); + + // Only 24 and 32 bpp are supported, so every pixel takes at least 3 bytes of the file. + if (width <= 0 || height <= 0 || (long)width * height * 3 > bytes.Length) + { + throw new InvalidDataException("Unsupported BMP size " + width + "x" + height + "."); + } + } + public Application GetApplicationByPid(uint pid) { return Kernel.ProcessManager.GetProcessByPid(pid) as Application; diff --git a/SRC/Aura_OS/System/Processing/Applications/EditorApp.cs b/SRC/Aura_OS/System/Processing/Applications/EditorApp.cs index 4e927019d..e624cb0fb 100644 --- a/SRC/Aura_OS/System/Processing/Applications/EditorApp.cs +++ b/SRC/Aura_OS/System/Processing/Applications/EditorApp.cs @@ -10,7 +10,7 @@ using Aura_OS.System.Processing.Processes; using Aura_OS.System.Graphics.UI.GUI; using Aura_OS.System.Graphics.UI.GUI.Components; -using Cosmos.System; +using Cosmos.Kernel.System.Keyboard; namespace Aura_OS.System.Processing.Applications { @@ -45,7 +45,11 @@ public EditorApp(string filePath, int width, int height, int x = 0, int y = 0) _fileContentBox = new TextBox(3, _topPanel.Height + Window.TopBar.Height + 3, width - 5, height - _topPanel.Height - Window.TopBar.Height - 6, ""); _fileContentBox.Multiline = true; - _fileContentBox.Text = File.ReadAllText(filePath); + // An empty path (new document from the start menu) or a file that does not exist yet opens empty. + if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath)) + { + _fileContentBox.Text = File.ReadAllText(filePath); + } AddChild(_fileContentBox); _dialog = new("Save", "Your file has been saved!", (int)Width / 2 - 302 / 2, Height / 2 - 119 / 2); @@ -60,7 +64,29 @@ public EditorApp(string filePath, int width, int height, int x = 0, int y = 0) private void SaveFile() { - File.WriteAllText(_filePath, _fileContentBox.Text); + if (string.IsNullOrEmpty(_filePath)) + { + ShowDialog(DialogState.Error, "This document has no file path, nothing was saved."); + return; + } + + try + { + File.WriteAllText(_filePath, _fileContentBox.Text); + } + catch (Exception ex) + { + ShowDialog(DialogState.Error, "Save failed: " + ex.Message); + return; + } + + ShowDialog(DialogState.Information, "Your file has been saved!"); + } + + private void ShowDialog(DialogState state, string message) + { + _dialog.SetState(state); + _dialog.Message = message; _dialog.Visible = true; MarkDirty(); } diff --git a/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/DMG/Cycles.cs b/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/DMG/Cycles.cs index f1f71e066..206af0fb4 100644 --- a/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/DMG/Cycles.cs +++ b/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/DMG/Cycles.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; namespace Aura_OS.System.Processing.Applications.Emulators.GameBoyEmu.DMG { diff --git a/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/DMG/JOYPAD.cs b/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/DMG/JOYPAD.cs index 5c5361dc1..72fc71050 100644 --- a/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/DMG/JOYPAD.cs +++ b/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/DMG/JOYPAD.cs @@ -1,4 +1,4 @@ -using Cosmos.System; +using Cosmos.Kernel.System.Keyboard; using static Aura_OS.System.Processing.Applications.Emulators.GameBoyEmu.Utils.BitOps; namespace Aura_OS.System.Processing.Applications.Emulators.GameBoyEmu.DMG diff --git a/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/DMG/MMU.cs b/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/DMG/MMU.cs index 9f5c688d8..d5b0ebe37 100644 --- a/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/DMG/MMU.cs +++ b/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/DMG/MMU.cs @@ -194,7 +194,6 @@ public void writeByte(ushort addr, byte b) } //if (addr == 0xFF02 && b == 0x81) { //Temp Serial Link output for debug //Console.Write(Convert.ToChar(readByte(0xFF01))); - //Console.ReadLine(); //} IO[addr & 0x7F] = b; break; @@ -242,6 +241,14 @@ private void DMA(byte b) public void loadGamePak(byte[] rom) { + // GEN3-GAP(null-deref): a null dereference halts the kernel, so reject bad ROMs with a + // catchable exception instead of calling Init on a null gamePak. The smallest cartridge is + // 32 KiB (two 16 KiB banks); a shorter file would index past the ROM array while running. + if (rom == null || rom.Length < 0x8000) + { + throw new ArgumentException("Invalid GameBoy ROM."); + } + switch (rom[0x147]) { case 0x00: @@ -269,8 +276,7 @@ public void loadGamePak(byte[] rom) gamePak = new MBC5(); break; default: - Console.WriteLine("Unsupported MBC: " + rom[0x147].ToString("x2")); - break; + throw new NotSupportedException("Unsupported MBC: " + rom[0x147].ToString("x2")); } gamePak.Init(rom); } diff --git a/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/GameBoyApp.cs b/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/GameBoyApp.cs index 3c7b460f2..7a0f0e77d 100644 --- a/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/GameBoyApp.cs +++ b/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/GameBoyApp.cs @@ -4,11 +4,11 @@ * PROGRAMMERS: Valentin Charbonnier */ +using System.Collections.Generic; using Aura_OS.System.Graphics.UI.GUI; using Aura_OS.System.Processing.Applications.Emulators.GameBoyEmu.DMG; using Aura_OS.System.Processing.Applications.Emulators.GameBoyEmu.Utils; -using Cosmos.Core; -using Cosmos.System; +using Cosmos.Kernel.System.Keyboard; using CPU = Aura_OS.System.Processing.Applications.Emulators.GameBoyEmu.DMG.CPU; namespace Aura_OS.System.Processing.Applications.Emulators.GameBoyEmu @@ -52,7 +52,8 @@ public GameBoyApp(int width, int height, int x = 0, int y = 0) : base("GameBoyEm _mmu.loadGamePak(Rom); } - private KeyEvent keyEvent = null; + // Keys pressed this frame. Reused to avoid a per-frame allocation. + private List _pressedKeys = new List(); public override void Update() { @@ -60,9 +61,12 @@ public override void Update() if (Focused) { + KeyEvent keyEvent; + while (Input.KeyboardManager.TryGetKey(out keyEvent)) { _joypad.handleKeyDown(keyEvent.Key); + _pressedKeys.Add(keyEvent.Key); } } @@ -78,15 +82,14 @@ public override void Update() } _cyclesThisUpdate -= Constants.CYCLES_PER_UPDATE; - if (Focused) + // GEN3-GAP(key-release): only key presses are queued, so a key is held for one emulation + // slice and released here. (gen2 meant to do this but released nothing: the last failing + // TryGetKey had already set its out field to null.) + for (int i = 0; i < _pressedKeys.Count; i++) { - if (keyEvent != null) - { - _joypad.handleKeyUp(keyEvent.Key); - - keyEvent = null; - } + _joypad.handleKeyUp(_pressedKeys[i]); } + _pressedKeys.Clear(); } private void handleInterrupts() diff --git a/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/Utils/Constants.cs b/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/Utils/Constants.cs index 7ebb9ce7b..cca5e2338 100644 --- a/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/Utils/Constants.cs +++ b/SRC/Aura_OS/System/Processing/Applications/Emulators/GameBoyEmu/Utils/Constants.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; namespace Aura_OS.System.Processing.Applications.Emulators.GameBoyEmu.Utils { diff --git a/SRC/Aura_OS/System/Processing/Applications/MemoryInfoApp.cs b/SRC/Aura_OS/System/Processing/Applications/MemoryInfoApp.cs index 308307c58..54b154785 100644 --- a/SRC/Aura_OS/System/Processing/Applications/MemoryInfoApp.cs +++ b/SRC/Aura_OS/System/Processing/Applications/MemoryInfoApp.cs @@ -4,9 +4,9 @@ * PROGRAMMERS: Valentin Charbonnier */ +using System; using Aura_OS.System.Graphics.UI.GUI; -using Cosmos.Core; -using Cosmos.Core.Memory; +using Cosmos.Kernel.System.Diagnostics; namespace Aura_OS.System.Processing.Applications { @@ -14,6 +14,14 @@ public class MemoryInfoApp : Application { public static string ApplicationName = "MemoryInfo"; + // Last-collection figures from GC.GetGCMemoryInfo(), refreshed only when a collection + // happened (the snapshot does not change in between, and each call allocates). + private int _lastCollection = -1; + private long _gcHeapSize; + private long _gcCommitted; + private long _gcFragmented; + private long _gcPinnedObjects; + public MemoryInfoApp(int width, int height, int x = 0, int y = 0) : base(ApplicationName, width, height, x, y) { ForceDirty = true; @@ -23,16 +31,36 @@ public override void Draw() { base.Draw(); - DrawString("Available RAM = " + GCImplementation.GetAvailableRAM() + "MB", 0, 0); - DrawString("Used RAM = " + GCImplementation.GetUsedRAM() + "B", 0, (0 + Kernel.font.Height)); - DrawString("Small Allocated Object Count = " + HeapSmall.GetAllocatedObjectCount(), 0, (0 + 2 * Kernel.font.Height)); - DrawString("Small Page Count = " + RAT.GetPageCount((byte)RAT.PageType.HeapSmall), 0, (0 + 3 * Kernel.font.Height)); - DrawString("Medium Page Count = " + RAT.GetPageCount((byte)RAT.PageType.HeapMedium), 0, (0 + 4 * Kernel.font.Height)); - DrawString("Large Page Count = " + RAT.GetPageCount((byte)RAT.PageType.HeapLarge), 0, (0 + 5 * Kernel.font.Height)); - DrawString("RAT Page Count = " + RAT.GetPageCount((byte)RAT.PageType.RAT), 0, (0 + 6 * Kernel.font.Height)); - DrawString("SMT Page Count = " + RAT.GetPageCount((byte)RAT.PageType.SMT), 0, (0 + 7 * Kernel.font.Height)); - DrawString("GC Managed Page Count = " + RAT.GetPageCount((byte)RAT.PageType.SMT), 0, (0 + 8 * Kernel.font.Height)); - DrawString("Free Count = " + Kernel.FreeCount, 0, (0 + 9 * Kernel.font.Height)); + ulong totalPages = MemoryInfo.TotalPages; + ulong freePages = MemoryInfo.FreePages; + ulong pageSize = MemoryInfo.PageSizeBytes; + + int collections = MemoryInfo.TotalCollections; + if (collections != _lastCollection) + { + GCMemoryInfo gcInfo = GC.GetGCMemoryInfo(); + _gcHeapSize = gcInfo.HeapSizeBytes; + _gcCommitted = gcInfo.TotalCommittedBytes; + _gcFragmented = gcInfo.FragmentedBytes; + _gcPinnedObjects = gcInfo.PinnedObjectsCount; + _lastCollection = collections; + } + + // GEN3-GAP(meminfo): the page allocator's pool is the largest usable memory-map region only. + DrawString("Memory pool = " + ((totalPages * pageSize) >> 20) + "MB", 0, 0); + DrawString("Used memory = " + (((totalPages - freePages) * pageSize) >> 20) + "MB", 0, (0 + Kernel.font.Height)); + DrawString("Free memory = " + ((freePages * pageSize) >> 20) + "MB", 0, (0 + 2 * Kernel.font.Height)); + DrawString("Total Page Count = " + totalPages + " (" + pageSize + "B)", 0, (0 + 3 * Kernel.font.Height)); + DrawString("Free Page Count = " + freePages, 0, (0 + 4 * Kernel.font.Height)); + DrawString("Live heap = " + GC.GetTotalMemory(false) + "B", 0, (0 + 5 * Kernel.font.Height)); + DrawString("Heap size (last GC) = " + _gcHeapSize + "B", 0, (0 + 6 * Kernel.font.Height)); + DrawString("Committed (last GC) = " + _gcCommitted + "B", 0, (0 + 7 * Kernel.font.Height)); + DrawString("Fragmented (last GC) = " + _gcFragmented + "B", 0, (0 + 8 * Kernel.font.Height)); + DrawString("Pinned objects (last GC) = " + _gcPinnedObjects, 0, (0 + 9 * Kernel.font.Height)); + DrawString("Collections = " + collections, 0, (0 + 10 * Kernel.font.Height)); + DrawString("Objects freed = " + MemoryInfo.TotalObjectsFreed, 0, (0 + 11 * Kernel.font.Height)); + DrawString("GC time = " + MemoryInfo.GcTimePercent + "%", 0, (0 + 12 * Kernel.font.Height)); + DrawString("Free Count = " + Kernel.FreeCount, 0, (0 + 13 * Kernel.font.Height)); } } } diff --git a/SRC/Aura_OS/System/Processing/Applications/PictureApp.cs b/SRC/Aura_OS/System/Processing/Applications/PictureApp.cs index ca85431ec..6a1810678 100644 --- a/SRC/Aura_OS/System/Processing/Applications/PictureApp.cs +++ b/SRC/Aura_OS/System/Processing/Applications/PictureApp.cs @@ -5,7 +5,7 @@ */ using Aura_OS.System.Graphics.UI.GUI; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; namespace Aura_OS.System.Processing.Applications { diff --git a/SRC/Aura_OS/System/Processing/Applications/SampleApp.cs b/SRC/Aura_OS/System/Processing/Applications/SampleApp.cs index fa23dad6b..39ab81700 100644 --- a/SRC/Aura_OS/System/Processing/Applications/SampleApp.cs +++ b/SRC/Aura_OS/System/Processing/Applications/SampleApp.cs @@ -6,7 +6,7 @@ using Aura_OS.System.Graphics.UI.GUI; using Aura_OS.System.Graphics.UI.GUI.Components; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; using System.ComponentModel; using System.Drawing; using Component = Aura_OS.System.Graphics.UI.GUI.Components.Component; diff --git a/SRC/Aura_OS/System/Processing/Applications/SettingsApp.cs b/SRC/Aura_OS/System/Processing/Applications/SettingsApp.cs index 12b8d63c0..e07b5781a 100644 --- a/SRC/Aura_OS/System/Processing/Applications/SettingsApp.cs +++ b/SRC/Aura_OS/System/Processing/Applications/SettingsApp.cs @@ -5,14 +5,16 @@ */ using System; +using System.Collections.Generic; using System.Drawing; using System.IO; +using Aura_OS.System.Filesystem; using Aura_OS.System.Graphics.UI.GUI; using Aura_OS.System.Graphics.UI.GUI.Components; using Aura_OS.System.Processing.Interpreter.Commands; using Aura_OS.System.Processing.Processes; using Aura_OS.System.Utils; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; namespace Aura_OS.System.Processing.Applications { @@ -49,8 +51,8 @@ public class SettingsApp : Application private Dialog _dialog; - private uint _oldScreenWidth; - private uint _oldScreenHeight; + private int _oldScreenWidth; + private int _oldScreenHeight; private string _oldWallpaperPath; private bool _waitingReboot = false; @@ -89,11 +91,19 @@ public SettingsApp(int width, int height, int x = 0, int y = 0) : base(Applicati if (Kernel.Installed) { - Settings config = new Settings(@"0:\System\settings.ini"); + Settings config = new Settings(AuraPaths.SettingsIni); string autologin = config.GetValue("autologin"); - byte windowsTransparency = byte.Parse(config.GetValue("windowsTransparency")); + byte windowsTransparency; + if (!byte.TryParse(config.GetValue("windowsTransparency"), out windowsTransparency)) + { + windowsTransparency = 0xFF; + } _windowsAlpha.Value = windowsTransparency; - byte taskbarTransparency = byte.Parse(config.GetValue("taskbarTransparency")); + byte taskbarTransparency; + if (!byte.TryParse(config.GetValue("taskbarTransparency"), out taskbarTransparency)) + { + taskbarTransparency = 0xFF; + } _taskbarAlpha.Value = taskbarTransparency; if (autologin == "true") @@ -116,24 +126,58 @@ public SettingsApp(int width, int height, int x = 0, int y = 0) : base(Applicati _save.Click = new Action(() => { + // Reset a previous error; keep the reboot notice once a resolution change is pending. + _dialog.SetState(DialogState.Information); + _dialog.Message = _waitingReboot ? "Settings updated. Reboot needed to change resolution." : "Settings updated."; + Kernel.userLogged = _username.Text; Kernel.ComputerName = _computerName.Text; - Kernel.ThemeManager.BmpPath = _themeBmpPath.Text; - Kernel.ThemeManager.XmlPath = _themeXmlPath.Text; + if (!string.IsNullOrEmpty(Kernel.ComputerName)) + { + Cosmos.Kernel.System.Network.Config.DnsConfig.HostName = Kernel.ComputerName; + } + Kernel.ThemeManager.BmpPath = NormalizePath(_themeBmpPath.Text); + Kernel.ThemeManager.XmlPath = NormalizePath(_themeXmlPath.Text); Explorer.WindowManager.WindowsTransparency = (byte)_windowsAlpha.Value; Explorer.WindowManager.TaskbarTransparency = (byte)_taskbarAlpha.Value; Kernel.GuiDebug = _guiDebug.Checked; + string wallpaperPath = NormalizePath(_wallpaperPath.Text); + string wallpaperError = null; + + // A missing file or a BMP the gen3 loader rejects would throw out of Kernel.Run (crash screen) if (_oldWallpaperPath != _wallpaperPath.Text) { - Explorer.Desktop.SetWallpaper(_wallpaperPath.Text); + if (!File.Exists(wallpaperPath)) + { + wallpaperError = "Wallpaper path is not valid."; + } + else + { + try + { + Explorer.Desktop.SetWallpaper(wallpaperPath); + _oldWallpaperPath = _wallpaperPath.Text; + } + catch (Exception) + { + // GEN3-GAP(bmp): no top-down, bitfield or < 24 bpp BMPs + wallpaperError = "Wallpaper could not be loaded."; + } + } } - if (Kernel.Installed) + if (wallpaperError != null) + { + _dialog.SetState(DialogState.Error); + _dialog.Message = wallpaperError; + _dialog.MarkDirty(); + } + else if (Kernel.Installed) { if (UpdateDialog()) { - Settings config = new Settings(@"0:\System\settings.ini"); + Settings config = new Settings(AuraPaths.SettingsIni); config.EditValue("hostname", Kernel.ComputerName); config.EditValue("themeBmpPath", Kernel.ThemeManager.BmpPath); config.EditValue("themeXmlPath", Kernel.ThemeManager.XmlPath); @@ -141,7 +185,7 @@ public SettingsApp(int width, int height, int x = 0, int y = 0) : base(Applicati config.EditValue("taskbarTransparency", Explorer.WindowManager.TaskbarTransparency.ToString()); config.EditValue("screenWidth", _resX.Text); config.EditValue("screenHeight", _resY.Text); - config.EditValue("wallpaperPath", _wallpaperPath.Text); + config.EditValue("wallpaperPath", wallpaperPath); if (_autoLogin.Checked) { config.EditValue("autologin", "true"); @@ -204,17 +248,18 @@ public SettingsApp(int width, int height, int x = 0, int y = 0) : base(Applicati AddChild(_save); - _oldScreenWidth = Kernel.ScreenWidth; - _oldScreenHeight = Kernel.ScreenHeight; + _oldScreenWidth = (int)Kernel.ScreenWidth; + _oldScreenHeight = (int)Kernel.ScreenHeight; - _username.Text = Kernel.userLogged; + // A null TextBox.Text would be a null deref (kernel halt) on the first draw + _username.Text = Kernel.userLogged ?? ""; _password.Text = ""; - _computerName.Text = Kernel.ComputerName; - _themeBmpPath.Text = Kernel.ThemeManager.BmpPath; - _themeXmlPath.Text = Kernel.ThemeManager.XmlPath; + _computerName.Text = Kernel.ComputerName ?? ""; + _themeBmpPath.Text = Kernel.ThemeManager.BmpPath ?? ""; + _themeXmlPath.Text = Kernel.ThemeManager.XmlPath ?? ""; _resX.Text = Kernel.ScreenWidth.ToString(); _resY.Text = Kernel.ScreenHeight.ToString(); - _wallpaperPath.Text = Explorer.Desktop.GetWallpaperPath(); + _wallpaperPath.Text = Explorer.Desktop.GetWallpaperPath() ?? ""; _oldWallpaperPath = _wallpaperPath.Text; } @@ -314,16 +359,48 @@ public override void Draw() } } + /// + /// User-typed path to an absolute gen3 path (gen2 DOS-style input accepted, see AuraPath.FromLegacy). + /// The embedded: theme sentinel and empty input are returned unchanged. + /// + private static string NormalizePath(string path) + { + if (string.IsNullOrEmpty(path) || Files.IsEmbeddedPath(path)) + { + return path; + } + + return AuraPath.Resolve(path); + } + + /// + /// A theme file is valid on disk or as an embedded resource (live mode / missing install files). + /// + private static bool IsValidThemePath(string path) + { + return Files.IsEmbeddedPath(path) || File.Exists(path); + } + public bool UpdateDialog() { - uint width = uint.Parse(_resX.Text); - uint height = uint.Parse(_resY.Text); + int width; + int height; + + if (!int.TryParse(_resX.Text, out width) || !int.TryParse(_resY.Text, out height)) + { + _dialog.SetState(DialogState.Error); + _dialog.Message = "Resolution is not valid."; + _dialog.MarkDirty(); + + return false; + } if (_waitingReboot == false && (_oldScreenWidth != width || _oldScreenHeight != height)) { bool modeExists = false; + IReadOnlyList modes = Kernel.Canvas.AvailableModes; - foreach (var mode in Kernel.Canvas.AvailableModes) + foreach (Mode mode in modes) { if (mode.Width == width && mode.Height == height) { @@ -337,13 +414,24 @@ public bool UpdateDialog() _dialog.Message = "Settings updated. Reboot needed to change resolution."; _dialog.AddButton("Reboot", new Action(() => { - Cosmos.System.Power.Reboot(); + AuraPower.Reboot(); })); _dialog.MarkDirty(); _waitingReboot = true; return true; } + else if (modes.Count <= 1) + { + // GEN3-GAP(display-mode): only VMware SVGA II switches modes; on GOP/virtio-gpu + // AvailableModes holds just the current mode, set at boot by limine.conf. + _dialog.SetState(DialogState.Error); + _dialog.Message = "Resolution is fixed by the bootloader on this display."; + _dialog.MarkDirty(); + _waitingReboot = false; + + return false; + } else { _dialog.SetState(DialogState.Error); @@ -354,7 +442,7 @@ public bool UpdateDialog() return false; } } - else if (!File.Exists(_themeBmpPath.Text)) + else if (!IsValidThemePath(NormalizePath(_themeBmpPath.Text))) { _dialog.SetState(DialogState.Error); _dialog.Message = "Theme .bmp path is not valid."; @@ -362,7 +450,7 @@ public bool UpdateDialog() return false; } - else if (!File.Exists(_themeXmlPath.Text)) + else if (!IsValidThemePath(NormalizePath(_themeXmlPath.Text))) { _dialog.SetState(DialogState.Error); _dialog.Message = "Theme .xml path is not valid."; @@ -370,7 +458,7 @@ public bool UpdateDialog() return false; } - else if (!File.Exists(_wallpaperPath.Text)) + else if (!File.Exists(NormalizePath(_wallpaperPath.Text))) { _dialog.SetState(DialogState.Error); _dialog.Message = "Wallpaper path is not valid."; diff --git a/SRC/Aura_OS/System/Processing/Applications/SystemInfoApp.cs b/SRC/Aura_OS/System/Processing/Applications/SystemInfoApp.cs index ffa2d60c0..b4eefa2bf 100644 --- a/SRC/Aura_OS/System/Processing/Applications/SystemInfoApp.cs +++ b/SRC/Aura_OS/System/Processing/Applications/SystemInfoApp.cs @@ -8,7 +8,7 @@ using System.Drawing; using Aura_OS.System.Graphics.UI.GUI; using Aura_OS.System.Graphics.UI.GUI.Components; -using Cosmos.System.Network; +using Aura_OS.System.Network; namespace Aura_OS.System.Processing.Applications { @@ -34,49 +34,59 @@ public SystemInfoApp(int width, int height, int x = 0, int y = 0) : base(Applica _button = new Button(text, (Width / 2) - ((text.Length * Kernel.font.Width) / 2), 5 * Kernel.font.Height + 2, text.Length * Kernel.font.Width + 6, Kernel.font.Height + 6); _button.Click = new Action(() => { - if (NetworkStack.ConfigEmpty()) + if (!NetworkHelper.IsConfigured) { _version = "Aura [version " + Kernel.Version + "-" + Kernel.Revision + "]"; } else { - (string latestVersion, string latestRevision, string latestReleaseUrl) = Network.Version.GetLastVersionInfo(); - - int versionComparisonResult = Network.Version.CompareVersions(Kernel.Version, latestVersion); - - if (string.IsNullOrEmpty(Kernel.Version) || string.IsNullOrEmpty(latestVersion) || string.IsNullOrEmpty(Kernel.Revision) || string.IsNullOrEmpty(latestRevision)) + // Phase 1: still synchronous on the UI thread (gen2 behaviour). + // GEN3-GAP(backend): the HTTP download can throw (no TLS, os.json endpoint down). + try { - _version = "Failed to parse os.json."; - } - else - { - if (versionComparisonResult > 0) - { - _version = "You are on a dev version (last release is " + latestVersion + "-" + latestRevision + ")."; - } - else if (versionComparisonResult < 0) + (string latestVersion, string latestRevision, string latestReleaseUrl) = Network.Version.GetLastVersionInfo(); + + if (string.IsNullOrEmpty(Kernel.Version) || string.IsNullOrEmpty(latestVersion) || string.IsNullOrEmpty(Kernel.Revision) || string.IsNullOrEmpty(latestRevision)) { - _version = "Your version is outdated (last release is " + latestVersion + "-" + latestRevision + ")."; - _isOutdated = true; + _version = "Failed to parse os.json."; } else { - int revisionComparisonResult = Network.Version.CompareRevisions(Kernel.Revision, latestRevision); - if (revisionComparisonResult > 0) + int versionComparisonResult = Network.Version.CompareVersions(Kernel.Version, latestVersion); + + if (versionComparisonResult > 0) { _version = "You are on a dev version (last release is " + latestVersion + "-" + latestRevision + ")."; } - else if (revisionComparisonResult < 0) + else if (versionComparisonResult < 0) { - _version = "Your revision is outdated (last release is " + latestVersion + "-" + latestRevision + ")."; + _version = "Your version is outdated (last release is " + latestVersion + "-" + latestRevision + ")."; _isOutdated = true; } else { - _version = "You are up to date."; + int revisionComparisonResult = Network.Version.CompareRevisions(Kernel.Revision, latestRevision); + if (revisionComparisonResult > 0) + { + _version = "You are on a dev version (last release is " + latestVersion + "-" + latestRevision + ")."; + } + else if (revisionComparisonResult < 0) + { + _version = "Your revision is outdated (last release is " + latestVersion + "-" + latestRevision + ")."; + _isOutdated = true; + } + else + { + _version = "You are up to date."; + } } } } + catch (Exception ex) + { + Logs.DoOSLog("[Error] Update check failed: " + ex.Message); + _version = "Failed to check for updates."; + } } _button.Visible = false; MarkDirty(); @@ -97,7 +107,7 @@ public override void Draw() var version = "[version " + Kernel.Version + "-" + Kernel.Revision + "]"; - DrawString(_title, Cosmos.System.Graphics.Fonts.PCScreenFont.Default, Kernel.BlackColor, 0 + Width / 2 - _title.Length * Cosmos.System.Graphics.Fonts.PCScreenFont.Default.Width / 2, 0 + 1 * Kernel.font.Height); + DrawString(_title, Kernel.font, Kernel.BlackColor, 0 + Width / 2 - _title.Length * Kernel.font.Width / 2, 0 + 1 * Kernel.font.Height); DrawString(version, Kernel.font, Kernel.BlackColor, 0 + Width / 2 - version.Length * Kernel.font.Width / 2, 0 + 2 * Kernel.font.Height); DrawString(_credit, Kernel.font, Kernel.BlackColor, 0 + Width / 2 - _credit.Length * Kernel.font.Width / 2, 0 + 5 * Kernel.font.Height + 4); diff --git a/SRC/Aura_OS/System/Processing/Applications/Terminal/TerminalApp.cs b/SRC/Aura_OS/System/Processing/Applications/Terminal/TerminalApp.cs index 658dfe7de..c02211ebf 100644 --- a/SRC/Aura_OS/System/Processing/Applications/Terminal/TerminalApp.cs +++ b/SRC/Aura_OS/System/Processing/Applications/Terminal/TerminalApp.cs @@ -5,7 +5,7 @@ */ using Aura_OS.System.Users; -using Cosmos.System; +using Cosmos.Kernel.System.Keyboard; using System; using System.Collections.Generic; using Aura_OS.System.Graphics.UI.GUI; @@ -29,6 +29,12 @@ public class TerminalApp : Application private bool _redirect = false; private TerminalTextWriter _writer; + /// + /// Terminal whose writer is currently installed as Console.Out (null: Kernel.GuiSink). + /// Console.SetOut is process-global, so with several terminals only the owner may restore the sink. + /// + private static TerminalApp _redirectOwner; + public TerminalApp(int width, int height, int x = 0, int y = 0) : base(ApplicationName, width, height, x, y) { Window.Icon = Kernel.ResourceManager.GetIcon("16-terminal.bmp"); @@ -115,7 +121,8 @@ public override void Update() } else { - if (_commandIndex >= 0) + // Count check: Up on an empty history indexed _commands[0] (crash screen, C6). + if (_commandIndex >= 0 && _commandIndex < _commands.Count) { Console.mX -= _command.Length; _command = _commands[_commandIndex]; @@ -202,12 +209,21 @@ public override void MarkDirty() Console.MarkDirty(); } + public override void Stop() + { + // Minimized or closed: Update() no longer runs, give Console.Out back to the GUI sink now. + DeactivateRedirection(); + + base.Stop(); + } + public void ActivateRedirection() { if (_redirect == false) { global::System.Console.SetOut(_writer); _writer.Enable(); + _redirectOwner = this; _redirect = true; } } @@ -216,8 +232,25 @@ public void DeactivateRedirection() { if (_redirect == true) { - // global::System.Console.SetOut(global::System.Console.Out); _writer.Disable(); + + // GEN3-GAP(console-global): Console.SetOut is process-global. Restore Aura's serial sink, never + // Console.Out (SetOut(Console.Out) is a no-op) and never the KernelConsole, which would paint + // over the desktop. Skip it when another terminal already took Console.Out. + if (_redirectOwner == this) + { + if (Kernel.GuiSink != null) + { + global::System.Console.SetOut(Kernel.GuiSink); + } + else + { + global::System.Console.SetOut(global::System.IO.TextWriter.Null); + } + + _redirectOwner = null; + } + _redirect = false; } } diff --git a/SRC/Aura_OS/System/Processing/Applications/Terminal/TerminalText.cs b/SRC/Aura_OS/System/Processing/Applications/Terminal/TerminalText.cs index 87b922d30..89318bc07 100644 --- a/SRC/Aura_OS/System/Processing/Applications/Terminal/TerminalText.cs +++ b/SRC/Aura_OS/System/Processing/Applications/Terminal/TerminalText.cs @@ -6,74 +6,148 @@ using Aura_OS.System.Processing.Processes; using System; +using System.Diagnostics; using System.IO; using System.Text; namespace Aura_OS.System.Processing.Applications.Terminal { + /// + /// Console.Out of a focused terminal. Installed with Console.SetOut, so no member may throw: + /// gen3 does not run finally/lock release on the exception path and the SyncTextWriter monitor + /// would stay held (C7). Every body is wrapped in try/catch. + /// public class TerminalTextWriter : TextWriter { private TerminalApp _terminal; private bool _isEnabled; + /// + /// Minimum Stopwatch ticks between two presents (~16 ms). + /// + private long _presentInterval; + + /// + /// Stopwatch timestamp of the last present. + /// + private long _lastPresent; + + /// + /// True while the terminal is being drawn (a re-entrant write only appends text). + /// + private bool _drawing; + public TerminalTextWriter(TerminalApp terminal) { _terminal = terminal; _isEnabled = true; + _presentInterval = Stopwatch.Frequency / 60; + _lastPresent = 0; + _drawing = false; } public override void WriteLine(string value) { - if (_isEnabled) + try { - _terminal.Console.Foreground = Console.ForegroundColor; - _terminal.Console.Background = Console.BackgroundColor; + if (_isEnabled) + { + _terminal.Console.Foreground = Console.ForegroundColor; + _terminal.Console.Background = Console.BackgroundColor; - _terminal.Console.WriteLine(value); + _terminal.Console.WriteLine(value); - _terminal.Console.Draw(); - _terminal.Draw(); - Explorer.Screen.DrawImage(_terminal.Window.GetBuffer(), _terminal.Window.X, _terminal.Window.Y); - Kernel.Canvas.DrawImage(Explorer.Screen.Bitmap, 0, 0); - Kernel.Canvas.Display(); + Refresh(); + } + } + catch (Exception) + { } } public override void Write(string value) { - if (_isEnabled) + try { - _terminal.Console.Foreground = Console.ForegroundColor; - _terminal.Console.Background = Console.BackgroundColor; + if (_isEnabled && value != null) + { + _terminal.Console.Foreground = Console.ForegroundColor; + _terminal.Console.Background = Console.BackgroundColor; - _terminal.Console.Write(value); + _terminal.Console.Write(value); - _terminal.Console.Draw(); - _terminal.Draw(); - Explorer.Screen.DrawImage(_terminal.Window.GetBuffer(), _terminal.Window.X, _terminal.Window.Y); - Kernel.Canvas.DrawImage(Explorer.Screen.Bitmap, 0, 0); - Kernel.Canvas.Display(); + Refresh(); + } + } + catch (Exception) + { } } public override void Write(char value) { - if (_isEnabled) + try { - _terminal.Console.Foreground = Console.ForegroundColor; - _terminal.Console.Background = Console.BackgroundColor; + if (_isEnabled) + { + _terminal.Console.Foreground = Console.ForegroundColor; + _terminal.Console.Background = Console.BackgroundColor; - _terminal.Console.Write(value.ToString()); + _terminal.Console.Write(value.ToString()); - _terminal.Console.Draw(); - _terminal.Draw(); - Explorer.Screen.DrawImage(_terminal.Window.GetBuffer(), _terminal.Window.X, _terminal.Window.Y); - Kernel.Canvas.DrawImage(Explorer.Screen.Bitmap, 0, 0); - Kernel.Canvas.Display(); + Refresh(); + } + } + catch (Exception) + { } } - public override Encoding Encoding => Encoding.ASCII; + /// + /// Used by WriteLine() and char[] writes (otherwise split into one Write(char) per char). + /// + public override void Write(char[] buffer, int index, int count) + { + try + { + if (_isEnabled && buffer != null && count > 0) + { + _terminal.Console.Foreground = Console.ForegroundColor; + _terminal.Console.Background = Console.BackgroundColor; + + _terminal.Console.Write(new string(buffer, index, count)); + + Refresh(); + } + } + catch (Exception) + { + } + } + + /// + /// Used by span writes (otherwise split into one Write(char) per char). + /// + public override void Write(ReadOnlySpan buffer) + { + try + { + if (_isEnabled && buffer.Length > 0) + { + _terminal.Console.Foreground = Console.ForegroundColor; + _terminal.Console.Background = Console.BackgroundColor; + + _terminal.Console.Write(new string(buffer)); + + Refresh(); + } + } + catch (Exception) + { + } + } + + public override Encoding Encoding => Encoding.UTF8; public void Enable() { @@ -84,5 +158,48 @@ public void Disable() { _isEnabled = false; } + + /// + /// Draw the terminal window on screen and present it, at most once every ~16 ms. + /// + private void Refresh() + { + // A skipped refresh is repainted by the main loop on its next frame. + _terminal.MarkDirty(); + + if (_drawing) + { + return; + } + + // GEN3-GAP(present): no partial Canvas.Display(rect), every present copies the whole frame, + // so a burst of writes presents at most once per ~16 ms (the main loop presents each frame anyway). + long now = Stopwatch.GetTimestamp(); + if (now - _lastPresent < _presentInterval) + { + return; + } + + _lastPresent = now; + _drawing = true; + + try + { + _terminal.Console.Draw(); + _terminal.Draw(); + + if (Explorer.Screen != null) + { + Explorer.Screen.DrawImage(_terminal.Window.GetBuffer(), _terminal.Window.X, _terminal.Window.Y); + } + + Kernel.Present(); + } + catch (Exception) + { + } + + _drawing = false; + } } } diff --git a/SRC/Aura_OS/System/Processing/Executable.cs b/SRC/Aura_OS/System/Processing/Executable.cs index 87511d597..49f27e29c 100644 --- a/SRC/Aura_OS/System/Processing/Executable.cs +++ b/SRC/Aura_OS/System/Processing/Executable.cs @@ -7,8 +7,8 @@ using System; using System.Collections.Generic; using System.IO; -using System.IO.Compression; using System.Text; +using Aura_OS.System.Compression; namespace Aura_OS.System.Processing { @@ -33,6 +33,12 @@ public Executable(byte[] executableBytes) private void ParseExecutable(byte[] executableBytes) { + // GEN3-GAP(null-deref): check the header before reading it (C6). + if (executableBytes == null || executableBytes.Length < SignatureSize + ArchiveSizeLength) + { + throw new InvalidOperationException("This is not a Cosmos executable."); + } + Signature = Encoding.ASCII.GetString(executableBytes, 0, SignatureSize); if (Signature != ExpectedSignature) @@ -41,7 +47,10 @@ private void ParseExecutable(byte[] executableBytes) } ArchiveSize = BitConverter.ToInt32(executableBytes, SignatureSize); - if (SignatureSize + ArchiveSizeLength + ArchiveSize > executableBytes.Length) + + // GEN3-GAP(null-deref): a negative size makes gen3's new byte[] return null instead of throwing, + // and a huge one overflowed the gen2 sum; compare without int overflow. + if (ArchiveSize < 0 || ArchiveSize > executableBytes.Length - SignatureSize - ArchiveSizeLength) { throw new InvalidOperationException("Cosmos executable corrupted."); } @@ -57,28 +66,49 @@ private void ExtractLuaScripts() { bool mainFound = false; - using (MemoryStream zipStream = new MemoryStream(ZipContent)) + // GEN3-GAP(finally): no using blocks, gen3 does not run finally/Dispose when an exception unwinds (C7), + // so a corrupted archive is caught here, the ZipStorer closed explicitly, then rethrown. + MemoryStream zipStream = new MemoryStream(ZipContent); + ZipStorer zip = null; + Exception error = null; + + try { - using (ZipStorer zip = ZipStorer.Open(zipStream, FileAccess.Read)) + zip = ZipStorer.Open(zipStream, FileAccess.Read); + + List dir = zip.ReadCentralDir(); + + foreach (ZipStorer.ZipFileEntry entry in dir) { - List dir = zip.ReadCentralDir(); + MemoryStream fileStream = new MemoryStream(); + zip.ExtractFile(entry, fileStream); + byte[] script = fileStream.ToArray(); + fileStream.Dispose(); + + LuaSources.Add(entry.FilenameInZip, script); - foreach (ZipStorer.ZipFileEntry entry in dir) + if (entry.FilenameInZip == "main.lua") { - using (MemoryStream fileStream = new MemoryStream()) - { - zip.ExtractFile(entry, fileStream); - byte[] script = fileStream.ToArray(); - LuaSources.Add(entry.FilenameInZip, script); - - if (entry.FilenameInZip == "main.lua") - { - mainFound = true; - } - } + mainFound = true; } } } + catch (Exception ex) + { + error = ex; + } + + if (zip != null) + { + zip.Close(); + } + + zipStream.Dispose(); + + if (error != null) + { + throw error; + } if (!mainFound) { diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Batch.cs b/SRC/Aura_OS/System/Processing/Interpreter/Batch.cs index dd0c78506..29e86dc7d 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Batch.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Batch.cs @@ -20,7 +20,7 @@ public static void Execute(string filename) { try { - if (filename.EndsWith(".bat")) + if (filename.EndsWith(".bat", StringComparison.OrdinalIgnoreCase)) { string[] lines = File.ReadAllLines(filename); foreach (string line in lines) diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/CommandManager.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/CommandManager.cs index 701b6e34f..8406caff8 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/CommandManager.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/CommandManager.cs @@ -17,8 +17,10 @@ using Aura_OS.System.Processing.Interpreter.Commands.SystemInfomation; using Aura_OS.System.Processing.Interpreter.Commands.Graphics; using Aura_OS.System.Processing.Interpreter.Commands.Processing; -using Cosmos.System.Network; +using Aura_OS.System.Filesystem; +using Aura_OS.System.Network; using Aura_OS.System.Graphics.UI.GUI; +using Cosmos.Kernel.System.Vfs; using System.Text; namespace Aura_OS.System.Processing.Interpreter.Commands @@ -97,10 +99,8 @@ public void RegisterAllCommands() CMDs.Add(new CommandMIV(new string[] { "miv", "edit" }));*/ - _commands.Add(new CommandAction(new string[] { "beep" }, () => - { - Cosmos.System.PCSpeaker.Beep(); - })); + // GEN3-GAP(pc-speaker): gen3 has no PC speaker driver (port I/O is internal), so the + // gen2 'beep' command is not registered (decision D2). _commands.Add(new CommandAction(new string[] { "crash" }, () => { throw new Exception("Exception test"); @@ -149,7 +149,7 @@ public void Execute(string cmd) { //CommandsHistory.Add(cmd); //adding last command to the commands history - if (cmd.Length <= 0) + if (cmd == null || cmd.Length <= 0) { Console.WriteLine(); return; @@ -169,6 +169,15 @@ public void Execute(string cmd) List arguments = Misc.ParseCommandLine(cmd); + if (arguments.Count == 0) + { + // Blank command (or a lone redirection): nothing to run. Never index an empty list (C6). + Kernel.Redirect = false; + Kernel.CommandOutput = ""; + Console.WriteLine(); + return; + } + string firstarg = arguments[0]; //command name if (arguments.Count > 0) @@ -279,16 +288,16 @@ private ReturnInfo CheckCommand(ICommand command) { if (command.Type == CommandType.Filesystem) { - if (Kernel.VirtualFileSystem == null || Kernel.VirtualFileSystem.GetVolumes().Count == 0) + if (VfsManager.Mounts.Count == 0) { - return new ReturnInfo(command, ReturnCode.ERROR, "No volume detected!"); + return new ReturnInfo(command, ReturnCode.ERROR, "No volume detected! Use vol /lp, vol /mp, vol /fp."); } } if (command.Type == CommandType.Network) { - if (NetworkStack.ConfigEmpty()) + if (!NetworkHelper.IsConfigured) { - return new ReturnInfo(command, ReturnCode.ERROR, "No network configuration detected! Use ipconfig /set."); + return new ReturnInfo(command, ReturnCode.ERROR, "No network configuration detected! Use ipconfig /ask or ipconfig /set."); } } return new ReturnInfo(command, ReturnCode.OK); @@ -318,9 +327,16 @@ private void ProcessCommandResult(ReturnInfo result) private void HandleRedirection(string filePath, string commandOutput) { - string fullPath = Kernel.CurrentDirectory + filePath; - - File.WriteAllText(fullPath, commandOutput); + try + { + File.WriteAllText(AuraPath.Resolve(filePath), commandOutput); + } + catch (Exception ex) + { + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine("Error: cannot write output to '" + filePath + "': " + ex.Message); + Console.ForegroundColor = ConsoleColor.White; + } } /// diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Compression/Zip.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Compression/Zip.cs index a2255d40d..9c7b81f11 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Compression/Zip.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Compression/Zip.cs @@ -5,12 +5,12 @@ * Valentin Charbonnier */ +using Aura_OS.System.Compression; +using Aura_OS.System.Filesystem; using Aura_OS.System.Processing.Interpreter; using System; using System.Collections.Generic; -using System.IO.Compression; using System.IO; -using UniLua; namespace Aura_OS.System.Processing.Interpreter.Commands.Util { @@ -46,12 +46,12 @@ public override ReturnInfo Execute(List arguments) private ReturnInfo Extract(List arguments) { - string archivePath = ResolvePath(arguments[1]); + string archivePath = AuraPath.Resolve(arguments[1]); string extractPath; if (arguments.Count > 2) { - extractPath = ResolvePath(arguments[2]); + extractPath = AuraPath.Resolve(arguments[2]); } else { @@ -59,46 +59,81 @@ private ReturnInfo Extract(List arguments) extractPath = Path.Combine(Kernel.CurrentDirectory, archiveName); } - Directory.CreateDirectory(extractPath); + if (!File.Exists(archivePath)) + { + return new ReturnInfo(this, ReturnCode.ERROR, "This file does not exist."); + } + + // GEN3-GAP(finally): `using` does not dispose when an exception unwinds (a bad archive throws + // InvalidDataException), so catch inside and close the archive explicitly. + ZipStorer zip = null; + string error = null; try { - using (ZipStorer zip = ZipStorer.Open(archivePath, FileAccess.Read)) + Directory.CreateDirectory(extractPath); + + zip = ZipStorer.Open(archivePath, FileAccess.Read); + + List dir = zip.ReadCentralDir(); + + foreach (ZipStorer.ZipFileEntry entry in dir) { - List dir = zip.ReadCentralDir(); + // Entry names use '/', and gen2 also accepted '\' (a plain character in gen3 names). + string name = entry.FilenameInZip.Replace('\\', '/').TrimStart('/'); + string outputFile = Path.GetFullPath(Path.Combine(extractPath, name)); - foreach (ZipStorer.ZipFileEntry entry in dir) + // Never write outside the destination ("../" in an entry name), and skip names the FAT + // driver would store as-is with reserved characters (GEN3-GAP(fat-names)). + if (!outputFile.StartsWith(AuraPath.AsDirectory(extractPath), StringComparison.Ordinal) + || !IsValidEntryName(name)) { - string outputFile = Path.Combine(extractPath, entry.FilenameInZip); - zip.ExtractFile(entry, outputFile); + continue; } - } - Console.WriteLine("Extraction completed."); - return new ReturnInfo(this, ReturnCode.OK); + zip.ExtractFile(entry, outputFile); + } } catch (Exception e) { - return new ReturnInfo(this, ReturnCode.ERROR, e.ToString()); + error = e.ToString(); } - } - private string ResolvePath(string path) - { - if (path.StartsWith("./")) + if (zip != null) { - path = path.Substring(2); - path = Kernel.CurrentDirectory + path; + try + { + zip.Dispose(); + } + catch (Exception e) + { + if (error == null) + { + error = e.ToString(); + } + } } - if (path == ".") + if (error != null) { - return Kernel.CurrentDirectory; + return new ReturnInfo(this, ReturnCode.ERROR, error); } - else + + Console.WriteLine("Extraction completed."); + return new ReturnInfo(this, ReturnCode.OK); + } + + private static bool IsValidEntryName(string name) + { + foreach (string part in name.Split('/')) { - return Path.Combine(Kernel.CurrentDirectory, path); + if (part.Length > 0 && !AuraPath.IsValidName(part)) + { + return false; + } } + + return true; } public override void PrintHelp() diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Cat.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Cat.cs index 7ed8b8e77..4b967d26a 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Cat.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Cat.cs @@ -4,6 +4,7 @@ * PROGRAMMER(S): Valentin Charbonnier */ +using Aura_OS.System.Filesystem; using System; using System.Collections.Generic; using System.IO; @@ -26,15 +27,20 @@ public CommandCat(string[] commandvalues) : base(commandvalues, CommandType.File /// public override ReturnInfo Execute(List arguments) { + if (arguments.Count < 1) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + try { - string file = arguments[0]; + string file = AuraPath.Resolve(arguments[0]); - if (File.Exists(Kernel.CurrentDirectory + file)) + if (File.Exists(file)) { StringBuilder sb = new(); - foreach (string line in File.ReadAllLines(Kernel.CurrentDirectory + file)) + foreach (string line in File.ReadAllLines(file)) { sb.AppendLine(line); } diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Cd.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Cd.cs index a9c681882..155a9b99b 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Cd.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Cd.cs @@ -26,6 +26,11 @@ public CommandCD(string[] commandvalues) : base(commandvalues, CommandType.Files /// public override ReturnInfo Execute(List arguments) { + if (arguments.Count < 1) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + string dir = arguments[0]; try @@ -54,6 +59,9 @@ public override void PrintHelp() Console.WriteLine("Available commands:"); Console.WriteLine("- cd {directory} change current directory"); Console.WriteLine("- cd .. go to last directory"); + Console.WriteLine("- cd ~ go to user directory"); + Console.WriteLine("- cd /1/Docs absolute path (volume N is /N/)"); + Console.WriteLine("- cd / list of volumes"); } } } \ No newline at end of file diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Cp.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Cp.cs index c567cb98f..5e94916ec 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Cp.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Cp.cs @@ -29,8 +29,18 @@ public override ReturnInfo Execute(List arguments) return new ReturnInfo(this, ReturnCode.ERROR_ARG); } - string sourcePath = ResolvePath(arguments[0]); - string destPath = ResolvePath(arguments[1]); + string sourcePath = AuraPath.Resolve(arguments[0]); + string destPath = AuraPath.Resolve(arguments[1]); + + // GEN3-GAP(fat-names): the FAT driver writes any character into a long name, so reject the + // reserved ones in the destination (a directory copy creates the whole chain). + foreach (string part in destPath.Split('/')) + { + if (part.Length > 0 && !AuraPath.IsValidName(part)) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Invalid destination name."); + } + } try { @@ -50,24 +60,6 @@ public override ReturnInfo Execute(List arguments) } } - private string ResolvePath(string path) - { - if (path.StartsWith("./")) - { - path = path.Substring(2); - path = Kernel.CurrentDirectory + path; - } - - if (path == ".") - { - return Kernel.CurrentDirectory; - } - else - { - return Path.Combine(Kernel.CurrentDirectory, path); - } - } - public override void PrintHelp() { Console.WriteLine("Usage:"); diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Dir.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Dir.cs index 2e8dea7b8..8606a3590 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Dir.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Dir.cs @@ -4,6 +4,7 @@ * PROGRAMMER(S): John Welsh */ +using Aura_OS.System.Filesystem; using System; using System.Collections.Generic; using System.IO; @@ -25,8 +26,16 @@ public CommandDir(string[] commandvalues) : base(commandvalues, CommandType.File /// public override ReturnInfo Execute() { - DirectoryListing.DispDirectories(Kernel.CurrentDirectory); - DirectoryListing.DispFiles(Kernel.CurrentDirectory); + try + { + DirectoryListing.DispDirectories(Kernel.CurrentDirectory); + DirectoryListing.DispFiles(Kernel.CurrentDirectory); + } + catch (Exception ex) + { + Console.ForegroundColor = ConsoleColor.White; + return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); + } Console.WriteLine(); return new ReturnInfo(this, ReturnCode.OK); } @@ -36,39 +45,53 @@ public override ReturnInfo Execute() /// public override ReturnInfo Execute(List arguments) { - string directory; - - if (!arguments[0].StartsWith("-")) + if (arguments.Count < 1) { - directory = arguments[0]; - - if (Directory.Exists(Kernel.CurrentDirectory + directory)) - { - DirectoryListing.DispDirectories(Kernel.CurrentDirectory + directory); - DirectoryListing.DispFiles(Kernel.CurrentDirectory + directory); - } + return Execute(); } - else + string directory; + + try { - if (arguments[0].Equals("-a")) + if (!arguments[0].StartsWith("-")) { - DirectoryListing.DispDirectories(Kernel.CurrentDirectory); - DirectoryListing.DispHiddenFiles(Kernel.CurrentDirectory); + directory = AuraPath.Resolve(arguments[0]); - if (arguments.Count == 2) + if (!Directory.Exists(directory)) { - directory = arguments[1]; - - DirectoryListing.DispDirectories(Kernel.CurrentDirectory + directory); - DirectoryListing.DispHiddenFiles(Kernel.CurrentDirectory + directory); + return new ReturnInfo(this, ReturnCode.ERROR, "This directory doesn't exist!"); } + + DirectoryListing.DispDirectories(directory); + DirectoryListing.DispFiles(directory); } + else { - return new ReturnInfo(this, ReturnCode.ERROR_ARG); + if (arguments[0].Equals("-a")) + { + directory = arguments.Count >= 2 ? AuraPath.Resolve(arguments[1]) : Kernel.CurrentDirectory; + + if (!Directory.Exists(directory)) + { + return new ReturnInfo(this, ReturnCode.ERROR, "This directory doesn't exist!"); + } + + DirectoryListing.DispDirectories(directory); + DirectoryListing.DispHiddenFiles(directory); + } + else + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } } } + catch (Exception ex) + { + Console.ForegroundColor = ConsoleColor.White; + return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); + } Console.WriteLine(); return new ReturnInfo(this, ReturnCode.OK); @@ -92,8 +115,11 @@ class DirectoryListing /// public static void DispDirectories(string directory) { - foreach (string dir in Directory.GetDirectories(directory)) + // gen3 returns full paths ("/0/Users"); listing "/" gives the volumes ("0", "1"). + foreach (string entry in Directory.GetDirectories(directory)) { + string dir = Path.GetFileName(entry); + if (!dir.StartsWith(".")) { Console.ForegroundColor = ConsoleColor.Yellow; @@ -118,8 +144,9 @@ public static void DispHiddenDirectories(string directory) /// public static void DispFiles(string directory) { - foreach (string file in Directory.GetFiles(directory)) + foreach (string entry in Directory.GetFiles(directory)) { + string file = Path.GetFileName(entry); Char formatDot = '.'; string[] ext = file.Split(formatDot); string lastext = ext[ext.Length - 1]; @@ -155,8 +182,9 @@ public static void DispFiles(string directory) /// public static void DispHiddenFiles(string directory) { - foreach (string file in Directory.GetFiles(directory)) + foreach (string entry in Directory.GetFiles(directory)) { + string file = Path.GetFileName(entry); Char formatDot = '.'; string[] ext = file.Split(formatDot); string lastext = ext[ext.Length - 1]; diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Edit.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Edit.cs index 5a44cd9a0..7ca76ffac 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Edit.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Edit.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; using System.IO; +using Aura_OS.System.Filesystem; using Aura_OS.System.Processing.Applications; using Aura_OS.System.Processing.Processes; @@ -27,10 +28,14 @@ public CommandEdit(string[] commandvalues) : base(commandvalues, CommandType.Fil /// public override ReturnInfo Execute(List arguments) { + if (arguments.Count < 1) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + try { - string file = arguments[0]; - string path = Kernel.CurrentDirectory + file; + string path = AuraPath.Resolve(arguments[0]); if (File.Exists(path)) { diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Hex.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Hex.cs index df4a09c70..8a02c039f 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Hex.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Hex.cs @@ -4,6 +4,7 @@ * PROGRAMMER(S): Valentin Charbonnier */ +using Aura_OS.System.Filesystem; using Aura_OS.Utils; using System; using System.Collections.Generic; @@ -26,15 +27,20 @@ public CommandHex(string[] commandvalues) : base(commandvalues, CommandType.File /// public override ReturnInfo Execute(List arguments) { + if (arguments.Count < 1) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + try { - string file = arguments[0]; + string file = AuraPath.Resolve(arguments[0]); - if (File.Exists(Kernel.CurrentDirectory + file)) + if (File.Exists(file)) { Console.WriteLine("Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"); Console.WriteLine(); - Console.WriteLine(Conversion.HexDump(File.ReadAllBytes(Kernel.CurrentDirectory + file))); + Console.WriteLine(Conversion.HexDump(File.ReadAllBytes(file))); } else { diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Mkdir.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Mkdir.cs index dd816e6b3..08d442909 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Mkdir.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Mkdir.cs @@ -4,6 +4,7 @@ * PROGRAMMER(S): John Welsh */ +using Aura_OS.System.Filesystem; using System; using System.Collections.Generic; using System.IO; @@ -35,74 +36,87 @@ public override ReturnInfo Execute() /// public override ReturnInfo Execute(List arguments) { - string dir = arguments[0]; + if (arguments.Count < 1) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } - if (dir.Contains(".")) + string dir = arguments[0].TrimEnd('/', '\\'); + + // GEN3-GAP(fat-names): the FAT driver writes any character into a long name, reject + // the reserved ones here. (The gen2 "no dot" rule is gone: gen3 FAT writes LFN entries.) + if (!IsValidPath(AuraPath.FromLegacy(dir))) { - Console.WriteLine("You can't have a dot in your directory name."); + return new ReturnInfo(this, ReturnCode.ERROR, "Invalid directory name."); } - else + try { - if (!Directory.Exists(Kernel.CurrentDirectory + dir)) + string path = AuraPath.Resolve(dir).TrimEnd('/'); + + if (!Directory.Exists(path)) { - Directory.CreateDirectory(Kernel.CurrentDirectory + dir); + Directory.CreateDirectory(path); } - else if (Directory.Exists(Kernel.CurrentDirectory + dir)) + else { - Char[] separators = new char[] { '(', ')' }; - Char[] directories = new char[] { '/', '\\' }; - - //getting last directory. - string x1 = Kernel.CurrentDirectory + dir; - string[] x2 = x1.Split(directories); - string x3 = x2[x2.Length - 1]; - int x4 = 0; - - //boucle - boucle: - x4 = x4 + 1; - string DirectoryAlreadyExist = x3 + "(" + x4 + ")"; - - //if directory has already been recreated once or more - if ((DirectoryAlreadyExist.Contains("(")) && (DirectoryAlreadyExist.Contains(")"))) - { - //get number - string[] endName = DirectoryAlreadyExist.Split(separators); - int num = int.Parse(endName[1]); + //if the directory already exists, create "name(2)", "name(3)", ... + int num = 1; + string newPath; - //add one to num + do + { num = num + 1; + newPath = path + "(" + num + ")"; + } + while (Directory.Exists(newPath)); - //set new directory name with the new number. - string newName = dir + "(" + num + ")"; + //create directory + Directory.CreateDirectory(newPath); - if (Directory.Exists(Kernel.CurrentDirectory + newName)) - { - goto boucle; - } + //display text to inform the user that the directory has been created with an another name + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine("That folder existed already, directory \"" + dir + "(" + num + ")" + "\" has been created."); + Console.ForegroundColor = ConsoleColor.White; + } + } + catch (Exception ex) + { + return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); + } - //create directory - Directory.CreateDirectory(Kernel.CurrentDirectory + newName); + return new ReturnInfo(this, ReturnCode.OK); + } - //display text to inform the user that the directory has been created with an another name - Console.ForegroundColor = ConsoleColor.Yellow; + /// + /// Every component typed by the user is a valid name, and the last one names a new directory + /// (not "", "." or ".."). + /// + private static bool IsValidPath(string path) + { + if (string.IsNullOrEmpty(path)) + { + return false; + } - Console.WriteLine("That folder existed already, directory \"" + newName + "\" has been created."); - } - else - { - //if not, we create directory with (1) - Directory.CreateDirectory(Kernel.CurrentDirectory + dir + "(1)"); + string last = string.Empty; - //display text to inform the user that the directory has been created with an another name - Console.ForegroundColor = ConsoleColor.Yellow; + foreach (string part in path.Split('/')) + { + if (part.Length == 0) + { + continue; + } - Console.WriteLine("That folder existed already, directory \"" + dir + "(1)" + "\" has been created."); - } + if (!AuraPath.IsValidName(part)) + { + return false; } + + last = part; } - return new ReturnInfo(this, ReturnCode.OK); + + return last.Length > 0 && last != "." && last != ".."; } /// diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Mkfil.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Mkfil.cs index 0314760c2..95b516723 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Mkfil.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Mkfil.cs @@ -4,6 +4,7 @@ * PROGRAMMER(S): John Welsh */ +using Aura_OS.System.Filesystem; using Aura_OS.System.Processing.Interpreter; using System; using System.Collections.Generic; @@ -36,16 +37,38 @@ public override ReturnInfo Execute() /// public override ReturnInfo Execute(List arguments) { + if (arguments.Count < 1) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + string file = arguments[0]; - if (!File.Exists(Kernel.CurrentDirectory + file)) + try { - File.Create(Kernel.CurrentDirectory + file); + string path = AuraPath.Resolve(file); + + // GEN3-GAP(fat-names): the FAT driver writes any character into a long name. + if (!AuraPath.IsValidName(Path.GetFileName(path))) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Invalid file name."); + } + + if (!File.Exists(path)) + { + // GEN3-GAP(finalizers): no finalizers, an undisposed FileStream keeps its descriptor forever. + File.Create(path).Dispose(); + } + else + { + Console.WriteLine(file + " already exists!"); + } } - else + catch (Exception ex) { - Console.WriteLine(file + " already exists!"); + return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); } + return new ReturnInfo(this, ReturnCode.OK); } diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Pic.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Pic.cs index 97c6f6cad..8f7e61e15 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Pic.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Pic.cs @@ -8,7 +8,8 @@ using System; using System.Collections.Generic; using System.IO; -using Cosmos.System.Graphics; +using Cosmos.Kernel.System.Graphics; +using Aura_OS.System.Filesystem; using Aura_OS.System.Processing.Applications; using Aura_OS.System.Processing.Processes; @@ -33,10 +34,25 @@ public override ReturnInfo Execute(List arguments) try { - string path = arguments[0]; + string path = AuraPath.Resolve(arguments[0]); string name = Path.GetFileName(path); - byte[] bytes = File.ReadAllBytes(Kernel.CurrentDirectory + path); + + if (!File.Exists(path)) + { + return new ReturnInfo(this, ReturnCode.ERROR, "This file does not exist."); + } + + byte[] bytes = File.ReadAllBytes(path); + + // GEN3-GAP(bmp): the gen3 BMP loader rejects top-down, bitfield and < 24 bpp images + // with an exception, reported by the catch below. Bitmap bitmap = new Bitmap(bytes); + + if (bitmap.Width <= 0 || bitmap.Height <= 0) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Invalid bitmap."); + } + int width = name.Length * 8 + 50; if (width < bitmap.Width) diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Rm.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Rm.cs index 3b31248c0..b8b94c09b 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Rm.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Rm.cs @@ -5,6 +5,7 @@ * Valentin Charbonnier */ +using Aura_OS.System.Filesystem; using System; using System.Collections.Generic; using System.IO; @@ -26,12 +27,36 @@ public CommandRm(string[] commandvalues) : base(commandvalues, CommandType.Files /// public override ReturnInfo Execute(List arguments) { + if (arguments.Count < 1) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + string path = arguments[0]; - string fullPath = Kernel.CurrentDirectory + path; + string fullPath = AuraPath.Resolve(path); + + try + { + if (System.Filesystem.Entries.ForceRemove(fullPath)) + { + // The current directory (or one of its parents) is gone: move to the parent of the + // removed entry, or relative paths and "cd .." would point at a deleted folder. + if (AuraPath.AsDirectory(Kernel.CurrentDirectory).StartsWith(AuraPath.AsDirectory(fullPath), StringComparison.OrdinalIgnoreCase)) + { + Kernel.CurrentDirectory = System.Filesystem.Utils.GetParentPath(fullPath); + } - if (System.Filesystem.Entries.ForceRemove(fullPath)) + return new ReturnInfo(this, ReturnCode.OK); + } + } + catch (IOException ex) + { + // Device or FAT error (a mount point is refused by ForceRemove, the plug says EBUSY too). + return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); + } + catch (Exception ex) { - return new ReturnInfo(this, ReturnCode.OK); + return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); } return new ReturnInfo(this, ReturnCode.ERROR); diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Tree.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Tree.cs index 99bfc72c7..fb650ce59 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Tree.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Tree.cs @@ -4,6 +4,7 @@ * PROGRAMMER(S): Valentin Charbonnier */ +using Aura_OS.System.Filesystem; using System; using System.Collections.Generic; using System.IO; @@ -44,9 +45,23 @@ public override ReturnInfo Execute() /// public override ReturnInfo Execute(List arguments) { + if (arguments.Count < 1) + { + return Execute(); + } + try { - DoTree(Kernel.CurrentDirectory + "/" + arguments[0], 0); + string directory = AuraPath.Resolve(arguments[0]); + + if (!Directory.Exists(directory)) + { + return new ReturnInfo(this, ReturnCode.ERROR, "This directory doesn't exist!"); + } + + string result = DoTree(directory, 0); + Console.WriteLine(result); + return new ReturnInfo(this, ReturnCode.OK); } catch (Exception ex) @@ -66,7 +81,7 @@ private string DoTree(string directory, int depth) { sb.Append(" "); } - sb.AppendLine(file); + sb.AppendLine(Path.GetFileName(file)); } for (int j = 0; j < directories.Length; j++) @@ -75,8 +90,9 @@ private string DoTree(string directory, int depth) { sb.Append(" "); } - sb.AppendLine(directories[j]); - sb.Append(DoTree(directory + "/" + directories[j], depth + 4)); + // gen3 returns full paths: print the name, recurse on the path itself. + sb.AppendLine(Path.GetFileName(directories[j])); + sb.Append(DoTree(directories[j], depth + 4)); } return sb.ToString(); diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Vol.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Vol.cs index 4205e5a6f..4adcf2f1a 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Vol.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Filesystem/Vol.cs @@ -4,15 +4,38 @@ * PROGRAMMER(S): Valentin Charbonnier */ +using Aura_OS.System.Filesystem; using Aura_OS.System.Processing.Interpreter; -using Cosmos.System.FileSystem; +using Cosmos.Kernel.HAL.Interfaces.Devices; +using Cosmos.Kernel.System.Filesystems.Fat; +using Cosmos.Kernel.System.Storage; +using Cosmos.Kernel.System.Vfs; using System; using System.Collections.Generic; +using System.IO; +using System.Text; namespace Aura_OS.System.Processing.Interpreter.Commands.Filesystem { class CommandVol : ICommand { + // gen2 numbering: the N-th FAT volume is mounted at /N (gen2 "N:\"). + // Templates: Cosmos DevKernel Storage/StorageView.cs, Commands/PartitionCommands.cs, MountCommands.cs. + + /// MBR system ID of the partitions vol /mp creates (FAT32 LBA). + private const byte MbrFat32LbaSystemId = 0x0C; + + /// First partition LBA on an MBR disk (1 MiB alignment). + private const ulong MbrFirstPartitionLba = 2048; + + private const ulong BytesPerMiB = 1024UL * 1024UL; + + private const string FormatLabel = "AURAOS"; + + // static readonly, NOT const (C16): enum values from a Cosmos assembly. + private static readonly FatType Fat32 = FatType.Fat32; + private static readonly FatType FatAuto = FatType.Unknown; + /// /// Empty constructor. /// @@ -31,227 +54,540 @@ public override ReturnInfo Execute() /// public override ReturnInfo Execute(List arguments) { - if (arguments[0].Equals("/l") || arguments[0].Equals("/list")) + if (arguments.Count < 1) { return ListVolumes(); } - else if (arguments[0].Equals("/cv") || arguments[0].Equals("/changevol")) + + try + { + if (arguments[0].Equals("/l") || arguments[0].Equals("/list")) + { + return ListVolumes(); + } + else if (arguments[0].Equals("/cv") || arguments[0].Equals("/changevol")) + { + if (arguments.Count < 2) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + + return ChangeVolume(arguments[1]); + } + else if (arguments[0].Equals("/fp") || arguments[0].Equals("/formatpartiton")) + { + int disk, partition; + if (!TryParseTwo(arguments, out disk, out partition)) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + + return FormatVolume(disk, partition); + } + else if (arguments[0].Equals("/lp") || arguments[0].Equals("/listpartitions")) + { + return ListDisk(); + } + else if (arguments[0].Equals("/mp") || arguments[0].Equals("/makepartition")) + { + int disk, size; + if (!TryParseTwo(arguments, out disk, out size)) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + + return MakeDisk(disk, size); + } + else if (arguments[0].Equals("/dp") || arguments[0].Equals("/deletepartition")) + { + int disk, partition; + if (!TryParseTwo(arguments, out disk, out partition)) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + + return DeleteDisk(disk, partition); + } + else + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + } + catch (Exception ex) { - return ChangeVolume(arguments[1]); + // A device error (e.g. an NVMe timeout) throws from ReadBlock/WriteBlock. + return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); } - else if (arguments[0].Equals("/fp") || arguments[0].Equals("/formatpartiton")) + } + + private static bool TryParseTwo(List arguments, out int first, out int second) + { + first = 0; + second = 0; + + return arguments.Count >= 3 + && int.TryParse(arguments[1], out first) + && int.TryParse(arguments[2], out second); + } + + public ReturnInfo DeleteDisk(int disknumber, int index) + { + IBlockDevice disk = StorageManager.GetDevice(disknumber); + if (disk == null) { - return FormatVolume(int.Parse(arguments[1]), int.Parse(arguments[2])); + return new ReturnInfo(this, ReturnCode.ERROR, "Failed to find our drive."); } - else if (arguments[0].Equals("/lp") || arguments[0].Equals("/listpartitions")) + + IReadOnlyList partitions = StorageManager.GetPartitions(disk); + if (index < 1 || index > partitions.Count) { - return ListDisk(); + return new ReturnInfo(this, ReturnCode.ERROR, "Failed to find partition #" + index + " on disk #" + disknumber + "."); } - else if (arguments[0].Equals("/mp") || arguments[0].Equals("/makepartition")) + + Partition target = partitions[index - 1]; + + if (IsSuperfloppy(partitions)) { - return MakeDisk(int.Parse(arguments[1]), int.Parse(arguments[2])); + return new ReturnInfo(this, ReturnCode.ERROR, "Disk #" + disknumber + " has no partition table (whole-disk FAT volume)."); } - else if (arguments[0].Equals("/dp") || arguments[0].Equals("/deletepartition")) + + string error; + if (!ReleasePartition(target, out error)) { - return DeleteDisk(int.Parse(arguments[1]), int.Parse(arguments[2])); + return new ReturnInfo(this, ReturnCode.ERROR, error); } - else + + // Identity is (start, count), not an index. + if (!PartitionManager.Delete(disk, new PartitionManager.PartitionLocation(target.StartSector, target.BlockCount))) { - return new ReturnInfo(this, ReturnCode.ERROR_ARG); - } + Volumes.MountAll(); + return new ReturnInfo(this, ReturnCode.ERROR, "Failed to delete partition #" + index + " on disk #" + disknumber + "."); + } + + Console.WriteLine("Partition #" + index + " deleted on disk #" + disknumber + "!"); + + StorageManager.RescanPartitions(disk); + Volumes.MountAll(); + + return new ReturnInfo(this, ReturnCode.OK); } - public ReturnInfo DeleteDisk(int disknumber, int index) + public ReturnInfo MakeDisk(int disknumber, int size) { - Disk ourDisk = null; - int counter = 0; + if (size <= 0) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Partition size must be greater than 0 MB."); + } - index--; + IBlockDevice disk = StorageManager.GetDevice(disknumber); + if (disk == null) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Failed to find our drive."); + } - foreach (var disk in Kernel.VirtualFileSystem.GetDisks()) + // Divisor check: a null/zero divide halts the gen3 kernel. + if (disk.BlockSize == 0 || disk.BlockSize > BytesPerMiB) { - if (counter == disknumber) - { - ourDisk = disk; + return new ReturnInfo(this, ReturnCode.ERROR, "Unsupported sector size on disk #" + disknumber + "."); + } - ourDisk.DeletePartition(index); + // GEN3-GAP(mbr): Mbr.IsMbr only checks 0x55AA, which a FAT "superfloppy" (no partition table) + // also carries: a new entry would be written into its boot sector. + if (IsSuperfloppy(StorageManager.GetPartitions(disk))) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Disk #" + disknumber + " holds a whole-disk FAT volume (no partition table), refusing to create a partition."); + } - Console.WriteLine("Partition #" + (index + 1) + " deleted on disk #" + disknumber + "!"); + // GPT first: a GPT disk also carries a protective MBR. + bool isGpt = Gpt.IsGpt(disk); + if (!isGpt && !Mbr.IsMbr(disk)) + { + // Blank disk: write an empty MBR first, then rescan before computing the append point. + Mbr.Create(disk); + StorageManager.RescanPartitions(disk); + Console.WriteLine("No partition table on disk #" + disknumber + ", MBR created."); + } - Kernel.VirtualFileSystem.Disks.Clear(); - Kernel.VirtualFileSystem.Initialize(false); + ulong start = isGpt ? Gpt.FirstUsableLba : MbrFirstPartitionLba; - break; + IReadOnlyList partitions = StorageManager.GetPartitions(disk); + for (int i = 0; i < partitions.Count; i++) + { + ulong end = partitions[i].StartSector + partitions[i].BlockCount; + if (end > start) + { + start = end; } + } + + ulong sectors = (ulong)size * (BytesPerMiB / disk.BlockSize); - counter++; + if (start >= disk.BlockCount || sectors > disk.BlockCount - start) + { + ulong free = start < disk.BlockCount ? (disk.BlockCount - start) * disk.BlockSize / BytesPerMiB : 0; + return new ReturnInfo(this, ReturnCode.ERROR, "Not enough free space on disk #" + disknumber + " (" + free + " MB available)."); } - if (ourDisk == null) + + if (!PartitionManager.Create(disk, start, sectors, MbrFat32LbaSystemId, Gpt.BasicDataPartitionType)) { - return new ReturnInfo(this, ReturnCode.ERROR, "Failed to find our drive."); + return new ReturnInfo(this, ReturnCode.ERROR, "Failed to create partition (no free slot or bad geometry)."); } + StorageManager.RescanPartitions(disk); + + Console.WriteLine("Partition created on disk #" + disknumber + "!"); + + // A fresh partition holds no filesystem: use vol /fp to format it. + Volumes.MountAll(); + return new ReturnInfo(this, ReturnCode.OK); } - public ReturnInfo MakeDisk(int disknumber, int size) + public ReturnInfo DiskInfo(int disknumber) { - Disk ourDisk = null; - int counter = 0; - - foreach (var disk in Kernel.VirtualFileSystem.GetDisks()) + IBlockDevice disk = StorageManager.GetDevice(disknumber); + if (disk == null) { - if (counter == disknumber) - { - ourDisk = disk; + return new ReturnInfo(this, ReturnCode.ERROR, "Failed to find our drive."); + } - ourDisk.CreatePartition(size); + DisplayInformation(disknumber, disk); - Console.WriteLine("Partition created on disk #" + disknumber + "!"); + return new ReturnInfo(this, ReturnCode.OK); + } - Kernel.VirtualFileSystem.Disks.Clear(); - Kernel.VirtualFileSystem.Initialize(false); + public ReturnInfo ListDisk() + { + if (!StorageManager.IsEnabled) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Storage support is disabled."); + } - break; - } + IReadOnlyList disks = StorageManager.Devices; - counter++; + if (disks.Count == 0) + { + Console.WriteLine("No disk detected (only SATA/AHCI, NVMe and USB disks are supported)."); + return new ReturnInfo(this, ReturnCode.OK); } - if (ourDisk == null) + + for (int i = 0; i < disks.Count; i++) { - return new ReturnInfo(this, ReturnCode.ERROR, "Failed to find our drive."); + DisplayInformation(i, disks[i]); } return new ReturnInfo(this, ReturnCode.OK); } - public ReturnInfo DiskInfo(int disknumber) + public ReturnInfo FormatVolume(int driveName, int partition) { - Disk ourDisk = null; - int counter = 0; + IBlockDevice disk = StorageManager.GetDevice(driveName); + if (disk == null) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Failed to find our drive."); + } - foreach (var disk in Kernel.VirtualFileSystem.GetDisks()) + IReadOnlyList partitions = StorageManager.GetPartitions(disk); + if (partition < 1 || partition > partitions.Count) { - if (counter == disknumber) - { - ourDisk = disk; + return new ReturnInfo(this, ReturnCode.ERROR, "Failed to find partition #" + partition + " on disk #" + driveName + "."); + } - ourDisk.DisplayInformation(); + Partition target = partitions[partition - 1]; - break; - } + string error; + if (!ReleasePartition(target, out error)) + { + return new ReturnInfo(this, ReturnCode.ERROR, error); + } - counter++; + // FAT32 first (gen2 behaviour); a partition too small for FAT32 gets FAT12/16. + bool formatted = VfsManager.TryFormat(Volumes.FatDriver, target, new FatFormatOptions { Type = Fat32, VolumeLabel = FormatLabel }) + || VfsManager.TryFormat(Volumes.FatDriver, target, new FatFormatOptions { Type = FatAuto, VolumeLabel = FormatLabel }); + + if (!formatted) + { + Volumes.MountAll(); + return new ReturnInfo(this, ReturnCode.ERROR, "Failed to format partition #" + partition + " on disk #" + driveName + "."); } - if (ourDisk == null) + + string label; + Console.WriteLine("Partition #" + partition + " formatted to " + DetectFilesystem(target, out label) + " on disk #" + driveName + "!"); + + Volumes.MountAll(); + + VfsManager.VfsMount mount = FindMount(target); + if (mount != null) { - return new ReturnInfo(this, ReturnCode.ERROR, "Failed to find our drive."); + Console.WriteLine("Mounted at " + AuraPath.AsDirectory(mount.MountPoint)); } return new ReturnInfo(this, ReturnCode.OK); } - public ReturnInfo ListDisk() + public ReturnInfo ChangeVolume(string volume) { - int counter = 0; + // Accepts "1", "1:", "1:\" (gen2) and "/1", "/1/". + string number = volume.Trim().TrimEnd('\\', '/').TrimEnd(':').TrimStart('/'); - foreach (var disk in Kernel.VirtualFileSystem.GetDisks()) + VfsManager.VfsMount mount; + if (number.Length == 0 || !VfsManager.TryGetMount("/" + number, out mount)) { - string type = disk.IsMBR ? "MBR" : "GPT"; - - Console.WriteLine(); - Console.WriteLine("Disk #: " + counter + " (" + type + ")"); - - disk.DisplayInformation(); - - counter++; + return new ReturnInfo(this, ReturnCode.ERROR, "The specified drive is not found."); } + Kernel.CurrentVolume = AuraPath.AsDirectory(mount.MountPoint); + Kernel.CurrentDirectory = Kernel.CurrentVolume; + return new ReturnInfo(this, ReturnCode.OK); } - public ReturnInfo FormatVolume(int driveName, int partition) + public ReturnInfo ListVolumes() { - Disk ourDisk = null; - int counter = 0; + IReadOnlyList vols = VfsManager.Mounts; - partition--; + Console.WriteLine(); + Console.WriteLine(" Volume ###\tFormat\tSize\t\tLabel\t\tPartition"); + Console.WriteLine(" ----------\t------\t--------\t-----------\t---------"); - foreach (var disk in Kernel.VirtualFileSystem.GetDisks()) + if (vols.Count == 0) { - if (counter == driveName) - { - ourDisk = disk; + Console.WriteLine(" No volume mounted."); + } - disk.FormatPartition(partition, "FAT32", true); + for (int i = 0; i < vols.Count; i++) + { + VfsManager.VfsMount vol = vols[i]; + string name = AuraPath.AsDirectory(vol.MountPoint); + string label = ""; + string format = vol.Partition != null ? DetectFilesystem(vol.Partition, out label) : vol.Name; + string parent = vol.Partition != null ? vol.Partition.Name : vol.Source; - Console.WriteLine("Partition #" + (partition + 1) + " formatted to FAT32 on disk #" + driveName + "!"); + // GEN3-GAP(driveinfo): TryStatFs sweeps the whole FAT (fine for a user command). + ulong freeBytes, totalBytes; + string size = Volumes.TryGetSpace(vol.MountPoint, out freeBytes, out totalBytes) + ? (totalBytes / BytesPerMiB) + " MB" + : "? MB"; - Kernel.VirtualFileSystem.Disks.Clear(); - Kernel.VirtualFileSystem.Initialize(false); + string marker = name == Kernel.CurrentVolume && vols.Count > 1 ? " >" : " "; - break; - } - - counter++; + Console.WriteLine(marker + name + "\t \t" + format + " \t" + size + "\t\t" + label + "\t\t" + parent); } - if (ourDisk == null) + + return new ReturnInfo(this, ReturnCode.OK); + } + + /// + /// Prints one disk, its table type and its partitions (1-based, the numbering of /fp and /dp). + /// + private static void DisplayInformation(int disknumber, IBlockDevice disk) + { + IReadOnlyList partitions = StorageManager.GetPartitions(disk); + + Console.WriteLine(); + Console.WriteLine("Disk #: " + disknumber + " (" + DescribePartitionTable(disk, partitions) + ")"); + Console.WriteLine(" Name: " + disk.Name + ", " + (disk.BlockCount * disk.BlockSize / BytesPerMiB) + " MB, " + + disk.BlockCount + " sectors of " + disk.BlockSize + " bytes"); + + if (partitions.Count == 0) { - return new ReturnInfo(this, ReturnCode.ERROR, "Failed to find our drive."); + Console.WriteLine(" (no partitions)"); } - return new ReturnInfo(this, ReturnCode.OK); + for (int i = 0; i < partitions.Count; i++) + { + Partition part = partitions[i]; + string label; + string format = DetectFilesystem(part, out label); + VfsManager.VfsMount mount = FindMount(part); + + Console.WriteLine(" Partition #" + (i + 1) + ": " + part.Name + + " Start=" + part.StartSector + + " Sectors=" + part.BlockCount + + " " + (part.BlockCount * part.BlockSize / BytesPerMiB) + " MB" + + " " + format + + (label.Length > 0 ? " \"" + label + "\"" : "") + + (mount != null ? " mounted at " + AuraPath.AsDirectory(mount.MountPoint) : "")); + } } - public ReturnInfo ChangeVolume(string volume) + /// + /// GEN3-GAP(mbr): GPT first, then MBR; a superfloppy also passes Mbr.IsMbr. + /// + private static string DescribePartitionTable(IBlockDevice disk, IReadOnlyList partitions) { try { - bool exist = false; + if (Gpt.IsGpt(disk)) + { + return "GPT"; + } - foreach (var vol in Kernel.VirtualFileSystem.GetVolumes()) + if (IsSuperfloppy(partitions)) { - if (vol.mName == volume + ":\\") - { - exist = true; - Kernel.CurrentVolume = vol.mName; - Kernel.CurrentDirectory = Kernel.CurrentVolume; - } + return "None (whole-disk FAT)"; } - if (!exist) + + if (Mbr.IsMbr(disk)) { - return new ReturnInfo(this, ReturnCode.ERROR, "The specified drive is not found."); + return "MBR"; } } - catch + catch (Exception) { - return new ReturnInfo(this, ReturnCode.ERROR, "The specified drive is not found."); + return "unreadable"; } - return new ReturnInfo(this, ReturnCode.OK); + return "None"; } - public ReturnInfo ListVolumes() + /// + /// A FAT volume formatted straight onto the disk: StorageManager surfaces it as one partition at LBA 0. + /// + private static bool IsSuperfloppy(IReadOnlyList partitions) { - var vols = Kernel.VirtualFileSystem.GetVolumes(); + return partitions.Count == 1 && partitions[0].StartSector == 0; + } - Console.WriteLine(); - Console.WriteLine(" Volume ###\tFormat\tSize"); - Console.WriteLine(" ----------\t------\t--------"); + /// + /// FAT type from the boot sector (DevKernel StorageView.DetectFilesystem). + /// GEN3-GAP(fat-label): no API reads the volume label, so it comes from the BPB + /// (11 bytes at 0x2B on FAT12/16, 0x47 on FAT32, present when the boot signature is 0x29). + /// + private static string DetectFilesystem(Partition partition, out string label) + { + label = ""; + + if (partition == null || partition.BlockSize < 512 || partition.BlockSize > 4096) + { + return "unknown"; + } + + byte[] boot = new byte[partition.BlockSize]; + try + { + partition.ReadBlock(FatBootSector.BootSectorLba, 1, boot); + } + catch (Exception) + { + return "unreadable"; + } + + FatBootSector bootSector; + if (!FatBootSector.TryParse(boot, out bootSector) || bootSector == null) + { + return "unknown"; + } + + string type; + bool fat32 = false; + + switch (bootSector.Type) + { + case FatType.Fat12: + type = "FAT12"; + break; + case FatType.Fat16: + type = "FAT16"; + break; + case FatType.Fat32: + type = "FAT32"; + fat32 = true; + break; + default: + type = "FAT"; + break; + } + + int signatureOffset = fat32 ? 0x42 : 0x26; + int labelOffset = fat32 ? 0x47 : 0x2B; + + if (boot[signatureOffset] == 0x29) + { + label = Encoding.ASCII.GetString(boot, labelOffset, 11).Trim(); + } + + return type; + } - foreach (var vol in vols) + /// + /// The mount of a partition, by location (Host + StartSector): a rescan creates new Partition objects. + /// + private static VfsManager.VfsMount FindMount(Partition partition) + { + IReadOnlyList mounts = VfsManager.Mounts; + for (int i = 0; i < mounts.Count; i++) { - if (vol.mName == Kernel.CurrentVolume && vols.Count > 1) + Partition p = mounts[i].Partition; + if (p != null && ReferenceEquals(p.Host, partition.Host) && p.StartSector == partition.StartSector) { - Console.WriteLine(" >" + vol.mName + "\t \t" + Kernel.VirtualFileSystem.GetFileSystemType(vol.mName) + " \t" + vol.mSize + " MB\t" + vol.mParent); + return mounts[i]; } - else + } + + return null; + } + + /// + /// Unmounts (flush + detach) every mount of a partition before a format or a delete. + /// GEN3-GAP(mounts): VfsManager guards format by Partition reference only, so do it by location here. + /// Refuses the system volume and the volume holding the current directory. + /// + private static bool ReleasePartition(Partition target, out string error) + { + error = null; + + IReadOnlyList mounts = VfsManager.Mounts; + List mountPoints = new List(); + + for (int i = 0; i < mounts.Count; i++) + { + Partition p = mounts[i].Partition; + if (p == null || !ReferenceEquals(p.Host, target.Host) || p.StartSector != target.StartSector) { - Console.WriteLine(" " + vol.mName + "\t \t" + Kernel.VirtualFileSystem.GetFileSystemType(vol.mName) + " \t" + vol.mSize + " MB\t" + vol.mParent); + continue; } + + string volume = AuraPath.AsDirectory(mounts[i].MountPoint); + + // Only an installed system is protected: in live mode AuraPaths.SystemVolume falls back to + // "/0/" without any System/settings.ini, and that disk must stay formattable before setup. + if (AuraPaths.SystemVolume != null && volume == AuraPaths.SystemVolume + && File.Exists(volume + "System/settings.ini")) + { + error = "This partition holds the system volume (" + volume + ")."; + return false; + } + + if (volume == Kernel.CurrentVolume + || AuraPath.AsDirectory(Kernel.CurrentDirectory).StartsWith(volume, StringComparison.Ordinal)) + { + error = "This partition holds the current directory (" + volume + "), leave it first (cd / or vol /cv)."; + return false; + } + + mountPoints.Add(mounts[i].MountPoint); } - return new ReturnInfo(this, ReturnCode.OK); + for (int i = 0; i < mountPoints.Count; i++) + { + try + { + VfsManager.TryUnmount(mountPoints[i]); + } + catch (Exception ex) + { + // The mount is already removed from the table; only its last writes may be lost. + Console.WriteLine("Warning: " + mountPoints[i] + " unmounted, but its last writes may be lost: " + ex.Message); + } + } + + if (mountPoints.Count > 0) + { + Volumes.RefreshSystemVolume(); + } + + return true; } /// @@ -261,10 +597,10 @@ public override void PrintHelp() { Console.WriteLine("Available commands:"); Console.WriteLine("- vol /l List volumes"); - Console.WriteLine("- vol /cv {volume} Change current volume"); + Console.WriteLine("- vol /cv {volume} Change current volume (e.g. vol /cv 1)"); Console.WriteLine("- vol /lp List partitions"); Console.WriteLine("- vol /fp {disknumber} {partitionnumber} Format partition to FAT32"); - Console.WriteLine("- vol /mp {disknumber} {size} Make MBR partition"); + Console.WriteLine("- vol /mp {disknumber} {size} Make partition (size in MB)"); Console.WriteLine("- vol /dp {disknumber} {partitionnumber} Delete partition"); } } diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Graphics/LsRes.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Graphics/LsRes.cs index 383ac8e27..ec8fc8497 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Graphics/LsRes.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Graphics/LsRes.cs @@ -6,6 +6,7 @@ using System; using System.Text; +using Cosmos.Kernel.System.Graphics; namespace Aura_OS.System.Processing.Interpreter.Commands.Graphics { @@ -29,9 +30,28 @@ public override ReturnInfo Execute() sb.AppendLine("Available modes:"); - foreach (var mode in Kernel.Canvas.AvailableModes) + // Null before BeforeRun acquired the screen (e.g. lsres in boot.bat): a null dereference halts gen3 (C6). + if (Kernel.Canvas != null) { - sb.AppendLine("- " + mode.ToString()); + // GEN3-GAP(display-mode): firmware/virtio-gpu displays list only the current mode + // (resolution fixed by limine.conf); only VMware SVGA lists switchable modes. + foreach (var mode in Kernel.Canvas.AvailableModes) + { + sb.AppendLine("- " + mode.ToString()); + } + } + + sb.AppendLine(); + sb.AppendLine("Displays:"); + + for (int i = 0; i < DisplayManager.Count; i++) + { + DisplayDevice display; + + if (DisplayManager.TryGet(i, out display) && display != null) + { + sb.AppendLine("- " + display.DriverName + " " + display.Name + " " + display.Width.ToString() + "x" + display.Height.ToString() + "x" + display.BitsPerPixel.ToString()); + } } Console.WriteLine(sb.ToString()); diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Information/Logs.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Information/Logs.cs index 1b6f32ab3..293e83aab 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Information/Logs.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Information/Logs.cs @@ -18,7 +18,7 @@ class CommandLogs : ICommand /// public CommandLogs(string[] commandvalues) : base(commandvalues) { - Description = "to display Cosmos kernel logs"; + Description = "to display Aura logs"; } /// @@ -32,7 +32,7 @@ public override ReturnInfo Execute() { if (entry.Level == LogLevel.Kernel) { - sb.AppendLine(entry.DateTime.ToString() + " - [Cosmos] - " + entry.Log); + sb.AppendLine(entry.DateTime.ToString() + " - [Kernel] - " + entry.Log); } else { @@ -79,7 +79,7 @@ public void ShowLogs(LogLevel level) { if (entry.Level == LogLevel.Kernel) { - sb.AppendLine(entry.DateTime.ToString() + " - [Cosmos] - " + entry.Log); + sb.AppendLine(entry.DateTime.ToString() + " - [Kernel] - " + entry.Log); } else { @@ -98,7 +98,9 @@ public override void PrintHelp() { Console.WriteLine("Usage:"); Console.WriteLine(" - logs Show all logs"); - Console.WriteLine(" - logs /k Show Cosmos logs"); + // GEN3-GAP(log-sink): Cosmos kernel logs cannot be captured any more (serial only); + // LogLevel.Kernel now carries Aura's own kernel-level messages. + Console.WriteLine(" - logs /k Show Aura kernel logs"); Console.WriteLine(" - logs /o Show AuraOS logs"); } } diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Information/SystemInfo.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Information/SystemInfo.cs index 8b7631712..057ff7806 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Information/SystemInfo.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Information/SystemInfo.cs @@ -5,7 +5,6 @@ */ using Aura_OS.Core; -using Cosmos.Core; using System; using System.Text; @@ -28,10 +27,15 @@ public override ReturnInfo Execute() { StringBuilder sb = new StringBuilder(); + // boot.bat runs before the canvas and the theme manager exist (a null dereference halts gen3). + string graphicMode = Kernel.Canvas != null ? Kernel.Canvas.Name : "None"; + string screenSize = Kernel.Canvas != null ? Kernel.Canvas.Mode.ToString() : "None"; + string themeName = Kernel.ThemeManager != null ? Kernel.ThemeManager.GetThemeName() : "None"; + sb.AppendLine(" . :? Computer name: " + Kernel.ComputerName); sb.AppendLine(" !?: G5. Operating system name: Aura"); - sb.AppendLine(" 7BP!.!@#! Kernel name: Cosmos-devkit"); - sb.AppendLine(" :5@@7J@@G~ .NET version: 6.0"); + sb.AppendLine(" 7BP!.!@#! Kernel name: Cosmos gen3 " + Cosmos.Kernel.System.Kernel.VersionString); + sb.AppendLine(" :5@@7J@@G~ .NET version: 10.0 (NativeAOT)"); sb.AppendLine(" :5~!GG&@B7. Operating system version: " + Kernel.Version); sb.AppendLine(" .^J55Y?!^B#GPGGY: Operating system revision: " + Kernel.Revision); sb.AppendLine(" :!JBGP&@@&BBG&B5??B^ Date and time: " + Time.MonthString() + "/" + Time.DayString() + "/" + Time.YearString() + ", " + Time.TimeString(true, true, true)); @@ -39,10 +43,10 @@ public override ReturnInfo Execute() sb.AppendLine(" :^?&@BPP55!YGJ?.~:.^!^:~GP: Total memory: " + Memory.TotalMemory + "MB"); sb.AppendLine(" :7J?G#5G5.?#G~#^!5J~:J7~^?~ Used memory: " + Memory.GetUsedMemory() + "MB"); sb.AppendLine(" ^5&@##BP!@?GY75!!7BJ?PB5??J&@5^:. Free memory: " + Memory.GetFreeMemory() + "MB"); - sb.AppendLine(" .:JGB&P&7@?BYG7G&G?P#5!PB&@&&@&57J Processor(s): " + CPU.GetCPUBrandString()); - sb.AppendLine(" ?@GB#GGBGJ?J7#@^JGPJ?7!7JPB#P! Graphic mode: " + Kernel.Canvas.Name()); - sb.AppendLine(" ^#&5BP&BGPJG!YB7.^5@&GP555PB@@G7: Screen size: " + Kernel.Canvas.Mode.ToString()); - sb.AppendLine(" ..~P#BB#B?~@#P7 !BP?!~^^^^^:!7 Theme name: " + Kernel.ThemeManager.GetThemeName()); + sb.AppendLine(" .:JGB&P&7@?BYG7G&G?P#5!PB&@&&@&57J Processor(s): " + CpuInfo.GetBrandString()); + sb.AppendLine(" ?@GB#GGBGJ?J7#@^JGPJ?7!7JPB#P! Graphic mode: " + graphicMode); + sb.AppendLine(" ^#&5BP&BGPJG!YB7.^5@&GP555PB@@G7: Screen size: " + screenSize); + sb.AppendLine(" ..~P#BB#B?~@#P7 !BP?!~^^^^^:!7 Theme name: " + themeName); sb.AppendLine(" J@@BPB#B7J@@@!P5^"); sb.AppendLine(" 7&P55BBBB?~?GYJ&@&G~"); sb.AppendLine(" .. P@&#PGG7.:#PJJ5#@P^"); diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Information/Version.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Information/Version.cs index b17ccdb75..b6d71e117 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Information/Version.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Information/Version.cs @@ -6,7 +6,6 @@ using Aura_OS.System.Processing.Interpreter; using Aura_OS.System.Network; -using Cosmos.System.Network; using JZero; using System; using System.Linq; @@ -32,15 +31,27 @@ public override ReturnInfo Execute() Console.ForegroundColor = ConsoleColor.White; - if (NetworkStack.ConfigEmpty()) + if (!NetworkHelper.IsConfigured) { Console.WriteLine("Aura [version " + Kernel.Version + "-" + Kernel.Revision + "]"); } else { - (string latestVersion, string latestRevision, string latestReleaseUrl) = System.Network.Version.GetLastVersionInfo(); + string latestVersion = null; + string latestRevision = null; + string latestReleaseUrl = null; - int versionComparisonResult = System.Network.Version.CompareVersions(Kernel.Version, latestVersion); + try + { + (latestVersion, latestRevision, latestReleaseUrl) = System.Network.Version.GetLastVersionInfo(); + } + catch (Exception) + { + // GEN3-GAP(backend): HTTP/DNS/TLS failure, fall back to the local version below. + latestVersion = null; + latestRevision = null; + latestReleaseUrl = null; + } if (string.IsNullOrEmpty(Kernel.Version) || string.IsNullOrEmpty(latestVersion) || string.IsNullOrEmpty(Kernel.Revision) || string.IsNullOrEmpty(latestRevision)) { @@ -48,6 +59,8 @@ public override ReturnInfo Execute() } else { + int versionComparisonResult = System.Network.Version.CompareVersions(Kernel.Version, latestVersion); + if (versionComparisonResult > 0) { Console.WriteLine("Aura [version " + Kernel.Version + "-" + Kernel.Revision + "], you are on a dev version (last release is " + latestVersion + "-" + latestRevision + ")."); diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Dns.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Dns.cs index faed83a30..22579177e 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Dns.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Dns.cs @@ -6,9 +6,9 @@ using System; using System.Collections.Generic; -using Cosmos.System.Network.IPv4.UDP.DNS; -using Cosmos.System.Network.IPv4; -using Cosmos.System.Network.Config; +using Cosmos.Kernel.System.Network; +using Cosmos.Kernel.System.Network.Config; +using Cosmos.Kernel.System.Network.DNS; using Aura_OS; using Aura_OS.System.Processing.Interpreter; @@ -40,7 +40,7 @@ public override ReturnInfo Execute() /// Arguments public override ReturnInfo Execute(List arguments) { - var xClient = new DnsClient(); + Address server; string domainname; if (arguments.Count < 1 || arguments.Count > 2) @@ -49,25 +49,57 @@ public override ReturnInfo Execute(List arguments) } else if (arguments.Count == 1) { - xClient.Connect(DNSConfig.DNSNameservers[0]); - Console.WriteLine("DNS used : " + DNSConfig.DNSNameservers[0].ToString()); - xClient.SendAsk(arguments[0]); + if (DnsConfig.Nameservers.Count == 0) + { + return new ReturnInfo(this, ReturnCode.ERROR, "No DNS server, use ipconfig /ask or ipconfig /nameserver -add {IP}"); + } + + server = DnsConfig.Nameservers[0]; domainname = arguments[0]; + Console.WriteLine("DNS used : " + server.ToString()); } else { - xClient.Connect(Address.Parse(arguments[0])); - xClient.SendAsk(arguments[1]); + server = Address.Parse(arguments[0]); + if (server is null) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Can't parse DNS server address: " + arguments[0]); + } + domainname = arguments[1]; } - Address address = xClient.Receive(); + // Cosmos DnsClient (not System.Net.Dns): it can query a chosen server. + DnsClient xClient = null; + Address address = null; + string error = null; + + try + { + xClient = new DnsClient(); + xClient.Connect(server); + xClient.SendQuery(domainname); // InvalidOperationException: no configured interface reaches the server + address = xClient.Receive(5000); + } + catch (Exception ex) + { + error = ex.Message; + } + + // gen3: finally/using do not run on the exception path, dispose explicitly. + if (xClient != null) + { + xClient.Dispose(); + } - xClient.Close(); + if (error != null) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Can't query DNS server " + server.ToString() + ": " + error); + } - if (address == null) + if (address is null) { - return new ReturnInfo(this, ReturnCode.ERROR, "Unable to find " + arguments[0]); + return new ReturnInfo(this, ReturnCode.ERROR, "Unable to find " + domainname); } else { diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Ftp.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Ftp.cs index 3eecd8b41..b60ffe776 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Ftp.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Ftp.cs @@ -6,24 +6,36 @@ using System; using System.Collections.Generic; -using Cosmos.System.Network.IPv4.UDP.DNS; -using Cosmos.System.Network.IPv4; -using Cosmos.System.Network.Config; -using Cosmos.System.Network.IPv4.TCP; -using System.Text; -using Aura_OS.System.Processing.Interpreter; -using CosmosFtpServer; +using System.IO; +using System.Net; +using Aura_OS.System.Filesystem; +using Aura_OS.System.Network; +using Cosmos.Network.Ftp; namespace Aura_OS.System.Processing.Interpreter.Commands.Network { class CommandFtp : ICommand { + /// + /// The background FTP server, if one was started. + /// + private static FtpServer s_server; + + /// + /// True from the start of a server until its thread has returned from Listen(). + /// + private static volatile bool s_running; + /// /// Empty constructor. /// - public CommandFtp(string[] commandvalues) : base(commandvalues, CommandType.Network) + /// + /// Not CommandType.Network: 'ftp /stop' must stay usable after the network configuration is gone, + /// starting a server checks the configuration itself. + /// + public CommandFtp(string[] commandvalues) : base(commandvalues) { - Description = "to start a FTP server at port 21."; + Description = "to start or stop a FTP server (port 21 by default)"; } /// @@ -31,56 +43,163 @@ public CommandFtp(string[] commandvalues) : base(commandvalues, CommandType.Netw /// public override ReturnInfo Execute() { - try + return Start(Kernel.CurrentDirectory, FtpServer.DefaultPort, null); + } + + /// + /// CommandFtp + /// + /// Arguments + public override ReturnInfo Execute(List arguments) + { + if (arguments.Count == 0) { - using (var xServer = new FtpServer(Kernel.VirtualFileSystem, Kernel.CurrentDirectory, true)) + return Execute(); + } + + if (arguments[0] == "/stop") + { + if (arguments.Count != 1) { - Console.WriteLine("FTP Server listening at " + NetworkConfiguration.CurrentAddress + ":21 ..."); + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } - xServer.Listen(); + if (s_server == null || !s_running) + { + return new ReturnInfo(this, ReturnCode.ERROR, "The FTP server is not running."); } + + // Listen() disconnects its clients and returns within ~10 ms; a closed server can't listen again. + s_server.Close(); + Console.WriteLine("FTP server stopped."); + + return new ReturnInfo(this, ReturnCode.OK); } - catch (Exception ex) + + if (arguments.Count > 3) { - return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); + return new ReturnInfo(this, ReturnCode.ERROR_ARG); } - return new ReturnInfo(this, ReturnCode.OK); + string root = AuraPath.Resolve(arguments[0]); + + int port = FtpServer.DefaultPort; + if (arguments.Count > 1 && (!int.TryParse(arguments[1], out port) || port < 1 || port > 65535)) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Invalid port: " + arguments[1]); + } + + // The address PASV replies name: 127.0.0.1 lets a client on the QEMU host reach the forwarded passive ports. + IPAddress passiveAddress = null; + if (arguments.Count > 2 && !IPAddress.TryParse(arguments[2], out passiveAddress)) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Invalid IPv4 address: " + arguments[2]); + } + + return Start(root, port, passiveAddress); } /// - /// CommandFtp + /// Starts the FTP server on a thread of its own, so the terminal stays usable. /// - /// Arguments - public override ReturnInfo Execute(List arguments) + private ReturnInfo Start(string root, int port, IPAddress passiveAddress) { - try + // GEN3-GAP(net-misc): FtpServer can't detect a port clash, so only one server at a time. + if (s_running) { - string vol = arguments[0]; + return new ReturnInfo(this, ReturnCode.ERROR, "The FTP server already runs on port " + s_server.Port + ", use 'ftp /stop' first."); + } - using (var xServer = new FtpServer(Kernel.VirtualFileSystem, vol, true)) + if (!NetworkHelper.IsConfigured) + { + return new ReturnInfo(this, ReturnCode.ERROR, "No network configuration detected! Use ipconfig /ask or ipconfig /set."); + } + + FtpServer server; + try + { + server = new FtpServer(root, port) { - Console.WriteLine("FTP Server listening at " + NetworkConfiguration.CurrentAddress + ":21 ..."); + // Runs on the FTP thread: never Console nor Logs (not thread-safe), serial only. + Log = static message => Cosmos.Kernel.System.Diagnostics.Log.WriteString(message + "\n"), + PassiveAddress = passiveAddress, + }; + } + catch (DirectoryNotFoundException ex) + { + return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); + } + catch (ArgumentException ex) + { + // Empty root, port out of range. + return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); + } - xServer.Listen(); - } + s_server = server; + s_running = true; + + string error = null; + try + { + // GEN3-GAP(net-threads): the network stack has no locks; the FTP thread is the only background user. + // GEN3-GAP(gc-conservative): FtpServer.Listen sleeps in Thread.Sleep; on kernels without the + // conservative-root GC fix the first collection on the UI thread corrupts its wait monitor (#GP). + new global::System.Threading.Thread(() => Serve(server)).Start(); } catch (Exception ex) { - return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); + error = ex.Message; + } + + if (error != null) + { + s_running = false; + return new ReturnInfo(this, ReturnCode.ERROR, "Can't start the FTP thread: " + error); + } + + string address = NetworkHelper.CurrentAddress is null ? "0.0.0.0" : NetworkHelper.CurrentAddress.ToString(); + + Console.WriteLine("FTP server serving " + server.RootDirectory + " at " + address + ":" + port + + " (passive ports " + server.PassivePortMin + "-" + server.PassivePortMax + "), use 'ftp /stop' to stop it."); + + if (passiveAddress is null) + { + Console.WriteLine("Under QEMU, add 127.0.0.1 as pasv-ip for clients that connect where PASV says, such as FileZilla."); } return new ReturnInfo(this, ReturnCode.OK); } + /// + /// FTP thread body: serves clients until 'ftp /stop'. + /// + private static void Serve(FtpServer server) + { + // No terminal to report to from this thread: whatever stops the server goes to the serial log. + try + { + server.Listen(); + } + catch (Exception ex) + { + Cosmos.Kernel.System.Diagnostics.Log.WriteString("[FTP] Server stopped: " + ex.Message + "\n"); + } + + s_running = false; + } + /// /// Print /help information /// public override void PrintHelp() { Console.WriteLine("Usage:"); - Console.WriteLine(" - ftp Open FTP server with path 0:\\"); - Console.WriteLine(" - ftp {path} Open FTP server with custom path"); + Console.WriteLine(" - ftp Start a FTP server on the current directory (port 21)"); + Console.WriteLine(" - ftp {path} [port] [pasv-ip] Start a FTP server on a custom path (/0/ is the first volume)"); + Console.WriteLine(" - ftp /stop Stop the FTP server"); + Console.WriteLine("The server runs in the background (anonymous login, up to 8 clients)."); + Console.WriteLine("Under QEMU, forward the ports (hostfwd=tcp::2121-:21 and tcp::50000-:50000 ... 50009)"); + Console.WriteLine("and use 127.0.0.1 as pasv-ip."); } } } \ No newline at end of file diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/IPConfig.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/IPConfig.cs index 7688a5dfa..443aece92 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/IPConfig.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/IPConfig.cs @@ -6,12 +6,9 @@ using Aura_OS.System.Network; -using Aura_OS.System.Processing.Processes; -using Cosmos.HAL; -using Cosmos.System.Network; -using Cosmos.System.Network.Config; -using Cosmos.System.Network.IPv4; -using Cosmos.System.Network.IPv4.UDP.DHCP; +using Cosmos.Kernel.System.Network; +using Cosmos.Kernel.System.Network.Config; +using Cosmos.Kernel.System.Network.IPv4; using System; using System.Collections.Generic; @@ -32,22 +29,26 @@ public CommandIPConfig(string[] commandvalues) : base(commandvalues) /// public override ReturnInfo Execute() { - if (NetworkStack.ConfigEmpty()) + if (!NetworkHelper.IsConfigured) { Console.WriteLine("No network configuration detected! Use ipconfig /help"); } - foreach (NetworkConfig config in NetworkConfiguration.NetworkConfigs) + + for (int i = 0; i < NetworkManager.DeviceCount; i++) { - switch (config.Device.CardType) + NetworkAdapter adapter = NetworkManager.GetAdapter(i); + IPConfig config = adapter.IPConfig; + + // GEN3-GAP(dhcp): a DHCP timeout/release can leave a 0.0.0.0 config behind, it counts as none. + if (config is null || config.Address.IsZero) { - case CardType.Ethernet: - Console.Write("Ethernet Card : " + config.Device.NameID + " - " + config.Device.Name); - break; - case CardType.Wireless: - Console.Write("Wireless Card : " + config.Device.NameID + " - " + config.Device.Name); - break; + continue; } - if (NetworkConfiguration.CurrentNetworkConfig.Device == config.Device) + + // GEN3-GAP(nic-names): no interface names nor card types; both gen3 drivers are Ethernet. + Console.Write("Ethernet Card : " + NetworkHelper.AliasOf(adapter) + " - " + adapter.Name); + + if (adapter == NetworkManager.Primary) { Console.WriteLine(" (current)"); } @@ -56,14 +57,14 @@ public override ReturnInfo Execute() Console.WriteLine(); } - Console.WriteLine("MAC Address : " + config.Device.MACAddress.ToString()); - Console.WriteLine("IP Address : " + config.IPConfig.IPAddress.ToString()); - Console.WriteLine("Subnet mask : " + config.IPConfig.SubnetMask.ToString()); - Console.WriteLine("Default Gateway : " + config.IPConfig.DefaultGateway.ToString()); + Console.WriteLine("MAC Address : " + adapter.MacAddress?.ToString()); + Console.WriteLine("IP Address : " + config.Address.ToString()); + Console.WriteLine("Subnet mask : " + config.SubnetMask.ToString()); + Console.WriteLine("Default Gateway : " + config.DefaultGateway.ToString()); Console.WriteLine("DNS Nameservers : "); - foreach (Address dnsnameserver in DNSConfig.DNSNameservers) + for (int j = 0; j < DnsConfig.Nameservers.Count; j++) { - Console.WriteLine(" " + dnsnameserver.ToString()); + Console.WriteLine(" " + DnsConfig.Nameservers[j].ToString()); } } @@ -76,6 +77,11 @@ public override ReturnInfo Execute() /// Arguments public override ReturnInfo Execute(List arguments) { + if (arguments.Count == 0) + { + return Execute(); + } + if (arguments[0] == "/release") { Dhcp.Release(); @@ -88,90 +94,122 @@ public override ReturnInfo Execute(List arguments) } else { - new ReturnInfo(this, ReturnCode.ERROR, "DHCP Discover failed. Can't apply dynamic IPv4 address."); + return new ReturnInfo(this, ReturnCode.ERROR, "DHCP Discover failed. Can't apply dynamic IPv4 address."); } } else if (arguments[0] == "/listnic") { - foreach (var device in NetworkDevice.Devices) + if (NetworkManager.DeviceCount == 0) { - switch (device.CardType) - { - case CardType.Ethernet: - Console.WriteLine("Ethernet Card - " + device.NameID + " - " + device.Name + " (" + device.MACAddress + ")"); - break; - case CardType.Wireless: - Console.WriteLine("Wireless Card - " + device.NameID + " - " + device.Name + " (" + device.MACAddress + ")"); - break; - } + Console.WriteLine("No network device found."); + } + + for (int i = 0; i < NetworkManager.DeviceCount; i++) + { + NetworkAdapter adapter = NetworkManager.GetAdapter(i); + + // GEN3-GAP(nic-names): eth{Index} aliases, no card type (both gen3 drivers are Ethernet). + Console.WriteLine("Ethernet Card - " + NetworkHelper.AliasOf(adapter) + " - " + adapter.Name + + " (" + adapter.MacAddress?.ToString() + ")" + + (adapter.LinkUp ? " - link up" : " - link down") + + (adapter == NetworkManager.Primary ? " (current)" : "")); } } else if (arguments[0] == "/set") { - if (arguments.Count == 3 || arguments.Count == 4) // ipconfig /set eth0 192.168.1.2/24 {gw} + if (arguments.Count != 3 && arguments.Count != 4) // ipconfig /set eth0 192.168.1.2/24 {gw|null} { - string[] adrnetwork = arguments[2].Split('/'); - Address ip = Address.Parse(adrnetwork[0]); - NetworkDevice nic = NetworkDevice.GetDeviceByName(arguments[1]); - Address gw = null; - if (arguments.Count == 4) - { - gw = Address.Parse(arguments[3]); - } + return new ReturnInfo(this, ReturnCode.ERROR, "Usage : ipconfig /set {device} {IPv4/CIDR} [Gateway|null]"); + } - int cidr; - try - { - cidr = int.Parse(adrnetwork[1]); - } - catch (Exception ex) - { - return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); - } - Address subnet = Address.CIDRToAddress(cidr); + NetworkAdapter nic = NetworkHelper.FindAdapter(arguments[1]); + if (!nic.IsValid) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Couldn't find network device: " + arguments[1] + " (see ipconfig /listnic)"); + } - if (nic == null) - { - return new ReturnInfo(this, ReturnCode.ERROR, "Couldn't find network device: " + arguments[1]); - } + string[] adrnetwork = arguments[2].Split('/'); + if (adrnetwork.Length != 2) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Can't parse IP address, use the IPv4/CIDR format (e.g. 192.168.1.2/24)."); + } - if (ip != null && subnet != null && gw != null) - { - IPConfig.Enable(nic, ip, subnet, gw); - Console.WriteLine("Config OK!"); - Kernel.NetworkConnected = true; - } - else if (ip != null && subnet != null) + int cidr; + if (!int.TryParse(adrnetwork[1], out cidr) || cidr < 1 || cidr > 32) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Invalid CIDR: " + adrnetwork[1] + " (expected 1 to 32)."); + } + + Address4 ip = Address4.Parse(adrnetwork[0], AddressNumericStyle.Dec); + Address4 subnet = Address4.CIDRToAddress(cidr); + + // No gateway (or "null"): 0.0.0.0, only on-link traffic works. + Address4 gw = Address4.Zero; + if (arguments.Count == 4 && arguments[3] != "null") + { + gw = Address4.Parse(arguments[3], AddressNumericStyle.Dec); + } + + if (ip is null || subnet is null || gw is null) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Can't parse IP addresses (make sure they are well formated)."); + } + + bool applied; + try + { + applied = IPConfig.Enable(nic, ip, subnet, gw); + } + catch (Exception ex) + { + // GEN3-GAP(dhcp): ArgumentException when another adapter already holds this address + // (duplicate key in the stack's address map). + return new ReturnInfo(this, ReturnCode.ERROR, "Can't apply the configuration: " + ex.Message); + } + + if (!applied) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Can't apply the configuration to " + arguments[1] + "."); + } + + // GEN3-GAP(tcp-primary): TCP always sources from NetworkManager.Primary, make the configured card primary. + if (nic != NetworkManager.Primary) + { + try { - IPConfig.Enable(nic, ip, subnet, ip); - Console.WriteLine("Config OK!"); - Kernel.NetworkConnected = true; + NetworkManager.Primary = nic; } - else + catch (Exception) { - return new ReturnInfo(this, ReturnCode.ERROR, "Can't parse IP addresses (make sure they are well formated)."); + // Invalid handle or network disabled: keep the current primary. } } - else - { - return new ReturnInfo(this, ReturnCode.ERROR, "Usage : ipconfig /set {device} {IPv4/CIDR} {Gateway|null}"); - } + + Console.WriteLine("Config OK!"); + Kernel.NetworkConnected = true; } else if (arguments[0] == "/nameserver") { - if (arguments[1] == "-add") + if (arguments.Count != 3 || (arguments[1] != "-add" && arguments[1] != "-rem")) { - DNSConfig.Add(Address.Parse(arguments[2])); - Console.WriteLine(arguments[2] + " has been added to nameservers."); + return new ReturnInfo(this, ReturnCode.ERROR, "Usage : ipconfig /nameserver {-add|-rem} {IP}"); } - else if (arguments[1] == "-rem") + + Address nameserver = Address.Parse(arguments[2]); + if (nameserver is null) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Can't parse IP address: " + arguments[2]); + } + + if (arguments[1] == "-add") { - DNSConfig.Remove(Address.Parse(arguments[2])); - Console.WriteLine(arguments[2] + " has been removed from nameservers list."); + DnsConfig.Add(nameserver); + Console.WriteLine(nameserver.ToString() + " has been added to nameservers."); } else { - return new ReturnInfo(this, ReturnCode.ERROR, "Usage : ipconfig /nameserver {add|remove} {IP}"); + DnsConfig.Remove(nameserver); + Console.WriteLine(nameserver.ToString() + " has been removed from nameservers list."); } } else @@ -192,10 +230,11 @@ public override void PrintHelp() Console.WriteLine("- ipconfig /release Tell the DHCP server to make the IP address available"); Console.WriteLine("- ipconfig /set Manually set an IP Address"); Console.WriteLine(" Usage:"); - Console.WriteLine(" - ipconfig /set {device} {IPv4} {Subnet} {Gateway}"); + Console.WriteLine(" - ipconfig /set {device} {IPv4/CIDR} [Gateway|null]"); + Console.WriteLine(" - {device} is eth0, eth1... (see /listnic), e.g. ipconfig /set eth0 192.168.1.2/24 192.168.1.254"); Console.WriteLine("- ipconfig /nameserver Manually set an DNS server"); Console.WriteLine(" Usage:"); - Console.WriteLine(" - ipconfig /nameserver {-add|-rem} {IPv4}"); + Console.WriteLine(" - ipconfig /nameserver {-add|-rem} {IP}"); } } } diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Package.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Package.cs index 5615adade..1c4cd9297 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Package.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Package.cs @@ -109,7 +109,8 @@ public override ReturnInfo Execute(List arguments) } catch (Exception ex) { - return new ReturnInfo(this, ReturnCode.ERROR_ARG, ex.ToString()); + // Network/HTTP failures (HttpException, NotSupportedException for https, ...). + return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); } } diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Ping.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Ping.cs index a6585b76c..21eb0b8b6 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Ping.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Ping.cs @@ -5,12 +5,11 @@ */ using System; -using Sys = Cosmos.System; -using Cosmos.System.Network; using System.Collections.Generic; -using Cosmos.System.Network.IPv4; -using Cosmos.System.Network.Config; -using Cosmos.System.Network.IPv4.UDP.DNS; +using Aura_OS.System.Network; +using Cosmos.Kernel.System.Network; +using Cosmos.Kernel.System.Network.IPv4; +using Cosmos.Kernel.System.Network.IPv6; namespace Aura_OS.System.Processing.Interpreter.Commands.Network { @@ -35,71 +34,99 @@ public override ReturnInfo Execute(List arguments) int PacketLost = 0; int PercentLoss; - Address source; - Address destination = Address.Parse(arguments[0]); - - if (destination != null) + if (arguments.Count != 1) { - source = IPConfig.FindNetwork(destination); + return new ReturnInfo(this, ReturnCode.ERROR_ARG); } - else //Make a DNS request if it's not an IP - { - var xClient = new DnsClient(); - xClient.Connect(DNSConfig.DNSNameservers[0]); - xClient.SendAsk(arguments[0]); - destination = xClient.Receive(); - xClient.Close(); - if (destination == null) - { - return new ReturnInfo(this, ReturnCode.ERROR, "Failed to get DNS response for " + arguments[0]); - } + // IP literal (v4 or v6), else a DNS request (A record) on the first nameserver. + Address destination = NetworkHelper.Resolve(arguments[0]); - source = IPConfig.FindNetwork(destination); + if (destination is null) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Failed to get DNS response for " + arguments[0]); } + Address6 destination6 = destination as Address6; + IcmpClient xClient = null; + Icmpv6Client xClient6 = null; + string error = null; + try { Console.WriteLine("Sending ping to " + destination.ToString()); - var xClient = new ICMPClient(); - xClient.Connect(destination); + // IcmpClient builds IPv4 packets only. + if (destination6 is not null) + { + xClient6 = new Icmpv6Client(); + xClient6.Connect(destination6); + } + else + { + xClient = new IcmpClient(); + xClient.Connect(destination); + } - for (int i = 0; i < 4; i++) + for (ushort sequence = 1; sequence <= 4; sequence++) { - xClient.SendEcho(); + // InvalidOperationException when no configured interface reaches the destination. + if (xClient6 != null) + { + xClient6.SendEcho(1, sequence); + } + else + { + xClient.SendEcho(1, sequence); + } PacketSent++; - var endpoint = new EndPoint(Address.Zero, 0); + var endpoint = new EndPoint(Address4.Zero, 0); - int second = xClient.Receive(ref endpoint, 4000); + // gen3 returns the elapsed milliseconds (10 ms steps), gen2 returned seconds. + // GEN3-GAP(net-misc): IcmpClient doesn't match the echo id/sequence. + int milliseconds = xClient6 != null ? xClient6.Receive(ref endpoint, 4000) : xClient.Receive(ref endpoint, 4000); - if (second == -1) + if (milliseconds == -1) { Console.WriteLine("Destination host unreachable."); PacketLost++; } else { - if (second < 1) + if (milliseconds == 0) { - Console.WriteLine("Reply received from " + endpoint.Address.ToString() + " time < 1s"); + Console.WriteLine("Reply received from " + endpoint.Address.ToString() + " time<10ms"); } - else if (second >= 1) + else { - Console.WriteLine("Reply received from " + endpoint.Address.ToString() + " time " + second + "s"); + Console.WriteLine("Reply received from " + endpoint.Address.ToString() + " time=" + milliseconds + "ms"); } PacketReceived++; } } + } + catch (Exception ex) + { + error = ex.Message; + } - xClient.Close(); + // gen3: finally/using do not run on the exception path, dispose explicitly. + if (xClient != null) + { + xClient.Dispose(); } - catch + + if (xClient6 != null) + { + xClient6.Dispose(); + } + + if (error != null) { - return new ReturnInfo(this, ReturnCode.ERROR, "Ping process error."); + return new ReturnInfo(this, ReturnCode.ERROR, "Ping process error: " + error); } PercentLoss = 25 * PacketLost; diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Udp.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Udp.cs index 22834d058..e636d6842 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Udp.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Udp.cs @@ -5,18 +5,19 @@ */ using System; -using Sys = Cosmos.System; -using Cosmos.System.Network; -using System.Text; using System.Collections.Generic; -using Cosmos.System.Network.IPv4; -using Cosmos.System.Network.IPv4.UDP; +using System.Net; +using System.Net.Sockets; +using System.Text; +using Cosmos.Kernel.System.Timer; using Aura_OS.System.Processing.Interpreter; namespace Aura_OS.System.Processing.Interpreter.Commands.Network { class CommandUdp : ICommand { + private const int DefaultListenTimeoutSeconds = 30; + /// /// Empty constructor. /// @@ -37,23 +38,86 @@ public override ReturnInfo Execute(List arguments) } if (arguments[0] == "/l") { - if (arguments.Count <= 1) + if (arguments.Count < 2 || arguments.Count > 3) { return new ReturnInfo(this, ReturnCode.ERROR_ARG); } - int port = int.Parse(arguments[1]); - Console.WriteLine("Listening at " + port + "..."); + int port; + if (!int.TryParse(arguments[1], out port) || port < 1 || port > 65535) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Invalid port: " + arguments[1]); + } - var client = new UdpClient(port); + // gen2 waited forever (ESC does not reach a command running in the GUI terminal): bounded wait. + int timeoutSeconds = DefaultListenTimeoutSeconds; + if (arguments.Count == 3 && (!int.TryParse(arguments[2], out timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > 86400)) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Invalid timeout: " + arguments[2]); + } - EndPoint RemoteIpEndPoint = new EndPoint(Address.Zero, 0); + Console.WriteLine("Listening at " + port + " for " + timeoutSeconds + "s..."); - byte[] received = client.Receive(ref RemoteIpEndPoint); + UdpClient client = null; + byte[] received = null; + string remote = null; + string error = null; + + try + { + client = new UdpClient(port); + + IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); + + // The BCL Receive returns an empty array at once when nothing is queued: wait first. + // GEN3-GAP(socket-misc): UDP Available counts queued datagrams, not bytes. + int timeoutMs = timeoutSeconds * 1000; + int waited = 0; + while (client.Available == 0 && waited < timeoutMs) + { + TimerManager.Wait(50); + waited += 50; + } + + if (client.Available > 0) + { + received = client.Receive(ref remoteIpEndPoint); + + // GEN3-GAP(ipaddress): explicit ToString(), interpolation prints 0.0.0.0. + // The IPEndPoint plug returns a null Address for an endpoint it doesn't know. + IPAddress remoteAddress = remoteIpEndPoint == null ? null : remoteIpEndPoint.Address; + remote = (remoteAddress is null ? "?" : remoteAddress.ToString()) + ":" + + (remoteIpEndPoint == null ? "?" : remoteIpEndPoint.Port.ToString()); + } + } + catch (Exception ex) + { + error = ex.Message; + } - Console.WriteLine("Received UDP packet from " + RemoteIpEndPoint.Address.ToString() + ": \"" + Encoding.ASCII.GetString(received) + "\""); + // gen3: finally/using do not run on the exception path, close explicitly. + if (client != null) + { + try + { + client.Close(); + } + catch (Exception) + { + } + } - client.Close(); + if (error != null) + { + return new ReturnInfo(this, ReturnCode.ERROR, error); + } + + if (received == null) + { + return new ReturnInfo(this, ReturnCode.ERROR, "No UDP packet received at " + port + " after " + timeoutSeconds + "s."); + } + + Console.WriteLine("Received UDP packet from " + remote + ": \"" + Encoding.ASCII.GetString(received) + "\""); return new ReturnInfo(this, ReturnCode.OK); } @@ -63,20 +127,54 @@ public override ReturnInfo Execute(List arguments) { return new ReturnInfo(this, ReturnCode.ERROR_ARG); } - Address ip = Address.Parse(arguments[1]); - int port = int.Parse(arguments[2]); + // GEN3-GAP(ipaddress): the plugged IPAddress.Parse returns null instead of throwing. + IPAddress ip = IPAddress.Parse(arguments[1]); + if (ip is null) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Can't parse IPv4 address: " + arguments[1]); + } - string message = arguments[3]; + int port; + if (!int.TryParse(arguments[2], out port) || port < 1 || port > 65535) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Invalid port: " + arguments[2]); + } + + string message = string.Join(" ", arguments.GetRange(3, arguments.Count - 3)); + byte[] data = Encoding.ASCII.GetBytes(message); - var xClient = new UdpClient(port); + UdpClient xClient = null; + string error = null; - xClient.Connect(ip, port); + try + { + xClient = new UdpClient(); + xClient.Send(data, data.Length, new IPEndPoint(ip, port)); // SendTo pumps the stack + } + catch (Exception ex) + { + error = ex.Message; + } + + if (xClient != null) + { + try + { + xClient.Close(); + } + catch (Exception) + { + } + } + + if (error != null) + { + return new ReturnInfo(this, ReturnCode.ERROR, error); + } - xClient.Send(Encoding.ASCII.GetBytes(message)); Console.WriteLine("Sent UDP packet to " + ip.ToString() + ":" + port); - xClient.Close(); return new ReturnInfo(this, ReturnCode.OK); } else @@ -91,7 +189,7 @@ public override ReturnInfo Execute(List arguments) public override void PrintHelp() { Console.WriteLine("Usage:"); - Console.WriteLine(" - udp /l {port} listen for an UDP packet at a specific port"); + Console.WriteLine(" - udp /l {port} [timeout_s] listen for an UDP packet at a specific port (default timeout 30s)"); Console.WriteLine(" - udp /s {ip} {port} {text_message} send an UDP packet to and IP/port"); } } diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Wget.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Wget.cs index d77a65353..1695bad8c 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Wget.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Network/Wget.cs @@ -7,12 +7,15 @@ using System; using System.Collections.Generic; using System.IO; +using Aura_OS.System.Filesystem; using Aura_OS.System.Network; namespace Aura_OS.System.Processing.Interpreter.Commands.Network { class CommandWget : ICommand { + private const string DefaultFileName = "index.html"; + /// /// Empty constructor. /// @@ -37,36 +40,95 @@ public override ReturnInfo Execute() /// Arguments public override ReturnInfo Execute(List arguments) { + if (arguments.Count < 1 || arguments.Count > 2) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + string url = arguments[0]; - if (url.StartsWith("https://")) + if (url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { + // GEN3-GAP(http-tls): no TLS in gen3. return new ReturnInfo(this, ReturnCode.ERROR_ARG, "HTTPS currently not supported, please use http://"); } + string fileName = GetFileName(url); + string path; + + if (arguments.Count == 2) + { + path = AuraPath.Resolve(arguments[1]); + + if (Directory.Exists(path)) + { + path = AuraPath.AsDirectory(path) + fileName; + } + else if (!AuraPath.IsValidName(Path.GetFileName(path))) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG, "Invalid file name: " + arguments[1]); + } + } + else + { + path = AuraPath.AsDirectory(Kernel.CurrentDirectory) + fileName; + } + try { - string file = Http.DownloadFile(url); + // Binary-safe: gen2 wrote the ASCII text to file.html whatever was downloaded. + byte[] data = Http.DownloadRawFile(url); - File.WriteAllText(Kernel.CurrentDirectory + "file.html", file); + File.WriteAllBytes(path, data); - Console.WriteLine(url + " saved to file.html"); + Console.WriteLine(url + " saved to " + path + " (" + data.Length + " bytes)"); } catch (Exception ex) { - return new ReturnInfo(this, ReturnCode.ERROR_ARG, "Exception: " + ex); + return new ReturnInfo(this, ReturnCode.ERROR, ex.Message); } return new ReturnInfo(this, ReturnCode.OK); } + /// + /// Last URL path segment (query and fragment removed), or index.html. + /// + private static string GetFileName(string url) + { + string rest = url; + + int scheme = rest.IndexOf("://"); + if (scheme >= 0) + { + rest = rest.Substring(scheme + 3); + } + + int cut = rest.IndexOfAny(new char[] { '?', '#' }); + if (cut >= 0) + { + rest = rest.Substring(0, cut); + } + + int slash = rest.LastIndexOf('/'); + if (slash < 0) + { + return DefaultFileName; // host only + } + + string name = rest.Substring(slash + 1); + + return AuraPath.IsValidName(name) ? name : DefaultFileName; + } + /// /// Print /help information /// public override void PrintHelp() { Console.WriteLine("Usage:"); - Console.WriteLine(" - wget {url}"); + Console.WriteLine(" - wget {url} save to the current directory (last URL segment or index.html)"); + Console.WriteLine(" - wget {url} {path} save to a custom file or directory (/N is the N-th volume)"); } } } \ No newline at end of file diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Power/Reboot.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Power/Reboot.cs index 16471842c..03f4456e0 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Power/Reboot.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Power/Reboot.cs @@ -7,7 +7,6 @@ using Aura_OS; using Aura_OS.System.Processing.Interpreter; using System; -using Sys = Cosmos.System; namespace Aura_OS.System.Processing.Interpreter.Commands.Power { @@ -27,7 +26,7 @@ public CommandReboot(string[] commandvalues) : base(commandvalues) public override ReturnInfo Execute() { Console.WriteLine("Restarting..."); - Sys.Power.Reboot(); + AuraPower.Reboot(); return new ReturnInfo(this, ReturnCode.OK); } } diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Power/Shutdown.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Power/Shutdown.cs index 2a0b69cc8..1ed6aaa31 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Power/Shutdown.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Power/Shutdown.cs @@ -5,7 +5,6 @@ */ using System; -using Sys = Cosmos.System; using Aura_OS; using Aura_OS.System.Processing.Interpreter; @@ -27,7 +26,7 @@ public CommandShutdown(string[] commandvalues) : base(commandvalues) public override ReturnInfo Execute() { Console.WriteLine("Shutting Down..."); - Sys.Power.Shutdown(); + AuraPower.Shutdown(); return new ReturnInfo(this, ReturnCode.OK); } } diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Processing/Lsprocess.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Processing/Lsprocess.cs index 96ed39e99..f56dea806 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Processing/Lsprocess.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Processing/Lsprocess.cs @@ -9,6 +9,7 @@ using System; using System.Collections.Generic; using System.Text; +using Cosmos.Kernel.System.Diagnostics; namespace Aura_OS.System.Processing.Interpreter.Commands.Util { @@ -41,9 +42,67 @@ public override ReturnInfo Execute() sb.AppendLine(); } + AppendKernelThreads(sb); + Console.WriteLine(sb.ToString()); return new ReturnInfo(this, ReturnCode.OK); } + + /// + /// Kernel scheduler threads (Aura processes all run on the main loop thread). + /// GEN3-GAP(idle-thread): the main loop is the scheduler's idle thread, so no CPU% is shown. + /// + private static void AppendKernelThreads(StringBuilder sb) + { + if (!SchedulerInfo.IsInitialized) + { + return; + } + + sb.AppendLine(); + sb.AppendLine("TID STATE RUNTIME"); + + int slotCount = SchedulerInfo.ThreadSlotCount; + for (int slot = 0; slot < slotCount; slot++) + { + if (!SchedulerInfo.TryGetThreadInSlot(slot, out KernelThreadInfo thread) || thread.State == KernelThreadState.Dead) + { + continue; + } + + sb.Append(thread.Id.ToString().PadRight(8, ' ')); + sb.Append(GetStateName(thread.State).PadRight(10, ' ')); + sb.Append((thread.TotalRuntimeNs / SchedulerInfo.NanosecondsPerMillisecond).ToString() + "ms"); + if (thread.IsIdle) + { + sb.Append(" (main loop)"); + } + + sb.AppendLine(); + } + } + + // No enum ToString() under NativeAOT: map the state by hand. + private static string GetStateName(KernelThreadState state) + { + switch (state) + { + case KernelThreadState.Created: + return "Created"; + case KernelThreadState.Ready: + return "Ready"; + case KernelThreadState.Running: + return "Running"; + case KernelThreadState.Blocked: + return "Blocked"; + case KernelThreadState.Sleeping: + return "Sleeping"; + case KernelThreadState.Dead: + return "Dead"; + default: + return "?"; + } + } } } diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Processing/Run.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Processing/Run.cs index 0d8d3eb8a..8d41f2f37 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Processing/Run.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Processing/Run.cs @@ -7,7 +7,9 @@ using System; using System.Collections.Generic; using System.IO; -using UniLua; +using Cosmos.Executable.Lua; +using Aura_OS.System.Filesystem; +using Aura_OS.System.Processing.Lua; namespace Aura_OS.System.Processing.Interpreter.Commands.Processing { @@ -22,7 +24,12 @@ public override ReturnInfo Execute(List arguments) { try { - string filePath = Path.Combine(Kernel.CurrentDirectory, arguments[0]); + if (arguments.Count == 0) + { + return new ReturnInfo(this, ReturnCode.ERROR_ARG); + } + + string filePath = AuraPath.Resolve(arguments[0]); string fileExtension = Path.GetExtension(filePath); @@ -37,15 +44,18 @@ public override ReturnInfo Execute(List arguments) if (fileExtension == string.Empty) { - foreach (var package in Kernel.PackageManager.Packages) + if (Kernel.PackageManager != null && Kernel.PackageManager.Packages != null) { - if (package.Name == arguments[0]) + foreach (var package in Kernel.PackageManager.Packages) { - return RunCexe(package.Executable, args); + if (package != null && package.Name == arguments[0]) + { + return RunCexe(package.Executable, args); + } } } - string installedPath = "0:\\System\\Programs\\" + arguments[0] + ".cexe"; + string installedPath = AuraPaths.ProgramsDir + arguments[0] + ".cexe"; if (File.Exists(installedPath)) { @@ -64,14 +74,21 @@ public override ReturnInfo Execute(List arguments) switch (fileExtension.ToLower()) { case ".bat": + // Batch builds a fresh CommandManager per line, which resets the static command table: + // put the caller's (the Terminal's, whose clear/exit are bound to it) back afterwards. + List callerCommands = CommandManager.GetCommands(); Batch.Execute(filePath); + if (callerCommands != null) + { + CommandManager._commands = callerCommands; + } break; case ".cexe": byte[] executableBytes = File.ReadAllBytes(filePath); Executable executable = new(executableBytes); return RunCexe(executable, args); case ".lua": - return RunLua(filePath); + return RunLua(filePath, args); default: return new ReturnInfo(this, ReturnCode.ERROR, "Unsupported file type."); } @@ -100,66 +117,65 @@ private ReturnInfo RunCexe(Executable executable, List args) } } - private ReturnInfo RunLua(string filePath) + /// + /// Run a Lua script with its arguments (arg table and ...). A script that returns a table + /// with a main function (gen2 convention) gets main() called; a plain script just runs. + /// + private ReturnInfo RunLua(string filePath, List args) { + ReturnInfo result = new ReturnInfo(this, ReturnCode.OK); + LuaInterpreter lua = null; + try { - // create Lua VM instance - var Lua = LuaAPI.NewState(); - - // load base libraries - Lua.L_OpenLibs(); + lua = AuraLua.Create(); - // load and run Lua script file - var LuaScriptFile = filePath; - var status = Lua.L_DoFile(LuaScriptFile); + ILuaState state = lua.State; - // capture errors - if (status != ThreadStatus.LUA_OK) - { - throw new Exception(Lua.ToString(-1)); - } + // arg[0] = script path, arg[1..n] = arguments (as lua script.lua args...) + state.CreateTable(args.Count, 1); + state.PushString(filePath); + state.RawSetI(-2, 0); - // ensuare the value returned by 'main.lua' is a Lua table - if (!Lua.IsTable(-1)) + for (int i = 0; i < args.Count; i++) { - throw new Exception( - "start's return value is not a table"); + state.PushString(args[i]); + state.RawSetI(-2, i + 1); } - var AwakeRef = StoreMethod("main"); - - Lua.Pop(1); - - CallMethod(AwakeRef); + state.SetGlobal("arg"); - int StoreMethod(string name) - { - Lua.GetField(-1, name); - if (!Lua.IsFunction(-1)) - { - throw new Exception(string.Format( - "method {0} not found!", name)); - } - return Lua.L_Ref(LuaDef.LUA_REGISTRYINDEX); - } - - void CallMethod(int funcRef) + // DoString gives the traceback, LuaException and os.exit handling; filePath is absolute + lua.DoString( + "local f = assert(loadfile(arg[0])) " + + "local m = f(table.unpack(arg)) " + + "if type(m) == 'table' and type(m.main) == 'function' then m.main() end", + "=run"); + } + catch (LuaException e) + { + result = new ReturnInfo(this, ReturnCode.ERROR, e.Message + (e.LuaStackTrace != null ? "\n" + e.LuaStackTrace : "")); + } + catch (LuaExitException e) + { + if (e.ExitCode != 0) { - Lua.RawGetI(LuaDef.LUA_REGISTRYINDEX, funcRef); - var status = Lua.PCall(0, 0, 0); - if (status != ThreadStatus.LUA_OK) - { - Console.WriteLine(Lua.ToString(-1)); - } + result = new ReturnInfo(this, ReturnCode.ERROR, "Exited with code " + e.ExitCode + "."); } } catch (Exception e) { - return new ReturnInfo(this, ReturnCode.ERROR, e.ToString()); + result = new ReturnInfo(this, ReturnCode.ERROR, e.ToString()); + } + + // GEN3-GAP(finally): not a using, gen3 does not run finally/Dispose when an exception unwinds (C7). + // GEN3-GAP(finalizers): Dispose closes the files the script left open. + if (lua != null) + { + lua.Dispose(); } - return new ReturnInfo(this, ReturnCode.OK); + return result; } public override void PrintHelp() diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Util/Env.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Util/Env.cs index 6ca39eadd..426a29319 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Util/Env.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Util/Env.cs @@ -36,7 +36,9 @@ public override ReturnInfo Execute(List arguments) string var = exportcmd[0]; string value = exportcmd[1]; - Kernel.EnvironmentVariables.Add(var, value); + // GEN3-GAP(env): BCL environment variables are unusable on gen3, Aura keeps its own table. + // Indexer, not Add: re-exporting an existing variable must overwrite it, not throw. + Kernel.EnvironmentVariables[var] = value; return new ReturnInfo(this, ReturnCode.OK); } diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Util/Help.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Util/Help.cs index 1acb0a8c4..8d97e04d7 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Util/Help.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Util/Help.cs @@ -78,7 +78,7 @@ private ReturnInfo ExecuteHelp(bool showaliases) count++; if (count == Kernel.console.Rows - 3) { - //Console.ReadKey(); TODO FIX THIS + //TODO FIX THIS: wait for a key from Aura's Input.KeyboardManager (never the Console key APIs, C10) count = 0; } */ diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Util/Lspci.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Util/Lspci.cs index 3ba5cdf61..f029e40de 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/Util/Lspci.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/Util/Lspci.cs @@ -4,10 +4,11 @@ * PROGRAMMER(S): Valentin Charbonnier */ -using Aura_OS.Utils; using System; +using System.Globalization; using System.Text; -using static Cosmos.HAL.PCIDevice; +using Aura_OS.System.Utils; +using Cosmos.Kernel.System.Diagnostics; namespace Aura_OS.System.Processing.Interpreter.Commands.Util { @@ -29,9 +30,27 @@ public override ReturnInfo Execute() int count = 0; StringBuilder sb = new(); - foreach (Cosmos.HAL.PCIDevice device in Cosmos.HAL.PCI.Devices) + // GEN3-GAP(pci): no typed PCI enumeration; each PCI function is a driver-kit node + // whose Path ("pci:ssss:bb:dd.f") and Description ("vvvv:dddd class cc.ss.pp") are parsed. + int nodeCount = DriverInfo.NodeCount; + for (int i = 0; i < nodeCount; i++) { - string line = Conversion.D2(device.bus) + ":" + Conversion.D2(device.slot) + ":" + Conversion.D2(device.function) + " - " + "0x" + Conversion.D4(Conversion.DecToHex(device.VendorID)) + ":0x" + Conversion.D4(Conversion.DecToHex(device.DeviceID)) + " : " + DeviceClass.GetTypeString(device) + ": " + DeviceClass.GetDeviceString(device); + if (!DriverInfo.TryGetNode(i, out DeviceNodeInfo node) || node.BusName != "pci") + { + continue; + } + + string line; + if (TryParseDescription(node.Description, out ushort vendor, out ushort device, out byte cls, out byte sub, out byte progIf)) + { + line = GetAddress(node.Path) + " - " + "0x" + vendor.ToString("X4") + ":0x" + device.ToString("X4") + " : " + PciNames.GetTypeString(cls, sub, progIf) + ": " + PciNames.GetDeviceString(vendor, device); + } + else + { + line = GetAddress(node.Path) + " - " + node.Description; + } + + line += " [" + (node.DriverName ?? "no driver") + "]"; sb.AppendLine(line); count++; @@ -39,7 +58,7 @@ public override ReturnInfo Execute() /* if (count == Kernel.console.Rows - 4) { - //Console.ReadKey(); + // key wait stays disabled: from the GUI Terminal it would block on, and drain, tty1 count = 0; } */ @@ -49,5 +68,49 @@ public override ReturnInfo Execute() return new ReturnInfo(this, ReturnCode.OK); } + + /// + /// "pci:0000:00:03.0" -> "00:03.0" (bus:device.function, hex). + /// + private static string GetAddress(string path) + { + if (path == null || path.Length <= 4) + { + return path ?? ""; + } + + int separator = path.IndexOf(':', 4); + return separator < 0 ? path : path.Substring(separator + 1); + } + + /// + /// Parses "vvvv:dddd class cc.ss.pp" (PciIdentity.Describe()). + /// + private static bool TryParseDescription(string desc, out ushort vendor, out ushort device, out byte cls, out byte sub, out byte progIf) + { + vendor = 0; + device = 0; + cls = 0; + sub = 0; + progIf = 0; + + if (desc == null || desc.Length < 9 || desc[4] != ':') + { + return false; + } + + int c = desc.IndexOf("class ", StringComparison.Ordinal); + if (c < 0 || desc.Length < c + 14) + { + return false; + } + c += 6; + + return ushort.TryParse(desc.AsSpan(0, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out vendor) + && ushort.TryParse(desc.AsSpan(5, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out device) + && byte.TryParse(desc.AsSpan(c, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out cls) + && byte.TryParse(desc.AsSpan(c + 3, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out sub) + && byte.TryParse(desc.AsSpan(c + 6, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out progIf); + } } } \ No newline at end of file diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/c_Console/Clear.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/c_Console/Clear.cs index cda27065e..2cf5a64e8 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/c_Console/Clear.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/c_Console/Clear.cs @@ -33,7 +33,7 @@ public override ReturnInfo Execute() } else { - Cosmos.System.Power.Shutdown(); + AuraPower.Shutdown(); } return new ReturnInfo(this, ReturnCode.OK); diff --git a/SRC/Aura_OS/System/Processing/Interpreter/Commands/c_Console/SetKeyboardMap.cs b/SRC/Aura_OS/System/Processing/Interpreter/Commands/c_Console/SetKeyboardMap.cs index 45c6d5d61..c961c26f0 100644 --- a/SRC/Aura_OS/System/Processing/Interpreter/Commands/c_Console/SetKeyboardMap.cs +++ b/SRC/Aura_OS/System/Processing/Interpreter/Commands/c_Console/SetKeyboardMap.cs @@ -2,7 +2,8 @@ using System; using System.Collections.Generic; using System.Text; -using Sys = Cosmos.System; +using Cosmos.Kernel.System; +using Aura_OS.System.Input; namespace Aura_OS.System.Processing.Interpreter.Commands.c_Console { @@ -22,18 +23,24 @@ public CommandKeyboardMap(string[] commandvalues) : base(commandvalues) /// Arguments public override ReturnInfo Execute(List arguments) { - switch (arguments[0]) + if (arguments == null || arguments.Count == 0) { - case "azerty": - Sys.KeyboardManager.SetKeyLayout(new Sys.ScanMaps.FRStandardLayout()); - break; - - case "qwerty": - Sys.KeyboardManager.SetKeyLayout(new Sys.ScanMaps.USStandardLayout()); - break; - default: - return new ReturnInfo(this, ReturnCode.ERROR, "This keyboardmap isn't supported, please type: setkeyboardmap /help"); + return new ReturnInfo(this, ReturnCode.ERROR_ARG); } + + if (!KernelFeatures.Keyboard) + { + return new ReturnInfo(this, ReturnCode.ERROR, "Keyboard support is disabled in this kernel."); + } + + // Accepts a layout code (us, gb, fr, de, es, tr, dv) or an alias (azerty, qwerty, qwertz, dvorak). + if (!KeyboardLayouts.Set(arguments[0])) + { + return new ReturnInfo(this, ReturnCode.ERROR, "This keyboardmap isn't supported, please type: setkeyboardmap /help"); + } + + KeyboardLayouts.Persist(); + return new ReturnInfo(this, ReturnCode.OK); } @@ -43,8 +50,20 @@ public override ReturnInfo Execute(List arguments) public override void PrintHelp() { Console.WriteLine("Available keyboards map:"); - Console.WriteLine("- setkeyboardmap azerty"); - Console.WriteLine("- setkeyboardmap qwerty"); + foreach (string code in KeyboardLayouts.Codes) + { + Console.WriteLine("- setkeyboardmap " + code.ToLowerInvariant() + " (" + KeyboardLayouts.GetDisplayName(code) + ")"); + } + + Console.WriteLine("Aliases:"); + foreach (string alias in KeyboardLayouts.Aliases) + { + string target = KeyboardLayouts.ResolveCode(alias); + if (target != null) + { + Console.WriteLine("- setkeyboardmap " + alias + " (= " + target.ToLowerInvariant() + ")"); + } + } } } } diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/ByteString.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/ByteString.cs deleted file mode 100644 index c18d5445c..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/ByteString.cs +++ /dev/null @@ -1,47 +0,0 @@ - using System; -using System.Collections.Generic; - -namespace UniLua -{ - internal class ByteStringBuilder - { - public ByteStringBuilder() - { - BufList = new LinkedList(); - TotalLength = 0; - } - - public override string ToString() - { - if( TotalLength <= 0 ) - return String.Empty; - - var result = new char[TotalLength]; - var i = 0; - var node = BufList.First; - while(node != null) - { - var buf = node.Value; - for(var j=0; j BufList; - private int TotalLength; - } -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Coder.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Coder.cs deleted file mode 100644 index 1622576e6..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Coder.cs +++ /dev/null @@ -1,1283 +0,0 @@ - -using NotImplementedException = System.NotImplementedException; - -namespace UniLua -{ - using InstructionPtr = Pointer; - using Math = System.Math; - using Exception = System.Exception; - - public struct Instruction - { - public uint Value; - - public Instruction( uint val ) - { - Value = val; - } - - public static explicit operator Instruction( uint val ) - { - return new Instruction(val); - } - - public static explicit operator uint( Instruction i ) - { - return i.Value; - } - - public override string ToString() - { - var op = GET_OPCODE(); - var a = GETARG_A(); - var b = GETARG_B(); - var c = GETARG_C(); - var ax = GETARG_Ax(); - var bx = GETARG_Bx(); - var sbx = GETARG_sBx(); - var mode = OpCodeInfo.GetMode( op ); - switch( mode.OpMode ) - { - case OpMode.iABC: - { - string ret = string.Format( "{0,-9} {1}" - , op - , a ); - if( mode.BMode != OpArgMask.OpArgN ) - ret += " " + (ISK(b) ? MYK(INDEXK(b)) : b); - if( mode.CMode != OpArgMask.OpArgN ) - ret += " " + (ISK(c) ? MYK(INDEXK(c)) : c); - return ret; - } - case OpMode.iABx: - { - string ret = string.Format( "{0,-9} {1}" - , op - , a ); - if( mode.BMode == OpArgMask.OpArgK ) - ret += " " + MYK(bx); - else if( mode.BMode == OpArgMask.OpArgU ) - ret += " " + bx; - return ret; - } - case OpMode.iAsBx: - { - return string.Format( "{0,-9} {1} {2}" - , op - , a - , sbx ); - } - case OpMode.iAx: - { - return string.Format( "{0,-9} {1}" - , op - , MYK(ax) ); - } - default: - throw new System.NotImplementedException(); - } - } - - public const int SIZE_C = 9; - public const int SIZE_B = 9; - public const int SIZE_Bx = (SIZE_C + SIZE_B); - public const int SIZE_A = 8; - public const int SIZE_Ax = (SIZE_C + SIZE_B + SIZE_A); - - public const int SIZE_OP = 6; - - public const int POS_OP = 0; - public const int POS_A = (POS_OP + SIZE_OP); - public const int POS_C = (POS_A + SIZE_A); - public const int POS_B = (POS_C + SIZE_C); - public const int POS_Bx = POS_C; - public const int POS_Ax = POS_A; - -#pragma warning disable 0429 - public const int MAXARG_Bx = SIZE_Bx>1) - : LuaLimits.MAX_INT - ; -#pragma warning restore 0429 - - public const int MAXARG_Ax = ((1<> POS_OP) & MASK1(SIZE_OP, 0) ); - } - - public Instruction SET_OPCODE( OpCode op ) - { - Value = (Value & MASK0(SIZE_OP, POS_OP)) | - ((((uint)op) << POS_OP) & MASK1(SIZE_OP, POS_OP)); - return this; - } - - public int GETARG( int pos, int size ) - { - return (int)( (Value >> pos) & MASK1(size, 0) ); - } - - public Instruction SETARG( int value, int pos, int size ) - { - Value = ((Value & MASK0(size, pos)) | - (((uint)value << pos) & MASK1(size, pos))); - return this; - } - - public int GETARG_A() { return GETARG( POS_A, SIZE_A ); } - public Instruction SETARG_A(int value) { - return SETARG( value, POS_A, SIZE_A ); - } - - public int GETARG_B() { return GETARG( POS_B, SIZE_B ); } - public Instruction SETARG_B(int value) { - return SETARG( value, POS_B, SIZE_B ); - } - - public int GETARG_C() { return GETARG( POS_C, SIZE_C ); } - public Instruction SETARG_C(int value) { - return SETARG( value, POS_C, SIZE_C ); - } - - public int GETARG_Bx() { return GETARG( POS_Bx, SIZE_Bx ); } - public Instruction SETARG_Bx(int value) { - return SETARG( value, POS_Bx, SIZE_Bx ); - } - - public int GETARG_Ax() { return GETARG( POS_Ax, SIZE_Ax ); } - public Instruction SETARG_Ax(int value) { - return SETARG( value, POS_Ax, SIZE_Ax ); - } - - public int GETARG_sBx() { return GETARG_Bx() - MAXARG_sBx; } - public Instruction SETARG_sBx(int value) { - return SETARG_Bx(value+MAXARG_sBx); - } - - public static Instruction CreateABC( OpCode op, int a, int b, int c ) - { - return (Instruction)( (((uint)op) << POS_OP) - | ((uint)a << POS_A) - | ((uint)b << POS_B) - | ((uint)c << POS_C)); - } - - public static Instruction CreateABx( OpCode op, int a, uint bc ) - { - return (Instruction)( (((uint)op) << POS_OP) - | ((uint)a << POS_A) - | ((uint)bc << POS_Bx)); - } - - public static Instruction CreateAx( OpCode op, int a ) - { - return (Instruction)( (((uint)op) << POS_OP) - | ((uint)a << POS_Ax)); - } - } - - public static class Coder - { - public const int NO_JUMP = -1; - private const int NO_REG = ((1<= fs.NumActVar ) - { - fs.FreeReg--; - Utl.Assert( reg == fs.FreeReg ); - } - } - - private static void FreeExp( FuncState fs, ExpDesc e ) - { - if( e.Kind == ExpKind.VNONRELOC ) - { - FreeReg( fs, e.Info ); - } - } - - private static bool IsNumeral( ExpDesc e ) - { - return e.Kind == ExpKind.VKNUM - && e.ExitTrue == NO_JUMP - && e.ExitFalse == NO_JUMP; - } - - private static bool ConstFolding( OpCode op, ExpDesc e1, ExpDesc e2 ) - { - if( !IsNumeral(e1) || !IsNumeral(e2) ) - return false; - - if( (op == OpCode.OP_DIV || op == OpCode.OP_MOD) - && e2.NumberValue == 0.0 ) - { - return false; // do not attempt to divide by 0 - } - - switch( op ) - { - case OpCode.OP_ADD: - e1.NumberValue = e1.NumberValue + e2.NumberValue; - break; - case OpCode.OP_SUB: - e1.NumberValue = e1.NumberValue - e2.NumberValue; - break; - case OpCode.OP_MUL: - e1.NumberValue = e1.NumberValue * e2.NumberValue; - break; - case OpCode.OP_DIV: - e1.NumberValue = e1.NumberValue / e2.NumberValue; - break; - case OpCode.OP_MOD: - var v1 = e1.NumberValue; - var v2 = e2.NumberValue; - e1.NumberValue = v1 - Math.Floor(v1/v2) * v2; - break; - case OpCode.OP_POW: - e1.NumberValue = Math.Pow( e1.NumberValue, e2.NumberValue ); - break; - case OpCode.OP_UNM: - e1.NumberValue = -e1.NumberValue; - break; - default: - throw new Exception("ConstFolding unknown op" + op); - } - - return true; - } - - public static void FixLine( FuncState fs, int line ) - { - fs.Proto.LineInfo[ fs.Pc-1 ] = line; - } - - private static void CodeArith( FuncState fs, OpCode op, - ExpDesc e1, ExpDesc e2, int line ) - { - if( ConstFolding( op, e1, e2 ) ) - return; - - int o2 = ( op != OpCode.OP_UNM && op != OpCode.OP_LEN ) - ? Exp2RK( fs, e2 ) : 0; - int o1 = Exp2RK( fs, e1 ); - if( o1 > o2 ) - { - FreeExp( fs, e1 ); - FreeExp( fs, e2 ); - } - else - { - FreeExp( fs, e2 ); - FreeExp( fs, e1 ); - } - e1.Info = CodeABC( fs, op, 0, o1, o2 ); - e1.Kind = ExpKind.VRELOCABLE; - FixLine( fs, line ); - } - - public static bool TestTMode( OpCode op ) - { - return OpCodeInfo.GetMode( op ).TMode; - } - - public static bool TestAMode( OpCode op ) - { - return OpCodeInfo.GetMode( op ).AMode; - } - - private static void FixJump( FuncState fs, int pc, int dest ) - { - Instruction jmp = fs.Proto.Code[pc]; - int offset = dest - (pc + 1); - Utl.Assert( dest != NO_JUMP ); - if( Math.Abs(offset) > Instruction.MAXARG_sBx ) - fs.Lexer.SyntaxError("control structure too long"); - jmp.SETARG_sBx( offset ); - fs.Proto.Code[pc] = jmp; - } - - // returns current `pc' and mark it as a jump target - // (to avoid wrong optimizations with consecutive - // instructions not in the same basic block) - public static int GetLabel( FuncState fs ) - { - fs.LastTarget = fs.Pc; - return fs.Pc; - } - - private static int GetJump( FuncState fs, int pc ) - { - int offset = fs.Proto.Code[pc].GETARG_sBx(); - if( offset == NO_JUMP ) // point to itself represents end of list - return NO_JUMP; // end of list - else - return (pc+1) + offset; // turn offset into absolute position - } - - private static InstructionPtr GetJumpControl( FuncState fs, int pc ) - { - InstructionPtr pi = new InstructionPtr( fs.Proto.Code, pc ); - if( pc >= 1 && TestTMode( (pi-1).Value.GET_OPCODE() )) - return (pi-1); - else - return pi; - } - - // check whether list has any jump that do not produce a value - // (or produce an inverted value) - private static bool NeedValue( FuncState fs, int list ) - { - for( ; list != NO_JUMP; list = GetJump( fs, list ) ) - { - Instruction i = GetJumpControl( fs, list ).Value; - if( i.GET_OPCODE() != OpCode.OP_TESTSET ) - return true; - } - return false; - } - - private static bool PatchTestReg( FuncState fs, int node, int reg ) - { - InstructionPtr pi = GetJumpControl( fs, node ); - if( pi.Value.GET_OPCODE() != OpCode.OP_TESTSET ) - return false; // cannot patch other instructions - - if( reg != NO_REG && reg != pi.Value.GETARG_B() ) - pi.Value = pi.Value.SETARG_A( reg ); - else - pi.Value = Instruction.CreateABC( OpCode.OP_TEST, - pi.Value.GETARG_B(), 0, pi.Value.GETARG_C() ); - - return true; - } - - private static void RemoveValues( FuncState fs, int list ) - { - for(; list != NO_JUMP; list = GetJump( fs, list ) ) - PatchTestReg( fs, list, NO_REG ); - } - - private static void PatchListAux( FuncState fs, int list, int vtarget, - int reg, int dtarget ) - { - while( list != NO_JUMP ) - { - int next = GetJump( fs, list ); - if( PatchTestReg( fs, list, reg ) ) - FixJump( fs, list, vtarget ); - else - FixJump( fs, list, dtarget ); // jump to default target - list = next; - } - } - - private static void DischargeJpc( FuncState fs ) - { - PatchListAux( fs, fs.Jpc, fs.Pc, NO_REG, fs.Pc ); - fs.Jpc = NO_JUMP; - } - - private static void InvertJump( FuncState fs, ExpDesc e ) - { - InstructionPtr pc = GetJumpControl( fs, e.Info ); - Utl.Assert( TestTMode( pc.Value.GET_OPCODE() ) - && pc.Value.GET_OPCODE() != OpCode.OP_TESTSET - && pc.Value.GET_OPCODE() != OpCode.OP_TEST ); - pc.Value = pc.Value.SETARG_A( pc.Value.GETARG_A() == 0 ? 1 : 0 ); - } - - private static int JumpOnCond( FuncState fs, ExpDesc e, bool cond ) - { - if( e.Kind == ExpKind.VRELOCABLE ) - { - Instruction ie = fs.GetCode( e ).Value; - if( ie.GET_OPCODE() == OpCode.OP_NOT ) - { - fs.Pc--; // remove previous OP_NOT - return CondJump( fs, OpCode.OP_TEST, ie.GETARG_B(), 0, - (cond ? 0 : 1) ); - } - // else go through - } - Discharge2AnyReg( fs, e ); - FreeExp( fs, e ); - return CondJump( fs, OpCode.OP_TESTSET, NO_REG, e.Info, - (cond ? 1 : 0) ); - } - - public static void GoIfTrue( FuncState fs, ExpDesc e ) - { - int pc; // pc of last jump - DischargeVars( fs, e ); - switch( e.Kind ) - { - case ExpKind.VJMP: - InvertJump( fs, e ); - pc = e.Info; - break; - - case ExpKind.VK: - case ExpKind.VKNUM: - case ExpKind.VTRUE: - pc = NO_JUMP; - break; - - default: - pc = JumpOnCond( fs, e, false ); - break; - } - - // insert last jump in `f' list - e.ExitFalse = Concat( fs, e.ExitFalse, pc ); - PatchToHere( fs, e.ExitTrue ); - e.ExitTrue = NO_JUMP; - } - - public static void GoIfFalse( FuncState fs, ExpDesc e ) - { - int pc; // pc of last jump - DischargeVars( fs, e ); - switch( e.Kind ) - { - case ExpKind.VJMP: - pc = e.Info; - break; - - case ExpKind.VNIL: - case ExpKind.VFALSE: - pc = NO_JUMP; - break; - - default: - pc = JumpOnCond( fs, e, true ); - break; - } - - // insert last jump in `t' list - e.ExitTrue = Concat( fs, e.ExitTrue, pc ); - PatchToHere( fs, e.ExitFalse ); - e.ExitFalse = NO_JUMP; - } - - private static void CodeNot( FuncState fs, ExpDesc e ) - { - DischargeVars( fs, e ); - switch( e.Kind ) - { - case ExpKind.VNIL: - case ExpKind.VFALSE: - e.Kind = ExpKind.VTRUE; - break; - - case ExpKind.VK: - case ExpKind.VKNUM: - case ExpKind.VTRUE: - e.Kind = ExpKind.VFALSE; - break; - - case ExpKind.VJMP: - InvertJump( fs, e ); - break; - - case ExpKind.VRELOCABLE: - case ExpKind.VNONRELOC: - Discharge2AnyReg( fs, e ); - FreeExp( fs, e ); - e.Info = CodeABC( fs, OpCode.OP_NOT, 0, e.Info, 0 ); - e.Kind = ExpKind.VRELOCABLE; - break; - - default: - throw new Exception("CodeNot unknown e.Kind:" + e.Kind); - } - - // interchange true and false lists - { int temp = e.ExitFalse; e.ExitFalse = e.ExitTrue; e.ExitTrue = temp; } - - RemoveValues( fs, e.ExitFalse ); - RemoveValues( fs, e.ExitTrue ); - } - - private static void CodeComp( FuncState fs, OpCode op, int cond, - ExpDesc e1, ExpDesc e2 ) - { - int o1 = Exp2RK( fs, e1 ); - int o2 = Exp2RK( fs, e2 ); - FreeExp( fs, e2 ); - FreeExp( fs, e1 ); - - // exchange args to replace by `<' or `<=' - if( cond == 0 && op != OpCode.OP_EQ ) { - int temp; - temp = o1; o1 = o2; o2 = temp; // o1 <==> o2 - cond = 1; - } - e1.Info = CondJump( fs, op, cond, o1, o2 ); - e1.Kind = ExpKind.VJMP; - } - - public static void Prefix( FuncState fs, UnOpr op, ExpDesc e, int line ) - { - ExpDesc e2 = new ExpDesc(); - e2.ExitTrue = NO_JUMP; - e2.ExitFalse = NO_JUMP; - e2.Kind = ExpKind.VKNUM; - e2.NumberValue = 0.0; - - switch( op ) - { - case UnOpr.MINUS: { - if( IsNumeral( e ) ) // minus constant? - { - e.NumberValue = -e.NumberValue; - } - else - { - Exp2AnyReg( fs, e ); - CodeArith( fs, OpCode.OP_UNM, e, e2, line ); - } - } break; - - case UnOpr.NOT: { - CodeNot( fs, e ); - } break; - - case UnOpr.LEN: { - Exp2AnyReg( fs, e ); // cannot operate on constants - CodeArith( fs, OpCode.OP_LEN, e, e2, line ); - } break; - - default: - throw new Exception("[Coder]Prefix Unknown UnOpr:" + op); - } - } - - public static void Infix( FuncState fs, BinOpr op, ExpDesc e ) - { - switch( op ) - { - case BinOpr.AND: { - GoIfTrue( fs, e ); - } break; - - case BinOpr.OR: { - GoIfFalse( fs, e ); - } break; - - case BinOpr.CONCAT: { - Exp2NextReg( fs, e ); // operand must be on the `stack' - } break; - - case BinOpr.ADD: - case BinOpr.SUB: - case BinOpr.MUL: - case BinOpr.DIV: - case BinOpr.MOD: - case BinOpr.POW: { - if( !IsNumeral(e) ) - Exp2RK( fs, e ); - } break; - - default: { - Exp2RK( fs, e ); - } break; - } - } - - public static void Posfix( FuncState fs, BinOpr op, - ExpDesc e1, ExpDesc e2, int line ) - { - switch( op ) - { - case BinOpr.AND: { - Utl.Assert( e1.ExitTrue == NO_JUMP ); - DischargeVars( fs, e2 ); - e2.ExitFalse = Concat( fs, e2.ExitFalse, e1.ExitFalse ); - e1.CopyFrom( e2 ); - break; - } - case BinOpr.OR: { - Utl.Assert( e1.ExitFalse == NO_JUMP ); - DischargeVars( fs, e2 ); - e2.ExitTrue = Concat( fs, e2.ExitTrue, e1.ExitTrue ); - e1.CopyFrom( e2 ); - break; - } - case BinOpr.CONCAT: { - Exp2Val( fs, e2 ); - var pe2 = fs.GetCode( e2 ); - if( e2.Kind == ExpKind.VRELOCABLE && - pe2.Value.GET_OPCODE() == OpCode.OP_CONCAT ) - { - Utl.Assert( e1.Info == pe2.Value.GETARG_B()-1 ); - FreeExp( fs, e1 ); - pe2.Value = pe2.Value.SETARG_B( e1.Info ); - e1.Kind = ExpKind.VRELOCABLE; - e1.Info = e2.Info; - } - else - { - // operand must be on the `stack' - Exp2NextReg( fs, e2 ); - CodeArith( fs, OpCode.OP_CONCAT, e1, e2, line ); - } - break; - } - case BinOpr.ADD: { - CodeArith( fs, OpCode.OP_ADD, e1, e2, line); - break; - } - case BinOpr.SUB: { - CodeArith( fs, OpCode.OP_SUB, e1, e2, line); - break; - } - case BinOpr.MUL: { - CodeArith( fs, OpCode.OP_MUL, e1, e2, line); - break; - } - case BinOpr.DIV: { - CodeArith( fs, OpCode.OP_DIV, e1, e2, line); - break; - } - case BinOpr.MOD: { - CodeArith( fs, OpCode.OP_MOD, e1, e2, line); - break; - } - case BinOpr.POW: { - CodeArith( fs, OpCode.OP_POW, e1, e2, line); - break; - } - case BinOpr.EQ: { - CodeComp( fs, OpCode.OP_EQ, 1, e1, e2 ); - break; - } - case BinOpr.LT: { - CodeComp( fs, OpCode.OP_LT, 1, e1, e2 ); - break; - } - case BinOpr.LE: { - CodeComp( fs, OpCode.OP_LE, 1, e1, e2 ); - break; - } - case BinOpr.NE: { - CodeComp( fs, OpCode.OP_EQ, 0, e1, e2 ); - break; - } - case BinOpr.GT: { - CodeComp( fs, OpCode.OP_LT, 0, e1, e2 ); - break; - } - case BinOpr.GE: { - CodeComp( fs, OpCode.OP_LE, 0, e1, e2 ); - break; - } - default: Utl.Assert(false); break; - } - } - - public static int Jump( FuncState fs ) - { - int jpc = fs.Jpc; // save list of jumps to here - fs.Jpc = NO_JUMP; - int j = CodeAsBx( fs, OpCode.OP_JMP, 0, NO_JUMP ); - j = Concat( fs, j, jpc ); - return j; - } - - public static void JumpTo( FuncState fs, int target ) - { - PatchList( fs, Jump(fs), target ); - } - - public static void Ret( FuncState fs, int first, int nret ) - { - CodeABC( fs, OpCode.OP_RETURN, first, nret+1, 0 ); - } - - private static int CondJump( FuncState fs, OpCode op, int a, int b, int c ) - { - CodeABC( fs, op, a, b, c ); - return Jump( fs ); - } - - public static void PatchList( FuncState fs, int list, int target ) - { - if( target == fs.Pc ) - PatchToHere( fs, list ); - else - { - Utl.Assert( target < fs.Pc ); - PatchListAux( fs, list, target, NO_REG, target ); - } - } - - public static void PatchClose( FuncState fs, int list, int level ) - { - level++; // argument is +1 to reserve 0 as non-op - while( list != NO_JUMP ) - { - int next = GetJump( fs, list ); - var pi = new InstructionPtr( fs.Proto.Code, list );; - Utl.Assert( pi.Value.GET_OPCODE() == OpCode.OP_JMP && - ( pi.Value.GETARG_A() == 0 || - pi.Value.GETARG_A() >= level ) ); - pi.Value = pi.Value.SETARG_A( level ); - list = next; - } - } - - public static void PatchToHere( FuncState fs, int list ) - { - GetLabel( fs ); - fs.Jpc = Concat( fs, fs.Jpc, list ); - } - - public static int Concat( FuncState fs, int l1, int l2 ) - { - if( l2 == NO_JUMP ) - return l1; - else if( l1 == NO_JUMP ) - return l2; - else - { - int list = l1; - int next = GetJump( fs, list ); - - // find last element - while( next != NO_JUMP ) - { - list = next; - next = GetJump( fs, list ); - } - FixJump( fs, list, l2 ); - return l1; - } - } - - public static int StringK( FuncState fs, string s ) - { - var o = new TValue(); - o.SetSValue(s); - return AddK( fs, ref o, ref o ); - } - - public static int NumberK( FuncState fs, double r ) - { - var o = new TValue(); - o.SetNValue(r); - return AddK( fs, ref o, ref o ); - } - - private static int BoolK( FuncState fs, bool b ) - { - var o = new TValue(); - o.SetBValue(b); - return AddK( fs, ref o, ref o ); - } - - private static int NilK( FuncState fs ) - { - // // cannot use nil as key; - // // instead use table itself to represent nil - // var k = fs.H; - // var o = new LuaNil(); - // return AddK( fs, k, o ); - - var o = new TValue(); - o.SetNilValue(); - return AddK( fs, ref o, ref o ); - } - - public static int AddK(FuncState fs, ref TValue key, ref TValue v) - { - int idx; - int keyHash = key.GetHashCode(); - - if (fs.H.TryGetValue(keyHash, out idx)) - return idx; - - idx = fs.Proto.K.Count; - fs.H.Add(keyHash, idx); - - var newItem = new StkId(); - newItem.V.SetObj(ref v); - fs.Proto.K.Add(newItem); - return idx; - } - - public static void Indexed( FuncState fs, ExpDesc t, ExpDesc k ) - { - t.Ind.T = t.Info; - t.Ind.Idx = Exp2RK( fs, k ); - t.Ind.Vt = (t.Kind == ExpKind.VUPVAL) ? ExpKind.VUPVAL - : ExpKind.VLOCAL; // FIXME - t.Kind = ExpKind.VINDEXED; - } - - private static bool HasJumps( ExpDesc e ) - { - return e.ExitTrue != e.ExitFalse; - } - - private static int CodeLabel( FuncState fs, int a, int b, int jump ) - { - GetLabel( fs ); // those instructions may be jump targets - return CodeABC( fs, OpCode.OP_LOADBOOL, a, b, jump ); - } - - private static void Discharge2Reg( FuncState fs, ExpDesc e, int reg ) - { - DischargeVars( fs, e ); - switch( e.Kind ) - { - case ExpKind.VNIL: { - CodeNil( fs, reg, 1 ); - break; - } - case ExpKind.VFALSE: - case ExpKind.VTRUE: { - CodeABC( fs, OpCode.OP_LOADBOOL, reg, - (e.Kind == ExpKind.VTRUE ? 1 : 0), 0 ); - break; - } - case ExpKind.VK: { - CodeK( fs, reg, e.Info ); - break; - } - case ExpKind.VKNUM: { - CodeK( fs, reg, NumberK( fs, e.NumberValue ) ); - break; - } - case ExpKind.VRELOCABLE: { - InstructionPtr pi = fs.GetCode(e); - pi.Value = pi.Value.SETARG_A(reg); - break; - } - case ExpKind.VNONRELOC: { - if( reg != e.Info ) - CodeABC( fs, OpCode.OP_MOVE, reg, e.Info, 0 ); - break; - } - default: { - Utl.Assert( e.Kind == ExpKind.VVOID || e.Kind == ExpKind.VJMP ); - return; // nothing to do... - } - } - e.Info = reg; - e.Kind = ExpKind.VNONRELOC; - } - - public static void CheckStack( FuncState fs, int n ) - { - int newStack = fs.FreeReg + n; - if( newStack > fs.Proto.MaxStackSize ) - { - if( newStack >= LuaLimits.MAXSTACK ) - { - fs.Lexer.SyntaxError("function or expression too complex"); - } - fs.Proto.MaxStackSize = (byte)newStack; - } - } - - public static void ReserveRegs( FuncState fs, int n ) - { - CheckStack( fs, n ); - fs.FreeReg += n; - } - - private static void Discharge2AnyReg( FuncState fs, ExpDesc e ) - { - if( e.Kind != ExpKind.VNONRELOC ) - { - ReserveRegs( fs, 1 ); - Discharge2Reg( fs, e, fs.FreeReg-1 ); - } - } - - private static void Exp2Reg( FuncState fs, ExpDesc e, int reg ) - { - Discharge2Reg( fs, e, reg ); - if( e.Kind == ExpKind.VJMP ) - { - e.ExitTrue = Concat( fs, e.ExitTrue, e.Info ); - } - - if( HasJumps(e) ) - { - int p_f = NO_JUMP; - int p_t = NO_JUMP; - if( NeedValue( fs, e.ExitTrue ) || NeedValue( fs, e.ExitFalse ) ) - { - int fj = (e.Kind == ExpKind.VJMP) ? NO_JUMP : Jump( fs ); - p_f = CodeLabel( fs, reg, 0, 1 ); - p_t = CodeLabel( fs, reg, 1, 0 ); - PatchToHere( fs, fj ); - } - - // position after whole expression - int final = GetLabel( fs ); - PatchListAux( fs, e.ExitFalse, final, reg, p_f ); - PatchListAux( fs, e.ExitTrue, final, reg, p_t ); - } - - e.ExitFalse = NO_JUMP; - e.ExitTrue = NO_JUMP; - e.Info = reg; - e.Kind = ExpKind.VNONRELOC; - } - - public static void Exp2NextReg( FuncState fs, ExpDesc e ) - { - DischargeVars( fs, e ); - FreeExp( fs, e ); - ReserveRegs( fs, 1 ); - Exp2Reg( fs, e, fs.FreeReg-1 ); - } - - public static void Exp2Val( FuncState fs, ExpDesc e ) - { - if( HasJumps(e) ) - Exp2AnyReg( fs, e ); - else - DischargeVars( fs, e ); - } - - public static int Exp2RK( FuncState fs, ExpDesc e ) - { - Exp2Val( fs, e ); - switch( e.Kind ) - { - case ExpKind.VTRUE: - case ExpKind.VFALSE: - case ExpKind.VNIL: { - // constant fits in RK operand? - if( fs.Proto.K.Count <= Instruction.MAXINDEXRK ) - { - e.Info = (e.Kind == ExpKind.VNIL) ? NilK(fs) - : BoolK( fs, (e.Kind == ExpKind.VTRUE ) ); - e.Kind = ExpKind.VK; - return Instruction.RKASK( e.Info ); - } - else break; - } - case ExpKind.VKNUM: - case ExpKind.VK: - { - if( e.Kind == ExpKind.VKNUM ) - { - e.Info = NumberK( fs, e.NumberValue ); - e.Kind = ExpKind.VK; - } - - if( e.Info <= Instruction.MAXINDEXRK ) - return Instruction.RKASK( e.Info ); - else break; - } - - default: break; - } - - return Exp2AnyReg( fs, e ); - } - - public static int Exp2AnyReg( FuncState fs, ExpDesc e ) - { - DischargeVars( fs, e ); - if( e.Kind == ExpKind.VNONRELOC ) - { - // exp is already in a register - if( ! HasJumps( e ) ) - return e.Info; - - // reg. is not a local? - if( e.Info >= fs.NumActVar ) - { - Exp2Reg( fs, e, e.Info ); - return e.Info; - } - } - Exp2NextReg( fs, e ); // default - return e.Info; - } - - public static void Exp2AnyRegUp( FuncState fs, ExpDesc e ) - { - if( e.Kind != ExpKind.VUPVAL || HasJumps( e ) ) - { - Exp2AnyReg( fs, e ); - } - } - - public static void DischargeVars( FuncState fs, ExpDesc e ) - { - switch( e.Kind ) - { - case ExpKind.VLOCAL: - e.Kind = ExpKind.VNONRELOC; - break; - - case ExpKind.VUPVAL: - e.Info = CodeABC( fs, OpCode.OP_GETUPVAL, 0, e.Info, 0 ); - e.Kind = ExpKind.VRELOCABLE; - break; - - case ExpKind.VINDEXED: - OpCode op = OpCode.OP_GETTABUP; - FreeReg( fs, e.Ind.Idx ); - if( e.Ind.Vt == ExpKind.VLOCAL ) - { - FreeReg( fs, e.Ind.T ); - op = OpCode.OP_GETTABLE; - } - e.Info = CodeABC( fs, op, 0, e.Ind.T, e.Ind.Idx ); - e.Kind = ExpKind.VRELOCABLE; - break; - - case ExpKind.VVARARG: - case ExpKind.VCALL: - SetOneRet( fs, e ); - break; - - default: break; - } - } - - public static void SetReturns( FuncState fs, ExpDesc e, int nResults ) - { - if( e.Kind == ExpKind.VCALL ) { // expression is an open function call? - var pi = fs.GetCode(e); - pi.Value = pi.Value.SETARG_C( nResults+1 ); - } - else if( e.Kind == ExpKind.VVARARG ) { - var pi = fs.GetCode(e); - pi.Value = pi.Value.SETARG_B( nResults+1 ).SETARG_A( fs.FreeReg ); - ReserveRegs( fs, 1 ); - } - } - - public static void SetMultiRet( FuncState fs, ExpDesc e ) - { - SetReturns( fs, e, LuaDef.LUA_MULTRET ); - } - - public static void SetOneRet( FuncState fs, ExpDesc e ) - { - // expression is an open function call? - if( e.Kind == ExpKind.VCALL ) - { - e.Kind = ExpKind.VNONRELOC; - e.Info = ( fs.GetCode( e ) ).Value.GETARG_A(); - } - else if( e.Kind == ExpKind.VVARARG ) - { - var pi = fs.GetCode( e ); - pi.Value = pi.Value.SETARG_B( 2 ); - e.Kind = ExpKind.VRELOCABLE; // can relocate its simple result - } - } - - public static void StoreVar( FuncState fs, ExpDesc v, ExpDesc e ) - { - switch( v.Kind ) - { - case ExpKind.VLOCAL: { - FreeExp( fs, e ); - Exp2Reg( fs, e, v.Info ); - break; - } - - case ExpKind.VUPVAL: { - int c = Exp2AnyReg( fs, e ); - CodeABC( fs, OpCode.OP_SETUPVAL, c, v.Info, 0 ); - break; - } - - case ExpKind.VINDEXED: { - OpCode op = (v.Ind.Vt == ExpKind.VLOCAL) - ? OpCode.OP_SETTABLE - : OpCode.OP_SETTABUP; - int c = Exp2RK( fs, e ); - CodeABC( fs, op, v.Ind.T, v.Ind.Idx, c ); - break; - } - - default: - { - throw new NotImplementedException("invalid var kind to store"); - } - } - FreeExp( fs, e ); - } - - public static void Self( FuncState fs, ExpDesc e, ExpDesc key ) - { - Exp2AnyReg( fs, e ); - int ereg = e.Info; // register where `e' is placed - FreeExp( fs, e ); - e.Info = fs.FreeReg; // base register for op_self - e.Kind = ExpKind.VNONRELOC; - ReserveRegs( fs, 2 ); - CodeABC( fs, OpCode.OP_SELF, e.Info, ereg, Coder.Exp2RK(fs, key) ); - FreeExp( fs, key ); - } - - public static void SetList( FuncState fs, int t, int nelems, int tostore ) - { - int c = (nelems - 1) / LuaDef.LFIELDS_PER_FLUSH + 1; - int b = (tostore == LuaDef.LUA_MULTRET) ? 0 : tostore; - Utl.Assert( tostore != 0 ); - - if( c <= Instruction.MAXARG_C ) - { - CodeABC( fs, OpCode.OP_SETLIST, t, b, c ); - } - else if( c <= Instruction.MAXARG_Ax ) - { - CodeABC( fs, OpCode.OP_SETLIST, t, b, 0 ); - CodeExtraArg( fs, c ); - } - else - { - fs.Lexer.SyntaxError("constructor too long"); - } - - // free registers with list values - fs.FreeReg = t + 1; - } - - public static void CodeNil( FuncState fs, int from, int n ) - { - int l = from + n - 1; // last register to set nil - if( fs.Pc > fs.LastTarget ) // no jumps to current position? - { - var previous = new InstructionPtr( fs.Proto.Code, fs.Pc-1 ); - if( previous.Value.GET_OPCODE() == OpCode.OP_LOADNIL ) - { - int pfrom = previous.Value.GETARG_A(); - int pl = pfrom + previous.Value.GETARG_B(); - - // can connect both? - if( (pfrom <= from && from <= pl + 1) || - (from <= pfrom && pfrom <= l + 1)) - { - if( pfrom < from ) from = pfrom; // from=min(from,pfrom) - if( pl > l ) l = pl; // l=max(l,pl) - previous.Value = previous.Value.SETARG_A( from ); - previous.Value = previous.Value.SETARG_B( l - from ); - return; - } - } - // else go through - } - - // else no optimization - CodeABC( fs, OpCode.OP_LOADNIL, from, n-1, 0 ); - } - - private static int CodeExtraArg( FuncState fs, int a ) - { - Utl.Assert( a <= Instruction.MAXARG_Ax ); - return Code( fs, Instruction.CreateAx( OpCode.OP_EXTRAARG, a ) ); - } - - public static int CodeK( FuncState fs, int reg, int k ) - { - if( k <= Instruction.MAXARG_Bx ) - return CodeABx( fs, OpCode.OP_LOADK, reg, (uint)k ); - else - { - int p = CodeABx( fs, OpCode.OP_LOADKX, reg, 0 ); - CodeExtraArg( fs, k ); - return p; - } - } - - public static int CodeAsBx( FuncState fs, OpCode op, int a, int sBx ) - { - return CodeABx( fs, op, a, ((uint)sBx)+Instruction.MAXARG_sBx); - } - - public static int CodeABx( FuncState fs, OpCode op, int a, uint bc ) - { - var mode = OpCodeInfo.GetMode(op); - Utl.Assert( mode.OpMode == OpMode.iABx - || mode.OpMode == OpMode.iAsBx ); - Utl.Assert( mode.CMode == OpArgMask.OpArgN ); - Utl.Assert( a < Instruction.MAXARG_A & bc <= Instruction.MAXARG_Bx ); - return Code( fs, Instruction.CreateABx( op, a, bc ) ); - } - - public static int CodeABC( FuncState fs, OpCode op, int a, int b, int c ) - { - return Code( fs, Instruction.CreateABC( op, a, b, c ) ); - } - - public static int Code( FuncState fs, Instruction i ) - { - DischargeJpc( fs ); // `pc' will change - - while( fs.Proto.Code.Count <= fs.Pc ) - { - fs.Proto.Code.Add( new Instruction(LuaLimits.MAX_INT) ); - } - fs.Proto.Code[ fs.Pc ] = i; - - while( fs.Proto.LineInfo.Count <= fs.Pc ) - { - fs.Proto.LineInfo.Add( LuaLimits.MAX_INT ); - } - fs.Proto.LineInfo[ fs.Pc ] = fs.Lexer.LastLine; - - return fs.Pc++; - } - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Common.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Common.cs deleted file mode 100644 index 9411efaf4..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Common.cs +++ /dev/null @@ -1,128 +0,0 @@ - -namespace UniLua -{ - public static class LuaConf - { - public const int LUAI_BITSINT = 32; - -#pragma warning disable 0429 - public const int LUAI_MAXSTACK = (LUAI_BITSINT >= 32) - ? 1000000 - : 15000 - ; -#pragma warning restore 0429 - - // reserve some space for error handling - public const int LUAI_FIRSTPSEUDOIDX = (-LUAI_MAXSTACK-1000); - - public const string LUA_SIGNATURE = "\u001bLua"; - public static string LUA_DIRSEP { - get { return System.IO.Path.DirectorySeparatorChar.ToString(); } - } - } - - public static class LuaLimits - { - public const int MAX_INT = System.Int32.MaxValue - 2; - public const int MAXUPVAL = System.Byte.MaxValue; - public const int LUAI_MAXCCALLS = 200; - public const int MAXSTACK = 250; - } - - public static class LuaDef - { - public const int LUA_MINSTACK = 20; - public const int BASIC_STACK_SIZE = LUA_MINSTACK * 2; - public const int EXTRA_STACK = 5; - - public const int LUA_RIDX_MAINTHREAD = 1; - public const int LUA_RIDX_GLOBALS = 2; - public const int LUA_RIDX_LAST = LUA_RIDX_GLOBALS; - - public const int LUA_MULTRET = -1; - - public const int LUA_REGISTRYINDEX = LuaConf.LUAI_FIRSTPSEUDOIDX; - - // number of list items accumulate before a SETLIST instruction - public const int LFIELDS_PER_FLUSH = 50; - - public const int LUA_IDSIZE = 60; - - public const string LUA_VERSION_MAJOR = "5"; - public const string LUA_VERSION_MINOR = "2"; - public const string LUA_VERSION = "Lua " + LUA_VERSION_MAJOR + "." + LUA_VERSION_MINOR; - - public const string LUA_ENV = "_ENV"; - - public const int BASE_CI_SIZE = 8; - } - - public static class LuaConstants - { - public const int LUA_NOREF = -2; - public const int LUA_REFNIL = -1; - } - - public enum LuaType - { - LUA_TNONE = -1, - LUA_TNIL = 0, - LUA_TBOOLEAN = 1, - LUA_TLIGHTUSERDATA = 2, - LUA_TNUMBER = 3, - LUA_TSTRING = 4, - LUA_TTABLE = 5, - LUA_TFUNCTION = 6, - LUA_TUSERDATA = 7, - LUA_TTHREAD = 8, - - LUA_TUINT64 = 9, - - LUA_NUMTAGS = 10, - - LUA_TPROTO, - LUA_TUPVAL, - LUA_TDEADKEY, - } - - public enum ClosureType - { - LUA, - CSHARP, - } - - public enum ThreadStatus - { - LUA_RESUME_ERROR = -1, - LUA_OK = 0, - LUA_YIELD = 1, - LUA_ERRRUN = 2, - LUA_ERRSYNTAX = 3, - LUA_ERRMEM = 4, - LUA_ERRGCMM = 5, - LUA_ERRERR = 6, - - LUA_ERRFILE = 7, - } - - /* ORDER TM */ - internal enum LuaOp - { - LUA_OPADD = 0, - LUA_OPSUB = 1, - LUA_OPMUL = 2, - LUA_OPDIV = 3, - LUA_OPMOD = 4, - LUA_OPPOW = 5, - LUA_OPUNM = 6, - } - - public enum LuaEq - { - LUA_OPEQ = 0, - LUA_OPLT = 1, - LUA_OPLE = 2, - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Do.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Do.cs deleted file mode 100644 index 8b10c68f6..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Do.cs +++ /dev/null @@ -1,343 +0,0 @@ - -// #define DEBUG_D_PRE_CALL -// #define DEBUG_D_POS_CALL - -namespace UniLua -{ - using ULDebug = UniLua.Tools.ULDebug; - using InstructionPtr = Pointer; - using Exception = System.Exception; - - public class LuaRuntimeException : Exception - { - public ThreadStatus ErrCode { get; private set; } - - public LuaRuntimeException( ThreadStatus errCode ) - { - ErrCode = errCode; - } - } - - public partial class LuaState - { - internal void D_Throw( ThreadStatus errCode ) - { - throw new LuaRuntimeException( errCode ); - } - - private ThreadStatus D_RawRunProtected( PFuncDelegate func, ref T ud ) - { - int oldNumCSharpCalls = NumCSharpCalls; - ThreadStatus res = ThreadStatus.LUA_OK; - try - { - func(ref ud); - } - catch( LuaRuntimeException e ) - { - NumCSharpCalls = oldNumCSharpCalls; - res = e.ErrCode; - } - NumCSharpCalls = oldNumCSharpCalls; - return res; - } - - private void SetErrorObj( ThreadStatus errCode, StkId oldTop ) - { - switch( errCode ) - { - case ThreadStatus.LUA_ERRMEM: // memory error? - oldTop.V.SetSValue("not enough memory"); - break; - - case ThreadStatus.LUA_ERRERR: - oldTop.V.SetSValue("error in error handling"); - break; - - default: // error message on current top - oldTop.V.SetObj(ref Stack[Top.Index-1].V); - break; - } - Top = Stack[oldTop.Index+1]; - } - - private ThreadStatus D_PCall( PFuncDelegate func, ref T ud, - int oldTopIndex, int errFunc ) - { - int oldCIIndex = CI.Index; - bool oldAllowHook = AllowHook; - int oldNumNonYieldable = NumNonYieldable; - int oldErrFunc = ErrFunc; - - ErrFunc = errFunc; - ThreadStatus status = D_RawRunProtected( func, ref ud ); - if( status != ThreadStatus.LUA_OK ) // an error occurred? - { - F_Close( Stack[oldTopIndex] ); - SetErrorObj( status, Stack[oldTopIndex] ); - CI = BaseCI[oldCIIndex]; - AllowHook = oldAllowHook; - NumNonYieldable = oldNumNonYieldable; - } - ErrFunc = oldErrFunc; - return status; - } - - private void D_Call( StkId func, int nResults, bool allowYield ) - { - if( ++NumCSharpCalls >= LuaLimits.LUAI_MAXCCALLS ) - { - if( NumCSharpCalls == LuaLimits.LUAI_MAXCCALLS ) - G_RunError( "CSharp Stack Overflow" ); - else if( NumCSharpCalls >= - (LuaLimits.LUAI_MAXCCALLS + (LuaLimits.LUAI_MAXCCALLS>>3)) - ) - D_Throw( ThreadStatus.LUA_ERRERR ); - } - if( !allowYield ) - NumNonYieldable++; - if( !D_PreCall( func, nResults ) ) // is a Lua function ? - V_Execute(); - if( !allowYield ) - NumNonYieldable--; - NumCSharpCalls--; - } - - /// - /// return true if function has been executed - /// - private bool D_PreCall( StkId func, int nResults ) - { - // prepare for Lua call - -#if DEBUG_D_PRE_CALL - Console.WriteLine( "============================ D_PreCall func:" + func ); -#endif - - int funcIndex = func.Index; - if(!func.V.TtIsFunction()) { - // not a function - // retry with `function' tag method - func = tryFuncTM( func ); - - // now it must be a function - return D_PreCall( func, nResults ); - } - - if(func.V.ClIsLuaClosure()) { - var cl = func.V.ClLValue(); - Utl.Assert(cl != null); - var p = cl.Proto; - - D_CheckStack(p.MaxStackSize + p.NumParams); - func = Stack[funcIndex]; - - // - int n = (Top.Index - func.Index) - 1; - for( ; n 0 ) - { -#if DEBUG_D_POS_CALL - Console.WriteLine( "[D] ==== PosCall new LuaNil()" ); -#endif - Stack[resIndex++].V.SetNilValue(); - } - Top = Stack[resIndex]; -#if DEBUG_D_POS_CALL - Console.WriteLine( "[D] ==== PosCall return " + (wanted - LuaDef.LUA_MULTRET) ); -#endif - return (wanted - LuaDef.LUA_MULTRET); - } - - private CallInfo ExtendCI() - { - int newIndex = CI.Index + 1; - if(newIndex >= BaseCI.Length) { - int newLength = BaseCI.Length*2; - var newBaseCI = new CallInfo[newLength]; - int i = 0; - while(i < BaseCI.Length) { - newBaseCI[i] = BaseCI[i]; - newBaseCI[i].List = newBaseCI; - ++i; - } - while(i < newLength) { - var newCI = new CallInfo(); - newBaseCI[i] = newCI; - newCI.List = newBaseCI; - newCI.Index = i; - ++i; - } - BaseCI = newBaseCI; - CI = newBaseCI[CI.Index]; - return newBaseCI[newIndex]; - } - else { - return BaseCI[newIndex]; - } - } - - private int AdjustVarargs( LuaProto p, int actual ) - { - // `...' - // : func (base)fixed-p1 fixed-p2 var-p1 var-p2 top - // : func nil nil var-p1 var-p2 (base)fixed-p1 fixed-p2 (reserved...) top - // - // `...' - // func (base)fixed-p1 fixed-p2 (reserved...) top - - int NumFixArgs = p.NumParams; - Utl.Assert( actual >= NumFixArgs, "AdjustVarargs (actual >= NumFixArgs) is false" ); - - int fixedArg = Top.Index - actual; // first fixed argument - int stackBase = Top.Index; // final position of first argument - for( int i=stackBase; ifunc.Index; --i) - { Stack[i].V.SetObj(ref Stack[i-1].V); } - - IncrTop(); - func.V.SetObj(ref tmObj.V); - return func; - } - - private void D_CheckStack(int n) - { - if(StackLast - Top.Index <= n) - D_GrowStack(n); - // TODO: FOR DEBUGGING - // else - // CondMoveStack(); - } - - // some space for error handling - private const int ERRORSTACKSIZE = LuaConf.LUAI_MAXSTACK + 200; - - private void D_GrowStack(int n) - { - int size = Stack.Length; - if(size > LuaConf.LUAI_MAXSTACK) - D_Throw(ThreadStatus.LUA_ERRERR); - - int needed = Top.Index + n + LuaDef.EXTRA_STACK; - int newsize = 2 * size; - if(newsize > LuaConf.LUAI_MAXSTACK) - { newsize = LuaConf.LUAI_MAXSTACK; } - if(newsize < needed) - { newsize = needed; } - if(newsize > LuaConf.LUAI_MAXSTACK) - { - D_ReallocStack(ERRORSTACKSIZE); - G_RunError("stack overflow"); - } - else - { - D_ReallocStack(newsize); - } - } - - private void D_ReallocStack(int size) - { - Utl.Assert(size <= LuaConf.LUAI_MAXSTACK || size == ERRORSTACKSIZE); - var newStack = new StkId[size]; - int i = 0; - for( ; i { - DumpBlock( BitConverter.GetBytes( (uint)ins ) ); - }); - } - - private void DumpConstants( LuaProto proto ) - { - DumpVector( proto.K, (k) => { - var t = k.V.Tt; - DumpByte( (byte)t ); - switch( t ) - { - case (int)LuaType.LUA_TNIL: - break; - case (int)LuaType.LUA_TBOOLEAN: - DumpBool(k.V.BValue()); - break; - case (int)LuaType.LUA_TNUMBER: - DumpBlock( BitConverter.GetBytes(k.V.NValue) ); - break; - case (int)LuaType.LUA_TSTRING: - DumpString(k.V.SValue()); - break; - default: - Utl.Assert(false); - break; - } - }); - - DumpVector( proto.P, (p) => { - DumpFunction( p ); - }); - } - - private void DumpUpvalues( LuaProto proto ) - { - DumpVector( proto.Upvalues, (upval) => { - DumpByte( upval.InStack ? (byte)1 : (byte)0 ); - DumpByte( (byte)upval.Index ); - }); - } - - private void DumpDebug( LuaProto proto ) - { - DumpString( Strip ? null : proto.Source ); - - DumpVector( (Strip ? null : proto.LineInfo), (line) => { - DumpInt(line); - }); - - DumpVector( (Strip ? null : proto.LocVars), (locvar) => { - DumpString( locvar.VarName ); - DumpInt( locvar.StartPc ); - DumpInt( locvar.EndPc ); - }); - - DumpVector( (Strip ? null : proto.Upvalues), (upval) => { - DumpString( upval.Name ); - }); - } - - private void DumpFunction( LuaProto proto ) - { - DumpInt( proto.LineDefined ); - DumpInt( proto.LastLineDefined ); - DumpByte( (byte)proto.NumParams ); - DumpByte( proto.IsVarArg ? (byte)1 : (byte)0 ); - DumpByte( (byte)proto.MaxStackSize ); - DumpCode( proto ); - DumpConstants( proto ); - DumpUpvalues( proto ); - DumpDebug( proto ); - } - - private delegate void DumpItemDelegate( T item ); - private void DumpVector( IList list, DumpItemDelegate dumpItem ) - { - if( list == null ) - { - DumpInt( 0 ); - } - else - { - DumpInt( list.Count ); - for( var i=0; i ReservedWordDict; - static LLex() - { - ReservedWordDict = new Dictionary(); - ReservedWordDict.Add("and", TK.AND); - ReservedWordDict.Add("break", TK.BREAK); - ReservedWordDict.Add("do", TK.DO); - ReservedWordDict.Add("else", TK.ELSE); - ReservedWordDict.Add("elseif", TK.ELSEIF); - ReservedWordDict.Add("end", TK.END); - ReservedWordDict.Add("false", TK.FALSE); - ReservedWordDict.Add("for", TK.FOR); - ReservedWordDict.Add("function", TK.FUNCTION); - ReservedWordDict.Add("goto", TK.GOTO); - ReservedWordDict.Add("if", TK.IF); - ReservedWordDict.Add("in", TK.IN); - ReservedWordDict.Add("local", TK.LOCAL); - ReservedWordDict.Add("nil", TK.NIL); - ReservedWordDict.Add("not", TK.NOT); - ReservedWordDict.Add("or", TK.OR); - ReservedWordDict.Add("repeat", TK.REPEAT); - ReservedWordDict.Add("return", TK.RETURN); - ReservedWordDict.Add("then", TK.THEN); - ReservedWordDict.Add("true", TK.TRUE); - ReservedWordDict.Add("until", TK.UNTIL); - ReservedWordDict.Add("while", TK.WHILE); - } - - public LLex( ILuaState lua, ILoadInfo loadinfo, string name ) - { - Lua = (LuaState)lua; - LoadInfo = loadinfo; - LineNumber = 1; - LastLine = 1; - Token = null; - LookAhead = null; - _Saved = null; - Source = name; - - _Next(); - } - - public void Next() - { - LastLine = LineNumber; - if( LookAhead != null ) - { - Token = LookAhead; - LookAhead = null; - } - else - { - Token = _Lex(); - } - } - - public Token GetLookAhead() - { - Utl.Assert( LookAhead == null ); - LookAhead = _Lex(); - return LookAhead; - } - - private void _Next() - { - var c = LoadInfo.ReadByte(); - Current = (c == -1) ? EOZ : c; - } - - private void _SaveAndNext() - { - Saved.Append( (char)Current ); - _Next(); - } - - private void _Save( char c ) - { - Saved.Append( c ); - } - - private string _GetSavedString() - { - return Saved.ToString(); - } - - private void _ClearSaved() - { - _Saved = null; - } - - private bool _CurrentIsNewLine() - { - return Current == '\n' || Current == '\r'; - } - - private bool _CurrentIsDigit() - { - return Char.IsDigit( (char)Current ); - } - - private bool _CurrentIsXDigit() - { - return _CurrentIsDigit() || - ('A' <= Current && Current <= 'F') || - ('a' <= Current && Current <= 'f'); - } - - private bool _CurrentIsSpace() - { - return Char.IsWhiteSpace( (char)Current ); - } - - private bool _CurrentIsAlpha() - { - return Char.IsLetter( (char)Current ); - } - - private bool _IsReserved( string identifier, out TK type ) - { - return ReservedWordDict.TryGetValue( identifier, out type ); - } - - public bool IsReservedWord( string name ) - { - return ReservedWordDict.ContainsKey( name ); - } - - private void _IncLineNumber() - { - var old = Current; - _Next(); - if( _CurrentIsNewLine() && Current != old ) - _Next(); - if( ++LineNumber >= Int32.MaxValue ) - _Error( "chunk has too many lines" ); - } - - private string _ReadLongString( int sep ) - { - _SaveAndNext(); - - if( _CurrentIsNewLine() ) - _IncLineNumber(); - - while( true ) - { - switch( Current ) - { - case EOZ: - _LexError( _GetSavedString(), - "unfinished long string/comment", - (int)TK.EOS ); - break; - - case '[': - { - if( _SkipSep() == sep ) - { - _SaveAndNext(); - if( sep == 0 ) - { - _LexError( _GetSavedString(), - "nesting of [[...]] is deprecated", - (int)TK.EOS ); - } - } - break; - } - - case ']': - { - if( _SkipSep() == sep ) - { - _SaveAndNext(); - goto endloop; - } - break; - } - - case '\n': - case '\r': - { - _Save('\n'); - _IncLineNumber(); - break; - } - - default: - { - _SaveAndNext(); - break; - } - } - } - endloop: - var r = _GetSavedString(); - return r.Substring( 2+sep, r.Length - 2*(2+sep) ); - } - - private void _EscapeError( string info, string msg ) - { - _LexError( "\\"+info, msg, (int)TK.STRING ); - } - - private byte _ReadHexEscape() - { - int r = 0; - var c = new char[3] { 'x', (char)0, (char)0 }; - // read two hex digits - for( int i=1; i<3; ++i ) - { - _Next(); - c[i] = (char)Current; - if( !_CurrentIsXDigit() ) - { - _EscapeError( new String(c, 0, i+1), - "hexadecimal digit expected" ); - // error - } - r = (r << 4) + Int32.Parse( Current.ToString(), - NumberStyles.HexNumber ); - } - return (byte)r; - } - - private byte _ReadDecEscape() - { - int r = 0; - var c = new char[3]; - // read up to 3 digits - int i = 0; - for( i=0; i<3 && _CurrentIsDigit(); ++i ) - { - c[i] = (char)Current; - r = r*10 + Current - '0'; - _Next(); - } - if( r > Byte.MaxValue ) - _EscapeError( new String(c, 0, i), - "decimal escape too large" ); - return (byte)r; - } - - private string _ReadString() - { - var del = Current; - _Next(); - while( Current != del ) - { - switch( Current ) - { - case EOZ: - _Error( "unfinished string" ); - continue; - - case '\n': - case '\r': - _Error( "unfinished string" ); - continue; - - case '\\': - { - byte c; - _Next(); - switch( Current ) - { - case 'a': c=(byte)'\a'; break; - case 'b': c=(byte)'\b'; break; - case 'f': c=(byte)'\f'; break; - case 'n': c=(byte)'\n'; break; - case 'r': c=(byte)'\r'; break; - case 't': c=(byte)'\t'; break; - case 'v': c=(byte)'\v'; break; - case 'x': c=_ReadHexEscape(); break; - - case '\n': - case '\r': _Save('\n'); _IncLineNumber(); continue; - - case '\\': - case '\"': - case '\'': c=(byte)Current; break; - - case EOZ: continue; - - // zap following span of spaces - case 'z': { - _Next(); // skip `z' - while( _CurrentIsSpace() ) - { - if( _CurrentIsNewLine() ) - _IncLineNumber(); - else - _Next(); - } - continue; - } - - default: - { - if( !_CurrentIsDigit() ) - _EscapeError( Current.ToString(), - "invalid escape sequence" ); - - // digital escape \ddd - c = _ReadDecEscape(); - _Save( (char)c ); - continue; - // { - // c = (char)0; - // for(int i=0; i<3 && _CurrentIsDigit(); ++i) - // { - // c = (char)(c*10 + Current - '0'); - // _Next(); - // } - // _Save( c ); - // } - // continue; - } - } - _Save( (char)c ); - _Next(); - continue; - } - - default: - _SaveAndNext(); - continue; - } - } - _Next(); - return _GetSavedString(); - } - - private double _ReadNumber() - { - var expo = new char[] { 'E', 'e' }; - Utl.Assert( _CurrentIsDigit() ); - var first = Current; - _SaveAndNext(); - if( first == '0' && (Current == 'X' || Current == 'x')) - { - expo = new char[] { 'P', 'p' }; - _SaveAndNext(); - } - for(;;) - { - if( Current == expo[0] || Current == expo[1] ) - { - _SaveAndNext(); - if( Current == '+' || Current == '-' ) - _SaveAndNext(); - } - if( _CurrentIsXDigit() || Current == '.' ) - _SaveAndNext(); - else - break; - } - - double ret; - var str = _GetSavedString(); - if( LuaState.O_Str2Decimal( str, out ret ) ) - { - return ret; - } - else - { - _Error( "malformed number: " + str ); - return 0.0; - } - } - - // private float _ReadNumber() - // { - // do - // { - // _SaveAndNext(); - // } while( _CurrentIsDigit() || Current == '.' ); - // if( Current == 'E' || Current == 'e' ) - // { - // _SaveAndNext(); - // if( Current == '+' || Current == '-' ) - // _SaveAndNext(); - // } - // while( _CurrentIsAlpha() || _CurrentIsDigit() || Current == '_' ) - // _SaveAndNext(); - // float ret; - // if( !Single.TryParse( _GetSavedString(), out ret ) ) - // _Error( "malformed number" ); - // return ret; - // } - - private void _Error( string error ) - { - Lua.O_PushString( string.Format( - "{0}:{1}: {2}", - Source, LineNumber, error ) ); - Lua.D_Throw( ThreadStatus.LUA_ERRSYNTAX ); - } - - private void _LexError( string info, string msg, int tokenType ) - { - // TODO - _Error( msg + ":" + info ); - } - - public void SyntaxError( string msg ) - { - // TODO - _Error( msg ); - } - - private int _SkipSep() - { - int count = 0; - var boundary = Current; - _SaveAndNext(); - while( Current == '=' ) { - _SaveAndNext(); - count++; - } - return ( Current == boundary ? count : (-count)-1 ); - } - - private Token _Lex() - { - _ClearSaved(); - while( true ) - { - switch( Current ) - { - case '\n': - case '\r': { - _IncLineNumber(); - continue; - } - - case '-': { - _Next(); - if( Current != '-' ) return new LiteralToken('-'); - - // else is a long comment - _Next(); - if( Current == '[' ) - { - int sep = _SkipSep(); - _ClearSaved(); - if( sep >= 0 ) - { - _ReadLongString( sep ); - _ClearSaved(); - continue; - } - } - - // else is a short comment - while( !_CurrentIsNewLine() && Current != EOZ ) - _Next(); - continue; - } - - case '[': { - int sep = _SkipSep(); - if( sep >= 0 ) { - string seminfo = _ReadLongString( sep ); - return new StringToken( seminfo ); - } - else if( sep == -1 ) return new LiteralToken('['); - else _Error("invalid long string delimiter"); - continue; - } - - case '=': { - _Next(); - if( Current != '=' ) return new LiteralToken('='); - _Next(); - return new TypedToken( TK.EQ ); - } - - case '<': { - _Next(); - if( Current != '=' ) return new LiteralToken('<'); - _Next(); - return new TypedToken( TK.LE ); - } - - case '>': { - _Next(); - if( Current != '=' ) return new LiteralToken('>'); - _Next(); - return new TypedToken( TK.GE ); - } - - case '~': { - _Next(); - if( Current != '=' ) return new LiteralToken('~'); - _Next(); - return new TypedToken( TK.NE ); - } - - case ':': { - _Next(); - if( Current != ':' ) return new LiteralToken(':'); - _Next(); - return new TypedToken( TK.DBCOLON ); // new in 5.2 ? - } - - case '"': - case '\'': { - return new StringToken( _ReadString() ); - } - - case '.': { - _SaveAndNext(); - if( Current == '.' ) - { - _SaveAndNext(); - if( Current == '.' ) - { - _SaveAndNext(); - return new TypedToken( TK.DOTS ); - } - else - { - return new TypedToken( TK.CONCAT ); - } - } - else if( !_CurrentIsDigit() ) - return new LiteralToken('.'); - else - return new NumberToken( _ReadNumber() ); - } - - case EOZ: { - return new TypedToken( TK.EOS ); - } - - default: { - if( _CurrentIsSpace() ) - { - _Next(); - continue; - } - else if( _CurrentIsDigit() ) - { - return new NumberToken( _ReadNumber() ); - } - else if( _CurrentIsAlpha() || Current == '_' ) - { - do { - _SaveAndNext(); - } while( _CurrentIsAlpha() || - _CurrentIsDigit() || - Current == '_' ); - - string identifier = _GetSavedString(); - TK type; - if( _IsReserved( identifier, out type ) ) - { - return new TypedToken( type ); - } - else - { - return new NameToken( identifier ); - } - } - else - { - var c = Current; - _Next(); - return new LiteralToken(c); - } - } - } - } - } - - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaAPI.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaAPI.cs deleted file mode 100644 index 8f2f5e62b..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaAPI.cs +++ /dev/null @@ -1,1638 +0,0 @@ - using System; - -// #define DEBUG_RECORD_INS - -namespace UniLua -{ - public interface ILoadInfo - { - int ReadByte(); - int PeekByte(); - } - - public delegate int CSharpFunctionDelegate(ILuaState state); - public interface ILuaAPI - { - LuaState NewThread(); - - ThreadStatus Load( ILoadInfo loadinfo, string name, string mode ); - DumpStatus Dump( LuaWriter writeFunc ); - - ThreadStatus GetContext( out int context ); - void Call( int numArgs, int numResults ); - void CallK( int numArgs, int numResults, - int context, CSharpFunctionDelegate continueFunc ); - ThreadStatus PCall( int numArgs, int numResults, int errFunc); - ThreadStatus PCallK( int numArgs, int numResults, int errFunc, - int context, CSharpFunctionDelegate continueFunc ); - - ThreadStatus Resume( ILuaState from, int numArgs ); - int Yield( int numResults ); - int YieldK( int numResults, - int context, CSharpFunctionDelegate continueFunc ); - - int AbsIndex( int index ); - int GetTop(); - void SetTop( int top ); - - void Remove( int index ); - void Insert( int index ); - void Replace( int index ); - void Copy( int fromIndex, int toIndex ); - void XMove( ILuaState to, int n ); - - bool CheckStack( int size ); - bool GetStack( int level, LuaDebug ar ); - int Error(); - - int UpvalueIndex( int i ); - string GetUpvalue( int funcIndex, int n ); - string SetUpvalue( int funcIndex, int n ); - - void CreateTable( int narray, int nrec ); - void NewTable(); - bool Next( int index ); - void RawGetI( int index, int n ); - void RawSetI( int index, int n ); - void RawGet( int index ); - void RawSet( int index ); - void GetField( int index, string key ); - void SetField( int index, string key ); - void GetTable( int index ); - void SetTable( int index ); - - void Concat( int n ); - - LuaType Type( int index ); - string TypeName( LuaType t ); - bool IsNil( int index ); - bool IsNone( int index ); - bool IsNoneOrNil( int index ); - bool IsString( int index ); - bool IsTable( int index ); - bool IsFunction( int index ); - - bool Compare( int index1, int index2, LuaEq op ); - bool RawEqual( int index1, int index2 ); - int RawLen( int index ); - void Len( int index ); - - void PushNil(); - void PushBoolean( bool b ); - void PushNumber( double n ); - void PushInteger( int n ); - void PushUnsigned( uint n ); - string PushString( string s ); - void PushCSharpFunction( CSharpFunctionDelegate f ); - void PushCSharpClosure( CSharpFunctionDelegate f, int n ); - void PushValue( int index ); - void PushGlobalTable(); - void PushLightUserData( object o ); - void PushUInt64( UInt64 o ); - bool PushThread(); - - void Pop( int n ); - - bool GetMetaTable( int index ); - bool SetMetaTable( int index ); - - void GetGlobal( string name ); - void SetGlobal( string name ); - - string ToString( int index ); - double ToNumberX( int index, out bool isnum ); - double ToNumber( int index ); - int ToIntegerX( int index, out bool isnum ); - int ToInteger( int index ); - uint ToUnsignedX( int index, out bool isnum ); - uint ToUnsigned( int index ); - bool ToBoolean( int index ); - UInt64 ToUInt64( int index ); - UInt64 ToUInt64X( int index, out bool isnum ); - object ToObject( int index ); - object ToUserData( int index ); - ILuaState ToThread( int index ); - - ThreadStatus Status { get; } - - string DebugGetInstructionHistory(); - } - - public interface ILuaState : ILuaAPI, ILuaAuxLib - { - } - - public static class LuaAPI - { - public static ILuaState NewState() - { - return new LuaState(); - } - } - - internal delegate void PFuncDelegate(ref T ud); - - public partial class LuaState : ILuaState - { - LuaState ILuaAPI.NewThread() - { - LuaState newLua = new LuaState(G); - Top.V.SetThValue(newLua); - ApiIncrTop(); - - newLua.HookMask = HookMask; - newLua.BaseHookCount = BaseHookCount; - newLua.Hook = Hook; - newLua.ResetHookCount(); - - return newLua; - } - - // private void F_LoadBinary( object ud ) - // { - // byte[] bytes = (byte[])ud; - - // var reader = new BinaryBytesReader( bytes ); - // Undump u = new Undump( reader ); - - // LuaProto proto = Undump.LoadBinary( this, loadinfo, "" ); - - // var cl = new LuaLClosure( proto ); - // for( int i=0; i DG_F_Load = F_Load; - - ThreadStatus ILuaAPI.Load( ILoadInfo loadinfo, string name, string mode ) - { - var param = new LoadParameter(this, loadinfo, name, mode); - var status = D_PCall( DG_F_Load, ref param, Top.Index, ErrFunc ); - - if( status == ThreadStatus.LUA_OK ) { - var below = Stack[Top.Index-1]; - Utl.Assert(below.V.TtIsFunction() && below.V.ClIsLuaClosure()); - var cl = below.V.ClLValue(); - if(cl.Upvals.Length == 1) { - var gt = G.Registry.V.HValue().GetInt(LuaDef.LUA_RIDX_GLOBALS); - cl.Upvals[0].V.V.SetObj(ref gt.V); - } - } - - return status; - } - - DumpStatus ILuaAPI.Dump( LuaWriter writeFunc ) - { - Utl.ApiCheckNumElems( this, 1 ); - - var below = Stack[Top.Index-1]; - if(!below.V.TtIsFunction() || !below.V.ClIsLuaClosure()) - return DumpStatus.ERROR; - - var o = below.V.ClLValue(); - if(o == null) - return DumpStatus.ERROR; - - return DumpState.Dump(o.Proto, writeFunc, false); - } - - ThreadStatus ILuaAPI.GetContext( out int context ) - { - if( (CI.CallStatus & CallStatus.CIST_YIELDED) != 0 ) - { - context = CI.Context; - return CI.Status; - } - else - { - context = default(int); - return ThreadStatus.LUA_OK; - } - } - - void ILuaAPI.Call( int numArgs, int numResults ) - { - // StkId func = Top - (numArgs + 1); - // if( !D_PreCall( func, numResults ) ) - // { - // V_Execute(); - // } - - API.CallK( numArgs, numResults, 0, null ); - } - - void ILuaAPI.CallK( int numArgs, int numResults, - int context, CSharpFunctionDelegate continueFunc ) - { - Utl.ApiCheck( continueFunc == null || !CI.IsLua, - "cannot use continuations inside hooks" ); - Utl.ApiCheckNumElems( this, numArgs + 1 ); - Utl.ApiCheck( Status == ThreadStatus.LUA_OK, - "cannot do calls on non-normal thread" ); - CheckResults( numArgs, numResults ); - var func = Stack[Top.Index - (numArgs+1)]; - - // need to prepare continuation? - if( continueFunc != null && NumNonYieldable == 0 ) - { - CI.ContinueFunc = continueFunc; - CI.Context = context; - D_Call( func, numResults, true ); - } - // no continuation or no yieldable - else - { - D_Call( func, numResults, false ); - } - AdjustResults( numResults ); - } - - private struct CallS - { - public LuaState L; - public int FuncIndex; - public int NumResults; - } - - private static void F_Call(ref CallS ud) - { - CallS c = (CallS)ud; - c.L.D_Call(c.L.Stack[c.FuncIndex], c.NumResults, false); - } - private static PFuncDelegate DG_F_Call = F_Call; - - private void CheckResults( int numArgs, int numResults ) - { - Utl.ApiCheck( numResults == LuaDef.LUA_MULTRET || - CI.TopIndex - Top.Index >= numResults - numArgs, - "results from function overflow current stack size" ); - } - - private void AdjustResults( int numResults ) - { - if( numResults == LuaDef.LUA_MULTRET && - CI.TopIndex < Top.Index ) - { - CI.TopIndex = Top.Index; - } - } - - ThreadStatus ILuaAPI.PCall( int numArgs, int numResults, int errFunc) - { - return API.PCallK( numArgs, numResults, errFunc, 0, null ); - } - - ThreadStatus ILuaAPI.PCallK( int numArgs, int numResults, int errFunc, - int context, CSharpFunctionDelegate continueFunc ) - { - Utl.ApiCheck( continueFunc == null || !CI.IsLua, - "cannot use continuations inside hooks" ); - Utl.ApiCheckNumElems( this, numArgs + 1 ); - Utl.ApiCheck( Status == ThreadStatus.LUA_OK, - "cannot do calls on non-normal thread" ); - CheckResults( numArgs, numResults ); - - int func; - if( errFunc == 0 ) - func = 0; - else - { - StkId addr; - if( !Index2Addr( errFunc, out addr ) ) - Utl.InvalidIndex(); - - func = addr.Index; - } - - ThreadStatus status; - CallS c = new CallS(); - c.L = this; - c.FuncIndex = Top.Index - (numArgs + 1); - if( continueFunc == null || NumNonYieldable > 0 ) // no continuation or no yieldable? - { - c.NumResults = numResults; - status = D_PCall( DG_F_Call, ref c, c.FuncIndex, func ); - } - else - { - int ciIndex = CI.Index; - CI.ContinueFunc = continueFunc; - CI.Context = context; - CI.ExtraIndex = c.FuncIndex; - CI.OldAllowHook = AllowHook; - CI.OldErrFunc = ErrFunc; - ErrFunc = func; - CI.CallStatus |= CallStatus.CIST_YPCALL; - - D_Call( Stack[c.FuncIndex], numResults, true ); - - CallInfo ci = BaseCI[ciIndex]; - ci.CallStatus &= ~CallStatus.CIST_YPCALL; - ErrFunc = ci.OldErrFunc; - status = ThreadStatus.LUA_OK; - } - AdjustResults( numResults ); - return status; - } - - private void FinishCSharpCall() - { - CallInfo ci = CI; - Utl.Assert( ci.ContinueFunc != null ); // must have a continuation - Utl.Assert( NumNonYieldable == 0 ); - // finish `CallK' - AdjustResults( ci.NumResults ); - // call continuation function - if( (ci.CallStatus & CallStatus.CIST_STAT) == 0 ) // no call status? - { - ci.Status = ThreadStatus.LUA_YIELD; // `default' status - } - Utl.Assert( ci.Status != ThreadStatus.LUA_OK ); - ci.CallStatus = ( ci.CallStatus - & ~( CallStatus.CIST_YPCALL | CallStatus.CIST_STAT)) - | CallStatus.CIST_YIELDED; - - int n = ci.ContinueFunc( this ); // call - Utl.ApiCheckNumElems( this, n ); - // finish `D_PreCall' - D_PosCall( Top.Index-n ); - } - - private void Unroll() - { - while( true ) - { - if( CI.Index == 0 ) // stack is empty? - return; // coroutine finished normally - if( !CI.IsLua ) // C# function? - FinishCSharpCall(); - else // Lua function - { - V_FinishOp(); // finish interrupted instruction - V_Execute(); // execute down to higher C# `boundary' - } - } - } - struct UnrollParam - { - public LuaState L; - } - private static void UnrollWrap(ref UnrollParam param) - { - param.L.Unroll(); - } - private static PFuncDelegate DG_Unroll = UnrollWrap; - - private void ResumeError( string msg, int firstArg ) - { - Top = Stack[firstArg]; - Top.V.SetSValue(msg); - IncrTop(); - D_Throw( ThreadStatus.LUA_RESUME_ERROR ); - } - - // check whether thread has suspended protected call - private CallInfo FindPCall() - { - for(int i=CI.Index; i>=0; --i) { - var ci = BaseCI[i]; - if( (ci.CallStatus & CallStatus.CIST_YPCALL) != 0 ) - { return ci; } - } - return null; // no pending pcall - } - - private bool Recover( ThreadStatus status ) - { - CallInfo ci = FindPCall(); - if( ci == null ) // no recover point - return false; - - StkId oldTop = Stack[ci.ExtraIndex]; - F_Close( oldTop ); - SetErrorObj( status, oldTop ); - CI = ci; - AllowHook = ci.OldAllowHook; - NumNonYieldable = 0; - ErrFunc = ci.OldErrFunc; - ci.CallStatus |= CallStatus.CIST_STAT; - ci.Status = status; - return true; - } - - // do the work for `lua_resume' in protected mode - private void Resume(int firstArg) - { - int numCSharpCalls = NumCSharpCalls; - CallInfo ci = CI; - if( numCSharpCalls >= LuaLimits.LUAI_MAXCCALLS ) - ResumeError( "C stack overflow", firstArg ); - if( Status == ThreadStatus.LUA_OK ) // may be starting a coroutine - { - if( ci.Index > 0 ) // not in base level - { - ResumeError( "cannot resume non-suspended coroutine", firstArg ); - } - if( !D_PreCall( Stack[firstArg-1], LuaDef.LUA_MULTRET ) ) // Lua function? - { - V_Execute(); // call it - } - } - else if( Status != ThreadStatus.LUA_YIELD ) - { - ResumeError( "cannot resume dead coroutine", firstArg ); - } - else // resume from previous yield - { - Status = ThreadStatus.LUA_OK; - ci.FuncIndex = ci.ExtraIndex; - if( ci.IsLua ) // yielded inside a hook? - { - V_Execute(); // just continue running Lua code - } - else // `common' yield - { - if( ci.ContinueFunc != null ) - { - ci.Status = ThreadStatus.LUA_YIELD; // `default' status - ci.CallStatus |= CallStatus.CIST_YIELDED; - int n = ci.ContinueFunc( this ); // call continuation - Utl.ApiCheckNumElems( this, n ); - firstArg = Top.Index - n; // yield results come from continuation - } - D_PosCall(firstArg); - } - Unroll(); - } - Utl.Assert( numCSharpCalls == NumCSharpCalls ); - } - struct ResumeParam - { - public LuaState L; - public int firstArg; - } - private static void ResumeWrap(ref ResumeParam param) - { - param.L.Resume(param.firstArg); - } - private static PFuncDelegate DG_Resume = ResumeWrap; - - ThreadStatus ILuaAPI.Resume( ILuaState from, int numArgs ) - { - LuaState fromState = from as LuaState; - NumCSharpCalls = (fromState != null) ? fromState.NumCSharpCalls + 1 : 1; - NumNonYieldable = 0; // allow yields - - Utl.ApiCheckNumElems( this, (Status == ThreadStatus.LUA_OK) ? numArgs + 1 : numArgs ); - - var resumeParam = new ResumeParam(); - resumeParam.L = this; - resumeParam.firstArg = Top.Index-numArgs; - ThreadStatus status = D_RawRunProtected( DG_Resume, ref resumeParam ); - if( status == ThreadStatus.LUA_RESUME_ERROR ) // error calling `lua_resume'? - { - status = ThreadStatus.LUA_ERRRUN; - } - else // yield or regular error - { - while( status != ThreadStatus.LUA_OK && status != ThreadStatus.LUA_YIELD ) // error? - { - if( Recover( status ) ) // recover point? - { - var unrollParam = new UnrollParam(); - unrollParam.L = this; - status = D_RawRunProtected( DG_Unroll, ref unrollParam ); - } - else // unrecoverable error - { - Status = status; // mark thread as `dead' - SetErrorObj( status, Top ); - CI.TopIndex = Top.Index; - break; - } - } - Utl.Assert( status == Status ); - } - - NumNonYieldable = 1; // do not allow yields - NumCSharpCalls--; - Utl.Assert( NumCSharpCalls == ((fromState != null) ? fromState.NumCSharpCalls : 0) ); - return status; - } - - int ILuaAPI.Yield( int numResults ) - { - return API.YieldK( numResults, 0, null ); - } - - int ILuaAPI.YieldK( int numResults, - int context, CSharpFunctionDelegate continueFunc ) - { - CallInfo ci = CI; - Utl.ApiCheckNumElems( this, numResults ); - - if( NumNonYieldable > 0 ) - { - if( this != G.MainThread ) - G_RunError( "attempt to yield across metamethod/C-call boundary" ); - else - G_RunError( "attempt to yield from outside a coroutine" ); - } - Status = ThreadStatus.LUA_YIELD; - ci.ExtraIndex = ci.FuncIndex; // save current `func' - if( ci.IsLua ) // inside a hook - { - Utl.ApiCheck( continueFunc == null, "hooks cannot continue after yielding" ); - } - else - { - ci.ContinueFunc = continueFunc; - if( ci.ContinueFunc != null ) // is there a continuation - { - ci.Context = context; - } - ci.FuncIndex = Top.Index - (numResults + 1); - D_Throw( ThreadStatus.LUA_YIELD ); - } - Utl.Assert( (ci.CallStatus & CallStatus.CIST_HOOKED) != 0 ); // must be inside a hook - return 0; - } - - - int ILuaAPI.AbsIndex( int index ) - { - return (index > 0 || index <= LuaDef.LUA_REGISTRYINDEX) - ? index - : Top.Index - CI.FuncIndex + index; - } - - int ILuaAPI.GetTop() - { - return Top.Index - (CI.FuncIndex + 1); - } - - void ILuaAPI.SetTop( int index ) - { - if( index >= 0 ) - { - Utl.ApiCheck(index <= StackLast-(CI.FuncIndex+1), "new top too large"); - int newTop = CI.FuncIndex+1+index; - for(int i=Top.Index; i p.Index) { - Stack[i].V.SetObj( ref Stack[i-1].V ); - i--; - } - p.V.SetObj(ref Top.V); - } - - private void MoveTo( StkId fr, int index ) - { - StkId to; - if( !Index2Addr( index, out to ) ) - Utl.InvalidIndex(); - - to.V.SetObj(ref fr.V); - } - - void ILuaAPI.Replace( int index ) - { - Utl.ApiCheckNumElems( this, 1 ); - MoveTo( Stack[Top.Index-1], index ); - Top = Stack[Top.Index-1]; - } - - void ILuaAPI.Copy( int fromIndex, int toIndex ) - { - StkId fr; - if( !Index2Addr( fromIndex, out fr ) ) - Utl.InvalidIndex(); - MoveTo( fr, toIndex ); - } - - void ILuaAPI.XMove( ILuaState to, int n ) - { - var toLua = to as LuaState; - if( (LuaState)this == toLua ) - return; - - Utl.ApiCheckNumElems( this, n ); - Utl.ApiCheck( G == toLua.G, "moving among independent states" ); - Utl.ApiCheck( toLua.CI.TopIndex - toLua.Top.Index >= n, "not enough elements to move" ); - - int index = Top.Index-n; - Top = Stack[index]; - for(int i=0; i DG_GrowStack = GrowStackWrap; - - bool ILuaAPI.CheckStack(int size) - { - bool res = false; - - if(StackLast - Top.Index > size) - { res = true; } - // need to grow stack - else { - int inuse = Top.Index + LuaDef.EXTRA_STACK; - if(inuse > LuaConf.LUAI_MAXSTACK - size) - res = false; - else { - var param = new GrowStackParam(); - param.L = this; - param.size = size; - res = D_RawRunProtected(DG_GrowStack, ref param)==ThreadStatus.LUA_OK; - } - } - - if(res && CI.TopIndex < Top.Index + size) - CI.TopIndex = Top.Index + size; // adjust frame top - - return res; - } - - int ILuaAPI.Error() - { - Utl.ApiCheckNumElems( this, 1 ); - G_ErrorMsg(); - return 0; - } - - int ILuaAPI.UpvalueIndex( int i ) - { - return LuaDef.LUA_REGISTRYINDEX - i; - } - - private string AuxUpvalue(StkId addr, int n, out StkId val) - { - val = null; - - if(!addr.V.TtIsFunction()) - return null; - - if(addr.V.ClIsLuaClosure()) { - var f = addr.V.ClLValue(); - var p = f.Proto; - if(!(1 <= n && n <= p.Upvalues.Count)) - return null; - val = f.Upvals[n-1].V; - var name = p.Upvalues[n-1].Name; - return (name == null) ? "" : name; - } - else if(addr.V.ClIsCsClosure()) { - var f = addr.V.ClCsValue(); - if(!(1 <= n && n <= f.Upvals.Length)) - return null; - val = f.Upvals[n-1]; - return ""; - } - else return null; - } - - string ILuaAPI.GetUpvalue( int funcIndex, int n ) - { - StkId addr; - if( !Index2Addr( funcIndex, out addr ) ) - return null; - - StkId val; - var name = AuxUpvalue(addr, n, out val); - if(name == null) - return null; - - Top.V.SetObj(ref val.V); - ApiIncrTop(); - return name; - } - - string ILuaAPI.SetUpvalue( int funcIndex, int n ) - { - StkId addr; - if( !Index2Addr( funcIndex, out addr ) ) - return null; - - Utl.ApiCheckNumElems( this, 1 ); - - StkId val; - var name = AuxUpvalue(addr, n, out val); - if(name == null) - return null; - - Top = Stack[Top.Index-1]; - val.V.SetObj(ref Top.V); - return name; - } - - void ILuaAPI.CreateTable( int narray, int nrec ) - { - var tbl = new LuaTable(this); - Top.V.SetHValue(tbl); - ApiIncrTop(); - if(narray > 0 || nrec > 0) - { tbl.Resize(narray, nrec); } - } - - void ILuaAPI.NewTable() - { - API.CreateTable( 0, 0 ); - } - - bool ILuaAPI.Next( int index ) - { - StkId addr; - if( !Index2Addr( index, out addr ) ) - throw new System.Exception("table expected"); - - var tbl = addr.V.HValue(); - if( tbl == null ) - throw new System.Exception("table expected"); - - var key = Stack[Top.Index-1]; - if( tbl.Next( key, Top ) ) - { - ApiIncrTop(); - return true; - } - else - { - Top = Stack[Top.Index-1]; - return false; - } - } - - void ILuaAPI.RawGetI( int index, int n ) - { - StkId addr; - if( !Index2Addr( index, out addr ) ) - Utl.ApiCheck( false, "table expected" ); - - var tbl = addr.V.HValue(); - Utl.ApiCheck( tbl != null, "table expected" ); - - Top.V.SetObj(ref tbl.GetInt(n).V); - ApiIncrTop(); - } - - // void ILuaAPI.DebugRawGetI( int index, int n ) - // { - // StkId addr; - // if( !Index2Addr( index, out addr ) ) - // Utl.ApiCheck( false, "table expected" ); - - // var tbl = addr.Value as LuaTable; - // Utl.ApiCheck( tbl != null, "table expected" ); - - // var key = new LuaNumber( n ); - // LuaObject outKey, outValue; - // tbl.DebugGet( key, out outKey, out outValue ); - // Top.Value = outKey; - // ApiIncrTop(); - // Top.Value = outValue; - // ApiIncrTop(); - // } - - string ILuaAPI.DebugGetInstructionHistory() - { -#if DEBUG_RECORD_INS - var sb = new System.Text.StringBuilder(); - foreach( var i in InstructionHistory ) { - sb.AppendLine( i.ToString() ); - } - return sb.ToString(); -#else - return "DEBUG_RECORD_INS not defined"; -#endif - } - - void ILuaAPI.RawGet( int index ) - { - StkId addr; - if( !Index2Addr( index, out addr ) ) - throw new System.Exception("table expected"); - - if(!addr.V.TtIsTable()) - throw new System.Exception("table expected"); - - var tbl = addr.V.HValue(); - var below = Stack[Top.Index-1]; - below.V.SetObj( ref tbl.Get( ref below.V ).V ); - } - - void ILuaAPI.RawSetI( int index, int n ) - { - Utl.ApiCheckNumElems( this, 1 ); - StkId addr; - if( !Index2Addr( index, out addr ) ) - Utl.InvalidIndex(); - Utl.ApiCheck( addr.V.TtIsTable(), "table expected" ); - var tbl = addr.V.HValue(); - tbl.SetInt( n, ref Stack[Top.Index-1].V ); - Top = Stack[Top.Index-1]; - } - - void ILuaAPI.RawSet( int index ) - { - Utl.ApiCheckNumElems( this, 2 ); - StkId addr; - if( !Index2Addr( index, out addr ) ) - Utl.InvalidIndex(); - Utl.ApiCheck( addr.V.TtIsTable(), "table expected" ); - var tbl = addr.V.HValue(); - tbl.Set( ref Stack[Top.Index-2].V, ref Stack[Top.Index-1].V ); - Top = Stack[Top.Index-2]; - } - - void ILuaAPI.GetField( int index, string key ) - { - StkId addr; - if( !Index2Addr( index, out addr ) ) - Utl.InvalidIndex(); - - Top.V.SetSValue(key); - var below = Top; - ApiIncrTop(); - V_GetTable( addr, below, below ); - } - - void ILuaAPI.SetField( int index, string key ) - { - StkId addr; - if( !Index2Addr( index, out addr ) ) - Utl.InvalidIndex(); - - StkId.inc(ref Top).V.SetSValue( key ); - V_SetTable( addr, Stack[Top.Index-1], Stack[Top.Index-2] ); - Top = Stack[Top.Index-2]; - } - - void ILuaAPI.GetTable( int index ) - { - StkId addr; - if(! Index2Addr( index, out addr ) ) - Utl.InvalidIndex(); - - var below = Stack[Top.Index - 1]; - V_GetTable( addr, below, below ); - } - - void ILuaAPI.SetTable( int index ) - { - StkId addr; - Utl.ApiCheckNumElems( this, 2 ); - if(! Index2Addr( index, out addr ) ) - Utl.InvalidIndex(); - - var key = Stack[Top.Index - 2]; - var val = Stack[Top.Index - 1]; - V_SetTable( addr, key, val); - Top = Stack[Top.Index-2]; - } - - void ILuaAPI.Concat( int n ) - { - Utl.ApiCheckNumElems( this, n ); - if( n >= 2 ) - { - V_Concat( n ); - } - else if( n == 0 ) - { - Top.V.SetSValue(""); - ApiIncrTop(); - } - } - - LuaType ILuaAPI.Type( int index ) - { - StkId addr; - if( !Index2Addr( index, out addr ) ) - return LuaType.LUA_TNONE; - - return (LuaType)addr.V.Tt; - } - - internal static string TypeName( LuaType t ) - { - switch( t ) - { - case LuaType.LUA_TNIL: - return "nil"; - - case LuaType.LUA_TBOOLEAN: - return "boolean"; - - case LuaType.LUA_TLIGHTUSERDATA: - return "userdata"; - - case LuaType.LUA_TUINT64: - return "UInt64"; - - case LuaType.LUA_TNUMBER: - return "number"; - - case LuaType.LUA_TSTRING: - return "string"; - - case LuaType.LUA_TTABLE: - return "table"; - - case LuaType.LUA_TFUNCTION: - return "function"; - - case LuaType.LUA_TUSERDATA: - return "userdata"; - - case LuaType.LUA_TTHREAD: - return "thread"; - - case LuaType.LUA_TPROTO: - return "proto"; - - case LuaType.LUA_TUPVAL: - return "upval"; - - default: - return "no value"; - } - } - - string ILuaAPI.TypeName( LuaType t ) - { - return TypeName(t); - } - - internal string ObjTypeName( ref TValue v ) - { - return TypeName((LuaType)v.Tt); - } - - // ApiIncrTop() Top CI.Top - internal void O_PushString( string s ) - { - Top.V.SetSValue(s); - IncrTop(); - } - - bool ILuaAPI.IsNil( int index ) - { - return API.Type( index ) == LuaType.LUA_TNIL; - } - - bool ILuaAPI.IsNone( int index ) - { - return API.Type( index ) == LuaType.LUA_TNONE; - } - - bool ILuaAPI.IsNoneOrNil( int index ) - { - LuaType t = API.Type( index ); - return t == LuaType.LUA_TNONE || - t == LuaType.LUA_TNIL; - } - - bool ILuaAPI.IsString( int index ) - { - LuaType t = API.Type( index ); - return( t == LuaType.LUA_TSTRING || t == LuaType.LUA_TNUMBER ); - } - - bool ILuaAPI.IsTable( int index ) - { - return API.Type( index ) == LuaType.LUA_TTABLE; - } - - bool ILuaAPI.IsFunction( int index ) - { - return API.Type( index ) == LuaType.LUA_TFUNCTION; - } - - bool ILuaAPI.Compare( int index1, int index2, LuaEq op ) - { - StkId addr1; - if( !Index2Addr( index1, out addr1 ) ) - Utl.InvalidIndex(); - - StkId addr2; - if( !Index2Addr( index2, out addr2 ) ) - Utl.InvalidIndex(); - - switch( op ) - { - case LuaEq.LUA_OPEQ: return EqualObj( ref addr1.V, ref addr2.V, false ); - case LuaEq.LUA_OPLT: return V_LessThan( addr1, addr2 ); - case LuaEq.LUA_OPLE: return V_LessEqual( addr1, addr2 ); - default: Utl.ApiCheck( false, "invalid option" ); return false; - } - } - - bool ILuaAPI.RawEqual( int index1, int index2 ) - { - StkId addr1; - if( !Index2Addr( index1, out addr1 ) ) - return false; - - StkId addr2; - if( !Index2Addr( index2, out addr2 ) ) - return false; - - return V_RawEqualObj( ref addr1.V, ref addr2.V ); - } - - int ILuaAPI.RawLen( int index ) - { - StkId addr; - if( !Index2Addr( index, out addr ) ) - Utl.InvalidIndex(); - - switch( addr.V.Tt ) - { - case (int)LuaType.LUA_TSTRING: - { - var s = addr.V.SValue(); - return s == null ? 0 : s.Length; - } - case (int)LuaType.LUA_TUSERDATA: - { - return addr.V.RawUValue().Length; - } - case (int)LuaType.LUA_TTABLE: - { - return addr.V.HValue().Length; - } - default: return 0; - } - } - - void ILuaAPI.Len( int index ) - { - StkId addr; - if( !Index2Addr( index, out addr ) ) - Utl.InvalidIndex(); - - V_ObjLen( Top, addr ); - - ApiIncrTop(); - } - - void ILuaAPI.PushNil() - { - Top.V.SetNilValue(); - ApiIncrTop(); - } - - void ILuaAPI.PushBoolean( bool b ) - { - Top.V.SetBValue( b ); - ApiIncrTop(); - } - - void ILuaAPI.PushNumber( double n ) - { - Top.V.SetNValue( n ); - ApiIncrTop(); - } - - void ILuaAPI.PushInteger( int n ) - { - Top.V.SetNValue( (double)n ); - ApiIncrTop(); - } - - void ILuaAPI.PushUnsigned( uint n ) - { - Top.V.SetNValue( (double)n ); - ApiIncrTop(); - } - - string ILuaAPI.PushString( string s ) - { - if( s == null ) - { - API.PushNil(); - return null; - } - else - { - Top.V.SetSValue(s); - ApiIncrTop(); - return s; - } - } - - void ILuaAPI.PushCSharpFunction( CSharpFunctionDelegate f ) - { - API.PushCSharpClosure( f, 0 ); - } - - void ILuaAPI.PushCSharpClosure( CSharpFunctionDelegate f, int n ) - { - if( n == 0 ) - { - Top.V.SetClCsValue( new LuaCsClosureValue( f ) ); - } - else - { - // UpValue C# function - Utl.ApiCheckNumElems( this, n ); - Utl.ApiCheck( n <= LuaLimits.MAXUPVAL, "upvalue index too large" ); - - LuaCsClosureValue cscl = new LuaCsClosureValue( f, n ); - int index = Top.Index - n; - Top = Stack[index]; - for(int i=0; i 0 ) - { - var addrIndex = ci.FuncIndex + index; - Utl.ApiCheck( index <= ci.TopIndex - (ci.FuncIndex + 1), "unacceptable index" ); - if( addrIndex >= Top.Index ) { - addr = default(StkId); - return false; - } - - addr = Stack[addrIndex]; - return true; - } - else if( index > LuaDef.LUA_REGISTRYINDEX ) - { - Utl.ApiCheck( index != 0 && -index <= Top.Index - (ci.FuncIndex + 1), "invalid index" ); - addr = Stack[Top.Index + index]; - return true; - } - else if( index == LuaDef.LUA_REGISTRYINDEX ) - { - addr = G.Registry; - return true; - } - // upvalues - else - { - index = LuaDef.LUA_REGISTRYINDEX - index; - Utl.ApiCheck( index <= LuaLimits.MAXUPVAL + 1, "upvalue index too large" ); - var func = Stack[ci.FuncIndex]; - Utl.Assert(func.V.TtIsFunction()); - - if(func.V.ClIsLcsClosure()) { - addr = default(StkId); - return false; - } - - Utl.Assert(func.V.ClIsCsClosure()); - var clcs = func.V.ClCsValue(); - if(index > clcs.Upvals.Length) { - addr = default(StkId); - return false; - } - - addr = clcs.Upvals[index-1]; - return true; - } - } - - // private void RegisterGlobalFunc( string name, CSharpFunctionDelegate f ) - // { - // API.PushCSharpFunction( f ); - // API.SetGlobal( name ); - // } - - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaAuxLib.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaAuxLib.cs deleted file mode 100644 index 7bf363a1b..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaAuxLib.cs +++ /dev/null @@ -1,756 +0,0 @@ - -namespace UniLua -{ - using System; - using System.IO; - using System.Collections.Generic; - using Aura_OS.System.Processing; - using System.Text; - using System.Xml.Linq; - using Cosmos.HAL.Drivers.Video.SVGAII; - - public struct NameFuncPair - { - public string Name; - public CSharpFunctionDelegate Func; - - public NameFuncPair( string name, CSharpFunctionDelegate func ) - { - Name = name; - Func = func; - } - } - - public interface ILuaAuxLib - { - void L_Where( int level ); - int L_Error( string fmt, params object[] args ); - void L_CheckStack( int size, string msg ); - void L_CheckAny( int narg ); - void L_CheckType( int index, LuaType t ); - double L_CheckNumber( int narg ); - UInt64 L_CheckUInt64( int narg ); - int L_CheckInteger( int narg ); - string L_CheckString( int narg ); - uint L_CheckUnsigned( int narg ); - void L_ArgCheck( bool cond, int narg, string extraMsg ); - int L_ArgError( int narg, string extraMsg ); - string L_TypeName( int index ); - - string L_ToString( int index ); - bool L_GetMetaField( int index, string method ); - int L_GetSubTable( int index, string fname ); - - void L_RequireF( string moduleName, CSharpFunctionDelegate openFunc, bool global ); - void L_OpenLibs(); - void L_NewLibTable( NameFuncPair[] define ); - void L_NewLib( NameFuncPair[] define ); - void L_SetFuncs( NameFuncPair[] define, int nup ); - - int L_Opt(int n, int def); - - int L_OptInt( int narg, int def ); - string L_OptString( int narg, string def ); - bool L_CallMeta( int obj, string name ); - void L_Traceback( ILuaState otherLua, string msg, int level ); - int L_Len( int index ); - - ThreadStatus L_LoadBuffer( string s, string name ); - ThreadStatus L_LoadBufferX( string s, string name, string mode ); - ThreadStatus L_LoadFile( string filename ); - ThreadStatus L_LoadFileX( string filename, string mode ); - - ThreadStatus L_LoadString( string s ); - ThreadStatus L_LoadBytes( byte[] bytes, string name); - ThreadStatus L_DoByteArray(byte[] file, string name); - ThreadStatus L_DoString( string s ); - ThreadStatus L_DoFile( string filename ); - - - string L_Gsub( string src, string pattern, string rep ); - - // reference system - int L_Ref( int t ); - void L_Unref( int t, int reference ); - } - - class StringLoadInfo : ILoadInfo - { - public StringLoadInfo(string s ) - { - Str = s; - Pos = 0; - } - - public int ReadByte() - { - if( Pos >= Str.Length ) - return -1; - else - return Str[Pos++]; - } - - public int PeekByte() - { - if( Pos >= Str.Length ) - return -1; - else - return Str[Pos]; - } - - private string Str; - private int Pos; - } - - class BytesLoadInfo : ILoadInfo - { - public BytesLoadInfo( byte[] bytes ) - { - Bytes = bytes; - Pos = 0; - } - - public int ReadByte() - { - if( Pos >= Bytes.Length ) - return -1; - else - return Bytes[Pos++]; - } - - public int PeekByte() - { - if( Pos >= Bytes.Length ) - return -1; - else - return Bytes[Pos]; - } - - private byte[] Bytes; - private int Pos; - } - - public partial class LuaState - { - private const int LEVELS1 = 12; // size of the first part of the stack - private const int LEVELS2 = 10; // size of the second part of the stack - - public void L_Where( int level ) - { - LuaDebug ar = new LuaDebug(); - if( API.GetStack( level, ar ) ) // check function at level - { - GetInfo( "Sl", ar ); // get info about it - if( ar.CurrentLine > 0 ) // is there info? - { - API.PushString( string.Format( "{0}:{1}: ", ar.ShortSrc, ar.CurrentLine ) ); - return; - } - } - API.PushString( "" ); // else, no information available... - } - - public int L_Error( string fmt, params object[] args ) - { - L_Where( 1 ); - API.PushString( string.Format( fmt, args ) ); - API.Concat( 2 ); - return API.Error(); - } - - public void L_CheckStack( int size, string msg ) - { - // keep some extra space to run error routines, if needed - if(!API.CheckStack(size + LuaDef.LUA_MINSTACK)) { - if(msg != null) - { L_Error(string.Format("stack overflow ({0})", msg)); } - else - { L_Error("stack overflow"); } - } - } - - public void L_CheckAny( int narg ) - { - if( API.Type( narg ) == LuaType.LUA_TNONE ) - L_ArgError( narg, "value expected" ); - } - - public double L_CheckNumber( int narg ) - { - bool isnum; - double d = API.ToNumberX( narg, out isnum ); - if( !isnum ) - TagError( narg, LuaType.LUA_TNUMBER ); - return d; - } - - public UInt64 L_CheckUInt64( int narg ) - { - bool isnum; - UInt64 v = API.ToUInt64X( narg, out isnum ); - if( !isnum ) - TagError( narg, LuaType.LUA_TUINT64 ); - return v; - } - - public int L_CheckInteger( int narg ) - { - bool isnum; - int d = API.ToIntegerX( narg, out isnum ); - if( !isnum ) - TagError( narg, LuaType.LUA_TNUMBER ); - return d; - } - - public string L_CheckString( int narg ) - { - string s = API.ToString( narg ); - if( s == null ) TagError( narg, LuaType.LUA_TSTRING ); - return s; - } - - public uint L_CheckUnsigned( int narg ) - { - bool isnum; - uint d = API.ToUnsignedX( narg, out isnum ); - if( !isnum ) - TagError( narg, LuaType.LUA_TNUMBER ); - return d; - } - - public int L_Opt(int n, int def) - { - LuaType t = API.Type(n); - if (t == LuaType.LUA_TNONE || t == LuaType.LUA_TNIL) - { - return def; - } - else - { - return L_CheckInteger(n); - } - } - - public int L_OptInt( int narg, int def ) - { - LuaType t = API.Type( narg ); - if( t == LuaType.LUA_TNONE || - t == LuaType.LUA_TNIL ) - { - return def; - } - else - { - return L_CheckInteger( narg ); - } - } - - public string L_OptString( int narg, string def ) - { - LuaType t = API.Type( narg ); - if( t == LuaType.LUA_TNONE || - t == LuaType.LUA_TNIL ) - { - return def; - } - else - { - return L_CheckString( narg ); - } - } - - private int TypeError( int index, string typeName ) - { - string msg = string.Format( "{0} expected, got {1}", - typeName, L_TypeName( index ) ); - API.PushString( msg ); - return L_ArgError( index, msg ); - } - - private void TagError( int index, LuaType t ) - { - TypeError( index, API.TypeName( t ) ); - } - - public void L_CheckType( int index, LuaType t ) - { - if( API.Type( index ) != t ) - TagError( index, t ); - } - - public void L_ArgCheck( bool cond, int narg, string extraMsg ) - { - if( !cond ) - L_ArgError( narg, extraMsg ); - } - - public int L_ArgError( int narg, string extraMsg ) - { - - LuaDebug ar = new LuaDebug(); - if( !API.GetStack( 0, ar ) ) // no stack frame ? - return L_Error( "bad argument {0} ({1})", narg, extraMsg ); - - GetInfo( "n", ar ); - if( ar.NameWhat == "method" ) - { - narg--; // do not count 'self' - if( narg == 0 ) // error is in the self argument itself? - return L_Error( "calling '{0}' on bad self", ar.Name ); - } - if( ar.Name == null ) - ar.Name = PushGlobalFuncName( ar ) ? API.ToString(-1) : "?"; - return L_Error( "bad argument {0} to '{1}' ({2})", - narg, ar.Name, extraMsg ); - } - - public string L_TypeName( int index ) - { - return API.TypeName( API.Type( index ) ); - } - - public bool L_GetMetaField( int obj, string name ) - { - if( !API.GetMetaTable(obj) ) // no metatable? - return false; - API.PushString( name ); - API.RawGet( -2 ); - if( API.IsNil( -1 ) ) - { - API.Pop( 2 ); - return false; - } - else - { - API.Remove( -2 ); - return true; - } - } - - public bool L_CallMeta( int obj, string name ) - { - obj = API.AbsIndex( obj ); - if( !L_GetMetaField( obj, name ) ) // no metafield? - return false; - - API.PushValue( obj ); - API.Call( 1, 1 ); - return true; - } - - private void PushFuncName( LuaDebug ar ) - { - if( ar.NameWhat.Length > 0 && ar.NameWhat[0] != '\0' ) // is there a name? - API.PushString( string.Format( "function '{0}'", ar.Name ) ); - else if( ar.What.Length > 0 && ar.What[0] == 'm' ) // main? - API.PushString( "main chunk" ); - else if( ar.What.Length > 0 && ar.What[0] == 'C' ) - { - if( PushGlobalFuncName( ar ) ) - { - API.PushString( string.Format( "function '{0}'", API.ToString(-1) ) ); - API.Remove( -2 ); //remove name - } - else - API.PushString( "?" ); - } - else - API.PushString( string.Format( "function <{0}:{1}>", ar.ShortSrc, ar.LineDefined ) ); - } - - private int CountLevels() - { - LuaDebug ar = new LuaDebug(); - int li = 1; - int le = 1; - // find an upper bound - while( API.GetStack(le, ar) ) - { - li = le; - le *= 2; - } - // do a binary search - while(li < le) - { - int m = (li + le)/2; - if( API.GetStack( m, ar ) ) - li = m + 1; - else - le = m; - } - return le - 1; - } - - public void L_Traceback( ILuaState otherLua, string msg, int level ) - { - LuaState oLua = otherLua as LuaState; - LuaDebug ar = new LuaDebug(); - int top = API.GetTop(); - int numLevels = oLua.CountLevels(); - int mark = (numLevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0; - if( msg != null ) - API.PushString( string.Format( "{0}\n", msg ) ); - API.PushString( "stack traceback:" ); - while( otherLua.GetStack( level++, ar ) ) - { - if( level == mark ) // too many levels? - { - API.PushString( "\n\t..." ); - level = numLevels - LEVELS2; // and skip to last ones - } - else - { - oLua.GetInfo( "Slnt", ar ); - API.PushString( string.Format( "\n\t{0}:", ar.ShortSrc ) ); - if( ar.CurrentLine > 0 ) - API.PushString( string.Format( "{0}:", ar.CurrentLine ) ); - API.PushString(" in "); - PushFuncName( ar ); - if( ar.IsTailCall ) - API.PushString( "\n\t(...tail calls...)" ); - API.Concat( API.GetTop() - top ); - } - } - API.Concat( API.GetTop() - top ); - } - - public int L_Len( int index ) - { - API.Len( index ); - - bool isnum; - int l = (int)API.ToIntegerX( -1, out isnum ); - if( !isnum ) - L_Error( "object length is not a number" ); - API.Pop( 1 ); - return l; - } - - public ThreadStatus L_LoadBuffer( string s, string name ) - { - return L_LoadBufferX( s, name, null ); - } - - public ThreadStatus L_LoadBufferX( string s, string name, string mode ) - { - var loadinfo = new StringLoadInfo( s ); - return API.Load( loadinfo, name, mode ); - } - - public ThreadStatus L_LoadBytes( byte[] bytes, string name) - { - LuaFile.VirtualFiles.Add(name, bytes); - - var loadinfo = new BytesLoadInfo( bytes ); - return API.Load( loadinfo, name, null ); - } - - private ThreadStatus ErrFile( string what, int fnameindex ) - { - return ThreadStatus.LUA_ERRFILE; - } - - public ThreadStatus L_LoadFile( string filename ) - { - return L_LoadFileX( filename, null ); - } - - public ThreadStatus L_LoadFileX( string filename, string mode ) - { - var status = ThreadStatus.LUA_OK; - if( filename == null ) - { - // stdin - throw new System.NotImplementedException(); - } - - int fnameindex = API.GetTop() + 1; - API.PushString( "@" + filename ); - try - { - var loadinfo = LuaFile.OpenFile(filename); - - if (loadinfo.GetType() == typeof(FileLoadInfo)) - { - ((FileLoadInfo)loadinfo).SkipComment(); - status = API.Load(((FileLoadInfo)loadinfo), API.ToString(-1), mode); - ((FileLoadInfo)loadinfo).Dispose(); - } - else if (loadinfo.GetType() == typeof(BytesLoadInfo)) - { - status = API.Load(loadinfo, filename, null); - } - } - catch( LuaRuntimeException e ) - { - API.PushString( string.Format( "cannot open {0}: {1}", - filename, e.Message ) ); - return ThreadStatus.LUA_ERRFILE; - } - - API.Remove( fnameindex ); - return status; - } - - public ThreadStatus L_LoadString( string s ) - { - return L_LoadBuffer( s, s ); - } - - public ThreadStatus L_DoByteArray(byte[] file, string name) - { - var status = L_LoadBytes(file, name); - if (status != ThreadStatus.LUA_OK) - return status; - return API.PCall(0, LuaDef.LUA_MULTRET, 0); - } - - public ThreadStatus L_DoString( string s ) - { - var status = L_LoadString( s ); - if( status != ThreadStatus.LUA_OK ) - return status; - return API.PCall( 0, LuaDef.LUA_MULTRET, 0 ); - } - - public ThreadStatus L_DoFile( string filename ) - { - var status = L_LoadFile( filename ); - if( status != ThreadStatus.LUA_OK ) - return status; - return API.PCall( 0, LuaDef.LUA_MULTRET, 0 ); - } - - public string L_Gsub( string src, string pattern, string rep ) - { - string res = src.Replace(pattern, rep); - API.PushString( res ); - return res; - } - - public string L_ToString( int index ) - { - if( !L_CallMeta( index, "__tostring" ) ) // no metafield? // TODO L_CallMeta - { - switch( API.Type(index) ) - { - case LuaType.LUA_TNUMBER: - case LuaType.LUA_TSTRING: - API.PushValue( index ); - break; - - case LuaType.LUA_TBOOLEAN: - API.PushString( API.ToBoolean( index ) ? "true" : "false" ); - break; - - case LuaType.LUA_TNIL: - API.PushString( "nil" ); - break; - - default: - API.PushString( string.Format("{0}: {1:X}" - , L_TypeName( index ) - , API.ToObject( index ).GetHashCode() - ) ); - break; - } - } - return API.ToString( -1 ); - } - - // private static class LibLoadInfo - // { - // public static List Items; - - // static LibLoadInfo() - // { - // Items = new List(); - // Add( "_G", LuaState.LuaOpen_Base ); - // } - - // private static void Add( string name, CSharpFunctionDelegate loadFunc ) - // { - // Items.Add( new NameFuncPair { Name=name, LoadFunc=loadFunc } ); - // } - // } - - public void L_OpenLibs() - { - NameFuncPair[] define = new NameFuncPair[] - { - new NameFuncPair( "_G", LuaBaseLib.OpenLib ), - new NameFuncPair( LuaPkgLib.LIB_NAME, LuaPkgLib.OpenLib ), - new NameFuncPair( LuaCoroLib.LIB_NAME, LuaCoroLib.OpenLib ), - new NameFuncPair( LuaTableLib.LIB_NAME, LuaTableLib.OpenLib ), - new NameFuncPair( LuaIOLib.LIB_NAME, LuaIOLib.OpenLib ), - new NameFuncPair( LuaOSLib.LIB_NAME, LuaOSLib.OpenLib ), - // {LUA_OSLIBNAME, luaopen_os}, - new NameFuncPair( LuaStrLib.LIB_NAME, LuaStrLib.OpenLib ), - new NameFuncPair( LuaBitLib.LIB_NAME, LuaBitLib.OpenLib ), - new NameFuncPair( LuaMathLib.LIB_NAME, LuaMathLib.OpenLib ), - new NameFuncPair( LuaDebugLib.LIB_NAME, LuaDebugLib.OpenLib ), - new NameFuncPair( LuaEncLib.LIB_NAME, LuaEncLib.OpenLib ), - new NameFuncPair( LuaCosmosCryptoLib.LIB_NAME, LuaCosmosCryptoLib.OpenLib ), - }; - - for( var i=0; i= 0 ) - { - t = API.AbsIndex(t); - API.RawGetI(t, FreeList); - API.RawSetI(t, reference); // t[ref] = t[freelist] - API.PushInteger(reference); - API.RawSetI(t, FreeList); // t[freelist] = ref - } - } - -#if UNITY_IPHONE - public void FEED_AOT_FOR_IOS(LuaState lua) - { - lua.L_Opt( lua.L_CheckInteger, 1, 1); - } -#endif - - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaBaseLib.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaBaseLib.cs deleted file mode 100644 index c23a1fce9..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaBaseLib.cs +++ /dev/null @@ -1,441 +0,0 @@ - -namespace UniLua -{ - using System.Collections.Generic; - using ULDebug = UniLua.Tools.ULDebug; - using StringBuilder = System.Text.StringBuilder; - using Char = System.Char; - using Int32 = System.Int32; - using System; - - internal static class LuaBaseLib - { - internal static int OpenLib( ILuaState lua ) - { - NameFuncPair[] define = new NameFuncPair[] - { - new NameFuncPair( "assert", LuaBaseLib.B_Assert ), - new NameFuncPair( "collectgarbage", LuaBaseLib.B_CollectGarbage ), - new NameFuncPair( "dofile", LuaBaseLib.B_DoFile ), - new NameFuncPair( "error", LuaBaseLib.B_Error ), - new NameFuncPair( "ipairs", LuaBaseLib.B_Ipairs ), - new NameFuncPair( "loadfile", LuaBaseLib.B_LoadFile ), - new NameFuncPair( "load", LuaBaseLib.B_Load ), - new NameFuncPair( "loadstring", LuaBaseLib.B_Load ), - new NameFuncPair( "next", LuaBaseLib.B_Next ), - new NameFuncPair( "pairs", LuaBaseLib.B_Pairs ), - new NameFuncPair( "pcall", LuaBaseLib.B_PCall ), - new NameFuncPair( "print", LuaBaseLib.B_Print ), - new NameFuncPair( "rawequal", LuaBaseLib.B_RawEqual ), - new NameFuncPair( "rawlen", LuaBaseLib.B_RawLen ), - new NameFuncPair( "rawget", LuaBaseLib.B_RawGet ), - new NameFuncPair( "rawset", LuaBaseLib.B_RawSet ), - new NameFuncPair( "select", LuaBaseLib.B_Select ), - new NameFuncPair( "getmetatable", LuaBaseLib.B_GetMetaTable ), - new NameFuncPair( "setmetatable", LuaBaseLib.B_SetMetaTable ), - new NameFuncPair( "tonumber", LuaBaseLib.B_ToNumber ), - new NameFuncPair( "tostring", LuaBaseLib.B_ToString ), - new NameFuncPair( "type", LuaBaseLib.B_Type ), - new NameFuncPair( "xpcall", LuaBaseLib.B_XPCall ), - }; - - // set global _G - lua.PushGlobalTable(); - lua.PushGlobalTable(); - lua.SetField( -2, "_G" ); - - // open lib into global lib - lua.L_SetFuncs( define, 0 ); - // lua.RegisterGlobalFunc( "type", LuaBaseLib.B_Type ); - // lua.RegisterGlobalFunc( "pairs", LuaBaseLib.B_Pairs ); - // lua.RegisterGlobalFunc( "ipairs", LuaBaseLib.B_Ipairs ); - // lua.RegisterGlobalFunc( "print", LuaBaseLib.B_Print ); - // lua.RegisterGlobalFunc( "tostring", LuaBaseLib.B_ToString ); - - lua.PushString( LuaDef.LUA_VERSION ); - lua.SetField( -2, "_VERSION" ); - - return 1; - } - - public static int B_Assert( ILuaState lua ) - { - if( !lua.ToBoolean( 1 ) ) - return lua.L_Error( "{0}", lua.L_OptString( 2, "assertion failed!" ) ); - return lua.GetTop(); - } - - public static int B_CollectGarbage( ILuaState lua ) - { - // not implement gc - string opt = lua.L_OptString( 1, "collect" ); - switch( opt ) - { - case "count": - lua.PushNumber( 0 ); - lua.PushNumber( 0 ); - return 2; - - case "step": - case "isrunning": - lua.PushBoolean( true ); - return 1; - - default: - lua.PushInteger( 0 ); - return 1; - } - } - - private static int DoFileContinuation( ILuaState lua ) - { - return lua.GetTop() - 1; - } - - public static int B_DoFile( ILuaState lua ) - { - string filename = lua.L_OptString( 1, null ); - lua.SetTop( 1 ); - if( lua.L_LoadFile( filename ) != ThreadStatus.LUA_OK ) - lua.Error(); - lua.CallK( 0, LuaDef.LUA_MULTRET, 0, DoFileContinuation ); - return DoFileContinuation( lua ); - } - - public static int B_Error( ILuaState lua ) - { - int level = lua.L_OptInt( 2, 1 ); - lua.SetTop( 1 ); - if( lua.IsString( 1 ) && level > 0 ) - { - lua.L_Where( level ); - lua.PushValue( 1 ); - lua.Concat( 2 ); - } - return lua.Error(); - } - - private static int LoadAux( ILuaState lua, ThreadStatus status, int envidx ) - { - if( status == ThreadStatus.LUA_OK ) - { - if( envidx != 0 ) // `env' parameter? - { - lua.PushValue(envidx); // push `env' on stack - if( lua.SetUpvalue(-2, 1) == null ) // set `env' as 1st upvalue of loaded function - { - lua.Pop(1); // remove `env' if not used by previous call - } - } - return 1; - } - else // error (message is on top of the stack) - { - lua.PushNil(); - lua.Insert(-2); // put before error message - return 2; // return nil plus error message - } - } - - public static int B_LoadFile( ILuaState lua ) - { - string fname = lua.L_OptString( 1, null ); - string mode = lua.L_OptString( 2, null ); - int env = (!lua.IsNone(3) ? 3 : 0); // `env' index or 0 if no `env' - var status = lua.L_LoadFileX( fname, mode ); - return LoadAux(lua, status, env); - } - - public static int B_Load( ILuaState lua ) - { - ThreadStatus status; - string s = lua.ToString(1); - string mode = lua.L_OptString(3, "bt"); - int env = (! lua.IsNone(4) ? 4 : 0); // `env' index or 0 if no `env' - if( s != null ) - { - string chunkName = lua.L_OptString(2, s); - status = lua.L_LoadBufferX( s, chunkName, mode ); - } - else // loading from a reader function - { - throw new System.NotImplementedException(); // TODO - } - return LoadAux( lua, status, env ); - } - - private static int FinishPCall( ILuaState lua, bool status ) - { - // no space for extra boolean? - if(!lua.CheckStack(1)) { - lua.SetTop(0); // create space for return values - lua.PushBoolean(false); - lua.PushString("stack overflow"); - return 2; - } - lua.PushBoolean( status ); - lua.Replace( 1 ); - return lua.GetTop(); - } - - private static int PCallContinuation( ILuaState lua ) - { - int context; - ThreadStatus status = lua.GetContext( out context ); - return FinishPCall( lua, status == ThreadStatus.LUA_YIELD ); - } - private static CSharpFunctionDelegate DG_PCallContinuation = PCallContinuation; - - public static int B_PCall( ILuaState lua ) - { - lua.L_CheckAny( 1 ); - lua.PushNil(); - lua.Insert( 1 ); // create space for status result - - ThreadStatus status = lua.PCallK( lua.GetTop() - 2, - LuaDef.LUA_MULTRET, 0, 0, DG_PCallContinuation ); - - return FinishPCall( lua, status == ThreadStatus.LUA_OK ); - } - - public static int B_XPCall( ILuaState lua ) - { - int n = lua.GetTop(); - lua.L_ArgCheck( n>=2, 2, "value expected" ); - lua.PushValue( 1 ); // exchange function... - lua.Copy( 2, 1); // ...and error handler - lua.Replace( 2 ); - ThreadStatus status = lua.PCallK( n-2, LuaDef.LUA_MULTRET, - 1, 0, DG_PCallContinuation ); - return FinishPCall( lua, status == ThreadStatus.LUA_OK ); - } - - public static int B_RawEqual( ILuaState lua ) - { - lua.L_CheckAny( 1 ); - lua.L_CheckAny( 2 ); - lua.PushBoolean( lua.RawEqual( 1, 2 ) ); - return 1; - } - - public static int B_RawLen( ILuaState lua ) - { - LuaType t = lua.Type( 1 ); - lua.L_ArgCheck( t == LuaType.LUA_TTABLE || t == LuaType.LUA_TSTRING, - 1, "table or string expected" ); - lua.PushInteger( lua.RawLen( 1 ) ); - return 1; - } - - public static int B_RawGet( ILuaState lua ) - { - lua.L_CheckType( 1, LuaType.LUA_TTABLE ); - lua.L_CheckAny( 2 ); - lua.SetTop( 2 ); - lua.RawGet( 1 ); - return 1; - } - - public static int B_RawSet( ILuaState lua ) - { - lua.L_CheckType( 1, LuaType.LUA_TTABLE ); - lua.L_CheckAny( 2 ); - lua.L_CheckAny( 3 ); - lua.SetTop( 3 ); - lua.RawSet( 1 ); - return 1; - } - - public static int B_Select( ILuaState lua ) - { - int n = lua.GetTop(); - if( lua.Type( 1 ) == LuaType.LUA_TSTRING && - lua.ToString( 1 )[0] == '#' ) - { - lua.PushInteger( n-1 ); - return 1; - } - else - { - int i = lua.L_CheckInteger( 1 ); - if( i < 0 ) i = n + i; - else if( i > n ) i = n; - lua.L_ArgCheck( 1 <= i, 1, "index out of range" ); - return n - i; - } - } - - public static int B_GetMetaTable( ILuaState lua ) - { - lua.L_CheckAny( 1 ); - if( !lua.GetMetaTable( 1 ) ) - { - lua.PushNil(); - return 1; // no metatable - } - lua.L_GetMetaField( 1, "__metatable" ); - return 1; - } - - public static int B_SetMetaTable( ILuaState lua ) - { - LuaType t = lua.Type( 2 ); - lua.L_CheckType( 1, LuaType.LUA_TTABLE ); - lua.L_ArgCheck( t == LuaType.LUA_TNIL || t == LuaType.LUA_TTABLE, - 2, "nil or table expected" ); - if( lua.L_GetMetaField( 1, "__metatable" ) ) - return lua.L_Error( "cannot change a protected metatable" ); - lua.SetTop( 2 ); - lua.SetMetaTable( 1 ); - return 1; - } - - public static int B_ToNumber( ILuaState lua ) - { - LuaType t = lua.Type( 2 ); - if( t == LuaType.LUA_TNONE || t == LuaType.LUA_TNIL ) // standard conversion - { - bool isnum; - double n = lua.ToNumberX( 1, out isnum ); - if( isnum ) - { - lua.PushNumber( n ); - return 1; - } // else not a number; must be something - lua.L_CheckAny( 1 ); - } - else - { - string s = lua.L_CheckString( 1 ); - int numBase = lua.L_CheckInteger( 2 ); - bool negative = false; - lua.L_ArgCheck( (2 <= numBase && numBase <= 36), 2, - "base out of range" ); - s = s.Trim( ' ', '\f', '\n', '\r', '\t', '\v' ); - s = s + '\0'; // guard - int pos = 0; - if(s[pos] == '-') { pos++; negative = true; } - else if(s[pos] == '+') pos++; - if( Char.IsLetterOrDigit( s, pos ) ) - { - double n = 0.0; - do - { - int digit; - if( Char.IsDigit( s, pos ) ) - digit = Int32.Parse( s[pos].ToString() ); - else - digit = Char.ToUpper( s[pos] ) - 'A' + 10; - if( digit >= numBase ) - break; // invalid numeral; force a fail - n = n * (double)numBase + (double)digit; - pos++; - } while( Char.IsLetterOrDigit( s, pos ) ); - if( pos == s.Length - 1 ) // except guard, no invalid trailing characters? - { - lua.PushNumber( negative ? -n : n ); - return 1; - } // else not a number - } // else not a number - } - lua.PushNil(); // not a number - return 1; - } - - public static int B_Type( ILuaState lua ) - { - var t = lua.Type( 1 ); - var tname = lua.TypeName( t ); - lua.PushString( tname ); - return 1; - } - - private static int PairsMeta( ILuaState lua, string method, bool isZero - , CSharpFunctionDelegate iter ) - { - if( !lua.L_GetMetaField( 1, method ) ) // no metamethod? - { - lua.L_CheckType( 1, LuaType.LUA_TTABLE ); - lua.PushCSharpFunction( iter ); - lua.PushValue( 1 ); - if( isZero ) - lua.PushInteger( 0 ); - else - lua.PushNil(); - } - else - { - lua.PushValue( 1 ); - lua.Call( 1, 3 ); - } - return 3; - } - - public static int B_Next( ILuaState lua ) - { - lua.SetTop( 2 ); - if( lua.Next(1) ) - { - return 2; - } - else - { - lua.PushNil(); - return 1; - } - } - static CSharpFunctionDelegate DG_B_Next = B_Next; - - public static int B_Pairs( ILuaState lua ) - { - return PairsMeta( lua, "__pairs", false, DG_B_Next ); - } - - private static int IpairsAux( ILuaState lua ) - { - int i = lua.ToInteger( 2 ); - i++; // next value - lua.PushInteger( i ); - lua.RawGetI( 1, i ); - return lua.IsNil( -1 ) ? 1 : 2; - } - static CSharpFunctionDelegate DG_IpairsAux = IpairsAux; - - public static int B_Ipairs( ILuaState lua ) - { - return PairsMeta( lua, "__ipairs", true, DG_IpairsAux ); - } - - public static int B_Print( ILuaState lua ) - { - StringBuilder sb = new StringBuilder(); - int n = lua.GetTop(); - lua.GetGlobal( "tostring" ); - for( int i=1; i<=n; ++i ) - { - lua.PushValue( -1 ); - lua.PushValue( i ); - lua.Call( 1, 1 ); - string s = lua.ToString( -1 ); - if( s == null ) - return lua.L_Error("'tostring' must return a string to 'print'"); - if( i > 1 ) - sb.Append( "\t" ); - sb.Append( s ); - lua.Pop( 1 ); - } - Console.WriteLine( sb.ToString() ); - return 0; - } - - public static int B_ToString( ILuaState lua ) - { - lua.L_CheckAny( 1 ); - lua.L_ToString( 1 ); - return 1; - } - - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaBitLib.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaBitLib.cs deleted file mode 100644 index 490be6933..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaBitLib.cs +++ /dev/null @@ -1,204 +0,0 @@ -using UniLua; - -namespace UniLua -{ - - internal class LuaBitLib - { - public const string LIB_NAME = "bit32"; - private const int LUA_NBITS = 32; - private const uint ALLONES = ~(~(uint)0 << LUA_NBITS - 1 << 1); - - public static int OpenLib(ILuaState lua) - { - NameFuncPair[] define = new NameFuncPair[] - { - new NameFuncPair( "arshift", B_ArithShift ), - new NameFuncPair( "band", B_And ), - new NameFuncPair( "bnot", B_Not ), - new NameFuncPair( "bor", B_Or ), - new NameFuncPair( "bxor", B_Xor ), - new NameFuncPair( "btest", B_Test ), - new NameFuncPair( "extract", B_Extract ), - new NameFuncPair( "lrotate", B_LeftRotate ), - new NameFuncPair( "lshift", B_LeftShift ), - new NameFuncPair( "replace", B_Replace ), - new NameFuncPair( "rrotate", B_RightRotate ), - new NameFuncPair( "rshift", B_RightShift ), - }; - - lua.L_NewLib(define); - return 1; - } - - private static uint Trim(uint x) - { - return x & ALLONES; - } - - private static uint Mask(int n) - { - return ~(ALLONES << 1 << n - 1); - } - - private static int B_Shift(ILuaState lua, uint r, int i) - { - if (i < 0) // shift right? - { - i = -i; - r = Trim(r); - if (i >= LUA_NBITS) r = 0; - else r >>= i; - } - else // shift left - { - if (i >= LUA_NBITS) r = 0; - else r <<= i; - r = Trim(r); - } - lua.PushUnsigned(r); - return 1; - } - - private static int B_LeftShift(ILuaState lua) - { - return B_Shift(lua, lua.L_CheckUnsigned(1), lua.L_CheckInteger(2)); - } - - private static int B_RightShift(ILuaState lua) - { - return B_Shift(lua, lua.L_CheckUnsigned(1), -lua.L_CheckInteger(2)); - } - - private static int B_ArithShift(ILuaState lua) - { - uint r = lua.L_CheckUnsigned(1); - int i = lua.L_CheckInteger(2); - if (i < 0 || (r & (uint)1 << LUA_NBITS - 1) == 0) - return B_Shift(lua, r, -i); - else // arithmetic shift for `nagetive' number - { - if (i >= LUA_NBITS) - r = ALLONES; - else - r = Trim(r >> i | ~(~(uint)0 >> i)); // add signal bit - lua.PushUnsigned(r); - } - return 1; - } - - private static uint AndAux(ILuaState lua) - { - int n = lua.GetTop(); - uint r = ~(uint)0; - for (int i = 1; i <= n; ++i) - { - r &= lua.L_CheckUnsigned(i); - } - return Trim(r); - } - - private static int B_And(ILuaState lua) - { - uint r = AndAux(lua); - lua.PushUnsigned(r); - return 1; - } - - private static int B_Not(ILuaState lua) - { - uint r = ~lua.L_CheckUnsigned(1); - lua.PushUnsigned(Trim(r)); - return 1; - } - - private static int B_Or(ILuaState lua) - { - int n = lua.GetTop(); - uint r = 0; - for (int i = 1; i <= n; ++i) - { - r |= lua.L_CheckUnsigned(i); - } - lua.PushUnsigned(Trim(r)); - return 1; - } - - private static int B_Xor(ILuaState lua) - { - int n = lua.GetTop(); - uint r = 0; - for (int i = 1; i <= n; ++i) - { - r ^= lua.L_CheckUnsigned(i); - } - lua.PushUnsigned(Trim(r)); - return 1; - } - - private static int B_Test(ILuaState lua) - { - uint r = AndAux(lua); - lua.PushBoolean(r != 0); - return 1; - } - - private static int FieldArgs(ILuaState lua, int farg, out int width) - { - int f = lua.L_CheckInteger(farg); - int w = lua.L_OptInt(farg + 1, 1); - lua.L_ArgCheck(0 <= f, farg, "field cannot be nagetive"); - lua.L_ArgCheck(0 < w, farg + 1, "width must be positive"); - if (f + w > LUA_NBITS) - lua.L_Error("trying to access non-existent bits"); - width = w; - return f; - } - - private static int B_Extract(ILuaState lua) - { - uint r = lua.L_CheckUnsigned(1); - int w; - int f = FieldArgs(lua, 2, out w); - r = r >> f & Mask(w); - lua.PushUnsigned(r); - return 1; - } - - private static int B_Rotate(ILuaState lua, int i) - { - uint r = lua.L_CheckUnsigned(1); - i &= LUA_NBITS - 1; // i = i % NBITS - r = Trim(r); - r = r << i | r >> LUA_NBITS - i; - lua.PushUnsigned(Trim(r)); - return 1; - } - - private static int B_LeftRotate(ILuaState lua) - { - return B_Rotate(lua, lua.L_CheckInteger(2)); - } - - private static int B_RightRotate(ILuaState lua) - { - return B_Rotate(lua, -lua.L_CheckInteger(2)); - } - - private static int B_Replace(ILuaState lua) - { - uint r = lua.L_CheckUnsigned(1); - uint v = lua.L_CheckUnsigned(2); - int w; - int f = FieldArgs(lua, 3, out w); - uint m = Mask(w); - v &= m; //erase bits outside given width - r = r & ~(m << f) | v << f; - lua.PushUnsigned(r); - return 1; - } - - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaCoroLib.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaCoroLib.cs deleted file mode 100644 index 3bf84b9ea..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaCoroLib.cs +++ /dev/null @@ -1,152 +0,0 @@ - -namespace UniLua -{ - - internal class LuaCoroLib - { - public const string LIB_NAME = "coroutine"; - - public static int OpenLib( ILuaState lua ) - { - NameFuncPair[] define = new NameFuncPair[] - { - new NameFuncPair( "create", CO_Create ), - new NameFuncPair( "resume", CO_Resume ), - new NameFuncPair( "running", CO_Running ), - new NameFuncPair( "status", CO_Status ), - new NameFuncPair( "wrap", CO_Wrap ), - new NameFuncPair( "yield", CO_Yield ), - }; - - lua.L_NewLib( define ); - return 1; - } - - private static int CO_Create( ILuaState lua ) - { - lua.L_CheckType( 1, LuaType.LUA_TFUNCTION ); - ILuaState newLua = lua.NewThread(); - lua.PushValue( 1 ); // move function to top - lua.XMove( newLua, 1 ); // move function from lua to newLua - return 1; - } - - private static int AuxResume( ILuaState lua, ILuaState co, int narg ) - { - if(!co.CheckStack(narg)) { - lua.PushString("too many arguments to resume"); - return -1; // error flag - } - if( co.Status == ThreadStatus.LUA_OK && co.GetTop() == 0 ) - { - lua.PushString( "cannot resume dead coroutine" ); - return -1; // error flag - } - lua.XMove( co, narg ); - ThreadStatus status = co.Resume( lua, narg ); - if( status == ThreadStatus.LUA_OK || status == ThreadStatus.LUA_YIELD ) - { - int nres = co.GetTop(); - if(!lua.CheckStack(nres+1)) { - co.Pop(nres); // remove results anyway; - lua.PushString("too many results to resume"); - return -1; // error flag - } - co.XMove( lua, nres ); // move yielded values - return nres; - } - else - { - co.XMove( lua, 1 ); // move error message - return -1; - } - } - - private static int CO_Resume( ILuaState lua ) - { - ILuaState co = lua.ToThread( 1 ); - lua.L_ArgCheck( co != null, 1, "coroutine expected" ); - int r = AuxResume( lua, co, lua.GetTop() - 1 ); - if( r < 0 ) - { - lua.PushBoolean( false ); - lua.Insert( -2 ); - return 2; // return false + error message - } - else - { - lua.PushBoolean( true ); - lua.Insert( -(r+1) ); - return r+1; // return true + `resume' returns - } - } - - private static int CO_Running( ILuaState lua ) - { - bool isMain = lua.PushThread(); - lua.PushBoolean( isMain ); - return 2; - } - - private static int CO_Status( ILuaState lua ) - { - ILuaState co = lua.ToThread( 1 ); - lua.L_ArgCheck( co != null, 1, "coroutine expected" ); - if( (LuaState)lua == (LuaState)co ) - lua.PushString( "running" ); - else switch( co.Status ) - { - case ThreadStatus.LUA_YIELD: - lua.PushString( "suspended" ); - break; - case ThreadStatus.LUA_OK: - { - LuaDebug ar = new LuaDebug(); - if( co.GetStack( 0, ar ) ) // does it have frames? - lua.PushString( "normal" ); - else if( co.GetTop() == 0 ) - lua.PushString( "dead" ); - else - lua.PushString( "suspended" ); - break; - } - default: // some error occurred - lua.PushString( "dead" ); - break; - } - return 1; - } - - private static int CO_AuxWrap( ILuaState lua ) - { - ILuaState co = lua.ToThread( lua.UpvalueIndex(1) ); - int r = AuxResume( lua, co, lua.GetTop() ); - if( r < 0 ) - { - if( lua.IsString( -1 ) ) // error object is a string? - { - lua.L_Where( 1 ); // add extra info - lua.Insert( -2 ); - lua.Concat( 2 ); - } - lua.Error(); - } - return r; - } - - private static int CO_Wrap( ILuaState lua ) - { - CO_Create( lua ); - lua.PushCSharpClosure( CO_AuxWrap, 1 ); - return 1; - } - - private static int CO_Yield( ILuaState lua ) - { - return lua.Yield( lua.GetTop() ); - } - - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaCosmosCryptoLib.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaCosmosCryptoLib.cs deleted file mode 100644 index bd464eb07..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaCosmosCryptoLib.cs +++ /dev/null @@ -1,96 +0,0 @@ - -using acryptohashnet; -using Aura_OS; -using System; -using System.IO; -using System.Linq; -using System.Text; -using UniLua; - -namespace UniLua -{ - internal class LuaCosmosCryptoLib - { - public const string LIB_NAME = "cosmos.crypto"; - - public static int OpenLib(ILuaState lua) - { - NameFuncPair[] define = new NameFuncPair[] - { - new NameFuncPair( "strtomd5", CRYPTO_md5 ), - new NameFuncPair( "strtosha256", CRYPTO_sha256 ), - new NameFuncPair( "strtosha512", CRYPTO_sha512 ), - new NameFuncPair("filetomd5", FILE_CRYPTO_md5), - new NameFuncPair("filetosha256", FILE_CRYPTO_sha256), - new NameFuncPair("filetosha512", FILE_CRYPTO_sha512), - }; - - lua.L_NewLib(define); - return 1; - } - - private static int CRYPTO_md5(ILuaState lua) - { - string input = lua.L_CheckString(1); - var hashBytes = Aura_OS.System.Security.MD5.hash(input); - lua.PushString(hashBytes); - return 1; - } - - private static int CRYPTO_sha256(ILuaState lua) - { - string input = lua.L_CheckString(1); - var hashBytes = Aura_OS.System.Security.Sha256.hash(Encoding.UTF8.GetBytes(input)); - lua.PushString(hashBytes); - return 1; - } - - private static int CRYPTO_sha512(ILuaState lua) - { - string input = lua.L_CheckString(1); - var hashAlgorithm = new SHA512(); - var hashBytes = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(input)); - lua.PushString(ToHexString(hashBytes)); - return 1; - } - - private static int FILE_CRYPTO_md5(ILuaState lua) - { - string filePath = Path.Combine(Kernel.CurrentDirectory, lua.L_CheckString(1)); - var hashAlgorithm = new MD5(); - using (var stream = File.OpenRead(filePath)) - { - var hashBytes = hashAlgorithm.ComputeHash(stream); - lua.PushString(ToHexString(hashBytes)); - } - return 1; - } - - private static int FILE_CRYPTO_sha256(ILuaState lua) - { - string filePath = Path.Combine(Kernel.CurrentDirectory, lua.L_CheckString(1)); - byte[] file = File.ReadAllBytes(filePath); - var hashBytes = Aura_OS.System.Security.Sha256.hash(file); - lua.PushString(hashBytes); - return 1; - } - - private static int FILE_CRYPTO_sha512(ILuaState lua) - { - string filePath = Path.Combine(Kernel.CurrentDirectory, lua.L_CheckString(1)); - var hashAlgorithm = new SHA512(); - using (var stream = File.OpenRead(filePath)) - { - var hashBytes = hashAlgorithm.ComputeHash(stream); - lua.PushString(ToHexString(hashBytes)); - } - return 1; - } - - private static string ToHexString(byte[] bytes) - { - return Aura_OS.Utils.Conversion.Hex(bytes); - } - } -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaDebug.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaDebug.cs deleted file mode 100644 index 9a267e36f..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaDebug.cs +++ /dev/null @@ -1,516 +0,0 @@ - -namespace UniLua -{ - public class LuaDebug - { - public string Name; - public string NameWhat; - public int ActiveCIIndex; - public int CurrentLine; - public int NumUps; - public bool IsVarArg; - public int NumParams; - public bool IsTailCall; - public string Source; - public int LineDefined; - public int LastLineDefined; - public string What; - public string ShortSrc; - } - - public partial class LuaState - { - bool ILuaAPI.GetStack( int level, LuaDebug ar ) - { - if( level < 0 ) - return false; - - int index; - for( index = CI.Index; level > 0 && index > 0; --index ) - { level--; } - - bool status = false; - if( level == 0 && index > 0 ) { - status = true; - ar.ActiveCIIndex = index; - } - return status; - } - - public int GetInfo( string what, LuaDebug ar ) - { - CallInfo ci; - StkId func; - - int pos = 0; - if( what[pos] == '>' ) - { - ci = null; - func = Stack[Top.Index - 1]; - - Utl.ApiCheck(func.V.TtIsFunction(), "function expected"); - pos++; - - Top = Stack[Top.Index-1]; - } - else - { - ci = BaseCI[ar.ActiveCIIndex]; - func = Stack[ci.FuncIndex]; - Utl.Assert(Stack[ci.FuncIndex].V.TtIsFunction()); - } - - // var IsClosure( func.Value ) ? func.Value - int status = AuxGetInfo( what, ar, func, ci ); - if( what.Contains( "f" ) ) - { - Top.V.SetObj(ref func.V); - IncrTop(); - } - if( what.Contains( "L" ) ) - { - CollectValidLines( func ); - } - return status; - } - - private int AuxGetInfo( string what, LuaDebug ar, StkId func, CallInfo ci ) - { - int status = 1; - for( int i=0; i LuaDef.LUA_IDSIZE ) - { - ar.ShortSrc = ar.Source.Substring(0, LuaDef.LUA_IDSIZE); - } - else ar.ShortSrc = ar.Source; - } - - private void AddInfo( string msg ) - { - // var api = (ILuaAPI)this; - // TODO - if( CI.IsLua ) - { - var line = GetCurrentLine(CI); - var src = GetCurrentLuaFunc(CI).Proto.Source; - if( src == null ) - src = "?"; - - // PushString, PushString API - // API ApiIncrTop Top CI.Top - // api.PushString( msg ); - O_PushString( string.Format( "{0}:{1}: {2}", - src, line, msg ) ); - } - } - - internal void G_RunError( string fmt, params object[] args ) - { - AddInfo( string.Format( fmt, args ) ); - G_ErrorMsg(); - } - - private void G_ErrorMsg() - { - if( ErrFunc != 0 ) // is there an error handling function? - { - StkId errFunc = RestoreStack( ErrFunc ); - - if(!errFunc.V.TtIsFunction()) - D_Throw( ThreadStatus.LUA_ERRERR ); - - var below = Stack[Top.Index-1]; - Top.V.SetObj(ref below.V); - below.V.SetObj(ref errFunc.V); - IncrTop(); - - D_Call( below, 1, false ); - } - - D_Throw( ThreadStatus.LUA_ERRRUN ); - } - - private string UpvalName( LuaProto p, int uv ) - { - // TODO - return "(UpvalName:NotImplemented)"; - } - - private string GetUpvalueName( CallInfo ci, StkId o, out string name ) - { - var func = Stack[ci.FuncIndex]; - Utl.Assert(func.V.TtIsFunction() && func.V.ClIsLuaClosure()); - var lcl = func.V.ClLValue(); - for(int i=0; i= a+2 ) - setreg = pc; - break; - } - - case OpCode.OP_CALL: - case OpCode.OP_TAILCALL: { - // effect all registers above base - if( reg >= a ) - setreg = pc; - break; - } - - case OpCode.OP_JMP: { - var b = ins.GETARG_sBx(); - var dest = pc + 1 + b; - // jump is forward and do not skip `lastpc' - if( pc < dest && dest <= lastpc ) - pc += b; // do the jump - break; - } - - case OpCode.OP_TEST: { - // jumped code can change `a' - if( reg == a ) - setreg = pc; - break; - } - - default: { - // any instruction that set A - if( Coder.TestAMode( op ) && reg == a ) { - setreg = pc; - } - break; - } - } - } - return setreg; - } - - private string GetObjName( LuaProto proto, int lastpc, int reg, - out string name ) - { - name = F_GetLocalName( proto, reg+1, lastpc ); - if( name != null ) // is a local? - return "local"; - - // else try symbolic execution - var pc = FindSetReg( proto, lastpc, reg ); - if( pc != -1 ) - { - var ins = proto.Code[pc]; - var op = ins.GET_OPCODE(); - switch( op ) - { - case OpCode.OP_MOVE: { - var b = ins.GETARG_B(); // move from `b' to `a' - if( b < ins.GETARG_A() ) - return GetObjName(proto, pc, b, out name); - break; - } - case OpCode.OP_GETTABUP: - case OpCode.OP_GETTABLE: { - var k = ins.GETARG_C(); - var t = ins.GETARG_B(); - var vn = (op == OpCode.OP_GETTABLE) - ? F_GetLocalName( proto, t+1, pc ) - : UpvalName( proto, t ); - KName( proto, pc, k, out name ); - return (vn == LuaDef.LUA_ENV) ? "global" : "field"; - } - - case OpCode.OP_GETUPVAL: { - name = UpvalName( proto, ins.GETARG_B() ); - return "upvalue"; - } - - case OpCode.OP_LOADK: - case OpCode.OP_LOADKX: { - var b = (op == OpCode.OP_LOADK) - ? ins.GETARG_Bx() - : proto.Code[pc+1].GETARG_Ax(); - var val = proto.K[b]; - if(val.V.TtIsString()) - { - name = val.V.SValue(); - return "constant"; - } - break; - } - - case OpCode.OP_SELF: { - var k = ins.GETARG_C(); // key index - KName( proto, pc, k, out name ); - return "method"; - } - - default: break; // go through to return null - } - } - - return null; // could not find reasonable name - } - - private bool IsInStack( CallInfo ci, StkId o ) - { - // TODO - return false; - } - - private void G_SimpleTypeError( ref TValue o, string op ) - { - string t = ObjTypeName( ref o ); - G_RunError( "attempt to {0} a {1} value", op, t ); - } - - private void G_TypeError( StkId o, string op ) - { - CallInfo ci = CI; - string name = null; - string kind = null; - string t = ObjTypeName(ref o.V); - if( ci.IsLua ) - { - kind = GetUpvalueName( ci, o, out name); - if( kind != null && IsInStack( ci, o ) ) - { - var lcl = Stack[ci.FuncIndex].V.ClLValue(); - kind = GetObjName( lcl.Proto, ci.CurrentPc, - (o.Index - ci.BaseIndex), out name ); - } - } - if( kind != null ) - G_RunError( "attempt to {0} {1} '{2}' (a {3} value)", - op, kind, name, t ); - else - G_RunError( "attempt to {0} a {1} value", op, t ); - } - - private void G_ArithError( StkId p1, StkId p2 ) - { - var n = new TValue(); - if( !V_ToNumber( p1, ref n ) ) - { p2 = p1; } // first operand is wrong - - G_TypeError( p2, "perform arithmetic on" ); - } - - private void G_OrderError( StkId p1, StkId p2 ) - { - string t1 = ObjTypeName(ref p1.V); - string t2 = ObjTypeName(ref p2.V); - if( t1 == t2 ) - G_RunError( "attempt to compare two {0} values", t1 ); - else - G_RunError( "attempt to compare {0} with {1}", t1, t2 ); - } - - private void G_ConcatError( StkId p1, StkId p2 ) - { - // TODO - } - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaDebugLib.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaDebugLib.cs deleted file mode 100644 index 728d20324..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaDebugLib.cs +++ /dev/null @@ -1,25 +0,0 @@ - -namespace UniLua -{ - internal class LuaDebugLib - { - public const string LIB_NAME = "debug"; - - public static int OpenLib( ILuaState lua ) - { - NameFuncPair[] define = new NameFuncPair[] - { - new NameFuncPair( "traceback", DBG_Traceback ), - }; - - lua.L_NewLib( define ); - return 1; - } - - private static int DBG_Traceback( ILuaState lua ) - { - return 0; - } - } -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaEncLib.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaEncLib.cs deleted file mode 100644 index 8ec4efd7b..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaEncLib.cs +++ /dev/null @@ -1,63 +0,0 @@ - using System; -using System.Text; - -namespace UniLua -{ - class LuaEncLib - { - public const string LIB_NAME = "enc"; - - private const string ENC_UTF8 = "utf8"; - - public static int OpenLib( ILuaState lua ) - { - var define = new NameFuncPair[] - { - new NameFuncPair( "encode", ENC_Encode ), - new NameFuncPair( "decode", ENC_Decode ), - }; - - lua.L_NewLib( define ); - - lua.PushString( ENC_UTF8 ); - lua.SetField( -2, "utf8" ); - - return 1; - } - - private static int ENC_Encode( ILuaState lua ) - { - var s = lua.ToString(1); - var e = lua.ToString(2); - if( e != ENC_UTF8 ) - throw new Exception("unsupported encoding:" + e); - - var bytes = Encoding.ASCII.GetBytes(s); - var sb = new StringBuilder(); - for( var i=0; i VirtualFiles; - - public static ILoadInfo OpenFile( string filename ) - { - foreach (var file in VirtualFiles.Keys) - { - if (file == filename) - { - return new BytesLoadInfo(VirtualFiles[filename]); ; - } - } - - return new FileLoadInfo( File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ) ); - } - - public static bool Readable( string filename ) - { - foreach (var file in VirtualFiles.Keys) - { - if (file == filename) - { - return true; - } - } - - try { - using( var stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ) ) { - return true; - } - } - catch( Exception ) { - return false; - } - } - } - - public class FileLoadInfo : ILoadInfo, IDisposable - { - public FileLoadInfo( FileStream stream ) - { - Stream = stream; - Reader = new StreamReader(Stream, System.Text.Encoding.ASCII); - Buf = new Queue(); - } - - public int ReadByte() - { - if( Buf.Count > 0 ) - return (int)Buf.Dequeue(); - else - return Reader.Read(); - } - - public int PeekByte() - { - if( Buf.Count > 0 ) - return (int)Buf.Peek(); - else - { - var c = Reader.Read(); - if( c == -1 ) - return c; - Save( (char)c ); - return c; - } - } - - public void Dispose() - { - Reader.Dispose(); - Stream.Dispose(); - } - - private const string UTF8_BOM = "\u00EF\u00BB\u00BF"; - private FileStream Stream; - private StreamReader Reader; - private Queue Buf; - - private void Save( char b ) - { - Buf.Enqueue( b ); - } - - private void Clear() - { - Buf.Clear(); - } - -#if false - private int SkipBOM() - { - for( var i=0; i>>>>>>>>>>>>>>>>>>> level:" + level ); -#endif - - var node = OpenUpval.First; - LinkedListNode prev = null; - while( node != null ) - { - var upval = node.Value; -#if DEBUG_FIND_UPVALUE - Console.WriteLine("[F_FindUpval] >>>>>>>>>>>>>>>>>>>> upval.V:" + upval.V ); -#endif - if(upval.V.Index < level.Index) - break; - - var next = node.Next; - if(upval.V == level) - return upval; - - prev = node; - node = next; - } - - // not found: create a new one - var ret = new LuaUpvalue(); - ret.V = level; - // ret.Prev = G.UpvalHead; - // ret.Next = G.UpvalHead.Next; - // ret.Next.Prev = ret; - // G.UpvalHead.Next = ret; - - if( prev == null ) - OpenUpval.AddFirst( ret ); - else - OpenUpval.AddAfter( prev, ret ); - -#if DEBUG_FIND_UPVALUE - Console.WriteLine("[F_FindUpval] >>>>>>>>>>>>>>>>>>>> create new one:" + ret.V ); -#endif - - return ret; - } - - private void F_Close( StkId level ) - { - var node = OpenUpval.First; - while( node != null ) - { - var upval = node.Value; - if( upval.V.Index < level.Index ) - break; - - var next = node.Next; - OpenUpval.Remove( node ); - node = next; - - upval.Value.V.SetObj(ref upval.V.V); - upval.V = upval.Value; - } - } - - private string F_GetLocalName( LuaProto proto, int localNumber, int pc ) - { - for( int i=0; - i> 52) & 0x7ffL); - long mantissa = bits & 0xfffffffffffffL; - - // Subnormal numbers; exponent is effectively one higher, - // but there's no extra normalisation bit in the mantissa - if (exponent==0) - { - exponent++; - } - // Normal numbers; leave exponent as it is but add extra - // bit to the front of the mantissa - else - { - mantissa = mantissa | (1L<<52); - } - - // Bias the exponent. It's actually biased by 1023, but we're - // treating the mantissa as m.0 rather than 0.m, so we need - // to subtract another 52 from it. - exponent -= 1075; - - if (mantissa == 0) - { - lua.PushNumber( 0.0 ); - lua.PushNumber( 0.0 ); - return 2; - } - - /* Normalize */ - while((mantissa & 1) == 0) - { /* i.e., Mantissa is even */ - mantissa >>= 1; - exponent++; - } - - double m = (double)mantissa; - double e = (double)exponent; - while( m >= 1 ) - { - m /= 2.0; - e += 1.0; - } - - if( negative ) m = -m; - lua.PushNumber( m ); - lua.PushNumber( e ); - return 2; - } - - private static int Math_Ldexp( ILuaState lua ) - { - lua.PushNumber( lua.L_CheckNumber(1) * Math.Pow(2, lua.L_CheckNumber(2)) ); - return 1; - } - - private static int Math_Log10( ILuaState lua ) - { - lua.PushNumber( Math.Log10( lua.L_CheckNumber(1) ) ); - return 1; - } - - private static int Math_Log( ILuaState lua ) - { - double x = lua.L_CheckNumber(1); - double res; - if( lua.IsNoneOrNil(2) ) - res = Math.Log(x); - else - { - double logBase = lua.L_CheckNumber(2); - if( logBase == 10.0 ) - res = Math.Log10(x); - else - res = Math.Log(x, logBase); - } - lua.PushNumber(res); - return 1; - } - - private static int Math_Max( ILuaState lua ) - { - int n = lua.GetTop(); - double dmax = lua.L_CheckNumber(1); - for( int i=2; i<=n; ++i ) - { - double d = lua.L_CheckNumber(i); - if( d > dmax ) - dmax = d; - } - lua.PushNumber(dmax); - return 1; - } - - private static int Math_Min( ILuaState lua ) - { - int n = lua.GetTop(); - double dmin = lua.L_CheckNumber(1); - for( int i=2; i<=n; ++i ) - { - double d = lua.L_CheckNumber(i); - if( d < dmin ) - dmin = d; - } - lua.PushNumber(dmin); - return 1; - } - - private static int Math_Modf( ILuaState lua ) - { - double d = lua.L_CheckNumber(1); - double c = Math.Ceiling(d); - lua.PushNumber( c ); - lua.PushNumber( d-c ); - return 2; - } - - private static int Math_Pow( ILuaState lua ) - { - lua.PushNumber( Math.Pow( lua.L_CheckNumber(1), - lua.L_CheckNumber(2))); - return 1; - } - - private static int Math_Rad( ILuaState lua ) - { - lua.PushNumber( lua.L_CheckNumber(1) * RADIANS_PER_DEGREE ); - return 1; - } - - private static int Math_Random( ILuaState lua ) - { - double r = RandObj.NextDouble(); - switch( lua.GetTop() ) - { - case 0: // no argument - lua.PushNumber( r ); - break; - case 1: - { - double u = lua.L_CheckNumber(1); - lua.L_ArgCheck( 1.0 <= u, 1, "interval is empty" ); - lua.PushNumber( Math.Floor(r*u) + 1.0 ); // int in [1, u] - break; - } - case 2: - { - double l = lua.L_CheckNumber(1); - double u = lua.L_CheckNumber(2); - lua.L_ArgCheck( l <= u, 2, "interval is empty" ); - lua.PushNumber( Math.Floor(r*(u-l+1)) + l ); // int in [l, u] - break; - } - default: return lua.L_Error( "wrong number of arguments" ); - } - return 1; - } - - private static int Math_RandomSeed( ILuaState lua ) - { - RandObj = new Random( (int)lua.L_CheckUnsigned(1) ); - RandObj.Next(); - return 0; - } - - private static int Math_Sinh( ILuaState lua ) - { - lua.PushNumber( Math.Sinh( lua.L_CheckNumber(1) ) ); - return 1; - } - - private static int Math_Sin( ILuaState lua ) - { - lua.PushNumber( Math.Sin( lua.L_CheckNumber(1) ) ); - return 1; - } - - private static int Math_Sqrt( ILuaState lua ) - { - lua.PushNumber( Math.Sqrt( lua.L_CheckNumber(1) ) ); - return 1; - } - - private static int Math_Tanh( ILuaState lua ) - { - lua.PushNumber( Math.Tanh( lua.L_CheckNumber(1) ) ); - return 1; - } - - private static int Math_Tan( ILuaState lua ) - { - lua.PushNumber( Math.Tan( lua.L_CheckNumber(1) ) ); - return 1; - } - - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaObject.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaObject.cs deleted file mode 100644 index 769f49d00..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaObject.cs +++ /dev/null @@ -1,419 +0,0 @@ - -// #define DEBUG_DUMMY_TVALUE_MODIFY - -namespace UniLua -{ - using System; - using System.Collections.Generic; - using ULDebug = UniLua.Tools.ULDebug; - - public struct TValue - { - private const UInt64 CLOSURE_LUA = 0; // lua closure - private const UInt64 CLOSURE_CS = 1; // c# closure - private const UInt64 CLOSURE_LCS = 2; // light c# closure - - private const UInt64 BOOLEAN_FALSE = 0; - private const UInt64 BOOLEAN_TRUE = 1; - - public int Tt; - public double NValue; - public UInt64 UInt64Value; - public object OValue; -#if DEBUG_DUMMY_TVALUE_MODIFY - public bool Lock_; -#endif - - public override int GetHashCode() - { - return Tt.GetHashCode() ^ NValue.GetHashCode() - ^ UInt64Value.GetHashCode() - ^ (OValue != null ? OValue.GetHashCode() : 0x12345678); - } - public override bool Equals(object o) - { - if(!(o is TValue)) return false; - return Equals((TValue)o); - } - public bool Equals(TValue o) - { - if(Tt != o.Tt || NValue != o.NValue || UInt64Value != o.UInt64Value) - { return false; } - - switch(Tt) { - case (int)LuaType.LUA_TNIL: return true; - case (int)LuaType.LUA_TBOOLEAN: return BValue() == o.BValue(); - case (int)LuaType.LUA_TNUMBER: return NValue == o.NValue; - case (int)LuaType.LUA_TUINT64: return UInt64Value == o.UInt64Value; - case (int)LuaType.LUA_TSTRING: return SValue() == o.SValue(); - default: return System.Object.ReferenceEquals(OValue, o.OValue); - } - } - public static bool operator==(TValue lhs, TValue rhs) - { - return lhs.Equals(rhs); - } - public static bool operator!=(TValue lhs, TValue rhs) - { - return !lhs.Equals(rhs); - } - -#if DEBUG_DUMMY_TVALUE_MODIFY - private void CheckLock() { - if(Lock_) { - UnityEngine.Console.WriteLineError("changing a lock value"); - } - } -#endif - - internal bool TtIsNil() { return Tt == (int)LuaType.LUA_TNIL; } - internal bool TtIsBoolean() { return Tt == (int)LuaType.LUA_TBOOLEAN; } - internal bool TtIsNumber() { return Tt == (int)LuaType.LUA_TNUMBER; } - internal bool TtIsUInt64() { return Tt == (int)LuaType.LUA_TUINT64; } - internal bool TtIsString() { return Tt == (int)LuaType.LUA_TSTRING; } - internal bool TtIsTable() { return Tt == (int)LuaType.LUA_TTABLE; } - internal bool TtIsFunction() { return Tt == (int)LuaType.LUA_TFUNCTION; } - internal bool TtIsThread() { return Tt == (int)LuaType.LUA_TTHREAD; } - - internal bool ClIsLuaClosure() { return UInt64Value == CLOSURE_LUA; } - internal bool ClIsCsClosure() { return UInt64Value == CLOSURE_CS; } - internal bool ClIsLcsClosure() { return UInt64Value == CLOSURE_LCS; } - - internal bool BValue() { return UInt64Value != BOOLEAN_FALSE; } - internal string SValue() { return (string)OValue; } - internal LuaTable HValue() { return OValue as LuaTable; } - internal LuaLClosureValue ClLValue() { return (LuaLClosureValue)OValue; } - internal LuaCsClosureValue ClCsValue() { return (LuaCsClosureValue)OValue; } - internal LuaUserDataValue RawUValue() { return OValue as LuaUserDataValue; } - - internal void SetNilValue() { -#if DEBUG_DUMMY_TVALUE_MODIFY - CheckLock(); -#endif - Tt = (int)LuaType.LUA_TNIL; - NValue = 0.0; - UInt64Value = 0; - OValue = null; - } - internal void SetBValue(bool v) { -#if DEBUG_DUMMY_TVALUE_MODIFY - CheckLock(); -#endif - Tt = (int)LuaType.LUA_TBOOLEAN; - NValue = 0.0; - UInt64Value = v ? BOOLEAN_TRUE : BOOLEAN_FALSE; - OValue = null; - } - internal void SetObj(ref TValue v) { -#if DEBUG_DUMMY_TVALUE_MODIFY - CheckLock(); -#endif - Tt = v.Tt; - NValue = v.NValue; - UInt64Value = v.UInt64Value; - OValue = v.OValue; - } - internal void SetNValue(double v) { -#if DEBUG_DUMMY_TVALUE_MODIFY - CheckLock(); -#endif - Tt = (int)LuaType.LUA_TNUMBER; - NValue = v; - UInt64Value = 0; - OValue = null; - } - internal void SetUInt64Value(UInt64 v) { -#if DEBUG_DUMMY_TVALUE_MODIFY - CheckLock(); -#endif - Tt = (int)LuaType.LUA_TUINT64; - NValue = 0.0; - UInt64Value = v; - OValue = null; - } - internal void SetSValue(string v) { -#if DEBUG_DUMMY_TVALUE_MODIFY - CheckLock(); -#endif - Tt = (int)LuaType.LUA_TSTRING; - NValue = 0.0; - UInt64Value = 0; - OValue = v; - } - internal void SetHValue(LuaTable v) { -#if DEBUG_DUMMY_TVALUE_MODIFY - CheckLock(); -#endif - Tt = (int)LuaType.LUA_TTABLE; - NValue = 0.0; - UInt64Value = 0; - OValue = v; - } - internal void SetThValue(LuaState v) { -#if DEBUG_DUMMY_TVALUE_MODIFY - CheckLock(); -#endif - Tt = (int)LuaType.LUA_TTHREAD; - NValue = 0.0; - UInt64Value = 0; - OValue = v; - } - internal void SetPValue(object v) { -#if DEBUG_DUMMY_TVALUE_MODIFY - CheckLock(); -#endif - Tt = (int)LuaType.LUA_TLIGHTUSERDATA; - NValue = 0.0; - UInt64Value = 0; - OValue = v; - } - internal void SetClLValue(LuaLClosureValue v) { -#if DEBUG_DUMMY_TVALUE_MODIFY - CheckLock(); -#endif - Tt = (int)LuaType.LUA_TFUNCTION; - NValue = 0.0; - UInt64Value = CLOSURE_LUA; - OValue = v; - } - internal void SetClCsValue(LuaCsClosureValue v) { -#if DEBUG_DUMMY_TVALUE_MODIFY - CheckLock(); -#endif - Tt = (int)LuaType.LUA_TFUNCTION; - NValue = 0.0; - UInt64Value = CLOSURE_CS; - OValue = v; - } - internal void SetClLcsValue(CSharpFunctionDelegate v) { -#if DEBUG_DUMMY_TVALUE_MODIFY - CheckLock(); -#endif - Tt = (int)LuaType.LUA_TFUNCTION; - NValue = 0.0; - UInt64Value = CLOSURE_LCS; - OValue = v; - } - - public override string ToString() - { - if (TtIsString()) { - return string.Format("(string, {0})", SValue()); - } else if (TtIsNumber()) { - return string.Format("(number, {0})", NValue); - } else if (TtIsNil()) { - return "(nil)"; - } else { - return string.Format("(type:{0})", Tt); - } - } - } - - public class StkId - { - public TValue V; - - private StkId[] List; - public int Index { get; private set; } - - public void SetList(StkId[] list) { List = list; } - public void SetIndex(int index) { Index = index; } - - public static StkId inc(ref StkId val) - { - var ret = val; - val = val.List[val.Index+1]; - return ret; - } - - public override string ToString() - { - string detail; - if(V.TtIsString()) - { detail = V.SValue().Replace("\n", " "); } - else - { detail = "..."; } - return string.Format("StkId - {0} - {1}", LuaState.TypeName((LuaType)V.Tt), detail); - } - } - - public class LuaLClosureValue - { - public LuaProto Proto; - public LuaUpvalue[] Upvals; - - public LuaLClosureValue(LuaProto p) { - Proto = p; - - Upvals = new LuaUpvalue[p.Upvalues.Count]; - for(int i=0; i Code; - public List K; - public List P; - public List Upvalues; - - public int LineDefined; - public int LastLineDefined; - - public int NumParams; - public bool IsVarArg; - public byte MaxStackSize; - - public string Source; - public List LineInfo; - public List LocVars; - - public LuaProto() - { - Code = new List(); - K = new List(); - P = new List(); - Upvalues = new List(); - LineInfo = new List(); - LocVars = new List(); - } - - public int GetFuncLine( int pc ) - { - return (0 <= pc && pc < LineInfo.Count) ? LineInfo[pc] : 0; - } - } - - public class LuaUpvalue - { - public StkId V; - public StkId Value; - - public LuaUpvalue() - { - Value = new StkId(); - Value.V.SetNilValue(); - - V = Value; - } - } - - public class LuaCsClosureValue - { - public CSharpFunctionDelegate F; - public StkId[] Upvals; - - public LuaCsClosureValue( CSharpFunctionDelegate f ) - { - F = f; - } - - public LuaCsClosureValue( CSharpFunctionDelegate f, int numUpvalues ) - { - F = f; - Upvals = new StkId[numUpvalues]; - for(int i=0; i= path.Length ) - return false; - int end = pos+1; - while( end < path.Length && path[end] != LUA_PATH_SEP[0]) - end++; - - var template = path.Substring( pos, end-pos); - lua.PushString( template ); - - pos = end; - return true; - } - - private static string SearchPath( ILuaState lua, - string name, string path, string sep, string dirsep ) - { - var sb = new StringBuilder(); // to build error message - if( !String.IsNullOrEmpty(sep) ) // non-empty separator? - name = name.Replace( sep, dirsep ); // replace it by `dirsep' - int pos = 0; - while(PushNextTemplate(lua, path, ref pos)) - { - var template = lua.ToString(-1); - string filename = template.Replace( LUA_PATH_MARK, name ); - lua.Remove( -1 ); // remove path template - if( Readable( filename ) ) // does file exist and is readable? - return filename; // return that file name - lua.PushString( string.Format( "\n\tno file '{0}'", filename) ); - lua.Remove( -2 ); // remove file name - sb.Append( lua.ToString(-1) ); // concatenate error msg. entry - } - lua.PushString( sb.ToString() ); // create error message - return null; // not found - } - - private static string FindFile( ILuaState lua, - string name, string pname, string dirsep ) - { - lua.GetField( lua.UpvalueIndex(1), pname ); - string path = lua.ToString( -1 ); - if( path == null ) - lua.L_Error( "'package.{0}' must be a string", pname ); - return SearchPath( lua, name, path, ".", dirsep ); - } - - private static int CheckLoad( ILuaState lua, - bool stat, string filename ) - { - if( stat ) // module loaded successfully? - { - lua.PushString( filename ); // will be 2nd arg to module - return 2; // return open function and file name - } - else return lua.L_Error( - "error loading module '{0}' from file '{1}':\n\t{2}", - lua.ToString(1), filename, lua.ToString(-1) ); - } - - private static int SearcherLua( ILuaState lua ) - { - string name = lua.L_CheckString( 1 ); - string filename = FindFile( lua, name, "path", LUA_LSUBSEP ); - if( filename == null ) - return 1; - return CheckLoad( lua, - (lua.L_LoadFile(filename) == ThreadStatus.LUA_OK), - filename ); - } - - private static int LL_Module( ILuaState lua ) - { - // TODO - return 0; - } - - private static void FindLoader( ILuaState lua, string name ) - { - // will be at index 3 - lua.GetField( lua.UpvalueIndex(1), "searchers" ); - if( ! lua.IsTable(3) ) - lua.L_Error("'package.searchers' must be a table"); - - var sb = new StringBuilder(); - // iterator over available searchers to find a loader - for( int i=1; ; ++i ) - { - lua.RawGetI( 3, i ); // get a searcher - if( lua.IsNil( -1 ) ) // no more searchers? - { - lua.Pop( 1 ); // remove nil - lua.PushString( sb.ToString() ); - lua.L_Error( "module '{0}' not found:{1}", - name, lua.ToString(-1)); - return; - } - - lua.PushString( name ); - lua.Call( 1, 2 ); // call it - if( lua.IsFunction(-2) ) // did it find a loader - return; // module loader found - else if( lua.IsString(-2) ) // searcher returned error message? - { - lua.Pop( 1 ); // return extra return - sb.Append( lua.ToString(-1) ); - } - else - lua.Pop( 2 ); // remove both returns - } - } - - private static int LL_Require( ILuaState lua ) - { - string name = lua.L_CheckString( 1 ); - lua.SetTop( 1 ); - // _LOADED table will be at index 2 - lua.GetField( LuaDef.LUA_REGISTRYINDEX, "_LOADED" ); - // _LOADED[name] - lua.GetField( 2, name ); - // is it there? - if( lua.ToBoolean( -1 ) ) - return 1; // package is already loaded - // else must load package - // remove `GetField' result - lua.Pop( 1 ); - FindLoader( lua, name ); - lua.PushString( name ); // pass name as arg to module loader - lua.Insert( -2 ); // name is 1st arg (before search data) - lua.Call( 2, 1 ); // run loader to load module - if( !lua.IsNil( -1 ) ) // non-nil return? - lua.SetField( 2, name ); // _LOADED[name] = returned value - lua.GetField( 2, name ); - if( lua.IsNil( -1 ) ) // module did not set a value? - { - lua.PushBoolean( true ); // use true as result - lua.PushValue( -1 ); // extra copy to be returned - lua.SetField( 2, name ); // _LOADED[name] = true - } - return 1; - } - - private static int PKG_LoadLib( ILuaState lua ) - { - // TODO - return 0; - } - - private static int PKG_SearchPath( ILuaState lua ) - { - // TODO - return 0; - } - - private static int PKG_SeeAll( ILuaState lua ) - { - // TODO - return 0; - } - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaState.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaState.cs deleted file mode 100644 index 0f8bee968..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaState.cs +++ /dev/null @@ -1,306 +0,0 @@ - -// #define ENABLE_DUMP_STACK - -// #define DEBUG_RECORD_INS - -using System.Collections.Generic; - -namespace UniLua -{ - using InstructionPtr = Pointer; - using ULDebug = UniLua.Tools.ULDebug; - - public struct Pointer - { - private List List; - public int Index { get; set; } - - public T Value - { - get - { - return List[Index]; - } - set - { - List[Index] = value; - } - } - - public T ValueInc - { - get - { - return List[Index++]; - } - set - { - List[Index++] = value; - } - } - - public Pointer( List list, int index ) : this() - { - List = list; - Index = index; - } - - public Pointer( Pointer other ) : this() - { - List = other.List; - Index = other.Index; - } - - public static Pointer operator +( Pointer lhs, int rhs ) - { - return new Pointer( lhs.List, lhs.Index + rhs ); - } - - public static Pointer operator -( Pointer lhs, int rhs ) - { - return new Pointer( lhs.List, lhs.Index - rhs ); - } - } - - public enum CallStatus - { - CIST_NONE = 0, - - CIST_LUA = (1<<0), /* call is running a Lua function */ - CIST_HOOKED = (1<<1), /* call is running a debug hook */ - CIST_REENTRY = (1<<2), /* call is running on same invocation of - luaV_execute of previous call */ - CIST_YIELDED = (1<<3), /* call reentered after suspension */ - CIST_YPCALL = (1<<4), /* call is a yieldable protected call */ - CIST_STAT = (1<<5), /* call has an error status (pcall) */ - CIST_TAIL = (1<<6), /* call was tail called */ - } - - public class CallInfo - { - public CallInfo[] List; - public int Index; - - public int FuncIndex; - public int TopIndex; - - public int NumResults; - public CallStatus CallStatus; - - public CSharpFunctionDelegate ContinueFunc; - public int Context; - public int ExtraIndex; - public bool OldAllowHook; - public int OldErrFunc; - public ThreadStatus Status; - - // for Lua functions - public int BaseIndex; - public InstructionPtr SavedPc; - - public bool IsLua - { - get { return (CallStatus & CallStatus.CIST_LUA) != 0; } - } - - public int CurrentPc - { - get - { - Utl.Assert( IsLua ); - return SavedPc.Index - 1; - } - } - } - - public class GlobalState - { - public StkId Registry; - public LuaUpvalue UpvalHead; - public LuaTable[] MetaTables; - public LuaState MainThread; - - public GlobalState( LuaState state ) - { - MainThread = state; - Registry = new StkId(); - UpvalHead = new LuaUpvalue(); - MetaTables = new LuaTable[(int)LuaType.LUA_NUMTAGS]; - } - } - - public delegate void LuaHookDelegate(ILuaState lua, LuaDebug ar); - - public partial class LuaState - { - public StkId[] Stack; - public StkId Top; - public int StackSize; - public int StackLast; - public CallInfo CI; - public CallInfo[] BaseCI; - public GlobalState G; - public int NumNonYieldable; - public int NumCSharpCalls; - public int ErrFunc; - public ThreadStatus Status { get; set; } - public bool AllowHook; - public byte HookMask; - public int BaseHookCount; - public int HookCount; - public LuaHookDelegate Hook; - - public LinkedList OpenUpval; - -#if DEBUG_RECORD_INS - private Queue InstructionHistory; -#endif - - private ILuaAPI API; - - static LuaState() - { - TheNilValue = new StkId(); - TheNilValue.V.SetNilValue(); - } - - public LuaState( GlobalState g=null ) - { - API = (ILuaAPI)this; - - NumNonYieldable = 1; - NumCSharpCalls = 0; - Hook = null; - HookMask = 0; - BaseHookCount = 0; - AllowHook = true; - ResetHookCount(); - Status = ThreadStatus.LUA_OK; - - if( g == null ) - { - G = new GlobalState(this); - InitRegistry(); - } - else - { - G = g; - } - OpenUpval = new LinkedList(); - ErrFunc = 0; - -#if DEBUG_RECORD_INS - InstructionHistory = new Queue(); -#endif - - InitStack(); - } - - private void IncrTop() - { - StkId.inc(ref Top); - D_CheckStack(0); - } - - private StkId RestoreStack( int index ) - { - return Stack[index]; - } - - private void ApiIncrTop() - { - StkId.inc(ref Top); - // Console.WriteLine( "[ApiIncrTop] ==== Top.Index:" + Top.Index ); - // Console.WriteLine( "[ApiIncrTop] ==== CI.Top.Index:" + CI.Top.Index ); - Utl.ApiCheck( Top.Index <= CI.TopIndex, "stack overflow" ); - } - - private void InitStack() - { - Stack = new StkId[LuaDef.BASIC_STACK_SIZE]; - StackSize = LuaDef.BASIC_STACK_SIZE; - StackLast = LuaDef.BASIC_STACK_SIZE - LuaDef.EXTRA_STACK; - for(int i=0; i {2} {3}" - , i-baseIndex - , i - , inStack ? Stack[i].ToString() : "" - , postfix - ); - - sb.Append( body ).Append("\n"); - } - return sb.ToString(); - } - - public void DumpStack( int baseIndex, string tag="" ) - { -#if ENABLE_DUMP_STACK - Console.WriteLine(DumpStackToString(baseIndex, tag)); -#endif - } - - private void ResetHookCount() - { - HookCount = BaseHookCount; - } - - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaStrLib.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaStrLib.cs deleted file mode 100644 index 4d5913da8..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaStrLib.cs +++ /dev/null @@ -1,937 +0,0 @@ - -namespace UniLua -{ - using StringBuilder = System.Text.StringBuilder; - using Char = System.Char; - using Convert = System.Convert; - - internal static class LuaStrLib - { - public const string LIB_NAME = "string"; - - private const int CAP_UNFINISHED = -1; - private const int CAP_POSITION = -2; - private const int LUA_MAXCAPTURES = 32; - private const char L_ESC = '%'; - private const string FLAGS = "-+ #0"; - private static readonly char[] SPECIALS; - - static LuaStrLib() - { - SPECIALS = "^$*+?.([%-".ToCharArray(); - } - - public static int OpenLib( ILuaState lua ) - { - NameFuncPair[] define = new NameFuncPair[] - { - new NameFuncPair( "byte", Str_Byte ), - new NameFuncPair( "char", Str_Char ), - //new NameFuncPair( "dump", Str_Dump ), - new NameFuncPair( "find", Str_Find ), - new NameFuncPair( "format", Str_Format ), - new NameFuncPair( "gmatch", Str_Gmatch ), - new NameFuncPair( "gsub", Str_Gsub ), - new NameFuncPair( "len", Str_Len ), - new NameFuncPair( "lower", Str_Lower ), - new NameFuncPair( "match", Str_Match ), - new NameFuncPair( "rep", Str_Rep ), - new NameFuncPair( "reverse", Str_Reverse ), - new NameFuncPair( "sub", Str_Sub ), - new NameFuncPair( "upper", Str_Upper ), - }; - - lua.L_NewLib( define ); - CreateMetaTable( lua ); - - return 1; - } - - private static void CreateMetaTable( ILuaState lua ) - { - lua.CreateTable(0, 1); // table to be metatable for strings - lua.PushString( "" ); // dummy string - lua.PushValue( -2 ); // copy table - lua.SetMetaTable( -2 ); // set table as metatable for strings - lua.Pop( 1 ); - lua.PushValue( -2 ); // get string library - lua.SetField( -2, "__index" ); // metatable.__index = string - lua.Pop( 1 ); // pop metatable - } - - private static int PosRelative( int pos, int len ) - { - if( pos >= 0 ) return pos; - else if( 0 - pos > len ) return 0; - else return len - (-pos) + 1; - } - - private static int Str_Byte( ILuaState lua ) - { - string s = lua.L_CheckString(1); - int posi = PosRelative( lua.L_OptInt(2, 1), s.Length ); - int pose = PosRelative( lua.L_OptInt(3, posi), s.Length ); - if( posi < 1 ) posi = 1; - if( pose > s.Length ) pose = s.Length; - if( posi > pose ) return 0; // empty interval; return no values - int n = pose - posi + 1; - if( posi + n <= pose) // overflow? - return lua.L_Error( "string slice too long" ); - lua.L_CheckStack(n, "string slice too long"); - for( int i=0; i= ms.PatternEnd - 1 ) - lua.L_Error( "malformed pattern (missing arguments to '%b')" ); - if( ms.Src[s] != ms.Pattern[p] ) return -1; - else - { - char b = ms.Pattern[p]; - char e = ms.Pattern[p+1]; - int count = 1; - while( ++s < ms.SrcEnd ) - { - if( ms.Src[s] == e ) - { - if( --count == 0 ) return s+1; - } - else if( ms.Src[s] == b ) count++; - } - } - return -1; //string ends out of balance - } - - private static int MaxExpand( MatchState ms, int s, int p, int ep ) - { - int i = 0; // counts maximum expand for item - while( (s+i) < ms.SrcEnd && SingleMatch( ms, ms.Src[s+i], p, ep ) ) - i++; - // keeps trying to match with the maximum repetitions - while( i >= 0 ) - { - int res = Match( ms, (s+i), (ep+1) ); - if( res >= 0 ) return res; - i--; // else didn't match; reduce 1 repetition to try again - } - return -1; - } - - private static int MinExpand( MatchState ms, int s, int p, int ep ) - { - for(;;) - { - int res = Match( ms, s, ep+1 ); - if( res >= 0 ) - return res; - else if( s < ms.SrcEnd && SingleMatch( ms, ms.Src[s], p, ep ) ) - s++; // try with one more repetition - else return -1; - } - } - - private static int CaptureToClose( MatchState ms ) - { - var lua = ms.Lua; - int level=ms.Level; - for( level--; level>=0; level-- ) - { - if( ms.Capture[level].Len == CAP_UNFINISHED ) - return level; - } - return lua.L_Error( "invalid pattern capture" ); - } - - private static int StartCapture( MatchState ms, int s, int p, int what ) - { - var lua = ms.Lua; - int level = ms.Level; - if( level >= LUA_MAXCAPTURES ) - lua.L_Error( "too many captures" ); - ms.Capture[level].Init = s; - ms.Capture[level].Len = what; - ms.Level = level + 1; - int res = Match( ms, s, p ); - if( res == -1 ) // match failed? - ms.Level--; - return res; - } - - private static int EndCapture( MatchState ms, int s, int p ) - { - int l = CaptureToClose( ms ); - ms.Capture[l].Len = s - ms.Capture[l].Init; // close capture - int res = Match( ms, s, p ); - if( res == -1 ) // match failed? - ms.Capture[l].Len = CAP_UNFINISHED; // undo capture - return res; - } - - private static int CheckCapture( MatchState ms, char l ) - { - var lua = ms.Lua; - int i = (int)(l - '1'); - if( i < 0 || i >= ms.Level || ms.Capture[i].Len == CAP_UNFINISHED ) - return lua.L_Error( "invalid capture index %d", i+1 ); - return i; - } - - private static int MatchCapture( MatchState ms, int s, char l ) - { - int i = CheckCapture( ms, l ); - int len = ms.Capture[i].Len; - if( ms.SrcEnd - s >= len && - string.Compare(ms.Src, ms.Capture[i].Init, ms.Src, s, len) == 0 ) - return s + len; - else - return -1; - } - - private static int Match( MatchState ms, int s, int p ) - { - var lua = ms.Lua; - init: // using goto's to optimize tail recursion - if( p == ms.PatternEnd ) - return s; - switch( ms.Pattern[p] ) - { - case '(': // start capture - { - if( ms.Pattern[p+1] == ')' ) // position capture? - return StartCapture( ms, s, p+2, CAP_POSITION ); - else - return StartCapture( ms, s, p+1, CAP_UNFINISHED ); - } - case ')': // end capture - { - return EndCapture( ms, s, p+1 ); - } - case '$': - { - if( p+1 == ms.PatternEnd ) // is the `$' the last char in pattern? - return (s == ms.SrcEnd) ? s : -1; // check end of string - else goto default; - } - case L_ESC: // escaped sequences not in the format class[*+?-]? - { - switch( ms.Pattern[p+1] ) - { - case 'b': // balanced string? - { - s = MatchBalance( ms, s, p+2 ); - if( s == -1 ) return -1; - p += 4; goto init; // else return match(ms, s, p+4); - } - case 'f': // frontier? - { - p += 2; - if( ms.Pattern[p] != '[' ) - lua.L_Error( "missing '[' after '%f' in pattern" ); - int ep = ClassEnd( ms, p ); //points to what is next - char previous = (s == ms.SrcInit) ? '\0' : ms.Src[s-1]; - if( MatchBreaketClass(ms, previous, p, ep-1) || - !MatchBreaketClass(ms, ms.Src[s], p, ep-1) ) return -1; - p = ep; goto init; // else return match( ms, s, ep ); - } - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': // capture results (%0-%9)? - { - s = MatchCapture( ms, s, ms.Pattern[p+1] ); - if( s == -1 ) return -1; - p+=2; goto init; // else return match(ms, s, p+2); - } - default: goto dflt; - } - } - default: dflt: // pattern class plus optional suffix - { - int ep = ClassEnd( ms, p ); - bool m = s < ms.SrcEnd && SingleMatch(ms, ms.Src[s], p, ep); - if(ep < ms.PatternEnd){ - switch(ms.Pattern[ep]) //fix gmatch bug patten is [^a] - { - case '?': // optional - { - if( m ) - { - int res = Match(ms, s+1, ep+1); - if( res != -1 ) - return res; - } - p=ep+1; goto init; // else return match(ms, s, ep+1); - } - case '*': // 0 or more repetitions - { - return MaxExpand(ms, s, p, ep); - } - case '+': // 1 or more repetitions - { - return (m ? MaxExpand(ms, s+1, p, ep) : -1); - } - case '-': // 0 or more repetitions (minimum) - { - return MinExpand(ms, s, p, ep); - } - } - } - if(!m) return -1; - s++; p=ep; goto init; // else return match(ms, s+1, ep); - } - } - } - - private static void PushOneCapture - ( MatchState ms - , int i - , int start - , int end - ) - { - var lua = ms.Lua; - if( i >= ms.Level ) - { - if( i == 0 ) // ms.Level == 0, too - lua.PushString( ms.Src.Substring( start, end-start ) ); - else - lua.L_Error( "invalid capture index" ); - } - else - { - int l = ms.Capture[i].Len; - if( l == CAP_UNFINISHED ) - lua.L_Error( "unfinished capture" ); - if( l == CAP_POSITION ) - lua.PushInteger( ms.Capture[i].Init - ms.SrcInit + 1 ); - else - lua.PushString( ms.Src.Substring( ms.Capture[i].Init, l ) ); - } - } - - private static int PushCaptures(ILuaState lua, MatchState ms, int spos, int epos ) - { - int nLevels = (ms.Level == 0 && spos >= 0) ? 1 : ms.Level; - lua.L_CheckStack(nLevels, "too many captures"); - for( int i=0; i s.Length + 1 ) // start after string's end? - { - lua.PushNil(); // cannot find anything - return 1; - } - // explicit request or no special characters? - if( find && (lua.ToBoolean(4) || NoSpecials(p)) ) - { - // do a plain search - int pos = s.IndexOf( p, init-1 ); - if( pos >= 0 ) - { - lua.PushInteger( pos+1 ); - lua.PushInteger( pos+p.Length ); - return 2; - } - } - else - { - int s1 = init-1; - int ppos = 0; - bool anchor = p[ppos] == '^'; - if( anchor ) - ppos++; // skip anchor character - - MatchState ms = new MatchState(); - ms.Lua = lua; - ms.Src = s; - ms.SrcInit = s1; - ms.SrcEnd = s.Length; - ms.Pattern = p; - ms.PatternEnd = p.Length; - - do - { - ms.Level = 0; - int res = Match( ms, s1, ppos ); - if( res != -1 ) - { - if(find) - { - lua.PushInteger( s1+1 ); // start - lua.PushInteger( res ); // end - return PushCaptures(lua, ms, -1, 0) + 2; - } - else return PushCaptures(lua, ms, s1, res); - } - } while( s1++ < ms.SrcEnd && !anchor ); - } - lua.PushNil(); // not found - return 1; - } - - private static int Str_Find( ILuaState lua ) - { - return StrFindAux( lua, true ); - } - - private static int ScanFormat( ILuaState lua, string format, int s, out string form ) - { - int p = s; - // skip flags - while( p < format.Length && format[p] != '\0' && FLAGS.IndexOf(format[p]) != -1 ) - p++; - if( p - s > FLAGS.Length ) - lua.L_Error( "invalid format (repeat flags)" ); - if( Char.IsDigit( format[p] ) ) p++; // skip width - if( Char.IsDigit( format[p] ) ) p++; // (2 digits at most) - if( format[p] == '.' ) - { - p++; - if( Char.IsDigit( format[p] ) ) p++; // skip precision - if( Char.IsDigit( format[p] ) ) p++; // (2 digits at most) - } - if( Char.IsDigit( format[p] ) ) - lua.L_Error( "invalid format (width of precision too long)" ); - form = "%" + format.Substring( s, (p-s+1) ); - return p; - } - - private static int Str_Format( ILuaState lua ) - { - int top = lua.GetTop(); - StringBuilder sb = new StringBuilder(); - int arg = 1; - string format = lua.L_CheckString( arg ); - int s = 0; - int e = format.Length; - while(s < e) - { - if( format[s] != L_ESC ) - { - sb.Append( format[s++] ); - continue; - } - - if( format[++s] == L_ESC ) - { - sb.Append( format[s++] ); - continue; - } - - // else format item - if( ++arg > top ) - lua.L_ArgError( arg, "no value" ); - - string form; - s = ScanFormat( lua, format, s, out form ); - switch( format[s++] ) // TODO: properly handle form - { - case 'c': - { - sb.Append( (char)lua.L_CheckInteger(arg) ); - break; - } - case 'd': case 'i': - { - int n = lua.L_CheckInteger(arg); - sb.Append( n.ToString() ); - break; - } - case 'u': - { - int n = lua.L_CheckInteger(arg); - lua.L_ArgCheck( n >= 0, arg, - "not a non-negative number is proper range" ); - sb.Append( n.ToString() ); - break; - } - case 'o': - { - int n = lua.L_CheckInteger(arg); - lua.L_ArgCheck( n >= 0, arg, - "not a non-negative number is proper range" ); - sb.Append( Convert.ToString(n, 8) ); - break; - } - case 'x': - { - int n = lua.L_CheckInteger(arg); - lua.L_ArgCheck( n >= 0, arg, - "not a non-negative number is proper range" ); - // sb.Append( string.Format("{0:x}", n) ); - sb.AppendFormat("{0:x}", n); - break; - } - case 'X': - { - int n = lua.L_CheckInteger(arg); - lua.L_ArgCheck( n >= 0, arg, - "not a non-negative number is proper range" ); - // sb.Append( string.Format("{0:X}", n) ); - sb.AppendFormat("{0:X}", n); - break; - } - case 'e': case 'E': - { - sb.AppendFormat("{0:E}", lua.L_CheckNumber(arg)); - break; - } - case 'f': - { - sb.AppendFormat("{0:F}", lua.L_CheckNumber(arg)); - break; - } -#if LUA_USE_AFORMAT - case 'a': case 'A': -#endif - case 'g': case 'G': - { - sb.AppendFormat("{0:G}", lua.L_CheckNumber(arg)); - break; - } - case 'q': - { - AddQuoted(lua, sb, arg); - break; - } - case 's': - { - sb.Append(lua.L_CheckString(arg)); - break; - } - default: // also treat cases `pnLlh' - { - return lua.L_Error( "invalid option '{0}' to 'format'", - format[s-1] ); - } - } - } - lua.PushString( sb.ToString() ); - return 1; - } - - private static void AddQuoted(ILuaState lua, StringBuilder sb, int arg) - { - var s = lua.L_CheckString(arg); - sb.Append('"'); - for(var i=0; i=s.Length || !Char.IsDigit(s[i+1])) { - sb.AppendFormat("\\{0:D}", (int)c); - } - else { - sb.AppendFormat("\\{0:D3}", (int)c); - } - } - else { - sb.Append(c); - } - } - sb.Append('"'); - } - - private static int GmatchAux( ILuaState lua ) - { - MatchState ms = new MatchState(); - string src = lua.ToString( lua.UpvalueIndex(1) ); - string pattern = lua.ToString( lua.UpvalueIndex(2) ); - ms.Lua = lua; - ms.Src = src; - ms.SrcInit = 0; - ms.SrcEnd = src.Length; - ms.Pattern = pattern; - ms.PatternEnd = pattern.Length; - for( int s = lua.ToInteger( lua.UpvalueIndex(3) ) - ; s <= ms.SrcEnd - ; s++ ) - { - ms.Level = 0; - int e = Match( ms, s, 0 ); - if( e != -1 ) - { - int newStart = (e == 0) ? e+1: e; - lua.PushInteger( newStart ); - lua.Replace( lua.UpvalueIndex(3) ); - return PushCaptures(lua, ms, s, e); - } - } - return 0; // not found - } - - private static int Str_Gmatch( ILuaState lua ) - { - lua.L_CheckString(1); - lua.L_CheckString(2); - lua.SetTop(2); - lua.PushInteger(0); - lua.PushCSharpClosure( GmatchAux, 3 ); - return 1; - } - - private static void Add_S (MatchState ms, StringBuilder b, int s, int e) { - string news = ms.Lua.ToString(3); - for (int i = 0; i < news.Length; i++) { - if (news[i] != L_ESC) - b.Append(news[i]); - else { - i++; /* skip ESC */ - if (!Char.IsDigit((news[i]))) - b.Append(news[i]); - else if (news[i] == '0') - b.Append(ms.Src.Substring(s, (e - s))); - else { - PushOneCapture(ms, news[i] - '1', s, e); - b.Append(ms.Lua.ToString(-1)); /* add capture to accumulated result */ - } - } - } - } - - private static void Add_Value (MatchState ms, StringBuilder b, int s, int e) { - ILuaState lua = ms.Lua; - switch (lua.Type(3)) { - case LuaType.LUA_TNUMBER: - case LuaType.LUA_TSTRING: { - Add_S(ms, b, s, e); - return; - } - case LuaType.LUA_TFUNCTION: { - int n; - lua.PushValue(3); - n = PushCaptures(lua, ms, s, e); - lua.Call(n, 1); - break; - } - case LuaType.LUA_TTABLE: { - PushOneCapture(ms, 0, s, e); - lua.GetTable(3); - break; - } - } - if (lua.ToBoolean(-1)==false) { /* nil or false? */ - lua.Pop(1); - b.Append(ms.Src.Substring(s, (e - s))); /* keep original text */ - } - else if (!lua.IsString(-1)) - lua.L_Error("invalid replacement value (a %s)", lua.L_TypeName(-1)); - else - b.Append(lua.ToString(-1)); - } - - private static int Str_Gsub( ILuaState lua ) - { - - string src = lua.L_CheckString(1); - int srcl = src.Length; - string p = lua.L_CheckString(2); - LuaType tr = lua.Type(3); - int max_s = lua.L_OptInt(4, srcl + 1); - int anchor = 0; - if (p[0] == '^') - { - p = p.Substring(1); - anchor = 1; - } - int n = 0; - MatchState ms = new MatchState(); - StringBuilder b = new StringBuilder(srcl); - lua.L_ArgCheck(tr == LuaType.LUA_TNUMBER || tr == LuaType.LUA_TSTRING || - tr == LuaType.LUA_TFUNCTION || tr == LuaType.LUA_TTABLE, 3, - "string/function/table expected"); - ms.Lua = lua; - ms.Src = src; - ms.SrcInit = 0; - ms.SrcEnd = srcl; - ms.Pattern = p; - ms.PatternEnd = p.Length; - int s = 0; - while (n < max_s) { - ms.Level = 0; - int e = Match(ms, s, 0); - if (e != -1) { - n++; - Add_Value(ms, b, s, e); - } - if ((e != -1) && e > s) /* non empty match? */ - s = e; /* skip it */ - else if (s < ms.SrcEnd) - { - char c = src[s]; - ++s; - b.Append(c); - } - else break; - if (anchor != 0) break; - } - b.Append(src.Substring(s, ms.SrcEnd - s)); - lua.PushString(b.ToString()); - lua.PushInteger(n); /* number of substitutions */ - return 2; - } - - private static int Str_Len( ILuaState lua ) - { - string s = lua.L_CheckString(1); - lua.PushInteger( s.Length ); - return 1; - } - - private static int Str_Lower( ILuaState lua ) - { - string s = lua.L_CheckString(1); - lua.PushString( s.ToLower() ); - return 1; - } - - private static int Str_Match( ILuaState lua ) - { - return StrFindAux( lua, false ); - } - - private static int Str_Rep(ILuaState lua) - { - string s = lua.L_CheckString(1); - int n = lua.L_CheckInteger(2); - - StringBuilder sb = new StringBuilder(s.Length * n); - for (int i = 0; i < n; ++i) - sb.Append(s); - - lua.PushString(sb.ToString()); - return 1; - } - - private static int Str_Reverse( ILuaState lua ) - { - string s = lua.L_CheckString(1); - StringBuilder sb = new StringBuilder(s.Length); - for( int i=s.Length-1; i>=0; --i ) - sb.Append( s[i] ); - lua.PushString( sb.ToString() ); - return 1; - } - - private static int Str_Sub( ILuaState lua ) - { - string s = lua.L_CheckString(1); - int start = PosRelative( lua.L_CheckInteger(2), s.Length ); - int end = PosRelative( lua.L_OptInt(3, -1), s.Length ); - if( start < 1 ) start = 1; - if( end > s.Length ) end = s.Length; - if( start <= end ) - lua.PushString( s.Substring(start-1, end-start+1) ); - else - lua.PushString( "" ); - return 1; - } - - private static int Str_Upper( ILuaState lua ) - { - string s = lua.L_CheckString(1); - lua.PushString( s.ToUpper() ); - return 1; - } - - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaTable.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaTable.cs deleted file mode 100644 index ae5f3d2d4..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaTable.cs +++ /dev/null @@ -1,581 +0,0 @@ - -// #define DEBUG_DUMMY_TVALUE_MODIFY - -using System; -using System.Collections.Generic; - -namespace UniLua -{ - using ULDebug = UniLua.Tools.ULDebug; - - public class LuaTable { - public LuaTable MetaTable; - public uint NoTagMethodFlags; - - public LuaTable(LuaState l) { - InitLuaTable(l); - } - - ~LuaTable() - { - Recycle(); - } - - public StkId Get(ref TValue key) - { - if(key.Tt == (int)LuaType.LUA_TNIL) { return TheNilValue; } - - if(IsPositiveInteger(ref key)) - { return GetInt((int)key.NValue); } - - if(key.Tt == (int)LuaType.LUA_TSTRING) - { return GetStr(key.SValue()); } - - var h = key.GetHashCode(); - for(var node = GetHashNode(h); node != null; node = node.Next) { - if(node.Key.V == key) { - { return node.Val; } - } - } - - return TheNilValue; - } - - public StkId GetInt(int key) - { - if(0 < key && key-1 < ArrayPart.Length) - { return ArrayPart[key-1]; } - - var k = new TValue(); - k.SetNValue(key); - for(var node = GetHashNode(ref k); node != null; node = node.Next) { - if(node.Key.V.TtIsNumber() && node.Key.V.NValue == (double)key) { - return node.Val; - } - } - - return TheNilValue; - } - - public StkId GetStr(string key) - { - var h = key.GetHashCode(); - for(var node = GetHashNode(h); node != null; node = node.Next) { - if(node.Key.V.TtIsString() && node.Key.V.SValue() == key) - { return node.Val; } - } - - return TheNilValue; - } - - public void Set(ref TValue key, ref TValue val) - { - var cell = Get(ref key); - if(cell == TheNilValue) { - cell = NewTableKey(ref key); - } - cell.V.SetObj(ref val); - } - - public void SetInt(int key, ref TValue val) - { - var cell = GetInt(key); - if(cell == TheNilValue) { - var k = new TValue(); - k.SetNValue(key); - cell = NewTableKey(ref k); - } - cell.V.SetObj(ref val); - // Console.WriteLine(string.Format("---------------- SetInt {0} -> {1}", key, val)); - // DumpParts(); - } - - /* - ** returns the index of a `key' for table traversals. First goes all - ** elements in the array part, then elements in the hash part. The - ** beginning of a traversal is signaled by -1. - */ - private int FindIndex(StkId key) - { - if(key.V.TtIsNil()) - { return -1; } - - // is `key' inside array part? - int i = ArrayIndex(ref key.V); - if(0 < i && i <= ArrayPart.Length) - { return i-1; } - - var n = GetHashNode(ref key.V); - // check whether `key' is somewhere in the chain - for(;;) { - if(L.V_RawEqualObj(ref n.Key.V, ref key.V)) - { return ArrayPart.Length + n.Index; } - n = n.Next; - - // key not found - if(n == null) { L.G_RunError("invalid key to 'next'"); } - } - } - - public bool Next(StkId key, StkId val) - { - // find original element - int i = FindIndex(key); - - // try first array part - for(i++; i 0 && ArrayPart[j-1].V.TtIsNil()) { - /* there is a boundary in the array part: (binary) search for it */ - uint i = 0; - while(j - i > 1) { - uint m = (i+j)/2; - if(ArrayPart[m-1].V.TtIsNil()) { j = m; } - else { i = m; } - } - return (int)i; - } - /* else must find a boundary in hash part */ - else if(HashPart == DummyHashPart) - return (int)j; - else return UnboundSearch(j); - } } - - public void Resize(int nasize, int nhsize) - { - int oasize = ArrayPart.Length; - var oldHashPart = HashPart; - if(nasize > oasize) // array part must grow? - SetArraryVector(nasize); - - // create new hash part with appropriate size - SetNodeVector(nhsize); - - // array part must shrink? - if(nasize < oasize) { - var oldArrayPart = ArrayPart; - ArrayPart = DummyArrayPart; - // re-insert elements from vanishing slice - for(int i=nasize; i 0 && (v.NValue % 1) == 0 && v.NValue <= int.MaxValue); //fix large number key bug - } - - private HNode GetHashNode(int hashcode) - { - uint n = (uint)hashcode; - return HashPart[n % HashPart.Length]; - } - - private HNode GetHashNode(ref TValue v) - { - if(IsPositiveInteger(ref v)) { return GetHashNode((int)v.NValue); } - - if(v.TtIsString()) { return GetHashNode(v.SValue().GetHashCode()); } - - return GetHashNode(v.GetHashCode()); - } - - private void SetArraryVector(int size) - { - Utl.Assert(size >= ArrayPart.Length); - - var newArrayPart = new StkId[size]; - int i = 0; - for( ; i MAXBITS) { L.G_RunError("table overflow"); } - - size = (1 << lsize); - HashPart = new HNode[size]; - for(int i=0; i 0) { - var node = HashPart[--LastFree]; - if(node.Key.V.TtIsNil()) { return node; } - } - return null; - } - - /* - ** returns the index for `key' if `key' is an appropriate key to live in - ** the array part of the table, -1 otherwise. - */ - private int ArrayIndex(ref TValue k) - { - if(IsPositiveInteger(ref k)) - return (int)k.NValue; - else - return -1; - } - - private static readonly byte[] Log2_ = new byte[] { - 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, - 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 - }; - private int CeilLog2(int x) - { - Utl.Assert(x > 0); - int l = 0; - x--; - while(x >= 256) { l+=8; x>>=8; } - return l + Log2_[x]; - } - - private int CountInt(ref TValue key, ref int[] nums) - { - int k = ArrayIndex(ref key); - if(0 < k && k <= MAXASIZE) { - nums[CeilLog2(k)]++; - return 1; - } - else return 0; - } - - private int NumUseArray(ref int[] nums) - { - int ause = 0; - int i = 1; - for(int lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { - int lc = 0; // counter - int lim = ttlg; - if(lim > ArrayPart.Length) { - lim = ArrayPart.Length; - if(i > lim) { break; } // no more elements to count - } - - // count elements in range (2^(lg-1), 2^lg] - for(; i<=lim; ++i) { - if(!ArrayPart[i-1].V.TtIsNil()) { lc++; } - } - nums[lg] += lc; - ause += lc; - } - return ause; - } - - private int NumUseHash(ref int[] nums, ref int nasize) - { - int totaluse = 0; - int ause = 0; - int i = HashPart.Length; - while(i-- > 0) { - var n = HashPart[i]; - if(!n.Val.V.TtIsNil()) { - ause += CountInt(ref n.Key.V, ref nums); - totaluse++; - } - } - nasize += ause; - return totaluse; - } - - private int ComputeSizes(ref int[] nums, ref int nasize) - { - int a = 0; - int na = 0; - int n = 0; - for(int i=0, tti=1; tti/2 0) { - a += nums[i]; - if(a > tti/2) { - n = tti; - na = a; - } - } - if(a == nasize) { break; } // all elements already conted - } - nasize = n; - Utl.Assert(nasize/2 <= na && na <= nasize); - return na; - } - - private static int[] Nums = new int[MAXBITS + 1]; - private void Rehash(ref TValue k) - { - for(int i=0; i<=MAXBITS; ++i) { Nums[i] = 0; } - - int nasize = NumUseArray(ref Nums); - int totaluse = nasize; - totaluse += NumUseHash(ref Nums, ref nasize); - nasize += CountInt(ref k, ref Nums); - totaluse++; - int na = ComputeSizes(ref Nums, ref nasize); - Resize(nasize, totaluse-na); - } - - private void DumpParts() - { - Console.WriteLine("------------------ [DumpParts] enter -----------------------"); - Console.WriteLine("<< Array Part >>"); - for(var i=0; i>"); - for(var i=0; i LuaLimits.MAX_INT) { - /* table was built with bad purposes: resort to linear search */ - i = 1; - while(!GetInt((int)i).V.TtIsNil()) { i++; } - return (int)(i-1); - } - } - /* now do a binary search between them */ - while(j - i > 1) { - uint m = (i + j) / 2; - if(GetInt((int)m).V.TtIsNil()) { j = m; } - else { i = m; } - } - return (int)i; - } - } -} diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaTableLib.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaTableLib.cs deleted file mode 100644 index 9f8625c34..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/LuaTableLib.cs +++ /dev/null @@ -1,281 +0,0 @@ - -#define LUA_COMPAT_UNPACK - -namespace UniLua -{ - using StringBuilder = System.Text.StringBuilder; - - internal class LuaTableLib - { - public const string LIB_NAME = "table"; - - public static int OpenLib( ILuaState lua ) - { - NameFuncPair[] define = new NameFuncPair[] - { - new NameFuncPair( "concat", TBL_Concat ), - new NameFuncPair( "maxn", TBL_MaxN ), - new NameFuncPair( "insert", TBL_Insert ), - new NameFuncPair( "pack", TBL_Pack ), - new NameFuncPair( "unpack", TBL_Unpack ), - new NameFuncPair( "remove", TBL_Remove ), - new NameFuncPair( "sort", TBL_Sort ), - }; - - lua.L_NewLib( define ); - -#if LUA_COMPAT_UNPACK - // _G.unpack = table.unpack - lua.GetField( -1, "unpack" ); - lua.SetGlobal( "unpack" ); -#endif - - return 1; - } - - private static int TBL_Concat( ILuaState lua ) - { - string sep = lua.L_OptString( 2, "" ); - lua.L_CheckType( 1, LuaType.LUA_TTABLE ); - int i = lua.L_OptInt( 3, 1 ); - int last = lua.L_Opt(4, lua.L_Len(1)); - - StringBuilder sb = new StringBuilder(); - for( ; i max ) max = v; - } - } - lua.PushNumber( max ); - return 1; - } - - private static int AuxGetN( ILuaState lua, int n ) - { - lua.L_CheckType( n, LuaType.LUA_TTABLE ); - return lua.L_Len( n ); - } - - private static int TBL_Insert( ILuaState lua ) - { - int e = AuxGetN(lua, 1) + 1; // first empty element - int pos; // where to insert new element - switch( lua.GetTop() ) - { - case 2: // called with only 2 arguments - { - pos = e; // insert new element at the end - break; - } - case 3: - { - pos = lua.L_CheckInteger(2); // 2nd argument is the position - if( pos > e ) e = pos; // `grow' array if necessary - for( int i=e; i>pos; --i ) // move up elements - { - lua.RawGetI( 1, i-1 ); - lua.RawSetI( 1, i ); // t[i] = t[i-1] - } - break; - } - default: - { - return lua.L_Error( "wrong number of arguments to 'insert'" ); - } - } - lua.RawSetI( 1, pos ); // t[pos] = v - return 0; - } - - private static int TBL_Remove( ILuaState lua ) - { - int e = AuxGetN(lua, 1); - int pos = lua.L_OptInt( 2, e ); - if( !(1 <= pos && pos <= e) ) // position is outside bounds? - return 0; // nothing to remove - lua.RawGetI(1, pos); /* result = t[pos] */ - for( ; pos 0 ) // at least one element? - { - lua.PushValue( 1 ); - lua.RawSetI( -2, 1 ); // insert first element - lua.Replace( 1 ); // move table into index 1 - for( int i=n; i>=2; --i ) // assign other elements - lua.RawSetI( 1, i ); - } - return 1; // return table - } - - private static int TBL_Unpack( ILuaState lua ) - { - lua.L_CheckType( 1, LuaType.LUA_TTABLE ); - int i = lua.L_OptInt( 2, 1 ); - int e = lua.L_OptInt( 3, lua.L_Len(1) ); - if( i > e ) return 0; // empty range - int n = e - i + 1; // number of elements - if( n <= 0 || !lua.CheckStack(n) ) // n <= 0 means arith. overflow - return lua.L_Error( "too many results to unpack" ); - lua.RawGetI( 1, i ); // push arg[i] (avoiding overflow problems - while( i++ < e ) // push arg[i + 1...e] - lua.RawGetI( 1, i ); - return n; - } - - // quick sort //////////////////////////////////////////////////////// - - private static void Set2( ILuaState lua, int i, int j ) - { - lua.RawSetI( 1, i ); - lua.RawSetI( 1, j ); - } - - private static bool SortComp( ILuaState lua, int a, int b ) - { - if( !lua.IsNil(2) ) // function? - { - lua.PushValue( 2 ); - lua.PushValue( a-1 ); // -1 to compensate function - lua.PushValue( b-2 ); // -2 to compensate function add `a' - lua.Call( 2, 1 ); - bool res = lua.ToBoolean( -1 ); - lua.Pop( 1 ); - return res; - } - else /// a < b? - return lua.Compare( a, b, LuaEq.LUA_OPLT ); - } - - private static void AuxSort( ILuaState lua, int l, int u ) - { - while( l < u ) // for tail recursion - { - // sort elements a[l], a[(l+u)/2] and a[u] - lua.RawGetI( 1, l ); - lua.RawGetI( 1, u ); - if( SortComp( lua, -1, -2 ) ) // a[u] < a[l]? - Set2( lua, l, u ); - else - lua.Pop( 2 ); - if( u-l == 1 ) break; // only 2 elements - int i = (l+u) / 2; - lua.RawGetI( 1, i ); - lua.RawGetI( 1, l ); - if( SortComp( lua, -2, -1 ) ) // a[i] < a[l]? - Set2( lua, i, l ); - else - { - lua.Pop( 1 ); // remove a[l] - lua.RawGetI( 1, u ); - if( SortComp( lua, -1, -2 ) ) // a[u] < a[i]? - Set2( lua, i, u ); - else - lua.Pop( 2 ); - } - if( u-l == 2 ) break; // only 3 arguments - lua.RawGetI( 1, i ); // Pivot - lua.PushValue( -1 ); - lua.RawGetI( 1, u-1 ); - Set2(lua, i, u-1); - /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */ - i = l; - int j = u-1; - for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */ - /* repeat ++i until a[i] >= P */ - lua.RawGetI( 1, ++i ); - while( SortComp(lua, -1, -2) ) - { - if (i>=u) lua.L_Error( "invalid order function for sorting" ); - lua.Pop(1); /* remove a[i] */ - lua.RawGetI( 1, ++i ); - } - /* repeat --j until a[j] <= P */ - lua.RawGetI( 1, --j ); - while ( SortComp(lua, -3, -1) ) { - if (j<=l) lua.L_Error( "invalid order function for sorting" ); - lua.Pop(1); /* remove a[j] */ - lua.RawGetI( 1, --j ); - } - if (j= R(A) + 1 */ - OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */ - OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */ - OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */ - - OP_TEST,/* A C if not (R(A) <=> C) then pc++ */ - OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ - - OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */ - OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */ - OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */ - - OP_FORLOOP,/* A sBx R(A)+=R(A+2); - if R(A) - /// basic instruction format - /// - internal enum OpMode - { - iABC, - iABx, - iAsBx, - iAx, - } - - internal class OpCodeMode - { - public bool TMode; - public bool AMode; - public OpArgMask BMode; - public OpArgMask CMode; - public OpMode OpMode; - - public OpCodeMode(bool tMode, bool aMode, OpArgMask bMode, OpArgMask cMode, OpMode opMode) - { - TMode = tMode; - AMode = aMode; - BMode = bMode; - CMode = cMode; - OpMode = opMode; - } - } - - internal static class OpCodeInfo - { - public static OpCodeMode GetMode( OpCode op ) - { - return Info[(int)op]; - } - - private static Dictionary Info; - - static OpCodeInfo() - { - Info = new Dictionary(); - var opCode = OpCode.OP_MOVE; - var opCodeMode = new OpCodeMode(false, true, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iABC); - Info.Add((int)opCode, opCodeMode); - Info.Add( (int)OpCode.OP_LOADK, new OpCodeMode(false, true, OpArgMask.OpArgK, OpArgMask.OpArgN, OpMode.iABx) ); - Info.Add( (int)OpCode.OP_LOADKX, new OpCodeMode(false, true, OpArgMask.OpArgN, OpArgMask.OpArgN, OpMode.iABx) ); - Info.Add( (int)OpCode.OP_LOADBOOL, new OpCodeMode(false, true, OpArgMask.OpArgU, OpArgMask.OpArgU, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_LOADNIL, new OpCodeMode(false, true, OpArgMask.OpArgU, OpArgMask.OpArgN, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_GETUPVAL, new OpCodeMode(false, true, OpArgMask.OpArgU, OpArgMask.OpArgN, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_GETTABUP, new OpCodeMode(false, true, OpArgMask.OpArgU, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_GETTABLE, new OpCodeMode(false, true, OpArgMask.OpArgR, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_SETTABUP, new OpCodeMode(false, false, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_SETUPVAL, new OpCodeMode(false, false, OpArgMask.OpArgU, OpArgMask.OpArgN, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_SETTABLE, new OpCodeMode(false, false, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_NEWTABLE, new OpCodeMode(false, true, OpArgMask.OpArgU, OpArgMask.OpArgU, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_SELF, new OpCodeMode(false, true, OpArgMask.OpArgR, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_ADD, new OpCodeMode(false, true, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_SUB, new OpCodeMode(false, true, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_MUL, new OpCodeMode(false, true, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_DIV, new OpCodeMode(false, true, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_MOD, new OpCodeMode(false, true, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_POW, new OpCodeMode(false, true, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_UNM, new OpCodeMode(false, true, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_NOT, new OpCodeMode(false, true, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_LEN, new OpCodeMode(false, true, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_CONCAT, new OpCodeMode(false, true, OpArgMask.OpArgR, OpArgMask.OpArgR, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_JMP, new OpCodeMode(false, false, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iAsBx) ); - Info.Add( (int)OpCode.OP_EQ, new OpCodeMode(true, false, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_LT, new OpCodeMode(true, false, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_LE, new OpCodeMode(true, false, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_TEST, new OpCodeMode(true, false, OpArgMask.OpArgN, OpArgMask.OpArgU, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_TESTSET, new OpCodeMode(true, true, OpArgMask.OpArgR, OpArgMask.OpArgU, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_CALL, new OpCodeMode(false, true, OpArgMask.OpArgU, OpArgMask.OpArgU, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_TAILCALL, new OpCodeMode(false, true, OpArgMask.OpArgU, OpArgMask.OpArgU, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_RETURN, new OpCodeMode(false, false, OpArgMask.OpArgU, OpArgMask.OpArgN, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_FORLOOP, new OpCodeMode(false, true, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iAsBx) ); - Info.Add( (int)OpCode.OP_FORPREP, new OpCodeMode(false, true, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iAsBx) ); - Info.Add( (int)OpCode.OP_TFORCALL, new OpCodeMode(false, false, OpArgMask.OpArgN, OpArgMask.OpArgU, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_TFORLOOP, new OpCodeMode(false, true, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iAsBx) ); - Info.Add( (int)OpCode.OP_SETLIST, new OpCodeMode(false, false, OpArgMask.OpArgU, OpArgMask.OpArgU, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_CLOSURE, new OpCodeMode(false, true, OpArgMask.OpArgU, OpArgMask.OpArgN, OpMode.iABx) ); - Info.Add( (int)OpCode.OP_VARARG, new OpCodeMode(false, true, OpArgMask.OpArgU, OpArgMask.OpArgN, OpMode.iABC) ); - Info.Add( (int)OpCode.OP_EXTRAARG, new OpCodeMode(false, false, OpArgMask.OpArgU, OpArgMask.OpArgU, OpMode.iAx) ); - } - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Parser.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Parser.cs deleted file mode 100644 index 6a68dc343..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Parser.cs +++ /dev/null @@ -1,1945 +0,0 @@ - -using System; -using System.IO; -using System.Collections.Generic; - -using ULDebug = UniLua.Tools.ULDebug; - -namespace UniLua -{ - using InstructionPtr = Pointer; - - public class FuncState - { - public FuncState Prev; - public BlockCnt Block; - public LuaProto Proto; - public LuaState State; - public LLex Lexer; - - public Dictionary H; - - public int NumActVar; - public int FreeReg; - - public int Pc; - public int LastTarget; - public int Jpc; - public int FirstLocal; - - public FuncState() - { - Proto = new LuaProto(); - H = new Dictionary(); - NumActVar = 0; - FreeReg = 0; - } - - public InstructionPtr GetCode( ExpDesc e ) - { - return new InstructionPtr( Proto.Code, e.Info ); - } - } - - public class BlockCnt - { - public BlockCnt Previous; - public int FirstLabel; - public int FirstGoto; - public int NumActVar; - public bool HasUpValue; - public bool IsLoop; - } - - public class ConstructorControl - { - public ExpDesc ExpLastItem; - public ExpDesc ExpTable; - public int NumRecord; - public int NumArray; - public int NumToStore; - - public ConstructorControl() - { - ExpLastItem = new ExpDesc(); - } - } - - public enum ExpKind - { - VVOID, /* no value */ - VNIL, - VTRUE, - VFALSE, - VK, /* info = index of constant in `k' */ - VKNUM, /* nval = numerical value */ - VNONRELOC, /* info = result register */ - VLOCAL, /* info = local register */ - VUPVAL, /* info = index of upvalue in 'upvalues' */ - VINDEXED, /* t = table register/upvalue; idx = index R/K */ - VJMP, /* info = instruction pc */ - VRELOCABLE, /* info = instruction pc */ - VCALL, /* info = instruction pc */ - VVARARG /* info = instruction pc */ - } - - public static class ExpKindUtl - { - public static bool VKIsVar( ExpKind k ) - { - return ((int)ExpKind.VLOCAL <= (int)k && - (int)k <= (int)ExpKind.VINDEXED); - } - - public static bool VKIsInReg( ExpKind k ) - { - return k == ExpKind.VNONRELOC || k == ExpKind.VLOCAL; - } - } - - public enum BinOpr - { - ADD, - SUB, - MUL, - DIV, - MOD, - POW, - CONCAT, - EQ, - LT, - LE, - NE, - GT, - GE, - AND, - OR, - NOBINOPR, - } - - public enum UnOpr - { - MINUS, - NOT, - LEN, - NOUNOPR, - } - - public class ExpDesc - { - public ExpKind Kind; - - public int Info; - - public struct IndData - { - public int T; - public int Idx; - public ExpKind Vt; - } - public IndData Ind; - - public double NumberValue; - - public int ExitTrue; - public int ExitFalse; - - public void CopyFrom( ExpDesc e ) - { - this.Kind = e.Kind; - this.Info = e.Info; - // this.Ind.T = e.Ind.T; - // this.Ind.Idx = e.Ind.Idx; - // this.Ind.Vt = e.Ind.Vt; - this.Ind = e.Ind; - this.NumberValue = e.NumberValue; - this.ExitTrue = e.ExitTrue; - this.ExitFalse = e.ExitFalse; - } - } - - public class VarDesc - { - public int Index; - } - - public class LabelDesc - { - public string Name; // label identifier - public int Pc; // position in code - public int Line; // line where it appear - public int NumActVar; // local level where it appears in current block - } - - public class LHSAssign - { - public LHSAssign Prev; - public ExpDesc Exp; - - public LHSAssign() { - Prev = null; - Exp = new ExpDesc(); - } - } - - public class Parser - { - public static LuaProto Parse( - ILuaState lua, ILoadInfo loadinfo, string name ) - { - var parser = new Parser(); - parser.Lua = (LuaState)lua; - parser.Lexer = new LLex( lua, loadinfo, name ); - - var topFuncState = new FuncState(); - parser.MainFunc( topFuncState ); - return topFuncState.Proto; - } - - private const int MAXVARS = 200; - - private LLex Lexer; - private FuncState CurFunc; - private List ActVars; - private List PendingGotos; - private List ActiveLabels; - private LuaState Lua; - - private Parser() - { - ActVars = new List(); - PendingGotos = new List(); - ActiveLabels = new List(); - CurFunc = null; - } - - private LuaProto AddPrototype() - { - var p = new LuaProto(); - CurFunc.Proto.P.Add( p ); - return p; - } - - private void CodeClosure( ExpDesc v ) - { - FuncState fs = CurFunc.Prev; - InitExp( v, ExpKind.VRELOCABLE, - Coder.CodeABx( fs, OpCode.OP_CLOSURE, 0, - (uint)(fs.Proto.P.Count-1) ) ); - - // fix it at stack top - Coder.Exp2NextReg( fs, v ); - } - - private void OpenFunc( FuncState fs, BlockCnt block ) - { - fs.Lexer = Lexer; - - fs.Prev = CurFunc; - CurFunc = fs; - - fs.Pc = 0; - fs.LastTarget = 0; - fs.Jpc = Coder.NO_JUMP; - fs.FreeReg = 0; - fs.NumActVar = 0; - fs.FirstLocal = ActVars.Count; - - // registers 0/1 are always valid - fs.Proto.MaxStackSize = 2; - fs.Proto.Source = Lexer.Source; - - EnterBlock( fs, block, false ); - } - - private void CloseFunc() - { - Coder.Ret( CurFunc, 0, 0 ); - - LeaveBlock( CurFunc ); - - CurFunc = CurFunc.Prev; - } - - private void MainFunc( FuncState fs ) - { - ExpDesc v = new ExpDesc(); - var block = new BlockCnt(); - OpenFunc( fs, block ); - fs.Proto.IsVarArg = true; // main func is always vararg - InitExp( v, ExpKind.VLOCAL, 0 ); - NewUpvalue( fs, LuaDef.LUA_ENV, v ); - Lexer.Next(); // read first token - StatList(); - // check TK_EOS - CloseFunc(); - } - - private bool BlockFollow( bool withUntil ) - { - switch( Lexer.Token.TokenType ) - { - case (int)TK.ELSE: - case (int)TK.ELSEIF: - case (int)TK.END: - case (int)TK.EOS: - return true; - - case (int)TK.UNTIL: - return withUntil; - - default: - return false; - } - } - - private bool TestNext( int tokenType ) - { - if( Lexer.Token.TokenType == tokenType ) - { - Lexer.Next(); - return true; - } - else return false; - } - - private void Check( int tokenType ) - { - if( Lexer.Token.TokenType != tokenType ) - ErrorExpected( tokenType ); - } - - private void CheckNext( int tokenType ) - { - Check( tokenType ); - Lexer.Next(); - } - - private void CheckCondition( bool cond, string msg ) - { - if( !cond ) - Lexer.SyntaxError( msg ); - } - - private void EnterLevel() - { - ++Lua.NumCSharpCalls; - CheckLimit( CurFunc, Lua.NumCSharpCalls, - LuaLimits.LUAI_MAXCCALLS, "C# levels" ); - } - - private void LeaveLevel() - { - --Lua.NumCSharpCalls; - } - - private void SemanticError( string msg ) - { - // TODO - Lexer.SyntaxError( msg ); - } - - private void ErrorLimit( FuncState fs, int limit, string what ) - { - int line = fs.Proto.LineDefined; - string where = (line == 0) - ? "main function" - : string.Format("function at line {0}", line); - string msg = string.Format("too many {0} (limit is {1}) in {2}", - what, limit, where); - Lexer.SyntaxError( msg ); - } - - private void CheckLimit( FuncState fs, int v, int l, string what ) - { - if( v > l ) - ErrorLimit( fs, l, what ); - } - - private int RegisterLocalVar( string varname ) - { - var v = new LocVar(); - v.VarName = varname; - v.StartPc = 0; - v.EndPc = 0; - CurFunc.Proto.LocVars.Add(v); - return CurFunc.Proto.LocVars.Count - 1; - } - - private VarDesc NewLocalVar( string name ) - { - var fs = CurFunc; - int reg = RegisterLocalVar( name ); - CheckLimit( fs, ActVars.Count + 1 - fs.FirstLocal, - MAXVARS, "local variables"); - var v = new VarDesc(); - v.Index = reg; - return v; - } - - private LocVar GetLocalVar( FuncState fs, int i ) - { - int idx = ActVars[fs.FirstLocal + i].Index; - Utl.Assert( idx < fs.Proto.LocVars.Count ); - return fs.Proto.LocVars[idx]; - } - - private void AdjustLocalVars( int nvars ) - { - var fs = CurFunc; - fs.NumActVar += nvars; - for( ; nvars > 0; --nvars ) - { - var v = GetLocalVar( fs, fs.NumActVar - nvars ); - v.StartPc = fs.Pc; - } - } - - private void RemoveVars( FuncState fs, int toLevel ) - { - var len = fs.NumActVar - toLevel; - while( fs.NumActVar > toLevel ) - { - var v = GetLocalVar( fs, --fs.NumActVar ); - v.EndPc = fs.Pc; - } - ActVars.RemoveRange( ActVars.Count-len, len ); - } - - private void CloseGoto( int g, LabelDesc label ) - { - var gt = PendingGotos[g]; - Utl.Assert( gt.Name == label.Name ); - if( gt.NumActVar < label.NumActVar ) - { - var v = GetLocalVar( CurFunc, gt.NumActVar ); - var msg = string.Format( - " at line {1} jumps into the scope of local '{2}'", - gt.Name, gt.Line, v.VarName); - SemanticError( msg ); - } - Coder.PatchList( CurFunc, gt.Pc, label.Pc ); - - PendingGotos.RemoveAt(g); - } - - // try to close a goto with existing labels; this solves backward jumps - private bool FindLabel( int g ) - { - var gt = PendingGotos[g]; - var block = CurFunc.Block; - for( int i=block.FirstLabel; i label.NumActVar && - (block.HasUpValue || ActiveLabels.Count > block.FirstLabel) ) - { - Coder.PatchClose( CurFunc, gt.Pc, label.NumActVar ); - } - CloseGoto( g, label ); - return true; - } - } - return false; - } - - private LabelDesc NewLebelEntry( string name, int line, int pc ) - { - var desc = new LabelDesc(); - desc.Name = name; - desc.Pc = pc; - desc.Line = line; - desc.NumActVar = CurFunc.NumActVar; - return desc; - } - - // check whether new label `label' matches any pending gotos in current - // block; solves forward jumps - private void FindGotos( LabelDesc label ) - { - int i = CurFunc.Block.FirstGoto; - while( i < PendingGotos.Count ) - { - if( PendingGotos[i].Name == label.Name ) - CloseGoto( i, label ); - else - ++i; - } - } - - // "export" pending gotos to outer level, to check them against - // outer labels; if the block being exited has upvalues, and - // the goto exits the scope of any variable (which can be the - // upvalue), close those variables being exited. - private void MoveGotosOut( FuncState fs, BlockCnt block ) - { - int i = block.FirstGoto; - - // correct pending gotos to current block and try to close it - // with visible labels - while( i < PendingGotos.Count ) - { - var gt = PendingGotos[i]; - if( gt.NumActVar > block.NumActVar ) - { - if( block.HasUpValue ) - Coder.PatchClose( fs, gt.Pc, block.NumActVar ); - gt.NumActVar = block.NumActVar; - } - if( !FindLabel(i) ) - ++i; // move to next one - } - } - - // create a label named `break' to resolve break statements - private void BreakLabel() - { - var desc = NewLebelEntry( "break", 0, CurFunc.Pc ); - ActiveLabels.Add( desc ); - FindGotos( ActiveLabels[ActiveLabels.Count-1] ); - } - - // generates an error for an undefined `goto'; choose appropriate - // message when label name is a reserved word (which can only be `break') - private void UndefGoto( LabelDesc gt ) - { - string template = Lexer.IsReservedWord( gt.Name ) - ? "<{0}> at line {1} not inside a loop" - : "no visible label '{0}' for at line {1}"; - var msg = string.Format( template, gt.Name, gt.Line ); - SemanticError( msg ); - } - - private void EnterBlock( FuncState fs, BlockCnt block, bool isLoop ) - { - block.IsLoop = isLoop; - block.NumActVar = fs.NumActVar; - block.FirstLabel = ActiveLabels.Count; - block.FirstGoto = PendingGotos.Count; - block.HasUpValue = false; - block.Previous = fs.Block; - fs.Block = block; - Utl.Assert( fs.FreeReg == fs.NumActVar ); - } - - private void LeaveBlock( FuncState fs ) - { - var block = fs.Block; - - if( block.Previous != null && block.HasUpValue ) - { - int j = Coder.Jump( fs ); - Coder.PatchClose( fs, j, block.NumActVar ); - Coder.PatchToHere( fs, j ); - } - - if( block.IsLoop ) - BreakLabel(); - - fs.Block = block.Previous; - RemoveVars( fs, block.NumActVar ); - Utl.Assert( block.NumActVar == fs.NumActVar ); - fs.FreeReg = fs.NumActVar; // free registers - ActiveLabels.RemoveRange( block.FirstLabel, - ActiveLabels.Count - block.FirstLabel ); - - // inner block? - if( block.Previous != null ) - MoveGotosOut( fs, block ); - - // pending gotos in outer block? - else if( block.FirstGoto < PendingGotos.Count ) - UndefGoto( PendingGotos[block.FirstGoto] ); // error - } - - private UnOpr GetUnOpr( int op ) - { - switch( op ) - { - case (int)TK.NOT: - return UnOpr.NOT; - case (int)'-': - return UnOpr.MINUS; - case (int)'#': - return UnOpr.LEN; - default: - return UnOpr.NOUNOPR; - } - } - - private BinOpr GetBinOpr( int op ) - { - switch( op ) - { - case (int)'+': return BinOpr.ADD; - case (int)'-': return BinOpr.SUB; - case (int)'*': return BinOpr.MUL; - case (int)'/': return BinOpr.DIV; - case (int)'%': return BinOpr.MOD; - case (int)'^': return BinOpr.POW; - case (int)TK.CONCAT: return BinOpr.CONCAT; - case (int)TK.NE: return BinOpr.NE; - case (int)TK.EQ: return BinOpr.EQ; - case (int)'<': return BinOpr.LT; - case (int)TK.LE: return BinOpr.LE; - case (int)'>': return BinOpr.GT; - case (int)TK.GE: return BinOpr.GE; - case (int)TK.AND: return BinOpr.AND; - case (int)TK.OR: return BinOpr.OR; - default: return BinOpr.NOBINOPR; - } - } - - private int GetBinOprLeftPrior( BinOpr opr ) - { - switch( opr ) - { - case BinOpr.ADD: return 6; - case BinOpr.SUB: return 6; - case BinOpr.MUL: return 7; - case BinOpr.DIV: return 7; - case BinOpr.MOD: return 7; - case BinOpr.POW: return 10; - case BinOpr.CONCAT: return 5; - case BinOpr.EQ: return 3; - case BinOpr.LT: return 3; - case BinOpr.LE: return 3; - case BinOpr.NE: return 3; - case BinOpr.GT: return 3; - case BinOpr.GE: return 3; - case BinOpr.AND: return 2; - case BinOpr.OR: return 1; - case BinOpr.NOBINOPR: - throw new Exception("GetBinOprLeftPrior(NOBINOPR)"); - default: - throw new Exception("Unknown BinOpr"); - } - } - - private int GetBinOprRightPrior( BinOpr opr ) - { - switch( opr ) - { - case BinOpr.ADD: return 6; - case BinOpr.SUB: return 6; - case BinOpr.MUL: return 7; - case BinOpr.DIV: return 7; - case BinOpr.MOD: return 7; - case BinOpr.POW: return 9; - case BinOpr.CONCAT: return 4; - case BinOpr.EQ: return 3; - case BinOpr.LT: return 3; - case BinOpr.LE: return 3; - case BinOpr.NE: return 3; - case BinOpr.GT: return 3; - case BinOpr.GE: return 3; - case BinOpr.AND: return 2; - case BinOpr.OR: return 1; - case BinOpr.NOBINOPR: - throw new Exception("GetBinOprRightPrior(NOBINOPR)"); - default: - throw new Exception("Unknown BinOpr"); - } - } - - private const int UnaryPrior = 8; - - // statlist -> { stat [';'] } - private void StatList() - { - while( ! BlockFollow( true ) ) - { - if( Lexer.Token.TokenType == (int)TK.RETURN ) - { - Statement(); - return; // 'return' must be last statement - } - Statement(); - } - } - - // fieldsel -> ['.' | ':'] NAME - private void FieldSel( ExpDesc v ) - { - var fs = CurFunc; - var key = new ExpDesc(); - Coder.Exp2AnyRegUp( fs, v ); - Lexer.Next(); // skip the dot or colon - CodeString( key, CheckName() ); - Coder.Indexed( fs, v, key ); - } - - // cond -> exp - private int Cond() - { - var v = new ExpDesc(); - Expr( v ); // read condition - - // `falses' are all equal here - if( v.Kind == ExpKind.VNIL ) - v.Kind = ExpKind.VFALSE; - - Coder.GoIfTrue( CurFunc, v ); - return v.ExitFalse; - } - - private void GotoStat( int pc ) - { - string label; - if( TestNext( (int)TK.GOTO ) ) - label = CheckName(); - else - { - Lexer.Next(); - label = "break"; - } - - PendingGotos.Add( NewLebelEntry( label, Lexer.LineNumber, pc ) ); - - // close it if label already defined - FindLabel( PendingGotos.Count-1 ); - } - - // check for repeated labels on the same block - private void CheckRepeated( FuncState fs, List list, string label ) - { - for( int i = fs.Block.FirstLabel; i < list.Count; ++i ) - { - if( label == list[i].Name ) - { - SemanticError( string.Format( - "label '{0}' already defined on line {1}", - label, list[i].Line ) ); - } - } - } - - // skip no-op statements - private void SkipNoOpStat() - { - while( Lexer.Token.TokenType == (int)';' || - Lexer.Token.TokenType == (int)TK.DBCOLON ) - { - Statement(); - } - } - - private void LabelStat( string label, int line ) - { - var fs = CurFunc; - CheckRepeated( fs, ActiveLabels, label ); - CheckNext( (int)TK.DBCOLON ); - - var desc = NewLebelEntry( label, line, fs.Pc ); - ActiveLabels.Add( desc ); - SkipNoOpStat(); - if( BlockFollow( false ) ) - { - // assume that locals are already out of scope - desc.NumActVar = fs.Block.NumActVar; - } - FindGotos( desc ); - } - - // whilestat -> WHILE cond DO block END - private void WhileStat( int line ) - { - var fs = CurFunc; - var block = new BlockCnt(); - - Lexer.Next(); // skip WHILE - int whileInit = Coder.GetLabel( fs ); - int condExit = Cond(); - EnterBlock( fs, block, true ); - CheckNext( (int)TK.DO ); - Block(); - Coder.JumpTo( fs, whileInit ); - CheckMatch( (int)TK.END, (int)TK.WHILE, line ); - LeaveBlock( fs ); - Coder.PatchToHere( fs, condExit ); - } - - // repeatstat -> REPEAT block UNTIL cond - private void RepeatStat( int line ) - { - var fs = CurFunc; - int repeatInit = Coder.GetLabel( fs ); - var blockLoop = new BlockCnt(); - var blockScope = new BlockCnt(); - EnterBlock( fs, blockLoop, true ); - EnterBlock( fs, blockScope, false ); - Lexer.Next(); - StatList(); - CheckMatch( (int)TK.UNTIL, (int)TK.REPEAT, line ); - int condExit = Cond(); - if( blockScope.HasUpValue ) - { - Coder.PatchClose( fs, condExit, blockScope.NumActVar ); - } - LeaveBlock( fs ); - Coder.PatchList( fs, condExit, repeatInit ); // close the loop - LeaveBlock( fs ); - } - - private int Exp1() - { - var e = new ExpDesc(); - Expr( e ); - Coder.Exp2NextReg( CurFunc, e ); - Utl.Assert( e.Kind == ExpKind.VNONRELOC ); - return e.Info; - } - - // forbody -> DO block - private void ForBody( int t, int line, int nvars, bool isnum ) - { - var fs = CurFunc; - var block = new BlockCnt(); - AdjustLocalVars( 3 ); // control variables - CheckNext( (int)TK.DO ); - int prep = isnum ? Coder.CodeAsBx( fs, OpCode.OP_FORPREP, t, Coder.NO_JUMP ) - : Coder.Jump( fs ); - EnterBlock( fs, block, false ); - AdjustLocalVars( nvars ); - Coder.ReserveRegs( fs, nvars ); - Block(); - LeaveBlock( fs ); - Coder.PatchToHere( fs, prep ); - - int endfor; - if( isnum ) // numeric for? - { - endfor = Coder.CodeAsBx( fs, OpCode.OP_FORLOOP, t, Coder.NO_JUMP ); - } - else // generic for - { - Coder.CodeABC( fs, OpCode.OP_TFORCALL, t, 0, nvars ); - Coder.FixLine( fs, line ); - endfor = Coder.CodeAsBx( fs, OpCode.OP_TFORLOOP, t+2, Coder.NO_JUMP ); - } - Coder.PatchList( fs, endfor, prep+1 ); - Coder.FixLine( fs, line ); - } - - // fornum -> NAME = exp1,expe1[,exp1] forbody - private void ForNum( string varname, int line ) - { - var fs = CurFunc; - var save = fs.FreeReg; - ActVars.Add( NewLocalVar("(for index)") ); - ActVars.Add( NewLocalVar("(for limit)") ); - ActVars.Add( NewLocalVar("(for step)") ); - ActVars.Add( NewLocalVar(varname) ); - CheckNext( (int)'=' ); - Exp1(); // initial value - CheckNext( (int)',' ); - Exp1(); // limit - if( TestNext( (int)',' ) ) - { - Exp1(); // optional step - } - else // default step = 1 - { - Coder.CodeK( fs, fs.FreeReg, Coder.NumberK( fs, 1 ) ); - Coder.ReserveRegs( fs, 1 ); - } - ForBody( save, line, 1, true ); - } - - // forlist -> NAME {,NAME} IN explist forbody - private void ForList( string indexName ) - { - var fs = CurFunc; - var e = new ExpDesc(); - int nvars = 4; // gen, state, control, plus at least one declared var - int save = fs.FreeReg; - - // create control variables - ActVars.Add( NewLocalVar("(for generator)") ); - ActVars.Add( NewLocalVar("(for state)") ); - ActVars.Add( NewLocalVar("(for control)") ); - - // create declared variables - ActVars.Add( NewLocalVar( indexName ) ); - while( TestNext( (int)',' ) ) - { - ActVars.Add( NewLocalVar( CheckName() ) ); - nvars++; - } - CheckNext( (int)TK.IN ); - int line = Lexer.LineNumber; - AdjustAssign( 3, ExpList(e), e ); - Coder.CheckStack( fs, 3 ); // extra space to call generator - ForBody( save, line, nvars-3, false ); - } - - // forstat -> FOR (fornum | forlist) END - private void ForStat( int line ) - { - var fs = CurFunc; - var block = new BlockCnt(); - EnterBlock( fs, block, true ); - Lexer.Next(); // skip `for' - string varname = CheckName(); - switch( Lexer.Token.TokenType ) - { - case (int)'=': ForNum( varname, line ); break; - case (int)',': case (int)TK.IN: ForList( varname ); break; - default: Lexer.SyntaxError("'=' or 'in' expected"); break; - } - CheckMatch( (int)TK.END, (int)TK.FOR, line ); - LeaveBlock( fs ); - } - - // test_then_block -> [IF | ELSEIF] cond THEN block - private int TestThenBlock( int escapeList ) - { - var fs = CurFunc; - var block = new BlockCnt(); - int jf; // instruction to skip `then' code (if condition is false) - - // skip IF or ELSEIF - Lexer.Next(); - - // read condition - var v = new ExpDesc(); - Expr( v ); - - CheckNext( (int)TK.THEN ); - if( Lexer.Token.TokenType == (int)TK.GOTO || - Lexer.Token.TokenType == (int)TK.BREAK ) - { - // will jump to label if condition is true - Coder.GoIfFalse( CurFunc, v ); - - // must enter block before `goto' - EnterBlock( fs, block, false ); - - // handle goto/break - GotoStat( v.ExitTrue ); - - // skip other no-op statements - SkipNoOpStat(); - - // `goto' is the entire block? - if( BlockFollow( false ) ) - { - LeaveBlock( fs ); - return escapeList; - } - else - { - jf = Coder.Jump( fs ); - } - } - // regular case (not goto/break) - else - { - // skip over block if condition is false - Coder.GoIfTrue( CurFunc, v ); - EnterBlock( fs, block, false ); - jf = v.ExitFalse; - } - - // `then' part - StatList(); - LeaveBlock( fs ); - - // followed by `else' or `elseif' - if( Lexer.Token.TokenType == (int)TK.ELSE || - Lexer.Token.TokenType == (int)TK.ELSEIF ) - { - // must jump over it - escapeList = Coder.Concat( fs, escapeList, Coder.Jump(fs) ); - } - Coder.PatchToHere( fs, jf ); - return escapeList; - } - - // ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END - private void IfStat( int line ) - { - var fs = CurFunc; - - // exit list for finished parts - int escapeList = Coder.NO_JUMP; - - // IF cond THEN block - escapeList = TestThenBlock( escapeList ); - - // ELSEIF cond THEN block - while( Lexer.Token.TokenType == (int)TK.ELSEIF ) - escapeList = TestThenBlock( escapeList ); - - // `else' part - if( TestNext( (int)TK.ELSE ) ) - Block(); - - CheckMatch( (int)TK.END, (int)TK.IF, line ); - Coder.PatchToHere( fs, escapeList ); - } - - private void LocalFunc() - { - var b = new ExpDesc(); - var fs = CurFunc; - var v = NewLocalVar(CheckName()); - ActVars.Add(v); - AdjustLocalVars(1); /// enter its scope - Body( b, false, Lexer.LineNumber ); - GetLocalVar( fs, b.Info ).StartPc = fs.Pc; - } - - // stat -> LOCAL NAME {`,' NAME} [`=' explist] - private void LocalStat() - { - int nvars = 0; - int nexps; - var e = new ExpDesc(); - do { - var v = NewLocalVar( CheckName() ); - ActVars.Add(v); - ++nvars; - } while( TestNext( (int)',' ) ); - - if( TestNext( (int)'=' ) ) - nexps = ExpList( e ); - else - { - e.Kind = ExpKind.VVOID; - nexps = 0; - } - AdjustAssign( nvars, nexps, e ); - AdjustLocalVars( nvars ); - } - - // funcname -> NAME {fieldsel} [`:' NAME] - private bool FuncName( ExpDesc v ) - { - SingleVar( v ); - while( Lexer.Token.TokenType == (int)'.' ) - { - FieldSel( v ); - } - if( Lexer.Token.TokenType == (int)':' ) - { - FieldSel( v ); - return true; // is method - } - else - { - return false; - } - } - - // funcstat -> FUNCTION funcname BODY - private void FuncStat( int line ) - { - var v = new ExpDesc(); - var b = new ExpDesc(); - Lexer.Next(); - bool isMethod = FuncName( v ); - Body( b, isMethod, line ); - Coder.StoreVar( CurFunc, v, b ); - Coder.FixLine( CurFunc, line ); - } - - // stat -> func | assignment - private void ExprStat() - { - var v = new LHSAssign(); - SuffixedExp( v.Exp ); - - // stat -> assignment ? - if( Lexer.Token.TokenType == (int)'=' || - Lexer.Token.TokenType == (int)',' ) - { - v.Prev = null; - Assignment( v, 1 ); - } - - // stat -> func - else - { - if( v.Exp.Kind != ExpKind.VCALL ) - Lexer.SyntaxError("syntax error"); - - var pi = CurFunc.GetCode( v.Exp ); - pi.Value = pi.Value.SETARG_C( 1 ); // call statment uses no results - } - } - - // stat -> RETURN [explist] [';'] - private void RetStat() - { - var fs = CurFunc; - int first, nret; // registers with returned values - if( BlockFollow( true ) || Lexer.Token.TokenType == (int)';' ) - { - first = nret = 0; // return no values - } - else - { - var e = new ExpDesc(); - nret = ExpList( e ); - if( HasMultiRet( e.Kind ) ) - { - Coder.SetMultiRet( fs, e ); - if( e.Kind == ExpKind.VCALL && nret == 1 ) // tail call? - { - var pi = fs.GetCode(e); - pi.Value = pi.Value.SET_OPCODE( OpCode.OP_TAILCALL ); - Utl.Assert( pi.Value.GETARG_A() == fs.NumActVar ); - } - first = fs.NumActVar; - nret = LuaDef.LUA_MULTRET; - } - else - { - if( nret == 1 ) // only one single value - { - first = Coder.Exp2AnyReg( fs, e ); - } - else - { - Coder.Exp2NextReg( fs, e ); // values must go to the `stack' - first = fs.NumActVar; - Utl.Assert( nret == fs.FreeReg - first ); - } - } - } - Coder.Ret( fs, first, nret ); - TestNext( (int)';' ); // skip optional semicolon - } - - private void Statement() - { - // Console.WriteLine("Statement ::" + Lexer.Token); - int line = Lexer.LineNumber; - EnterLevel(); - switch( Lexer.Token.TokenType ) - { - case (int)';': { - Lexer.Next(); - break; - } - - // stat -> ifstat - case (int)TK.IF: { - IfStat( line ); - break; - } - - // stat -> whilestat - case (int)TK.WHILE: { - WhileStat( line ); - break; - } - - // stat -> DO block END - case (int)TK.DO: { - Lexer.Next(); - Block(); - CheckMatch( (int)TK.END, (int)TK.DO, line ); - break; - } - - // stat -> forstat - case (int)TK.FOR: { - ForStat( line ); - break; - } - - // stat -> repeatstat - case (int)TK.REPEAT: { - RepeatStat( line ); - break; - } - - // stat -> funcstat - case (int)TK.FUNCTION: { - FuncStat( line ); - break; - } - - // stat -> localstat - case (int)TK.LOCAL: { - Lexer.Next(); - - // local function? - if( TestNext( (int)TK.FUNCTION ) ) - LocalFunc(); - else - LocalStat(); - break; - } - - // stat -> label - case (int)TK.DBCOLON: { - Lexer.Next(); // skip double colon - LabelStat( CheckName(), line ); - break; - } - - // stat -> retstat - case (int)TK.RETURN: { - Lexer.Next(); // skip RETURN - RetStat(); - break; - } - - // stat -> breakstat - // stat -> 'goto' NAME - case (int)TK.BREAK: - case (int)TK.GOTO: { - GotoStat( Coder.Jump( CurFunc ) ); - break; - } - - // stat -> func | assignment - default: - ExprStat(); - break; - } - // Console.WriteLine( "MaxStackSize: " + CurFunc.Proto.MaxStackSize ); - // Console.WriteLine( "FreeReg: " + CurFunc.FreeReg ); - // Console.WriteLine( "NumActVar: " + CurFunc.NumActVar ); - Utl.Assert( CurFunc.Proto.MaxStackSize >= CurFunc.FreeReg && - CurFunc.FreeReg >= CurFunc.NumActVar ); - CurFunc.FreeReg = CurFunc.NumActVar; // free registers - LeaveLevel(); - } - - private string CheckName() - { - // Console.WriteLine( Lexer.Token ); - var t = Lexer.Token as NameToken; - - // TEST CODE - if( t == null ) - { - Console.WriteLine( Lexer.LineNumber + ":" + Lexer.Token ); - } - string name = t.SemInfo; - Lexer.Next(); - return name; - } - - private int SearchVar( FuncState fs, string name ) - { - for( int i=fs.NumActVar-1; i>=0; i-- ) - { - if( name == GetLocalVar( fs, i ).VarName ) - return i; - } - return -1; // not found - } - - private void MarkUpvalue( FuncState fs, int level ) - { - var block = fs.Block; - while( block.NumActVar > level ) block = block.Previous; - block.HasUpValue = true; - } - - private ExpKind SingleVarAux( FuncState fs, string name, ExpDesc e, bool flag ) - { - if( fs == null ) - return ExpKind.VVOID; - - // look up locals at current level - int v = SearchVar( fs, name ); - if( v >= 0 ) - { - InitExp( e, ExpKind.VLOCAL, v ); - if( !flag ) - MarkUpvalue( fs, v ); // local will be used as an upval - return ExpKind.VLOCAL; - } - - // not found as local at current level; try upvalues - int idx = SearchUpvalues( fs, name ); - if( idx < 0 ) // not found? - { - if( SingleVarAux( fs.Prev, name, e, false ) == ExpKind.VVOID ) - return ExpKind.VVOID; // not found; is a global - idx = NewUpvalue( fs, name, e ); - } - InitExp( e, ExpKind.VUPVAL, idx ); - return ExpKind.VUPVAL; - } - - private void SingleVar( ExpDesc e ) - { - string name = CheckName(); - if( SingleVarAux( CurFunc, name, e, true ) == ExpKind.VVOID ) - { - ExpDesc key = new ExpDesc(); - SingleVarAux( CurFunc, LuaDef.LUA_ENV, e, true ); - Utl.Assert( e.Kind == ExpKind.VLOCAL || - e.Kind == ExpKind.VUPVAL ); - CodeString( key, name ); - Coder.Indexed( CurFunc, e, key ); - } - } - - private void AdjustAssign( int nvars, int nexps, ExpDesc e ) - { - var fs = CurFunc; - int extra = nvars - nexps; - if( HasMultiRet( e.Kind ) ) - { - // includes call itself - ++extra; - if( extra < 0 ) - extra = 0; - Coder.SetReturns( fs, e, extra ); - if( extra > 1 ) - Coder.ReserveRegs( fs, extra-1 ); - } - else - { - if( e.Kind != ExpKind.VVOID ) - Coder.Exp2NextReg( fs, e ); // close last expression - if( extra > 0 ) - { - int reg = fs.FreeReg; - Coder.ReserveRegs( fs, extra ); - Coder.CodeNil( fs, reg, extra ); - } - } - } - - // check whether, in an assignment to an upvalue/local variable, the - // upvalue/local variable is begin used in a previous assignment to a - // table. If so, save original upvalue/local value in a safe place and - // use this safe copy in the previous assignment. - private void CheckConflict( LHSAssign lh, ExpDesc v ) - { - var fs = CurFunc; - - // eventual position to save local variable - int extra = fs.FreeReg; - bool conflict = false; - - // check all previous assignments - for( ; lh != null; lh = lh.Prev ) - { - var e = lh.Exp; - // assign to a table? - if( e.Kind == ExpKind.VINDEXED ) - { - // table is the upvalue/local being assigned now? - if( e.Ind.Vt == v.Kind && e.Ind.T == v.Info ) - { - conflict = true; - e.Ind.Vt = ExpKind.VLOCAL; - e.Ind.T = extra; // previous assignment will use safe copy - } - // index is the local being assigned? (index cannot be upvalue) - if( v.Kind == ExpKind.VLOCAL && e.Ind.Idx == v.Info ) - { - conflict = true; - e.Ind.Idx = extra; // previous assignment will use safe copy - } - } - } - if( conflict ) - { - // copy upvalue/local value to a temporary (in position 'extra') - var op = (v.Kind == ExpKind.VLOCAL) ? OpCode.OP_MOVE : OpCode.OP_GETUPVAL; - Coder.CodeABC( fs, op, extra, v.Info, 0 ); - Coder.ReserveRegs( fs, 1 ); - } - } - - // assignment -> ',' suffixedexp assignment - private void Assignment( LHSAssign lh, int nvars ) - { - CheckCondition( ExpKindUtl.VKIsVar( lh.Exp.Kind ), "syntax error" ); - ExpDesc e = new ExpDesc(); - - if( TestNext( (int)',' ) ) - { - var nv = new LHSAssign(); - nv.Prev = lh; - SuffixedExp( nv.Exp ); - if( nv.Exp.Kind != ExpKind.VINDEXED ) - CheckConflict( lh, nv.Exp ); - CheckLimit( CurFunc, nvars + Lua.NumCSharpCalls, - LuaLimits.LUAI_MAXCCALLS, "C# levels" ); - Assignment( nv, nvars+1 ); - } - else - { - CheckNext( (int)'=' ); - - int nexps = ExpList( e ); - if( nexps != nvars ) - { - AdjustAssign( nvars, nexps, e ); - if( nexps > nvars ) - { - // remove extra values - CurFunc.FreeReg -= (nexps - nvars); - } - } - else - { - Coder.SetOneRet( CurFunc, e ); - Coder.StoreVar( CurFunc, lh.Exp, e ); - return; - } - } - - // default assignment - InitExp( e, ExpKind.VNONRELOC, CurFunc.FreeReg-1 ); - Coder.StoreVar( CurFunc, lh.Exp, e ); - } - - private int ExpList( ExpDesc e ) - { - int n = 1; // at least one expression - Expr( e ); - while( TestNext( (int)',' ) ) - { - Coder.Exp2NextReg( CurFunc, e ); - Expr( e ); - n++; - } - return n; - } - - private void Expr( ExpDesc e ) - { - SubExpr( e, 0 ); - } - - private BinOpr SubExpr( ExpDesc e, int limit ) - { - // Console.WriteLine("SubExpr limit:" + limit); - EnterLevel(); - UnOpr uop = GetUnOpr( Lexer.Token.TokenType ); - if( uop != UnOpr.NOUNOPR ) - { - int line = Lexer.LineNumber; - Lexer.Next(); - SubExpr( e, UnaryPrior ); - Coder.Prefix( CurFunc, uop, e, line ); - } - else SimpleExp( e ); - - // expand while operators have priorities higher than `limit' - BinOpr op = GetBinOpr(Lexer.Token.TokenType ); - while( op != BinOpr.NOBINOPR && GetBinOprLeftPrior( op ) > limit ) - { - // Console.WriteLine("op:" + op); - int line = Lexer.LineNumber; - Lexer.Next(); - Coder.Infix( CurFunc, op, e ); - - // read sub-expression with higher priority - ExpDesc e2 = new ExpDesc(); - BinOpr nextOp = SubExpr( e2, GetBinOprRightPrior( op ) ); - Coder.Posfix( CurFunc, op, e, e2, line ); - op = nextOp; - } - - LeaveLevel(); - return op; - } - - private bool HasMultiRet( ExpKind k ) - { - return k == ExpKind.VCALL || k == ExpKind.VVARARG; - } - - private void ErrorExpected( int token ) - { - Lexer.SyntaxError( string.Format( "{0} expected", - ((char)token).ToString() ) ); - } - - private void CheckMatch( int what, int who, int where ) - { - if( !TestNext( what ) ) - { - if( where == Lexer.LineNumber ) - ErrorExpected( what ); - else - Lexer.SyntaxError( string.Format( - "{0} expected (to close {1} at line {2})", - ((char)what).ToString(), - ((char)who).ToString(), - where ) ); - } - } - - // block -> statlist - private void Block() - { - var fs = CurFunc; - var block = new BlockCnt(); - EnterBlock( fs, block, false ); - StatList(); - LeaveBlock( fs ); - } - - // index -> '[' expr ']' - private void YIndex( ExpDesc v ) - { - Lexer.Next(); - Expr( v ); - Coder.Exp2Val( CurFunc, v ); - CheckNext( (int)']' ); - } - - // recfield -> (NAME | '[' exp1 ']') = exp1 - private void RecField( ConstructorControl cc ) - { - var fs = CurFunc; - int reg = fs.FreeReg; - var key = new ExpDesc(); - var val = new ExpDesc(); - if( Lexer.Token.TokenType == (int)TK.NAME ) - { - CheckLimit( fs, cc.NumRecord, LuaLimits.MAX_INT, - "items in a constructor" ); - CodeString( key, CheckName() ); - } - // ls->t.token == '[' - else - { - YIndex( key ); - } - cc.NumRecord++; - CheckNext( (int)'=' ); - int rkkey = Coder.Exp2RK( fs, key ); - Expr( val ); - Coder.CodeABC( fs, OpCode.OP_SETTABLE, cc.ExpTable.Info, rkkey, - Coder.Exp2RK( fs, val ) ); - fs.FreeReg = reg; // free registers - } - - private void CloseListField( FuncState fs, ConstructorControl cc ) - { - // there is no list item - if( cc.ExpLastItem.Kind == ExpKind.VVOID ) - return; - - Coder.Exp2NextReg( fs, cc.ExpLastItem ); - cc.ExpLastItem.Kind = ExpKind.VVOID; - if( cc.NumToStore == LuaDef.LFIELDS_PER_FLUSH ) - { - // flush - Coder.SetList( fs, cc.ExpTable.Info, cc.NumArray, cc.NumToStore ); - - // no more item pending - cc.NumToStore = 0; - } - } - - private void LastListField( FuncState fs, ConstructorControl cc ) - { - if( cc.NumToStore == 0 ) - return; - - if( HasMultiRet( cc.ExpLastItem.Kind ) ) - { - Coder.SetMultiRet( fs, cc.ExpLastItem ); - Coder.SetList( fs, cc.ExpTable.Info, cc.NumArray, LuaDef.LUA_MULTRET ); - - // do not count last expression (unknown number of elements) - cc.NumArray--; - } - else - { - if( cc.ExpLastItem.Kind != ExpKind.VVOID ) - Coder.Exp2NextReg( fs, cc.ExpLastItem ); - Coder.SetList( fs, cc.ExpTable.Info, cc.NumArray, cc.NumToStore ); - } - } - - // listfield -> exp - private void ListField( ConstructorControl cc ) - { - Expr( cc.ExpLastItem ); - CheckLimit( CurFunc, cc.NumArray, LuaLimits.MAX_INT, - "items in a constructor" ); - cc.NumArray++; - cc.NumToStore++; - } - - // field -> listfield | recfield - private void Field( ConstructorControl cc ) - { - switch( Lexer.Token.TokenType ) - { - // may be 'listfield' or 'recfield' - case (int)TK.NAME: { - // expression? - if( Lexer.GetLookAhead().TokenType != (int)'=' ) - ListField( cc ); - else - RecField( cc ); - break; - } - - case (int)'[': { - RecField( cc ); - break; - } - - default: { - ListField( cc ); - break; - } - } - } - - // converts an integer to a "floating point byte", represented as - // (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if - // eeeee != 0 and (xxx) otherwise. - private int Integer2FloatingPointByte(uint x) - { - int e = 0; // exponent - if( x < 8 ) - return (int)x; - while( x >= 0x10 ) - { - x = (x+1) >> 1; - ++e; - } - return ((e+1) << 3) | ((int)x - 8); - } - - // constructor -> '{' [ field { sep field } [sep] ] '}' - // sep -> ',' | ';' - private void Constructor( ExpDesc t ) - { - var fs = CurFunc; - int line = Lexer.LineNumber; - int pc = Coder.CodeABC( fs, OpCode.OP_NEWTABLE, 0, 0, 0 ); - var cc = new ConstructorControl(); - cc.ExpTable = t; - InitExp( t, ExpKind.VRELOCABLE, pc ); - InitExp( cc.ExpLastItem, ExpKind.VVOID, 0); // no value (yet) - Coder.Exp2NextReg( fs, t ); - CheckNext( (int)'{' ); - do { - Utl.Assert( cc.ExpLastItem.Kind == ExpKind.VVOID || - cc.NumToStore > 0 ); - if( Lexer.Token.TokenType == (int)'}' ) - break; - CloseListField( fs, cc ); - Field( cc ); - } while( TestNext( (int)',' ) || TestNext( (int)';' ) ); - CheckMatch( (int)'}', (int)'{', line ); - LastListField( fs, cc ); - - // set initial array size and table size - // OP_NEWTABLE ARG_B ARG_C , - // , - // var ins = fs.Proto.Code[pc]; - // ins.SETARG_B( 0 ); - // ins.SETARG_C( 0 ); - - // , , bytecode luac - var ins = fs.Proto.Code[pc]; - ins.SETARG_B( Integer2FloatingPointByte( (uint)cc.NumArray ) ); - ins.SETARG_C( Integer2FloatingPointByte( (uint)cc.NumRecord) ); - fs.Proto.Code[pc] = ins; // Instruction - } - - private void ParList() - { - int numParams = 0; - CurFunc.Proto.IsVarArg = false; - - // is `parlist' not empty? - if( Lexer.Token.TokenType != (int)')' ) - { - do { - switch( Lexer.Token.TokenType ) - { - // param -> NAME - case (int)TK.NAME: { - var v =NewLocalVar( CheckName() ); - ActVars.Add( v ); - ++numParams; - break; - } - - case (int)TK.DOTS: { - Lexer.Next(); - CurFunc.Proto.IsVarArg = true; - break; - } - - default: { - Lexer.SyntaxError(" or '...' expected"); - break; - } - } - } while( !CurFunc.Proto.IsVarArg && TestNext( (int)',' ) ); - } - AdjustLocalVars( numParams ); - CurFunc.Proto.NumParams = CurFunc.NumActVar; - Coder.ReserveRegs( CurFunc, CurFunc.NumActVar ); - } - - private void Body( ExpDesc e, bool isMethod, int line ) - { - var newFs = new FuncState(); - var block = new BlockCnt(); - newFs.Proto = AddPrototype(); - newFs.Proto.LineDefined = line; - OpenFunc( newFs, block ); - CheckNext( (int)'(' ); - if( isMethod ) - { - // create `self' parameter - var v = NewLocalVar("self"); - ActVars.Add(v); - AdjustLocalVars(1); - } - ParList(); - CheckNext( (int)')' ); - StatList(); - newFs.Proto.LastLineDefined = Lexer.LineNumber; - CheckMatch( (int)TK.END, (int)TK.FUNCTION, line ); - CodeClosure(e); - CloseFunc(); - } - - private void FuncArgs( ExpDesc e, int line ) - { - var args = new ExpDesc(); - switch( Lexer.Token.TokenType ) - { - // funcargs -> `(' [ explist ] `)' - case (int)'(': { - Lexer.Next(); - if( Lexer.Token.TokenType == ')' ) // arg list is empty? - args.Kind = ExpKind.VVOID; - else { - ExpList( args ); - Coder.SetMultiRet( CurFunc, args ); - } - CheckMatch( (int)')', (int)'(', line ); - break; - } - - // funcargs -> constructor - case (int)'{': { - Constructor( args ); - break; - } - - // funcargs -> STRING - case (int)TK.STRING: { - var st = Lexer.Token as StringToken; - CodeString( args, st.SemInfo ); - Lexer.Next(); - break; - } - - default: { - Lexer.SyntaxError( "function arguments expected" ); - break; - } - } - - Utl.Assert( e.Kind == ExpKind.VNONRELOC ); - int baseReg = e.Info; - int nparams; - if( HasMultiRet( args.Kind ) ) - nparams = LuaDef.LUA_MULTRET; - else { - if( args.Kind != ExpKind.VVOID ) - Coder.Exp2NextReg( CurFunc, args ); // close last argument - nparams = CurFunc.FreeReg - (baseReg+1); - } - InitExp( e, ExpKind.VCALL, Coder.CodeABC( CurFunc, - OpCode.OP_CALL, baseReg, nparams+1, 2 ) ); - Coder.FixLine( CurFunc, line ); - - // call remove function and arguments and leaves - // (unless changed) one result - CurFunc.FreeReg = baseReg + 1; - } - - // ============================================================== - // Expression parsing - // ============================================================== - - // primaryexp -> NAME | '(' expr ')' - private void PrimaryExp( ExpDesc e ) - { - switch( Lexer.Token.TokenType ) - { - case (int)'(': { - int line = Lexer.LineNumber; - Lexer.Next(); - Expr( e ); - CheckMatch( (int)')', (int)'(', line ); - Coder.DischargeVars( CurFunc, e ); - return; - } - - case (int)TK.NAME: { - SingleVar( e ); - return; - } - - default: { - Lexer.SyntaxError("unexpected symbol"); - return; - } - } - } - - // suffixedexp -> primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs - private void SuffixedExp( ExpDesc e ) - { - var fs = CurFunc; - int line = Lexer.LineNumber; - PrimaryExp( e ); - for(;;) - { - switch( Lexer.Token.TokenType ) - { - case (int)'.': { // fieldsel - FieldSel( e ); - break; - } - case (int)'[': { // `[' exp1 `]' - var key = new ExpDesc(); - Coder.Exp2AnyRegUp( fs, e ); - YIndex( key ); - Coder.Indexed( fs, e, key ); - break; - } - case (int)':': { // `:' NAME funcargs - var key = new ExpDesc(); - Lexer.Next(); - CodeString( key, CheckName() ); - Coder.Self( fs, e, key ); - FuncArgs( e, line ); - break; - } - case (int)'(': - case (int)TK.STRING: - case (int)'{': { // funcargs - Coder.Exp2NextReg( CurFunc, e ); - FuncArgs( e, line ); - break; - } - default: return; - } - } - } - - private void SimpleExp( ExpDesc e ) - { - var t = Lexer.Token; - switch( t.TokenType ) - { - case (int)TK.NUMBER: { - var nt = t as NumberToken; - InitExp( e, ExpKind.VKNUM, 0 ); - e.NumberValue = nt.SemInfo; - break; - } - - case (int)TK.STRING: { - var st = t as StringToken; - CodeString( e, st.SemInfo ); - break; - } - - case (int)TK.NIL: { - InitExp( e, ExpKind.VNIL, 0 ); - break; - } - - case (int)TK.TRUE: { - InitExp( e, ExpKind.VTRUE, 0 ); - break; - } - - case (int)TK.FALSE: { - InitExp( e, ExpKind.VFALSE, 0 ); - break; - } - - case (int)TK.DOTS: { - CheckCondition( CurFunc.Proto.IsVarArg, - "cannot use '...' outside a vararg function" ); - InitExp( e, ExpKind.VVARARG, - Coder.CodeABC( CurFunc, OpCode.OP_VARARG, 0, 1, 0 ) ); - break; - } - - case (int)'{': { - Constructor( e ); - return; - } - - case (int)TK.FUNCTION: { - Lexer.Next(); - Body( e, false, Lexer.LineNumber ); - return; - } - - default: { - SuffixedExp( e ); - return; - } - } - Lexer.Next(); - } - - private int SearchUpvalues( FuncState fs, string name ) - { - var upvalues = fs.Proto.Upvalues; - for( int i=0; i< upvalues.Count; ++i ) - { - if( upvalues[i].Name == name ) - return i; - } - return -1; - } - - private int NewUpvalue( FuncState fs, string name, ExpDesc e ) - { - var f = fs.Proto; - int idx = f.Upvalues.Count; - var upval = new UpvalDesc(); - upval.InStack = (e.Kind == ExpKind.VLOCAL); - upval.Index = e.Info; - upval.Name = name; - f.Upvalues.Add( upval ); - return idx; - } - - private void CodeString( ExpDesc e, string s ) - { - InitExp( e, ExpKind.VK, Coder.StringK( CurFunc, s) ); - } - - private void InitExp( ExpDesc e, ExpKind k, int i ) - { - e.Kind = k; - e.Info = i; - e.ExitTrue = Coder.NO_JUMP; - e.ExitFalse = Coder.NO_JUMP; - } - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/TagMethod.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/TagMethod.cs deleted file mode 100644 index 45be6e96b..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/TagMethod.cs +++ /dev/null @@ -1,102 +0,0 @@ - -namespace UniLua -{ - // grep `NoTagMethodFlags' if num of TMS >= 32 - internal enum TMS - { - TM_INDEX, - TM_NEWINDEX, - TM_GC, - TM_MODE, - TM_LEN, - TM_EQ, - TM_ADD, - TM_SUB, - TM_MUL, - TM_DIV, - TM_MOD, - TM_POW, - TM_UNM, - TM_LT, - TM_LE, - TM_CONCAT, - TM_CALL, - TM_N /* number of elements in the enum */ - } - - public partial class LuaState - { - private string GetTagMethodName( TMS tm ) - { - switch( tm ) - { - case TMS.TM_INDEX: return "__index"; - case TMS.TM_NEWINDEX: return "__newindex"; - case TMS.TM_GC: return "__gc"; - case TMS.TM_MODE: return "__mode"; - case TMS.TM_LEN: return "__len"; - case TMS.TM_EQ: return "__eq"; - case TMS.TM_ADD: return "__add"; - case TMS.TM_SUB: return "__sub"; - case TMS.TM_MUL: return "__mul"; - case TMS.TM_DIV: return "__div"; - case TMS.TM_MOD: return "__mod"; - case TMS.TM_POW: return "__pow"; - case TMS.TM_UNM: return "__unm"; - case TMS.TM_LT: return "__lt"; - case TMS.TM_LE: return "__le"; - case TMS.TM_CONCAT: return "__concat"; - case TMS.TM_CALL: return "__call"; - default: throw new System.NotImplementedException(); - } - } - - private StkId T_GetTM( LuaTable mt, TMS tm ) - { - if( mt == null ) - return null; - - var res = mt.GetStr( GetTagMethodName( tm ) ); - if(res.V.TtIsNil()) // no tag method? - { - // cache this fact - mt.NoTagMethodFlags |= 1u << (int)tm; - return null; - } - else - return res; - } - - private StkId T_GetTMByObj( ref TValue o, TMS tm ) - { - LuaTable mt = null; - - switch( o.Tt ) - { - case (int)LuaType.LUA_TTABLE: - { - var tbl = o.HValue(); - mt = tbl.MetaTable; - break; - } - case (int)LuaType.LUA_TUSERDATA: - { - var ud = o.RawUValue(); - mt = ud.MetaTable; - break; - } - default: - { - mt = G.MetaTables[o.Tt]; - break; - } - } - return (mt != null) - ? mt.GetStr( GetTagMethodName( tm ) ) - : TheNilValue; - } - - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/ULDebug.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/ULDebug.cs deleted file mode 100644 index 2509598e5..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/ULDebug.cs +++ /dev/null @@ -1,19 +0,0 @@ - #define UNITY - -namespace UniLua.Tools -{ - // thanks to dharco - // refer to https://github.com/dharco/UniLua/commit/2854ddf2500ab2f943f01a6d3c9af767c092ce75 - public class ULDebug - { - public static System.Action Log = NoAction; - public static System.Action LogError = NoAction; - - private static void NoAction(object msg) { } - - static ULDebug() - { - } - } -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Undump.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Undump.cs deleted file mode 100644 index e87e05269..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/Undump.cs +++ /dev/null @@ -1,376 +0,0 @@ - // #define DEBUG_BINARY_READER -// #define DEBUG_UNDUMP - -using System; - -using ULDebug = UniLua.Tools.ULDebug; - -namespace UniLua -{ - public class BinaryBytesReader - { - private ILoadInfo LoadInfo; - public int SizeOfSizeT; - - - public BinaryBytesReader( ILoadInfo loadinfo ) - { - LoadInfo = loadinfo; - SizeOfSizeT = 0; - } - - public byte[] ReadBytes( int count ) - { - byte[] ret = new byte[count]; - for( int i=0; i Int32.MaxValue ) - throw new NotImplementedException(); - - return (int)ret; - } - - public double ReadDouble() - { - var bytes = ReadBytes( 8 ); - double ret = BitConverter.ToDouble( bytes, 0 ); -#if DEBUG_BINARY_READER - Console.WriteLine( "ReadDouble: " + ret ); -#endif - return ret; - } - - public byte ReadByte() - { - var c = LoadInfo.ReadByte(); - if( c == -1 ) - throw new UndumpException("truncated"); -#if DEBUG_BINARY_READER - Console.WriteLine( "ReadBytes: " + c ); -#endif - return (byte)c; - } - - public string ReadString() - { - var n = ReadSizeT(); - if( n == 0 ) - return null; - - var bytes = ReadBytes( n ); - - // n=1: removing trailing '\0' - string ret = System.Text.Encoding.ASCII.GetString( bytes, 0, n-1 ); -#if DEBUG_BINARY_READER - Console.WriteLine( "ReadString n:" + n + " ret:" + ret ); -#endif - return ret; - } - } - - class UndumpException : Exception - { - public string Why; - - public UndumpException( string why ) - { - Why = why; - } - } - - public class Undump - { - private BinaryBytesReader Reader; - - - public static LuaProto LoadBinary( ILuaState lua, - ILoadInfo loadinfo, string name ) - { - try - { - var reader = new BinaryBytesReader( loadinfo ); - var undump = new Undump( reader ); - undump.LoadHeader(); - return undump.LoadFunction(); - } - catch( UndumpException e ) - { - var Lua = (LuaState)lua; - Lua.O_PushString( string.Format( - "{0}: {1} precompiled chunk", name, e.Why ) ); - Lua.D_Throw( ThreadStatus.LUA_ERRSYNTAX ); - return null; - } - } - - private Undump( BinaryBytesReader reader ) - { - Reader = reader; - } - - private int LoadInt() - { - return Reader.ReadInt(); - } - - private byte LoadByte() - { - return Reader.ReadByte(); - } - - private byte[] LoadBytes( int count ) - { - return Reader.ReadBytes( count ); - } - - private string LoadString() - { - return Reader.ReadString(); - } - - private bool LoadBoolean() - { - return LoadByte() != 0; - } - - private double LoadNumber() - { - return Reader.ReadDouble(); - } - - private void LoadHeader() - { - byte[] header = LoadBytes( 4 // Signature - + 8 // version, format version, size of int ... etc - + 6 // Tail - ); - byte v = header[ 4 /* skip signature */ - + 4 /* offset of sizeof(size_t) */ - ]; -#if DEBUG_UNDUMP - Console.WriteLine(string.Format("sizeof(size_t): {0}", v)); -#endif - Reader.SizeOfSizeT = v ; - } - - private Instruction LoadInstruction() - { - return (Instruction)Reader.ReadUInt(); - } - - private LuaProto LoadFunction() - { -#if DEBUG_UNDUMP - Console.WriteLine( "LoadFunction enter" ); -#endif - - LuaProto proto = new LuaProto(); - proto.LineDefined = LoadInt(); - proto.LastLineDefined = LoadInt(); - proto.NumParams = LoadByte(); - proto.IsVarArg = LoadBoolean(); - proto.MaxStackSize = LoadByte(); - - LoadCode(proto); - LoadConstants(proto); - LoadUpvalues(proto); - LoadDebug(proto); - return proto; - } - - private void LoadCode( LuaProto proto ) - { - var n = LoadInt(); -#if DEBUG_UNDUMP - Console.WriteLine( "LoadCode n:" + n ); -#endif - proto.Code.Clear(); - for( int i=0; i= s.Length ) - return false; - - char c = s[pos]; - if( c == '-' ) - { - ++pos; - return true; - } - else if( c == '+' ) - { - ++pos; - } - return false; - } - - private static bool IsXDigit( char c ) - { - if( Char.IsDigit( c ) ) - return true; - - if( 'a' <= c && c <= 'f' ) - return true; - - if( 'A' <= c && c <= 'F' ) - return true; - - return false; - } - - private static double ReadHexa( string s, ref int pos, double r, out int count ) - { - count = 0; - while( pos < s.Length && IsXDigit( s[pos] ) ) - { - r = (r * 16.0) + Int32.Parse( s[pos].ToString(), NumberStyles.HexNumber ); - ++pos; - ++count; - } - return r; - } - - private static double ReadDecimal( string s, ref int pos, double r, out int count ) - { - count = 0; - while( pos < s.Length && Char.IsDigit( s[pos] ) ) - { - r = (r * 10.0) + Int32.Parse( s[pos].ToString() ); - ++pos; - ++count; - } - return r; - } - - // following C99 specification for 'strtod' - public static double StrX2Number( string s, ref int curpos ) - { - int pos = curpos; - while( pos < s.Length && Char.IsWhiteSpace( s[pos] )) ++pos; - bool negative = IsNegative( s, ref pos ); - - // check `0x' - if( pos >= s.Length || !(s[pos] == '0' && (s[pos+1] == 'x' || s[pos+1] == 'X')) ) - return 0.0; - - pos += 2; // skip `0x' - - double r = 0.0; - int i = 0; - int e = 0; - r = ReadHexa( s, ref pos, r, out i ); - if( pos < s.Length && s[pos] == '.' ) - { - ++pos; // skip `.' - r = ReadHexa( s, ref pos, r, out e ); - } - if( i == 0 && e == 0 ) - return 0.0; // invalid format (no digit) - - // each fractional digit divides value by 2^-4 - e *= -4; - curpos = pos; - - // exponent part - if( pos < s.Length && (s[pos] == 'p' || s[pos] == 'P') ) - { - ++pos; // skip `p' - bool expNegative = IsNegative( s, ref pos ); - if( pos >= s.Length || !Char.IsDigit( s[pos] ) ) - goto ret; - - int exp1 = 0; - while( pos < s.Length && Char.IsDigit( s[pos] ) ) - { - exp1 = exp1 * 10 + Int32.Parse( s[pos].ToString() ); - ++pos; - } - if( expNegative ) - exp1 = -exp1; - e += exp1; - } - curpos = pos; - -ret: - if( negative ) r = -r; - - return r * Math.Pow(2.0, e); - } - - public static double Str2Number( string s, ref int curpos ) - { - int pos = curpos; - while( pos < s.Length && Char.IsWhiteSpace( s[pos] )) ++pos; - bool negative = IsNegative( s, ref pos ); - - double r = 0.0; - int i = 0; - int f = 0; - r = ReadDecimal( s, ref pos, r, out i ); - if( pos < s.Length && s[pos] == '.' ) - { - ++pos; - r = ReadDecimal( s, ref pos, r, out f ); - } - if( i == 0 && f == 0 ) - return 0.0; - - f = -f; - curpos = pos; - - // exponent part - double e = 0.0; - if( pos < s.Length && (s[pos] == 'e' || s[pos] == 'E') ) - { - ++pos; - bool expNegative = IsNegative( s, ref pos ); - if( pos >= s.Length || !Char.IsDigit( s[pos] ) ) - goto ret; - - int n; - e = ReadDecimal( s, ref pos, e, out n ); - if( expNegative ) - e = -e; - f += (int)e; - } - curpos = pos; - -ret: - if( negative ) r = -r; - - return r * Math.Pow(10, f); - } - - public static string TrimWhiteSpace( string str ) - { - int s = 0; - int e = str.Length; - - while( s < str.Length && Char.IsWhiteSpace( str[s] ) ) ++s; - if( s >= e ) - return ""; - - while( e >= 0 && Char.IsWhiteSpace( str[e-1] ) ) --e; - return str.Substring( s, e-s ); - } - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/VM.cs b/SRC/Aura_OS/System/Processing/Interpreter/UniLua/VM.cs deleted file mode 100644 index f5087619a..000000000 --- a/SRC/Aura_OS/System/Processing/Interpreter/UniLua/VM.cs +++ /dev/null @@ -1,1256 +0,0 @@ - // #define DEBUG_NEW_FRAME -// #define DEBUG_INSTRUCTION -// #define DEBUG_INSTRUCTION_WITH_STACK - -// #define DEBUG_OP_GETTABUP -// #define DEBUG_OP_GETUPVAL -// #define DEBUG_OP_GETTABLE -// #define DEBUG_OP_EQ -// #define DEBUG_OP_SETLIST -// #define DEBUG_OP_CLOSURE -// #define DEBUG_OP_SETTABLE - -// #define DEBUG_RECORD_INS - -using System; -using System.Collections.Generic; - -namespace UniLua -{ - using ULDebug = UniLua.Tools.ULDebug; - using StringBuilder = System.Text.StringBuilder; - - public partial class LuaState - { - private const int MAXTAGLOOP = 100; - - private struct ExecuteEnvironment - { - public StkId[] Stack; - public List K; - public int Base; - public Instruction I; - - public StkId RA - { - get { return Stack[Base + I.GETARG_A()]; } - } - - public StkId RB - { - get { return Stack[Base + I.GETARG_B()]; } - } - - public StkId RK( int x ) - { - return Instruction.ISK( x ) ? K[Instruction.INDEXK(x)] : Stack[Base+x]; - } - - public StkId RKB - { - get { return RK( I.GETARG_B() ); } - } - - public StkId RKC - { - get { return RK( I.GETARG_C() ); } - } - } - - private void V_Execute() - { - ExecuteEnvironment env; - CallInfo ci = CI; -newframe: - Utl.Assert(ci == CI); - var cl = Stack[ci.FuncIndex].V.ClLValue(); - - env.Stack = Stack; - env.K = cl.Proto.K; - env.Base = ci.BaseIndex; - -#if DEBUG_NEW_FRAME - Console.WriteLine( "#### NEW FRAME #########################################################################" ); - Console.WriteLine( "## cl:" + cl ); - Console.WriteLine( "## Base:" + env.Base ); - Console.WriteLine( "########################################################################################" ); -#endif - - while( true ) - { - Instruction i = ci.SavedPc.ValueInc; - env.I = i; - -#if DEBUG_SRC_INFO - int line = 0; - string src = ""; - if(ci.IsLua) { - line = GetCurrentLine(ci); - src = GetCurrentLuaFunc(ci).Proto.Source; - } -#endif - - StkId ra = env.RA; - -#if DEBUG_DUMP_INS_STACK -#if DEBUG_DUMP_INS_STACK_EX - DumpStack( env.Base, i.ToString() ); -#else - DumpStack( env.Base ); -#endif -#endif - -#if DEBUG_INSTRUCTION - Console.WriteLine( System.DateTime.Now + " [VM] ======================================================================== Instruction: " + i -#if DEBUG_INSTRUCTION_WITH_STACK - + "\n" + DumpStackToString( env.Base.Index ) -#endif - ); -#endif - -#if DEBUG_RECORD_INS - InstructionHistory.Enqueue(i); - if( InstructionHistory.Count > 100 ) { - InstructionHistory.Dequeue(); - } -#endif - - switch( i.GET_OPCODE() ) - { - case OpCode.OP_MOVE: - { - var rb = env.RB; - -#if DEBUG_OP_MOVE - Console.WriteLine( "[VM] ==== OP_MOVE rb:" + rb ); - Console.WriteLine( "[VM] ==== OP_MOVE ra:" + ra ); -#endif - - ra.V.SetObj(ref rb.V); - break; - } - - case OpCode.OP_LOADK: - { - var rb = env.K[i.GETARG_Bx()]; - ra.V.SetObj(ref rb.V); - break; - } - - case OpCode.OP_LOADKX: - { - Utl.Assert( ci.SavedPc.Value.GET_OPCODE() == OpCode.OP_EXTRAARG ); - var rb = env.K[ci.SavedPc.ValueInc.GETARG_Ax()]; - ra.V.SetObj(ref rb.V); - break; - } - - case OpCode.OP_LOADBOOL: - { - ra.V.SetBValue(i.GETARG_B() != 0); - if( i.GETARG_C() != 0 ) - ci.SavedPc.Index += 1; // skip next instruction (if C) - break; - } - - case OpCode.OP_LOADNIL: - { - int b = i.GETARG_B(); - int index = ra.Index; - do { - Stack[index++].V.SetNilValue(); - } while (b-- > 0); - break; - } - - case OpCode.OP_GETUPVAL: - { - int b = i.GETARG_B(); - ra.V.SetObj(ref cl.Upvals[b].V.V); - -#if DEBUG_OP_GETUPVAL - // for( var j=0; j 0 || c > 0) - { tbl.Resize(b, c); } - break; - } - - case OpCode.OP_SELF: - { - // OP_SELF put function referenced by a table on ra - // and the table on ra+1 - // - // RB: table - // RKC: key - var ra1 = Stack[ra.Index+1]; - var rb = env.RB; - ra1.V.SetObj(ref rb.V); - V_GetTable( rb, env.RKC, ra ); - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_ADD: - { - var rkb = env.RKB; - var rkc = env.RKC; - if(rkb.V.TtIsNumber() && rkc.V.TtIsNumber()) - { ra.V.SetNValue(rkb.V.NValue + rkc.V.NValue); } - else - { V_Arith(ra, rkb, rkc, TMS.TM_ADD); } - - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_SUB: - { - var rkb = env.RKB; - var rkc = env.RKC; - if(rkb.V.TtIsNumber() && rkc.V.TtIsNumber()) - { ra.V.SetNValue(rkb.V.NValue - rkc.V.NValue); } - else - { V_Arith(ra, rkb, rkc, TMS.TM_SUB); } - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_MUL: - { - var rkb = env.RKB; - var rkc = env.RKC; - if(rkb.V.TtIsNumber() && rkc.V.TtIsNumber()) - { ra.V.SetNValue(rkb.V.NValue * rkc.V.NValue); } - else - { V_Arith(ra, rkb, rkc, TMS.TM_MUL); } - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_DIV: - { - var rkb = env.RKB; - var rkc = env.RKC; - if(rkb.V.TtIsNumber() && rkc.V.TtIsNumber()) - { ra.V.SetNValue(rkb.V.NValue / rkc.V.NValue); } - else - { V_Arith(ra, rkb, rkc, TMS.TM_DIV); } - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_MOD: - { - var rkb = env.RKB; - var rkc = env.RKC; - if(rkb.V.TtIsNumber() && rkc.V.TtIsNumber()) { - var v1 = rkb.V.NValue; - var v2 = rkc.V.NValue; - ra.V.SetNValue(v1 - Math.Floor(v1/v2)*v2); - } - else - { V_Arith(ra, rkb, rkc, TMS.TM_MOD); } - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_POW: - { - var rkb = env.RKB; - var rkc = env.RKC; - if(rkb.V.TtIsNumber() && rkc.V.TtIsNumber()) - { ra.V.SetNValue(Math.Pow(rkb.V.NValue, rkc.V.NValue)); } - else - { V_Arith(ra, rkb, rkc, TMS.TM_POW); } - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_UNM: - { - var rb = env.RB; - if(rb.V.TtIsNumber()) { - ra.V.SetNValue(-rb.V.NValue); - } - else { - V_Arith(ra, rb, rb, TMS.TM_UNM); - env.Base = ci.BaseIndex; - } - break; - } - - case OpCode.OP_NOT: - { - var rb = env.RB; - ra.V.SetBValue(IsFalse(ref rb.V)); - break; - } - - case OpCode.OP_LEN: - { - V_ObjLen( ra, env.RB ); - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_CONCAT: - { - int b = i.GETARG_B(); - int c = i.GETARG_C(); - Top = Stack[env.Base + c + 1]; - V_Concat( c - b + 1 ); - env.Base = ci.BaseIndex; - - ra = env.RA; // 'V_Concat' may invoke TMs and move the stack - StkId rb = env.RB; - ra.V.SetObj(ref rb.V); - - Top = Stack[ci.TopIndex]; // restore top - break; - } - - case OpCode.OP_JMP: - { - V_DoJump( ci, i, 0 ); - break; - } - - case OpCode.OP_EQ: - { - var lhs = env.RKB; - var rhs = env.RKC; - var expectEq = i.GETARG_A() != 0; -#if DEBUG_OP_EQ - Console.WriteLine( "[VM] ==== OP_EQ lhs:" + lhs ); - Console.WriteLine( "[VM] ==== OP_EQ rhs:" + rhs ); - Console.WriteLine( "[VM] ==== OP_EQ expectEq:" + expectEq ); - Console.WriteLine( "[VM] ==== OP_EQ (lhs.V == rhs.V):" + (lhs.V == rhs.V) ); -#endif - if((lhs.V == rhs.V) != expectEq) - { - ci.SavedPc.Index += 1; // skip next jump instruction - } - else - { - V_DoNextJump( ci ); - } - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_LT: - { - var expectCmpResult = i.GETARG_A() != 0; - if( V_LessThan( env.RKB, env.RKC ) != expectCmpResult ) - ci.SavedPc.Index += 1; - else - V_DoNextJump( ci ); - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_LE: - { - var expectCmpResult = i.GETARG_A() != 0; - if( V_LessEqual( env.RKB, env.RKC ) != expectCmpResult ) - ci.SavedPc.Index += 1; - else - V_DoNextJump( ci ); - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_TEST: - { - if((i.GETARG_C() != 0) ? - IsFalse(ref ra.V) : !IsFalse(ref ra.V)) - { - ci.SavedPc.Index += 1; - } - else V_DoNextJump( ci ); - - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_TESTSET: - { - var rb = env.RB; - if((i.GETARG_C() != 0) ? - IsFalse(ref rb.V) : !IsFalse(ref rb.V)) - { - ci.SavedPc.Index += 1; - } - else - { - ra.V.SetObj(ref rb.V); - V_DoNextJump( ci ); - } - env.Base = ci.BaseIndex; - break; - } - - case OpCode.OP_CALL: - { - int b = i.GETARG_B(); - int nresults = i.GETARG_C() - 1; - if( b != 0) { Top = Stack[ra.Index + b]; } // else previous instruction set top - if( D_PreCall( ra, nresults ) ) { // C# function? - if( nresults >= 0 ) - Top = Stack[ci.TopIndex]; - env.Base = ci.BaseIndex; - } - else { // Lua function - ci = CI; - ci.CallStatus |= CallStatus.CIST_REENTRY; - goto newframe; - } - break; - } - - case OpCode.OP_TAILCALL: - { - int b = i.GETARG_B(); - if( b != 0) { Top = Stack[ra.Index + b]; } // else previous instruction set top - - Utl.Assert( i.GETARG_C() - 1 == LuaDef.LUA_MULTRET ); - - var called = D_PreCall( ra, LuaDef.LUA_MULTRET ); - - // C# function ? - if( called ) - { - env.Base = ci.BaseIndex; - } - - // LuaFunciton - else - { - var nci = CI; // called frame - var oci = BaseCI[CI.Index-1]; // caller frame - StkId nfunc = Stack[nci.FuncIndex];// called function - StkId ofunc = Stack[oci.FuncIndex];// caller function - var ncl = nfunc.V.ClLValue(); - var ocl = ofunc.V.ClLValue(); - - // last stack slot filled by 'precall' - int lim = nci.BaseIndex + ncl.Proto.NumParams; - - if(cl.Proto.P.Count > 0) - { F_Close( Stack[env.Base] ); } - - // move new frame into old one - var nindex = nfunc.Index; - var oindex = ofunc.Index; - while(nindex < lim) { - Stack[oindex++].V.SetObj(ref Stack[nindex++].V); - } - - oci.BaseIndex = ofunc.Index + (nci.BaseIndex - nfunc.Index); - oci.TopIndex = ofunc.Index + (Top.Index - nfunc.Index); - Top = Stack[oci.TopIndex]; - oci.SavedPc = nci.SavedPc; - oci.CallStatus |= CallStatus.CIST_TAIL; - ci = CI = oci; - - ocl = ofunc.V.ClLValue(); - Utl.Assert(Top.Index == oci.BaseIndex + ocl.Proto.MaxStackSize); - - goto newframe; - } - - break; - } - - case OpCode.OP_RETURN: - { - int b = i.GETARG_B(); - if( b != 0 ) { Top = Stack[ra.Index + b - 1]; } - if( cl.Proto.P.Count > 0 ) { F_Close(Stack[env.Base]); } - b = D_PosCall( ra.Index ); - if( (ci.CallStatus & CallStatus.CIST_REENTRY) == 0 ) - { - return; - } - else - { - ci = CI; - if( b != 0 ) Top = Stack[ci.TopIndex]; - goto newframe; - } - } - - case OpCode.OP_FORLOOP: - { - var ra1 = Stack[ra.Index + 1]; - var ra2 = Stack[ra.Index + 2]; - var ra3 = Stack[ra.Index + 3]; - - var step = ra2.V.NValue; - var idx = ra.V.NValue + step; // increment index - var limit = ra1.V.NValue; - - if( (0 < step) ? idx <= limit - : limit <= idx ) - { - ci.SavedPc.Index += i.GETARG_sBx(); // jump back - ra.V.SetNValue(idx);// updateinternal index... - ra3.V.SetNValue(idx);// ... and external index - } - - break; - } - - case OpCode.OP_FORPREP: - { - var init = new TValue(); - var limit = new TValue(); - var step = new TValue(); - - var ra1 = Stack[ra.Index + 1]; - var ra2 = Stack[ra.Index + 2]; - - // WHY: why limit is not used ? - - if(!V_ToNumber(ra, ref init)) - G_RunError("'for' initial value must be a number"); - if(!V_ToNumber(ra1, ref limit)) - G_RunError("'for' limit must be a number"); - if(!V_ToNumber(ra2, ref step)) - G_RunError("'for' step must be a number"); - - ra.V.SetNValue(init.NValue - step.NValue); - ci.SavedPc.Index += i.GETARG_sBx(); - - break; - } - - case OpCode.OP_TFORCALL: - { - int rai = ra.Index; - int cbi = ra.Index + 3; - Stack[cbi+2].V.SetObj(ref Stack[rai+2].V); - Stack[cbi+1].V.SetObj(ref Stack[rai+1].V); - Stack[cbi].V.SetObj(ref Stack[rai].V); - - StkId callBase = Stack[cbi]; - Top = Stack[cbi+3]; // func. +2 args (state and index) - - D_Call( callBase, i.GETARG_C(), true ); - - env.Base = ci.BaseIndex; - - Top = Stack[ci.TopIndex]; - i = ci.SavedPc.ValueInc; // go to next instruction - env.I = i; - ra = env.RA; - - DumpStack( env.Base ); -#if DEBUG_INSTRUCTION - Console.WriteLine( "[VM] ============================================================ OP_TFORCALL Instruction: " + i ); -#endif - - Utl.Assert( i.GET_OPCODE() == OpCode.OP_TFORLOOP ); - goto l_tforloop; - } - - case OpCode.OP_TFORLOOP: -l_tforloop: - { - StkId ra1 = Stack[ra.Index + 1]; - if(!ra1.V.TtIsNil()) // continue loop? - { - ra.V.SetObj(ref ra1.V); - ci.SavedPc += i.GETARG_sBx(); - } - break; - } - - // sets the values for a range of array elements in a table(RA) - // RA -> table - // RB -> number of elements to set - // C -> encodes the block number of the table to be initialized - // the values used to initialize the table are located in - // R(A+1), R(A+2) ... - case OpCode.OP_SETLIST: - { - int n = i.GETARG_B(); - int c = i.GETARG_C(); - if( n == 0 ) n = (Top.Index - ra.Index) - 1; - if( c == 0 ) - { - Utl.Assert( ci.SavedPc.Value.GET_OPCODE() == OpCode.OP_EXTRAARG ); - c = ci.SavedPc.ValueInc.GETARG_Ax(); - } - - var tbl = ra.V.HValue(); - Utl.Assert( tbl != null ); - - int last = ((c-1) * LuaDef.LFIELDS_PER_FLUSH) + n; - int rai = ra.Index; - for(; n>0; --n) { - tbl.SetInt(last--, ref Stack[rai+n].V); - } -#if DEBUG_OP_SETLIST - Console.WriteLine( "[VM] ==== OP_SETLIST ci.Top:" + ci.Top.Index ); - Console.WriteLine( "[VM] ==== OP_SETLIST Top:" + Top.Index ); -#endif - Top = Stack[ci.TopIndex]; // correct top (in case of previous open call) - break; - } - - case OpCode.OP_CLOSURE: - { - LuaProto p = cl.Proto.P[ i.GETARG_Bx() ]; - V_PushClosure( p, cl.Upvals, env.Base, ra ); -#if DEBUG_OP_CLOSURE - Console.WriteLine( "OP_CLOSURE:" + ra.Value ); - var racl = ra.Value as LuaLClosure; - if( racl != null ) - { - for( int ii=0; ii - /// VARARG implements the vararg operator `...' in expressions. - /// VARARG copies B-1 parameters into a number of registers - /// starting from R(A), padding with nils if there aren't enough values. - /// If B is 0, VARARG copies as many values as it can based on - /// the number of parameters passed. - /// If a fixed number of values is required, B is a value greater than 1. - /// If any number of values is required, B is 0. - /// - case OpCode.OP_VARARG: - { - int b = i.GETARG_B() - 1; - int n = (env.Base - ci.FuncIndex) - cl.Proto.NumParams - 1; - if( b < 0 ) // B == 0? - { - b = n; - D_CheckStack(n); - ra = env.RA; // previous call may change the stack - Top = Stack[ra.Index + n]; - } - - var p = ra.Index; - var q = env.Base - n; - for(int j=0; j= 2 ); - - do - { - var top = Top; - int n = 2; - var lhs = Stack[top.Index - 2]; - var rhs = Stack[top.Index - 1]; - if(!(lhs.V.TtIsString() || lhs.V.TtIsNumber()) || !ToString(ref rhs.V)) - { - if( !CallBinTM( lhs, rhs, lhs, TMS.TM_CONCAT ) ) - G_ConcatError( lhs, rhs ); - } - else if(rhs.V.SValue().Length == 0) { - ToString(ref lhs.V); - } - else if(lhs.V.TtIsString() && lhs.V.SValue().Length == 0) { - lhs.V.SetObj(ref rhs.V); - } - else - { - StringBuilder sb = new StringBuilder(); - n = 0; - for( ; n 1 ); - } - - private void V_DoJump( CallInfo ci, Instruction i, int e ) - { - int a = i.GETARG_A(); - if( a > 0 ) - F_Close(Stack[ci.BaseIndex + (a-1)]); - ci.SavedPc += i.GETARG_sBx() + e; - } - - private void V_DoNextJump( CallInfo ci ) - { - Instruction i = ci.SavedPc.Value; - V_DoJump( ci, i, 1 ); - } - - private bool V_ToNumber( StkId obj, ref TValue n ) - { - if( obj.V.TtIsNumber() ) { - n.SetNValue( obj.V.NValue ); - return true; - } - if( obj.V.TtIsString() ) { - double val; - if( O_Str2Decimal(obj.V.SValue(), out val) ) { - n.SetNValue( val ); - return true; - } - } - - return false; - } - - private bool V_ToString(ref TValue v) - { - if(!v.TtIsNumber()) { return false; } - - v.SetSValue(v.NValue.ToString()); - return true; - } - - private LuaOp TMS2OP( TMS op ) - { - switch( op ) - { - case TMS.TM_ADD: return LuaOp.LUA_OPADD; - case TMS.TM_SUB: return LuaOp.LUA_OPSUB; - case TMS.TM_MUL: return LuaOp.LUA_OPMUL; - case TMS.TM_DIV: return LuaOp.LUA_OPDIV; - case TMS.TM_POW: return LuaOp.LUA_OPPOW; - case TMS.TM_UNM: return LuaOp.LUA_OPUNM; - - // case TMS.TM_EQ: return LuaOp.LUA_OPEQ; - // case TMS.TM_LT: return LuaOp.LUA_OPLT; - // case TMS.TM_LE: return LuaOp.LUA_OPLE; - - default: throw new System.NotImplementedException(); - } - } - - private void CallTM( ref TValue f, ref TValue p1, ref TValue p2, StkId p3, bool hasres ) - { - var result = p3.Index; - var func = Top; - StkId.inc(ref Top).V.SetObj(ref f); // push function - StkId.inc(ref Top).V.SetObj(ref p1); // push 1st argument - StkId.inc(ref Top).V.SetObj(ref p2); // push 2nd argument - if( !hasres ) // no result? p3 is 3rd argument - StkId.inc(ref Top).V.SetObj(ref p3.V); - D_CheckStack(0); - D_Call( func, (hasres ? 1 : 0), CI.IsLua ); - if( hasres ) // if has result, move it ot its place - { - Top = Stack[Top.Index - 1]; - Stack[result].V.SetObj(ref Top.V); - } - } - - private bool CallBinTM( StkId p1, StkId p2, StkId res, TMS tm ) - { - var tmObj = T_GetTMByObj(ref p1.V, tm); - if(tmObj.V.TtIsNil()) - tmObj = T_GetTMByObj(ref p2.V, tm); - if(tmObj.V.TtIsNil()) - return false; - - CallTM( ref tmObj.V, ref p1.V, ref p2.V, res, true ); - return true; - } - - private void V_Arith( StkId ra, StkId rb, StkId rc, TMS op ) - { - var nb = new TValue(); - var nc = new TValue(); - if(V_ToNumber(rb, ref nb) && V_ToNumber(rc, ref nc)) - { - var res = O_Arith( TMS2OP(op), nb.NValue, nc.NValue ); - ra.V.SetNValue( res ); - } - else if( !CallBinTM( rb, rc, ra, op ) ) - { - G_ArithError( rb, rc ); - } - } - - private bool CallOrderTM( StkId p1, StkId p2, TMS tm, out bool error ) - { - if( !CallBinTM( p1, p2, Top, tm ) ) - { - error = true; // no metamethod - return false; - } - - error = false; - return !IsFalse(ref Top.V); - } - - private bool V_LessThan( StkId lhs, StkId rhs ) - { - // compare number - if(lhs.V.TtIsNumber() && rhs.V.TtIsNumber()) { - return lhs.V.NValue < rhs.V.NValue; - } - - // compare string - if(lhs.V.TtIsString() && rhs.V.TtIsString()) { - return string.Compare(lhs.V.SValue(), rhs.V.SValue()) < 0; - } - - bool error; - var res = CallOrderTM( lhs, rhs, TMS.TM_LT, out error ); - if( error ) - { - G_OrderError( lhs, rhs ); - return false; - } - return res; - } - - private bool V_LessEqual( StkId lhs, StkId rhs ) - { - // compare number - if(lhs.V.TtIsNumber() && rhs.V.TtIsNumber()) { - return lhs.V.NValue <= rhs.V.NValue; - } - - // compare string - if(lhs.V.TtIsString() && rhs.V.TtIsString()) { - return string.Compare(lhs.V.SValue(), rhs.V.SValue()) <= 0; - } - - // first try `le' - bool error; - var res = CallOrderTM( lhs, rhs, TMS.TM_LE, out error ); - if( !error ) - return res; - - // else try `lt' - res = CallOrderTM( rhs, lhs, TMS.TM_LT, out error ); - if( !error ) - return res; - - G_OrderError( lhs, rhs ); - return false; - } - - private void V_FinishOp() - { - int ciIndex = CI.Index; - int stackBase = CI.BaseIndex; - Instruction i = (CI.SavedPc - 1).Value; // interrupted instruction - OpCode op = i.GET_OPCODE(); - switch( op ) - { - case OpCode.OP_ADD: case OpCode.OP_SUB: case OpCode.OP_MUL: case OpCode.OP_DIV: - case OpCode.OP_MOD: case OpCode.OP_POW: case OpCode.OP_UNM: case OpCode.OP_LEN: - case OpCode.OP_GETTABUP: case OpCode.OP_GETTABLE: case OpCode.OP_SELF: - { - var tmp = Stack[stackBase + i.GETARG_A()]; - Top = Stack[Top.Index-1]; - tmp.V.SetObj(ref Stack[Top.Index].V); - break; - } - - case OpCode.OP_LE: case OpCode.OP_LT: case OpCode.OP_EQ: - { - bool res = !IsFalse(ref Stack[Top.Index-1].V); - Top = Stack[Top.Index-1]; - // metamethod should not be called when operand is K - Utl.Assert( !Instruction.ISK( i.GETARG_B() ) ); - if( op == OpCode.OP_LE && // `<=' using `<' instead? - T_GetTMByObj(ref Stack[stackBase + i.GETARG_B()].V, TMS.TM_LE ).V.TtIsNil() ) - { - res = !res; // invert result - } - - var ci = BaseCI[ciIndex]; - Utl.Assert( ci.SavedPc.Value.GET_OPCODE() == OpCode.OP_JMP ); - if( (res ? 1 : 0) != i.GETARG_A() ) - if( (i.GETARG_A() == 0) == res ) // condition failed? - { - ci.SavedPc.Index++; // skip jump instruction - } - break; - } - - case OpCode.OP_CONCAT: - { - StkId top = Stack[Top.Index - 1]; // top when `CallBinTM' was called - int b = i.GETARG_B(); // first element to concatenate - int total = top.Index-1 - (stackBase+b); // yet to concatenate - var tmp = Stack[top.Index-2]; - tmp.V.SetObj(ref top.V); // put TM result in proper position - if(total > 1) // are there elements to concat? - { - Top = Stack[Top.Index-1]; - V_Concat( total ); - } - // move final result to final position - var ci = BaseCI[ciIndex]; - var tmp2 = Stack[ci.BaseIndex + i.GETARG_A()]; - tmp2.V.SetObj(ref Stack[Top.Index-1].V); - Top = Stack[ci.TopIndex]; - break; - } - - case OpCode.OP_TFORCALL: - { - var ci = BaseCI[ciIndex]; - Utl.Assert( ci.SavedPc.Value.GET_OPCODE() == OpCode.OP_TFORLOOP ); - Top = Stack[ci.TopIndex]; // restore top - break; - } - - case OpCode.OP_CALL: - { - if( i.GETARG_C() - 1 >= 0 ) // numResults >= 0? - { - var ci = BaseCI[ciIndex]; - Top = Stack[ci.TopIndex]; // restore top - } - break; - } - - case OpCode.OP_TAILCALL: case OpCode.OP_SETTABUP: case OpCode.OP_SETTABLE: - break; - - default: - Utl.Assert( false ); - break; - } - } - - internal bool V_RawEqualObj( ref TValue t1, ref TValue t2 ) - { - return (t1.Tt == t2.Tt) && V_EqualObject( ref t1, ref t2, true ); - } - - private bool EqualObj( ref TValue t1, ref TValue t2, bool rawEq ) - { - return (t1.Tt == t2.Tt) && V_EqualObject( ref t1, ref t2, rawEq ); - } - - private StkId GetEqualTM( LuaTable mt1, LuaTable mt2, TMS tm ) - { - var tm1 = FastTM( mt1, tm ); - if(tm1 == null) // no metamethod - return null; - if(mt1 == mt2) // same metatables => same metamethods - return tm1; - var tm2 = FastTM( mt2, tm ); - if(tm2 == null) // no metamethod - return null; - if(V_RawEqualObj(ref tm1.V, ref tm2.V)) // same metamethods? - return tm1; - return null; - } - - private bool V_EqualObject( ref TValue t1, ref TValue t2, bool rawEq ) - { - Utl.Assert( t1.Tt == t2.Tt ); - StkId tm = null; - switch( t1.Tt ) - { - case (int)LuaType.LUA_TNIL: - return true; - case (int)LuaType.LUA_TNUMBER: - return t1.NValue == t2.NValue; - case (int)LuaType.LUA_TUINT64: - return t1.UInt64Value == t2.UInt64Value; - case (int)LuaType.LUA_TBOOLEAN: - return t1.BValue() == t2.BValue(); - case (int)LuaType.LUA_TSTRING: - return t1.SValue() == t2.SValue(); - case (int)LuaType.LUA_TUSERDATA: - { - var ud1 = t1.RawUValue(); - var ud2 = t2.RawUValue(); - if(ud1.Value == ud2.Value) - return true; - if(rawEq) - return false; - tm = GetEqualTM( ud1.MetaTable, ud2.MetaTable, TMS.TM_EQ ); - break; - } - case (int)LuaType.LUA_TTABLE: - { - var tbl1 = t1.HValue(); - var tbl2 = t2.HValue(); - if( System.Object.ReferenceEquals( tbl1, tbl2 ) ) - return true; - if( rawEq ) - return false; - tm = GetEqualTM( tbl1.MetaTable, tbl2.MetaTable, TMS.TM_EQ ); - break; - } - default: - return t1.OValue == t2.OValue; - } - if( tm == null ) // no TM? - return false; - CallTM(ref tm.V, ref t1, ref t2, Top, true ); // call TM - return !IsFalse(ref Top.V); - } - - } - -} - diff --git a/SRC/Aura_OS/System/Processing/Lua/AuraLua.cs b/SRC/Aura_OS/System/Processing/Lua/AuraLua.cs new file mode 100644 index 000000000..3cf6b9ef9 --- /dev/null +++ b/SRC/Aura_OS/System/Processing/Lua/AuraLua.cs @@ -0,0 +1,123 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: Lua interpreter factory (Cosmos.Executable.Lua) +* PROGRAMMER(S): Valentin Charbonnier +*/ + +using System; +using System.Collections.Generic; +using System.IO; +using Cosmos.Executable.Lua; +using Aura_OS.System.Processing.Interpreter.Commands; + +namespace Aura_OS.System.Processing.Lua +{ + /// + /// Creates the Lua interpreters Aura runs scripts with (run file.lua, .cexe programs). + /// + internal static class AuraLua + { + /// + /// Create a Lua 5.2 interpreter with the standard libraries, cosmos.crypto, + /// Aura's environment variables and os.execute wired to the shell. + /// The caller must Dispose() it (after its try/catch, not in a using). + /// + /// The Terminal's CommandManager when the caller has it; null uses a Batch-style one. + /// The interpreter. + internal static LuaInterpreter Create(CommandManager shell = null) + { + LuaInterpreter lua = new LuaInterpreter(); + + // Relative names for dofile, require, loadfile, io.open, os.remove... (Unix VFS path, ends with '/') + lua.WorkingDirectory = Kernel.CurrentDirectory; + + // GEN3-GAP(console-input): Console.In is the KernelConsole line editor, which would block the UI + // thread, paint over the GUI and drain tty1. io.read gives nil instead. + lua.Input = TextReader.Null; + + // Output stays null: print and io.write follow Console.Out, the Terminal's writer while it is focused. + + lua.ExecuteCommand = command => ExecuteCommand(lua, shell, command); + + // GEN3-GAP(env): Environment.GetEnvironmentVariable is always null on gen3, + // so os.getenv reads Aura's variables (set / export). + ILuaState state = lua.State; + state.GetGlobal("os"); + state.PushCSharpFunction(GetEnv); + state.SetField(-2, "getenv"); + state.Pop(1); + + LuaCryptoLib.Register(lua); + + return lua; + } + + /// + /// os.execute(command): run one shell line, then follow a cd it made. + /// + private static int ExecuteCommand(LuaInterpreter lua, CommandManager shell, string command) + { + int status = 0; + CommandManager manager = shell; + List callerCommands = null; + + try + { + if (manager == null) + { + // The CommandManager constructor resets the static command table (Batch.cs pattern). + // Keep the caller's table (the Terminal's, whose clear/exit are bound to it) and put it back afterwards. + callerCommands = CommandManager.GetCommands(); + manager = new CommandManager(); + + if (callerCommands != null && callerCommands.Count > 0) + { + CommandManager._commands = callerCommands; + } + else + { + callerCommands = null; + manager.Initialize(); + } + } + + manager.Execute(command); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + status = 1; + } + + // GEN3-GAP(finally): not in a finally, gen3 does not run finally blocks when an exception unwinds (C7). + if (callerCommands != null) + { + CommandManager._commands = callerCommands; + } + + lua.WorkingDirectory = Kernel.CurrentDirectory; + + return status; + } + + /// + /// os.getenv(name): the value from Kernel.EnvironmentVariables, nil when unset. + /// + private static int GetEnv(ILuaState lua) + { + string name = lua.L_CheckString(1); + string value; + + if (Kernel.EnvironmentVariables != null && Kernel.EnvironmentVariables.TryGetValue(name, out value) && value != null) + { + lua.PushString(value); + } + else + { + lua.PushNil(); + } + + return 1; + } + } +} diff --git a/SRC/Aura_OS/System/Processing/Lua/LuaCryptoLib.cs b/SRC/Aura_OS/System/Processing/Lua/LuaCryptoLib.cs new file mode 100644 index 000000000..12e174e55 --- /dev/null +++ b/SRC/Aura_OS/System/Processing/Lua/LuaCryptoLib.cs @@ -0,0 +1,125 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: Lua cosmos.crypto library +* PROGRAMMER(S): Valentin Charbonnier +*/ + +using System.IO; +using System.Text; +using Cosmos.Executable.Lua; +using Aura_OS.System.Filesystem; + +namespace Aura_OS.System.Processing.Lua +{ + /// + /// cosmos.crypto: string and file hashes for Lua scripts (port of gen2's LuaCosmosCryptoLib). + /// Hashes are uppercase hex strings, as in gen2. + /// + internal static class LuaCryptoLib + { + public const string LIB_NAME = "cosmos.crypto"; + + /// + /// Register cosmos.crypto in package.loaded and as the global "cosmos.crypto". + /// + /// Interpreter whose WorkingDirectory the file functions resolve against. + public static void Register(LuaInterpreter lua) + { + // GEN3-GAP(lua-host): a C# callback only receives ILuaState, so the file functions + // capture the interpreter to read its WorkingDirectory. + lua.State.L_RequireF(LIB_NAME, l => + { + NameFuncPair[] define = new NameFuncPair[] + { + new NameFuncPair("strtomd5", CRYPTO_md5), + new NameFuncPair("strtosha256", CRYPTO_sha256), + new NameFuncPair("strtosha512", CRYPTO_sha512), + new NameFuncPair("filetomd5", s => FILE_CRYPTO_md5(s, lua)), + new NameFuncPair("filetosha256", s => FILE_CRYPTO_sha256(s, lua)), + new NameFuncPair("filetosha512", s => FILE_CRYPTO_sha512(s, lua)), + }; + + l.L_NewLib(define); + return 1; + }, true); + + // L_RequireF leaves the library table on the stack + lua.State.Pop(1); + } + + private static int CRYPTO_md5(ILuaState lua) + { + string input = lua.L_CheckString(1); + lua.PushString(Aura_OS.System.Security.MD5.hash(input)); + return 1; + } + + private static int CRYPTO_sha256(ILuaState lua) + { + string input = lua.L_CheckString(1); + lua.PushString(Aura_OS.System.Security.Sha256.hash(Encoding.UTF8.GetBytes(input))); + return 1; + } + + private static int CRYPTO_sha512(ILuaState lua) + { + string input = lua.L_CheckString(1); + lua.PushString(Sha512Hex(Encoding.UTF8.GetBytes(input))); + return 1; + } + + // GEN3-GAP(finally): file functions read the whole file instead of hashing a stream: a stream left open by an + // exception is never closed on gen3 (no finally on the exception path, no finalizers). + // An exception thrown here (FileNotFoundException...) becomes a Lua error that pcall can catch. + + private static int FILE_CRYPTO_md5(ILuaState lua, LuaInterpreter interpreter) + { + byte[] file = File.ReadAllBytes(ResolvePath(interpreter, lua.L_CheckString(1))); + acryptohashnet.MD5 hashAlgorithm = new acryptohashnet.MD5(); + byte[] hashBytes = hashAlgorithm.ComputeHash(file); + hashAlgorithm.Dispose(); + lua.PushString(Aura_OS.Utils.Conversion.Hex(hashBytes)); + return 1; + } + + private static int FILE_CRYPTO_sha256(ILuaState lua, LuaInterpreter interpreter) + { + byte[] file = File.ReadAllBytes(ResolvePath(interpreter, lua.L_CheckString(1))); + lua.PushString(Aura_OS.System.Security.Sha256.hash(file)); + return 1; + } + + private static int FILE_CRYPTO_sha512(ILuaState lua, LuaInterpreter interpreter) + { + byte[] file = File.ReadAllBytes(ResolvePath(interpreter, lua.L_CheckString(1))); + lua.PushString(Sha512Hex(file)); + return 1; + } + + private static string Sha512Hex(byte[] data) + { + acryptohashnet.SHA512 hashAlgorithm = new acryptohashnet.SHA512(); + byte[] hashBytes = hashAlgorithm.ComputeHash(data); + hashAlgorithm.Dispose(); + return Aura_OS.Utils.Conversion.Hex(hashBytes); + } + + /// + /// Resolve a script-supplied file name as the Lua io library does: relative to the + /// interpreter's WorkingDirectory. gen2 "0:\..." names are converted first. + /// + private static string ResolvePath(LuaInterpreter interpreter, string path) + { + path = AuraPath.FromLegacy(path); + + string workingDirectory = interpreter.WorkingDirectory; + + if (workingDirectory != null && !Path.IsPathRooted(path)) + { + return Path.Combine(workingDirectory, path); + } + + return path; + } + } +} diff --git a/SRC/Aura_OS/System/Processing/PackageManager.cs b/SRC/Aura_OS/System/Processing/PackageManager.cs index 7ad3940cc..60ca22707 100644 --- a/SRC/Aura_OS/System/Processing/PackageManager.cs +++ b/SRC/Aura_OS/System/Processing/PackageManager.cs @@ -4,6 +4,7 @@ * PROGRAMMER(S): Valentin Charbonnier */ +using Aura_OS.System.Filesystem; using Aura_OS.System.Network; using JZero; using System; @@ -30,7 +31,20 @@ public void Update() { Console.WriteLine("Updating from '" + RepositoryUrl + "'..."); - string json = Http.DownloadFile(RepositoryUrl); + string json; + try + { + // GEN3-GAP(backend): the repository currently answers 301 -> https, then 404, and gen3 has no TLS. + json = Http.DownloadFile(RepositoryUrl); + } + catch (Exception ex) + { + Console.WriteLine("Failed to download the package list: " + ex.Message); + return; + } + + // gen2 appended to the list on every update. + Repository.Clear(); var rdr = new JsonReader(json); rdr.ReadArrayStart(); @@ -73,7 +87,7 @@ public void Update() } } - string installedPath = "0:\\System\\Programs\\" + package.Name + ".cexe"; + string installedPath = AuraPaths.ProgramsDir + package.Name + ".cexe"; if (File.Exists(installedPath)) { @@ -98,8 +112,16 @@ public void Upgrade() foreach (var package in Packages) { Console.Write("- '" + package.Link + "' "); - package.Download(); - Console.WriteLine("[OK]"); + + try + { + package.Download(); + Console.WriteLine("[OK]"); + } + catch (Exception ex) + { + Console.WriteLine("[FAILED] " + ex.Message); + } upgraded = true; } @@ -116,13 +138,22 @@ public void Add(string packageName) { if (package.Name == packageName) { + try + { + package.Download(); + } + catch (Exception ex) + { + Console.WriteLine("Failed to download " + packageName + ": " + ex.Message); + return; + } + package.Installed = true; Packages.Add(package); - package.Download(); - if (Directory.Exists("0:\\System\\Programs")) + if (Directory.Exists(AuraPaths.ProgramsDir)) { - File.WriteAllBytes("0:\\System\\Programs\\" + package.Name + ".cexe", package.Executable.RawData); + File.WriteAllBytes(AuraPaths.ProgramsDir + package.Name + ".cexe", package.Executable.RawData); Console.WriteLine(packageName + " installed."); } else diff --git a/SRC/Aura_OS/System/Processing/ProcessManager.cs b/SRC/Aura_OS/System/Processing/ProcessManager.cs index e43c8ed65..82a3aba88 100644 --- a/SRC/Aura_OS/System/Processing/ProcessManager.cs +++ b/SRC/Aura_OS/System/Processing/ProcessManager.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Aura_OS.System; using Aura_OS.System.Graphics.UI.GUI; diff --git a/SRC/Aura_OS/System/Processing/Processes/Explorer.cs b/SRC/Aura_OS/System/Processing/Processes/Explorer.cs index 8982259a1..cc013afbd 100644 --- a/SRC/Aura_OS/System/Processing/Processes/Explorer.cs +++ b/SRC/Aura_OS/System/Processing/Processes/Explorer.cs @@ -5,9 +5,10 @@ */ using Aura_OS.Processing; +using Aura_OS.System.Filesystem; using Aura_OS.System.Graphics.UI.GUI; using Aura_OS.System.Utils; -using Cosmos.System; +using Cosmos.Kernel.System.Mouse; namespace Aura_OS.System.Processing.Processes { @@ -42,7 +43,10 @@ public static bool ShowStartMenu public Explorer() : base("Explorer", ProcessType.KernelComponent) { - Screen = new((int)Kernel.ScreenWidth, (int)Kernel.ScreenHeight); + // Zero-copy alias of the canvas back buffer (Screen.Bitmap is null): the composited frame + // is shown by Kernel.Present() with a single Canvas.Display(), no extra 8 MB blit. + // Re-create it (and SetScreen again) if the canvas mode ever changes at runtime. + Screen = new DirectBitmap(Kernel.Canvas); WindowManager.Initialize(); WindowManager.SetScreen(Screen); @@ -77,7 +81,7 @@ public Explorer() : base("Explorer", ProcessType.KernelComponent) if (Kernel.Installed) { - Settings config = new Settings(@"0:\System\settings.ini"); + Settings config = new Settings(AuraPaths.SettingsIni); string value = config.GetValue("autologin"); string computerName = config.GetValue("hostname"); Kernel.ComputerName = computerName; diff --git a/SRC/Aura_OS/System/Processing/Runner.cs b/SRC/Aura_OS/System/Processing/Runner.cs index 57ca415ca..57eda534f 100644 --- a/SRC/Aura_OS/System/Processing/Runner.cs +++ b/SRC/Aura_OS/System/Processing/Runner.cs @@ -6,74 +6,164 @@ using System; using System.Collections.Generic; -using UniLua; +using System.Text; +using Cosmos.Executable.Lua; +using Aura_OS.System.Processing.Lua; namespace Aura_OS.System.Processing { public class ExecutableRunner { + /// + /// Run once before main.lua with the source lookup function as its argument: + /// dofile and loadfile serve the executable's own .lua files first, as gen2's LuaFile.VirtualFiles did. + /// + private const string EmbeddedLoaders = + "local source, rawloadfile, rawdofile, load = ..., loadfile, dofile, load\n" + + "function loadfile(name, ...)\n" + + " local code = type(name) == 'string' and source(name)\n" + + " if code then return load(code, '@' .. name, ...) end\n" + + " return rawloadfile(name, ...)\n" + + "end\n" + + "function dofile(name)\n" + + " local code = type(name) == 'string' and source(name)\n" + + " if code then return assert(load(code, '@' .. name))() end\n" + + " return rawdofile(name)\n" + + "end\n"; + public void Run(Executable executable, List args) { - try + if (executable == null || executable.LuaSources == null) { - LuaFile.VirtualFiles = new Dictionary(); + Console.WriteLine("Invalid executable."); + return; + } - // create Lua VM instance - var Lua = LuaAPI.NewState(); + if (args == null) + { + args = new List(); + } - // load base libraries - Lua.L_OpenLibs(); + LuaInterpreter lua = null; - // args - Lua.NewTable(); - Lua.PushValue(-1); - Lua.SetGlobal("arg"); + try + { + // create Lua VM instance (standard libraries, cosmos.crypto, os.execute, os.getenv) + lua = AuraLua.Create(); - Lua.PushString("main.lua"); - Lua.RawSetI(-2, 0); + ILuaState state = lua.State; - for (int i = 0; i < args.Count; i++) - { - Lua.PushString(args[i]); - Lua.RawSetI(-2, i + 1); - } + // GEN3-GAP(lua-host): Cosmos.Executable.Lua has no virtual-file loader (gen2 LuaFile.VirtualFiles), + // so every source becomes a package.preload entry, the module name require asks for. + Dictionary sources = new Dictionary(); + + state.GetGlobal("package"); + state.GetField(-1, "preload"); - foreach (var source in executable.LuaSources.Keys) + foreach (KeyValuePair source in executable.LuaSources) { - if (source == "main.lua") + // zip directory entries ("lib/") and assets + if (source.Key == null || source.Value == null || !source.Key.EndsWith(".lua", StringComparison.OrdinalIgnoreCase)) { continue; } - LoadLuaFile(source); + // L_LoadBytes reads one byte per char: decode UTF-8 and drop a BOM so non-ASCII literals survive + string code = Encoding.UTF8.GetString(source.Value).TrimStart('\uFEFF'); + + // capture errors + if (state.L_LoadBuffer(code, "@" + source.Key) != ThreadStatus.LUA_OK) + { + throw new LuaException(state.ToString(-1)); + } + + // "main.lua" -> "main", "lib/util.lua" -> "lib.util" + string module = source.Key.Substring(0, source.Key.Length - 4); + string dottedModule = module.Replace('/', '.').Replace('\\', '.'); + + if (dottedModule != module) + { + // gen2 resolved require "lib/util" straight to the file name: keep that working too + state.PushValue(-1); + state.SetField(-3, module); + } + + state.SetField(-2, dottedModule); + sources[source.Key] = code; } - LoadLuaFile("main.lua"); + state.Pop(2); - void LoadLuaFile(string fileName) + // dofile / loadfile on the executable's own files + if (state.L_LoadBuffer(EmbeddedLoaders, "=cexe") != ThreadStatus.LUA_OK) { - var status = Lua.L_LoadBytes(executable.LuaSources[fileName], fileName); + throw new LuaException(state.ToString(-1)); + } - // capture errors - if (status != ThreadStatus.LUA_OK) + state.PushCSharpFunction(l => + { + string code; + + if (sources.TryGetValue(l.L_CheckString(1), out code)) + { + l.PushString(code); + } + else { - throw new Exception(Lua.ToString(-1)); + l.PushNil(); } + + return 1; + }); + + if (state.PCall(1, 0, 0) != ThreadStatus.LUA_OK) + { + throw new LuaException(state.ToString(-1)); } - var status = Lua.PCall(0, LuaDef.LUA_MULTRET, 0); - if (status != ThreadStatus.LUA_OK) + // args: arg[0] = "main.lua", arg[1..n] = command-line arguments + state.CreateTable(args.Count, 1); + state.PushString("main.lua"); + state.RawSetI(-2, 0); + + for (int i = 0; i < args.Count; i++) { - throw new Exception(Lua.ToString(-1)); + state.PushString(args[i]); + state.RawSetI(-2, i + 1); } - LuaFile.VirtualFiles.Clear(); - LuaFile.VirtualFiles = null; + state.SetGlobal("arg"); + + // DoString gives the traceback, LuaException and os.exit handling; main.lua also gets the arguments as ... + lua.DoString("return package.preload['main'](table.unpack(arg))", "=main.lua"); + } + catch (LuaException e) + { + Console.WriteLine(e.Message); + + if (e.LuaStackTrace != null) + { + Console.WriteLine(e.LuaStackTrace); + } + } + catch (LuaExitException e) + { + if (e.ExitCode != 0) + { + Console.WriteLine("Exited with code " + e.ExitCode + "."); + } } catch (Exception e) { Console.WriteLine(e.ToString()); } + + // GEN3-GAP(finally): not a using, gen3 does not run finally/Dispose when an exception unwinds (C7). + // GEN3-GAP(finalizers): Dispose closes the files the program left open. + if (lua != null) + { + lua.Dispose(); + } } } } diff --git a/SRC/Aura_OS/System/Users/Settings.cs b/SRC/Aura_OS/System/Users/Settings.cs index 5e38eb87b..01a29f5ff 100644 --- a/SRC/Aura_OS/System/Users/Settings.cs +++ b/SRC/Aura_OS/System/Users/Settings.cs @@ -20,7 +20,8 @@ public Settings(string path) { this.path = path; - fileContent = null; + // A missing file behaves as an empty one: Add/Edit work and Push creates it. + fileContent = Array.Empty(); if (File.Exists(path)) { fileContent = File.ReadAllLines(path); @@ -128,6 +129,8 @@ public void Edit(string parameter, string value) } else { + // Add re-reads fileContent into config: clear it first or every line is duplicated. + config.Clear(); Add(parameter, value); } } diff --git a/SRC/Aura_OS/System/Users/Setup.cs b/SRC/Aura_OS/System/Users/Setup.cs index 0e4c31ad9..66a66ae98 100644 --- a/SRC/Aura_OS/System/Users/Setup.cs +++ b/SRC/Aura_OS/System/Users/Setup.cs @@ -7,13 +7,13 @@ using System; using System.IO; -using System.Linq; -using System.Runtime.CompilerServices; +using Aura_OS.System.Filesystem; +using Aura_OS.System.Network; using Aura_OS.System.Security; using Aura_OS.System.Users; using Aura_OS.System.Utils; -using Cosmos.Core.Memory; -using Cosmos.System.Network.Config; +using Cosmos.Kernel.System.Diagnostics; +using Cosmos.Kernel.System.Network; namespace Aura_OS.System { @@ -23,6 +23,7 @@ class Setup private string FinalPassword; private string FinalLang; private string FinalHostname; + private string FinalKeyboardLayout; /// /// Verify filesystem @@ -55,6 +56,15 @@ public void InitSetup(string username, string password, string hostname, string } if (InstallExists() == "continue") { + Volumes.RefreshSystemVolume(); + + if (AuraPaths.SystemVolume == null) + { + Console.WriteLine("No FAT volume is mounted, AuraOS cannot be installed."); + Console.WriteLine("Use 'vol /lp' to list partitions, 'vol /mp' to create one and 'vol /fp' to format it."); + return; + } + RegisterLanguage(language); RegisterUser(username, password); RegisterHostname(hostname); @@ -80,6 +90,13 @@ public void RegisterUser(string username, string password) { if ((username.Length >= 4) && (username.Length <= 20)) { + // The username becomes a directory name and a passwd field. + // GEN3-GAP(fat-names): the FAT driver accepts any character, so reject / \ : * ? " < > | here. + if (!AuraPath.IsValidName(username)) + { + throw new Exception("Username contains invalid characters."); + } + if ((password.Length >= 6) && (password.Length <= 40)) { FinalUsername = username; @@ -105,26 +122,37 @@ public void RegisterLanguage(string language) { Kernel.langSelected = "en_US"; FinalLang = "en_US"; - //Keyboard.Init(); } else if ((language.Equals("fr_FR")) || language.Equals("fr-FR")) { Kernel.langSelected = "fr_FR"; FinalLang = "fr_FR"; - //Keyboard.Init(); } else if ((language.Equals("nl_NL")) || language.Equals("nl-NL")) { Kernel.langSelected = "nl_NL"; FinalLang = "nl_NL"; - //Keyboard.Init(); } else if ((language.Equals("it_IT")) || language.Equals("it-IT")) { Kernel.langSelected = "it_IT"; FinalLang = "it_IT"; - //Keyboard.Init(); } + else + { + // Unknown language: default to en_US (FinalLang must not stay null, a null deref halts gen3) + Kernel.langSelected = "en_US"; + FinalLang = "en_US"; + } + + // fr_FR selects AZERTY; otherwise keep the live layout (setkeyboardmap / taskbar, "US" by default), + // since the setup command always passes en-US. Installation persists it as keyboardLayout. + FinalKeyboardLayout = FinalLang == "fr_FR" ? "FR" : Input.KeyboardLayouts.CurrentCode; + if (string.IsNullOrEmpty(FinalKeyboardLayout)) + { + FinalKeyboardLayout = "US"; + } + Input.KeyboardLayouts.Set(FinalKeyboardLayout); } /// @@ -134,11 +162,11 @@ public void InitDirs() { string[] DefaultSystemDirectories = { - @"0:\System\", - @"0:\System\Programs", - @"0:\System\Themes", - @"0:\System\Wallpapers", - @"0:\Users\" + AuraPaths.SystemDir, + AuraPaths.ProgramsDir, + AuraPaths.ThemesDir, + AuraPaths.WallpapersDir, + AuraPaths.UsersDir }; foreach (string dirs in DefaultSystemDirectories) @@ -153,10 +181,11 @@ public void InitDirs() /// public void InitFiles() { - if (Directory.Exists(@"0:\System")) + if (Directory.Exists(AuraPaths.SystemDir)) { - File.Create(@"0:\System\settings.ini"); - File.Create(@"0:\System\passwd"); + // gen3 has no finalizers: never leave a File.Create stream undisposed (truncate/create instead) + File.WriteAllText(AuraPaths.SettingsIni, string.Empty); + File.WriteAllText(AuraPaths.Passwd, string.Empty); } } @@ -167,9 +196,9 @@ public void CreateUserDirectories(string[] Users) { foreach (string user in Users) { - if (!Directory.Exists(@"0:\Users\" + user)) + if (!Directory.Exists(AuraPaths.UsersDir + user)) { - Directory.CreateDirectory(@"0:\Users\" + user); + Directory.CreateDirectory(AuraPaths.UsersDir + user); System.Users.Users.InitUserDirs(user); } @@ -201,18 +230,19 @@ public void Installation() string[] Users = { "root", dirUsername }; CreateUserDirectories(Users); + // GEN3-GAP(iso-files): theme assets are embedded resources (no ISO volume to copy from) Console.WriteLine("Copying SuaveSheet.bmp..."); - Filesystem.Entries.CopyFile(Files.IsoVolume + @"UI\Themes\SuaveSheet.bmp", @"0:\System\Themes\Suave.bmp"); + File.WriteAllBytes(AuraPaths.ThemesDir + "Suave.bmp", Files.Get("UI/Themes/SuaveSheet.bmp")); Console.WriteLine("Copying Suave.skin.xml..."); - Filesystem.Entries.CopyFile(Files.IsoVolume + @"UI\Themes\Suave.skin.xml", @"0:\System\Themes\Suave.xml"); + File.WriteAllBytes(AuraPaths.ThemesDir + "Suave.xml", Files.Get("UI/Themes/Suave.skin.xml")); Console.WriteLine("Saving wallpaper-1.bmp..."); - Filesystem.Entries.SaveFile(@"0:\System\Wallpapers\w1.bmp", Files.Wallpaper); - Heap.Collect(); + Filesystem.Entries.SaveFile(AuraPaths.WallpapersDir + "w1.bmp", Files.Wallpaper); + MemoryInfo.Collect(); Console.WriteLine("Saving wallpaper-2.bmp..."); - Filesystem.Entries.SaveFile(@"0:\System\Wallpapers\w2.bmp", Files.Wallpaper2); - Heap.Collect(); + Filesystem.Entries.SaveFile(AuraPaths.WallpapersDir + "w2.bmp", Files.Wallpaper2); + MemoryInfo.Collect(); - Settings config = new Settings(@"0:\System\settings.ini"); + Settings config = new Settings(AuraPaths.SettingsIni); if ((FinalLang.Equals("en_US")) || FinalLang.Equals("en-US")) { @@ -234,26 +264,30 @@ public void Installation() config.PutValue("language", "it_IT"); } + config.PutValue("keyboardLayout", FinalKeyboardLayout); + config.PutValue("hostname", FinalHostname); config.PutValue("setuptime", Time.MonthString() + "/" + Time.DayString() + "/" + Time.YearString() + ", " + Time.TimeString(true, true, true)); config.PutValue("autologin", "false"); - config.PutValue("themeBmpPath", @"0:\System\Themes\Suave.bmp"); - config.PutValue("themeXmlPath", @"0:\System\Themes\Suave.xml"); + config.PutValue("themeBmpPath", AuraPaths.ThemesDir + "Suave.bmp"); + config.PutValue("themeXmlPath", AuraPaths.ThemesDir + "Suave.xml"); config.PutValue("windowsTransparency", "255"); config.PutValue("taskbarTransparency", "255"); config.PutValue("screenWidth", Kernel.ScreenWidth.ToString()); config.PutValue("screenHeight", Kernel.ScreenHeight.ToString()); - config.PutValue("wallpaperPath", @"0:\System\Wallpapers\w1.bmp"); + config.PutValue("wallpaperPath", AuraPaths.WallpapersDir + "w1.bmp"); config.PutValue("debugger", "off"); - foreach (NetworkConfig networkConfig in NetworkConfiguration.NetworkConfigs) + for (int i = 0; i < NetworkManager.DeviceCount; i++) { - File.Create(@"0:\System\" + networkConfig.Device.NameID + ".ini"); - Settings settings = new Settings(@"0:\System\" + networkConfig.Device.NameID + ".ini"); + // GEN3-GAP(nic-names): no interface names in gen3, Aura aliases adapters as eth{Index} + string networkIni = AuraPaths.NetworkIni(NetworkHelper.AliasOf(NetworkManager.GetAdapter(i))); + File.WriteAllText(networkIni, string.Empty); + Settings settings = new Settings(networkIni); settings.Add("ipaddress", "0.0.0.0"); settings.Add("subnet", "0.0.0.0"); settings.Add("gateway", "0.0.0.0"); @@ -269,12 +303,17 @@ public void Installation() Kernel.userLogged = FinalUsername; Kernel.ComputerName = FinalHostname; + if (!string.IsNullOrEmpty(FinalHostname)) + { + Cosmos.Kernel.System.Network.Config.DnsConfig.HostName = FinalHostname; + } Console.WriteLine("Changing current directory to user directory..."); - Kernel.UserDirectory = @"0:\Users\" + dirUsername + @"\"; + Kernel.UserDirectory = AuraPaths.UsersDir + dirUsername + "/"; + Kernel.CurrentVolume = AuraPaths.SystemVolume; Kernel.CurrentDirectory = Kernel.UserDirectory; - Console.WriteLine("AuraOS v" + Kernel.Version + "-" + Kernel.Revision + " is now installed on 0:\\ :)"); + Console.WriteLine("AuraOS v" + Kernel.Version + "-" + Kernel.Revision + " is now installed on " + AuraPaths.SystemVolume + " :)"); } } } \ No newline at end of file diff --git a/SRC/Aura_OS/System/Users/Users.cs b/SRC/Aura_OS/System/Users/Users.cs index 7bc5b0ce2..cdf54455a 100644 --- a/SRC/Aura_OS/System/Users/Users.cs +++ b/SRC/Aura_OS/System/Users/Users.cs @@ -6,6 +6,7 @@ */ using System.IO; +using Aura_OS.System.Filesystem; using Aura_OS.System.Security; using System.Collections.Generic; using System; @@ -26,10 +27,10 @@ public static void InitUserDirs(string user) { string[] DefaultDirectories = { - @"0:\Users\" + user + @"\Desktop", - @"0:\Users\" + user + @"\Documents", - @"0:\Users\" + user + @"\Downloads", - @"0:\Users\" + user + @"\Music", + AuraPaths.UsersDir + user + "/Desktop", + AuraPaths.UsersDir + user + "/Documents", + AuraPaths.UsersDir + user + "/Downloads", + AuraPaths.UsersDir + user + "/Music", }; foreach (string dirs in DefaultDirectories) if (!Directory.Exists(dirs)) @@ -38,8 +39,8 @@ public static void InitUserDirs(string user) } #endregion UserDirs - public static string[] users; - static string[] reset; + public static string[] users = Array.Empty(); + static string[] reset = Array.Empty(); static List usersfile = new List(); /// @@ -78,7 +79,7 @@ public void Remove(string username) { LoadUsers(); DeleteUser(username); - //Directory.Delete(@"0:\Users\" + username, true); + //Directory.Delete(AuraPaths.UsersDir + username, true); Console.WriteLine("User has been remnoved."); } else @@ -95,10 +96,8 @@ public void ChangePassword(string username, string password) LoadUsers(); EditUser(username, password); - File.Delete(@"0:\System\passwd"); - File.Create(@"0:\System\passwd"); - PushUsers(); - //Directory.Delete(@"0:\Users\" + username, true); + PushUsers(); // WriteAllLines truncates passwd (gen2 Delete + undisposed Create leaked an fd) + //Directory.Delete(AuraPaths.UsersDir + username, true); Console.WriteLine("Password has been changed."); } @@ -133,8 +132,6 @@ public static void DeleteUser(string user) usersfile.Clear(); - File.Delete(@"0:\System\passwd"); - PushUsers(); } } @@ -219,15 +216,18 @@ public static void PutUser(string parameter, string value) public static void PushUsers() { - File.WriteAllLines(@"0:\System\passwd", users); + File.WriteAllLines(AuraPaths.Passwd, users); } public static void LoadUsers() { //reset of users string array in memory if there is "something" users = reset; - //load - users = File.ReadAllLines(@"0:\System\passwd"); + //load (a missing passwd behaves as an empty one: users never becomes null) + if (File.Exists(AuraPaths.Passwd)) + { + users = File.ReadAllLines(AuraPaths.Passwd); + } } } diff --git a/SRC/Aura_OS/System/Utils/AuraPower.cs b/SRC/Aura_OS/System/Utils/AuraPower.cs new file mode 100644 index 000000000..1e97bd32a --- /dev/null +++ b/SRC/Aura_OS/System/Utils/AuraPower.cs @@ -0,0 +1,45 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: Reboot / shutdown with a filesystem flush +* PROGRAMMERS: Valentin Charbonnier +*/ + +using System; +using Aura_OS.System.Filesystem; +using Cosmos.Kernel.System.Diagnostics; + +namespace Aura_OS.System +{ + /// + /// Every reboot/shutdown goes through here (inside ...Commands.Power a bare `Power` is that namespace). + /// Unmounts (flushes) every volume, then calls Cosmos.Kernel.System.Power. Does not return. + /// + public static class AuraPower + { + public static void Reboot() + { + Log.WriteString("[Aura] Rebooting...\n"); + UnmountVolumes(); + Cosmos.Kernel.System.Power.Reboot(); + } + + public static void Shutdown() + { + Log.WriteString("[Aura] Shutting down...\n"); + UnmountVolumes(); + Cosmos.Kernel.System.Power.Shutdown(); + } + + private static void UnmountVolumes() + { + try + { + Volumes.UnmountAll(); + } + catch (Exception) + { + // Power off anyway. + } + } + } +} diff --git a/SRC/Aura_OS/System/Utils/Crash.cs b/SRC/Aura_OS/System/Utils/Crash.cs index f47000278..82f0a17d9 100644 --- a/SRC/Aura_OS/System/Utils/Crash.cs +++ b/SRC/Aura_OS/System/Utils/Crash.cs @@ -5,7 +5,9 @@ */ using System; -using Sys = Cosmos.System; +using Cosmos.Kernel.System; +using Cosmos.Kernel.System.Diagnostics; +using CosmosKeyboard = Cosmos.Kernel.System.Keyboard.KeyboardManager; namespace Aura_OS.System { @@ -29,45 +31,110 @@ public static void WriteException(Exception ex) /// /// Stop the kernel and display exception + /// GEN3-GAP(cpu-exception): only managed exceptions reach this screen; CPU faults (#PF, #DE...) + /// halt in the Cosmos panic handler, whose report is on the serial log. /// /// Exception that stop the kernel public static void StopKernel(string exception, string description, string lastknowaddress, string ctxinterrupt) { Kernel.Running = false; - Kernel.Canvas.Clear(0xAA0000); + // First, so the reason survives in the serial log if drawing faults. + Log.WriteString("[CRASH] " + exception + ": " + description + "\n"); - Kernel.Canvas.DrawImageAlpha(Kernel.errorLogo, (int)((Kernel.Canvas.Mode.Width / 2) - (Kernel.errorLogo.Width / 2)), (int)((Kernel.Canvas.Mode.Height / 2) - (Kernel.errorLogo.Height / 2) - 89)); - - string CpuException = "CPU Exception x" + ctxinterrupt + " occured in Aura Operating System:"; - Kernel.Canvas.DrawString(CpuException, Kernel.font, Kernel.WhiteColor, (int)((Kernel.Canvas.Mode.Width / 2) - (CpuException.Length * Kernel.font.Width / 2)), (int)((Kernel.Canvas.Mode.Height / 2) - (Kernel.errorLogo.Height / 2)) + (89 + 1 * Kernel.font.Height)); + string CpuException; + if (ctxinterrupt == "0") + { + CpuException = "A fatal error occurred in Aura Operating System:"; + } + else + { + CpuException = "CPU Exception x" + ctxinterrupt + " occured in Aura Operating System:"; + } string Exception = "Exception: " + exception; - Kernel.Canvas.DrawString(Exception, Kernel.font, Kernel.WhiteColor, (int)((Kernel.Canvas.Mode.Width / 2) - (Exception.Length * Kernel.font.Width / 2)), (int)((Kernel.Canvas.Mode.Height / 2) - (Kernel.errorLogo.Height / 2)) + (89 + 2 * Kernel.font.Height)); - string Description = "Description: " + description; - Kernel.Canvas.DrawString(Description, Kernel.font, Kernel.WhiteColor, (int)((Kernel.Canvas.Mode.Width / 2) - (Description.Length * Kernel.font.Width / 2)), (int)((Kernel.Canvas.Mode.Height / 2) - (Kernel.errorLogo.Height / 2)) + (89 + 3 * Kernel.font.Height)); - string Version = "Aura Version: " + Kernel.Version; - Kernel.Canvas.DrawString(Version, Kernel.font, Kernel.WhiteColor, (int)((Kernel.Canvas.Mode.Width / 2) - (Version.Length * Kernel.font.Width / 2)), (int)((Kernel.Canvas.Mode.Height / 2) - (Kernel.errorLogo.Height / 2)) + (89 + 4 * Kernel.font.Height)); - string Revision = "Aura Revision: " + Kernel.Revision; - Kernel.Canvas.DrawString(Revision, Kernel.font, Kernel.WhiteColor, (int)((Kernel.Canvas.Mode.Width / 2) - (Revision.Length * Kernel.font.Width / 2)), (int)((Kernel.Canvas.Mode.Height / 2) - (Kernel.errorLogo.Height / 2)) + (89 + 5 * Kernel.font.Height)); + string PressKey = "Press any key to reboot..."; + + if (Kernel.Canvas == null || Kernel.errorLogo == null || Kernel.font == null) + { + // Boot failure before the canvas or the assets exist (a null dereference is a fatal #PF in gen3): + // text crash report on the KernelConsole (or on serial once Console.Out is redirected). + try + { + Console.WriteLine(); + Console.WriteLine(CpuException); + Console.WriteLine(Exception); + Console.WriteLine(Description); + Console.WriteLine(Version); + Console.WriteLine(Revision); + Console.WriteLine(PressKey); + } + catch + { + // No KernelConsole (no display): the serial log has the reason. + // (General catch: the local `Exception` string shadows the type name in this method.) + } + + WaitKeyAndReboot(); + return; + } + + int width = Kernel.Canvas.Width; + int height = Kernel.Canvas.Height; + int top = (height / 2) - (Kernel.errorLogo.Height / 2); + + Kernel.Canvas.Clear(unchecked((int)0xFFAA0000)); + + Kernel.Canvas.DrawImageAlpha(Kernel.errorLogo, (width / 2) - (Kernel.errorLogo.Width / 2), top - 89); - if (lastknowaddress != "") + Kernel.Canvas.DrawString(CpuException, Kernel.font, Kernel.WhiteColor, (width / 2) - (CpuException.Length * Kernel.font.Width / 2), top + (89 + 1 * Kernel.font.Height)); + + Kernel.Canvas.DrawString(Exception, Kernel.font, Kernel.WhiteColor, (width / 2) - (Exception.Length * Kernel.font.Width / 2), top + (89 + 2 * Kernel.font.Height)); + + Kernel.Canvas.DrawString(Description, Kernel.font, Kernel.WhiteColor, (width / 2) - (Description.Length * Kernel.font.Width / 2), top + (89 + 3 * Kernel.font.Height)); + + Kernel.Canvas.DrawString(Version, Kernel.font, Kernel.WhiteColor, (width / 2) - (Version.Length * Kernel.font.Width / 2), top + (89 + 4 * Kernel.font.Height)); + + Kernel.Canvas.DrawString(Revision, Kernel.font, Kernel.WhiteColor, (width / 2) - (Revision.Length * Kernel.font.Width / 2), top + (89 + 5 * Kernel.font.Height)); + + if (ctxinterrupt != "0" && !string.IsNullOrEmpty(lastknowaddress)) { string Lastknownaddress = "Last known address: 0x" + lastknowaddress; - Kernel.Canvas.DrawString(Lastknownaddress, Kernel.font, Kernel.WhiteColor, (int)((Kernel.Canvas.Mode.Width / 2) - (Lastknownaddress.Length * Kernel.font.Width / 2)), (int)((Kernel.Canvas.Mode.Height / 2) - (Kernel.errorLogo.Height / 2)) + (89 + 6 * Kernel.font.Height)); + Kernel.Canvas.DrawString(Lastknownaddress, Kernel.font, Kernel.WhiteColor, (width / 2) - (Lastknownaddress.Length * Kernel.font.Width / 2), top + (89 + 6 * Kernel.font.Height)); } - string PressKey = "Press any key to reboot..."; - Kernel.Canvas.DrawString(PressKey, Kernel.font, Kernel.WhiteColor, (int)((Kernel.Canvas.Mode.Width / 2) - (PressKey.Length * Kernel.font.Width / 2)), (int)((Kernel.Canvas.Mode.Height / 2) - (Kernel.errorLogo.Height / 2)) + (89 + 8 * Kernel.font.Height)); + Kernel.Canvas.DrawString(PressKey, Kernel.font, Kernel.WhiteColor, (width / 2) - (PressKey.Length * Kernel.font.Width / 2), top + (89 + 8 * Kernel.font.Height)); Kernel.Canvas.Display(); - Console.ReadKey(); + WaitKeyAndReboot(); + } + + /// + /// Waits for a fresh key press (keys typed before the crash are flushed; no echo, no KernelConsole + /// dependency, no tty1 drain), then reboots. + /// + private static void WaitKeyAndReboot() + { + try + { + if (KernelFeatures.Keyboard) + { + while (CosmosKeyboard.TryReadKey(out _)) + { + } + + CosmosKeyboard.ReadKey(); + } + } + catch (Exception) + { + } - Sys.Power.Reboot(); + AuraPower.Reboot(); } } -} \ No newline at end of file +} diff --git a/SRC/Aura_OS/System/Utils/CustomConsole.cs b/SRC/Aura_OS/System/Utils/CustomConsole.cs index e7e54cf80..25bd0aa8a 100644 --- a/SRC/Aura_OS/System/Utils/CustomConsole.cs +++ b/SRC/Aura_OS/System/Utils/CustomConsole.cs @@ -12,8 +12,13 @@ public class CustomConsole { public static System.Graphics.UI.GUI.Components.Console BootConsole; + // Every line goes to Logs first, which mirrors it to the serial log (before any drawing, + // so the message survives a fault while drawing). + public static void WriteLineInfo(string text) { + Logs.DoOSLog("[Info] " + text); + if (BootConsole != null) { BootConsole.Foreground = ConsoleColor.Cyan; @@ -26,17 +31,14 @@ public static void WriteLineInfo(string text) } else { - Console.ForegroundColor = ConsoleColor.Cyan; - Console.Write("[Info] "); - Console.ForegroundColor = ConsoleColor.White; - Console.Write(text + "\n"); + WriteConsole(ConsoleColor.Cyan, "[Info] ", text); } - - Logs.DoOSLog("[Info] " + text); } public static void WriteLineWarning(string text) { + Logs.DoOSLog("[WARNING] " + text); + if (BootConsole != null) { BootConsole.Foreground = ConsoleColor.Yellow; @@ -49,17 +51,14 @@ public static void WriteLineWarning(string text) } else { - Console.ForegroundColor = ConsoleColor.Yellow; - Console.Write("[WARNING] "); - Console.ForegroundColor = ConsoleColor.White; - Console.Write(text + "\n"); + WriteConsole(ConsoleColor.Yellow, "[WARNING] ", text); } - - Logs.DoOSLog("[WARNING] " + text); } public static void WriteLineOK(string text) { + Logs.DoOSLog("[OK] " + text); + if (BootConsole != null) { BootConsole.Foreground = ConsoleColor.Green; @@ -72,17 +71,14 @@ public static void WriteLineOK(string text) } else { - Console.ForegroundColor = ConsoleColor.Green; - Console.Write("[OK] "); - Console.ForegroundColor = ConsoleColor.White; - Console.Write(text + "\n"); + WriteConsole(ConsoleColor.Green, "[OK] ", text); } - - Logs.DoOSLog("[OK] " + text); } public static void WriteLineError(string text) { + Logs.DoOSLog("[Error] " + text); + if (BootConsole != null) { BootConsole.Foreground = ConsoleColor.DarkRed; @@ -95,13 +91,27 @@ public static void WriteLineError(string text) } else { - Console.ForegroundColor = ConsoleColor.DarkRed; - Console.Write("[Error] "); + WriteConsole(ConsoleColor.DarkRed, "[Error] ", text); + } + } + + /// + /// Before BootConsole exists: the gen3 KernelConsole (boot text on the framebuffer), or Kernel.GuiSink + /// once Console.Out is redirected. The plugged Console members throw when the KernelConsole is not + /// initialized (no display): the line is already on serial, so ignore it. + /// + private static void WriteConsole(ConsoleColor color, string prefix, string text) + { + try + { + Console.ForegroundColor = color; + Console.Write(prefix); Console.ForegroundColor = ConsoleColor.White; Console.Write(text + "\n"); } - - Logs.DoOSLog("[Error] " + text); + catch (Exception) + { + } } } -} \ No newline at end of file +} diff --git a/SRC/Aura_OS/System/Utils/ImageUtils.cs b/SRC/Aura_OS/System/Utils/ImageUtils.cs new file mode 100644 index 000000000..24000322d --- /dev/null +++ b/SRC/Aura_OS/System/Utils/ImageUtils.cs @@ -0,0 +1,100 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: Image helpers (wallpaper scaling) +* PROGRAMMERS: Valentin Charbonnier +*/ + +using Cosmos.Kernel.System.Graphics; + +namespace Aura_OS.System.Utils +{ + /// + /// GEN3-GAP(blit): gen3 has no public image scaling that produces a reusable image + /// (Canvas.DrawImage(img, x, y, w, h) rescales and allocates on every call), and gen3 runs at + /// the real framebuffer size (GEN3-GAP(display-mode)), so the 1920x1080 wallpapers are scaled + /// here once at load time, never per frame. + /// + public static class ImageUtils + { + /// + /// Returns a copy of the source image scaled to width x height with nearest-neighbour + /// sampling (16.16 fixed point, the same maths as gen3's private Canvas.ScaleImage). + /// Returns null for a null/empty source or a non-positive size. + /// + public static Bitmap ScaleTo(Image src, int w, int h) + { + if (src == null || w <= 0 || h <= 0) + { + return null; + } + + int srcWidth = src.Width; + int srcHeight = src.Height; + int[] s = src.RawData; + + if (srcWidth <= 0 || srcHeight <= 0 || s == null || s.Length < srcWidth * srcHeight) + { + return null; + } + + Bitmap dst = new Bitmap(w, h, ColorDepth.ColorDepth32); + int[] d = dst.RawData; + + long xRatio = (((long)srcWidth << 16) / w) + 1; + long yRatio = (((long)srcHeight << 16) / h) + 1; + + // Source column of every destination column, computed once (clamped: the +1 rounding + // can step past the last column when upscaling). + int[] columns = new int[w]; + for (int x = 0; x < w; x++) + { + int srcX = (int)((x * xRatio) >> 16); + columns[x] = srcX < srcWidth ? srcX : srcWidth - 1; + } + + for (int y = 0; y < h; y++) + { + int srcY = (int)((y * yRatio) >> 16); + if (srcY >= srcHeight) + { + srcY = srcHeight - 1; + } + + int srcRow = srcY * srcWidth; + int dstRow = y * w; + + for (int x = 0; x < w; x++) + { + d[dstRow + x] = s[srcRow + columns[x]]; + } + } + + return dst; + } + + /// + /// Scales an image to the screen (Kernel.ScreenWidth x Kernel.ScreenHeight). Returns the + /// source itself when it already has the screen size (no copy), or when it cannot be scaled. + /// gen2 required wallpapers to match the screen and blanked to black otherwise. + /// + public static Image ScaleToScreen(Image src) + { + if (src == null) + { + return null; + } + + int screenWidth = (int)Kernel.ScreenWidth; + int screenHeight = (int)Kernel.ScreenHeight; + + if (src.Width == screenWidth && src.Height == screenHeight) + { + return src; + } + + Bitmap scaled = ScaleTo(src, screenWidth, screenHeight); + + return scaled != null ? scaled : src; + } + } +} diff --git a/SRC/Aura_OS/System/Utils/PciNames.cs b/SRC/Aura_OS/System/Utils/PciNames.cs new file mode 100644 index 000000000..6fe29ce9e --- /dev/null +++ b/SRC/Aura_OS/System/Utils/PciNames.cs @@ -0,0 +1,632 @@ +// This code is licensed under the BSD 3-Clause license (see LICENSES/COSMOS/LICENSE.md for details) +/* +* PROJECT: Aura Operating System Development +* CONTENT: PCI class and device names +* PROGRAMMER(S): Valentin Charbonnier +* +* Tables copied from Cosmos (https://github.com/CosmosOS/Cosmos), file +* src/Cosmos.Kernel.HAL/Pci/DeviceString.cs (internal in gen3). +* Copyright (c) 2007-2026, CosmosOS, COSMOS Project. BSD 3-Clause. +* Adapted to take the raw ids; the "Aura additions" are QEMU devices. +*/ + +namespace Aura_OS.System.Utils +{ + /// + /// PCI names for lspci. + /// GEN3-GAP(pci): Cosmos keeps its name tables (DeviceString) internal, so Aura carries this copy. + /// + public static class PciNames + { + public static string GetDeviceString(ushort vendor, ushort device) + { + switch (vendor) + { + case 0x1022: //AMD + switch (device) + { + case 0x2000: + return "AMD PCnet LANCE PCI Ethernet Controller"; + default: + return "AMD Unknown device"; + } + case 0x104B: //Sony + switch (device) + { + case 0x1040: + return "Mylex BT958 SCSI Host Adaptor"; + default: + return "Mylex Unknown device"; + } + case 0x1234: //Bochs + switch (device) + { + case 0x1111: + return "Bochs BGA"; + default: + return "Bochs Unknown device"; + } + case 0x1274: //Ensoniq + switch (device) + { + case 0x1371: + return "Ensoniq AudioPCI"; + default: + return "Ensoniq Unknown device"; + } + case 0x15AD: //VMware + switch (device) + { + case 0x0405: + return "VMware NVIDIA 9500MGS"; + case 0x0740: + return "Vmware Virtual Machine Communication Interface"; + case 0x0770: + return "VMware Standard Enhanced PCI to USB Host Controller"; + case 0x0790: + return "VMware 6.0 Virtual USB 2.0 Host Controller"; + case 0x07A0: + return "VMware PCI Express Root Port"; + default: + return "VMware Unknown device"; + } + case 0x8086: //Intel + switch (device) + { + case 0x7190: + return "Intel 440BX/ZX AGPset Host Bridge"; + case 0x7191: + return "Intel 440BX/ZX AGPset PCI-to-PCI bridge"; + case 0x7110: + return "Intel PIIX4/4E/4M ISA Bridge"; + case 0x7111: + return "Intel PIIX4/82371AB/EB/MB IDE"; + case 0x7112: + return "Intel PIIX4/4E/4M USB Interface"; + case 0x7113: + return "Intel PIIX4/82371AB/EB/MB ACPI"; + // Aura additions (QEMU i440FX/Q35 machines) + case 0x100E: + return "Intel 82540EM Gigabit Ethernet Controller"; + case 0x10D3: + return "Intel 82574L Gigabit Network Connection"; + case 0x1237: + return "Intel 440FX - 82441FX PMC [Natoma]"; + case 0x2668: + return "Intel 82801FB (ICH6) High Definition Audio Controller"; + case 0x2918: + return "Intel 82801IB (ICH9) LPC Interface Controller"; + case 0x2922: + return "Intel 82801IR (ICH9R) 6 port SATA Controller [AHCI mode]"; + case 0x2930: + return "Intel 82801I (ICH9 Family) SMBus Controller"; + case 0x293E: + return "Intel 82801I (ICH9 Family) HD Audio Controller"; + case 0x29C0: + return "Intel 82G33/G31/P35/P31 Express DRAM Controller"; + case 0x7000: + return "Intel 82371SB PIIX3 ISA [Natoma/Triton II]"; + case 0x7010: + return "Intel 82371SB PIIX3 IDE [Natoma/Triton II]"; + case 0x7020: + return "Intel 82371SB PIIX3 USB [Natoma/Triton II]"; + default: + return "Intel Unknown device"; + } + // Aura addition + case 0x1AF4: //Red Hat (virtio) + switch (device) + { + case 0x1000: + return "Virtio network device"; + case 0x1001: + return "Virtio block device"; + case 0x1041: + return "Virtio 1.0 network device"; + case 0x1042: + return "Virtio 1.0 block device"; + case 0x1050: + return "Virtio 1.0 GPU"; + case 0x1052: + return "Virtio 1.0 input"; + default: + return "Virtio Unknown device"; + } + // Aura addition + case 0x1B36: //Red Hat (QEMU) + switch (device) + { + case 0x0008: + return "QEMU PCIe Host bridge"; + case 0x000D: + return "QEMU XHCI Host Controller"; + case 0x0010: + return "QEMU NVM Express Controller"; + default: + return "QEMU Unknown device"; + } + case 0x80EE: //VirtualBox + switch (device) + { + case 0xBEEF: + return "VirtualBox Graphics Adapter"; + case 0xCAFE: + return "VirtualBox Guest Service"; + default: + return "VirtualBox Unknown device"; + } + default: + return "Unknown device"; + } + } + + public static string GetTypeString(byte cls, byte sub, byte progIf) + { + switch (cls) + { + case 0x00: + switch (sub) + { + case 0x01: + return "VGA-Compatible Device"; + default: + return "0x00 Subclass"; + } + case 0x01: + switch (sub) + { + case 0x00: + return "SCSI Bus Controller"; + case 0x01: + return "IDE Controller"; + case 0x02: + return "Floppy Disk Controller"; + case 0x03: + return "IPI Bus Controller"; + case 0x04: + return "RAID Controller"; + case 0x05: + return "ATA Controller"; + case 0x06: + return "Serial ATA"; + case 0x80: + return "Unknown Mass Storage Controller"; + default: + return "Mass Storage Controller"; + } + case 0x02: + switch (sub) + { + case 0x00: + return "Ethernet Controller"; + case 0x01: + return "Token Ring Controller"; + case 0x02: + return "FDDI Controller"; + case 0x03: + return "ATM Controller"; + case 0x04: + return "ISDN Controller"; + case 0x05: + return "WorldFip Controller"; + case 0x06: + return "PICMG 2.14 Multi Computing"; + case 0x80: + return "Unknown Network Controller"; + default: + return "Network Controller"; + } + case 0x03: + switch (sub) + { + case 0x00: + switch (progIf) + { + case 0x00: + return "VGA-Compatible Controller"; + case 0x01: + return "8512-Compatible Controller"; + default: + return "Unknown Display Controller"; + } + case 0x01: + return "XGA Controller"; + case 0x02: + return "3D Controller (Not VGA-Compatible)"; + case 0x80: + return "Unknown Display Controller"; + default: + return "Display Controller"; + } + case 0x04: + switch (sub) + { + case 0x00: + return "Video Device"; + case 0x01: + return "Audio Device"; + case 0x02: + return "Computer Telephony Device"; + case 0x80: + return "Unknown Multimedia Controller"; + default: + return "Multimedia Controller"; + } + case 0x05: + switch (sub) + { + case 0x00: + return "RAM Controller"; + case 0x01: + return "Flash Controller"; + case 0x80: + return "Unknown Memory Controller"; + default: + return "Memory Controller"; + } + case 0x06: + switch (sub) + { + case 0x00: + return "Host Bridge"; + case 0x01: + return "ISA Bridge"; + case 0x02: + return "EISA Bridge"; + case 0x03: + return "MCA Bridge"; + case 0x04: + switch (progIf) + { + case 0x00: + return "PCI-to-PCI Bridge"; + case 0x01: + return "PCI-to-PCI Bridge (Subtractive Decode)"; + default: + return "Unknown PCI-to-PCI Bridge"; + } + case 0x05: + return "PCMCIA Bridge"; + case 0x06: + return "NuBus Bridge"; + case 0x07: + return "CardBus Bridge"; + case 0x08: + return "RACEway Bridge"; + case 0x09: + switch (progIf) + { + case 0x00: + return "PCI-to-PCI Bridge (Semi-Transparent, Primary)"; + case 0x01: + return "PCI-to-PCI Bridge (Semi-Transparent, Secondary)"; + default: + return "Unknown PCI-to-PCI Bridge"; + } + case 0x0A: + return "InfiniBrand-to-PCI Host Bridge"; + case 0x80: + return "Unknown Bridge Device"; + default: + return "Bridge Device"; + } + case 0x07: + switch (sub) + { + case 0x00: + switch (progIf) + { + case 0x00: + return "Generic XT-Compatible Serial Controller"; + case 0x01: + return "16450-Compatible Serial Controller"; + case 0x02: + return "16550-Compatible Serial Controller"; + case 0x03: + return "16650-Compatible Serial Controller"; + case 0x04: + return "16750-Compatible Serial Controller"; + case 0x05: + return "16850-Compatible Serial Controller"; + case 0x06: + return "16950-Compatible Serial Controller"; + default: + return "Simple Communication Controller"; + } + case 0x01: + switch (progIf) + { + case 0x00: + return "Parallel Port"; + case 0x01: + return "Bi-Directional Parallel Port"; + case 0x02: + return "ECP 1.X Compliant Parallel Port"; + case 0x03: + return "IEEE 1284 Controller"; + case 0xFE: + return "IEEE 1284 Target Device"; + default: + return "Parallel Port"; + } + case 0x02: + return "Multiport Serial Controller"; + case 0x03: + switch (progIf) + { + case 0x00: + return "Generic Modem"; + case 0x01: + return "Hayes Compatible Modem (16450-Compatible Interface)"; + case 0x02: + return "Hayes Compatible Modem (16550-Compatible Interface)"; + case 0x03: + return "Hayes Compatible Modem (16650-Compatible Interface)"; + case 0x04: + return "Hayes Compatible Modem (16750-Compatible Interface)"; + default: + return "Modem"; + } + case 0x04: + return "IEEE 488.1/2 (GPIB) Controller"; + case 0x05: + return "Smart Card"; + case 0x80: + return "Unknown Communications Device"; + default: + return "Simple Communication Controller"; + } + case 0x08: + switch (sub) + { + case 0x00: + switch (progIf) + { + case 0x00: + return "Generic 8259 PIC"; + case 0x01: + return "ISA PIC"; + case 0x02: + return "EISA PIC"; + case 0x10: + return "I/O APIC Interrupt Controller"; + case 0x20: + return "I/O(x) APIC Interrupt Controller"; + default: + return "PIC"; + } + case 0x01: + switch (progIf) + { + case 0x00: + return "Generic 8237 DMA Controller"; + case 0x01: + return "ISA DMA Controller"; + case 0x02: + return "EISA DMA Controller"; + default: + return "DMA Controller"; + } + case 0x02: + switch (progIf) + { + case 0x00: + return "Generic 8254 System Timer"; + case 0x01: + return "ISA System Timer"; + case 0x02: + return "EISA System Timer"; + default: + return "System Timer"; + } + case 0x03: + switch (progIf) + { + case 0x00: + return "Generic RTC Controller"; + case 0x01: + return "ISA RTC Controller"; + default: + return "RTC Controller"; + } + case 0x04: + return "Generic PCI Hot-Plug Controller"; + case 0x80: + return "Unknown System Peripheral"; + default: + return "Base System Peripheral"; + } + case 0x09: + switch (sub) + { + case 0x00: + return "Keyboard Controller"; + case 0x01: + return "Digitizer"; + case 0x02: + return "Mouse Controller"; + case 0x03: + return "Scanner Controller"; + case 0x04: + switch (progIf) + { + case 0x00: + return "Gameport Controller (Generic)"; + case 0x10: + return "Gameport Controller (Legacy)"; + default: + return "Gameport Controller"; + } + case 0x80: + return "Unknown Input Controller"; + default: + return "Input Device"; + } + case 0x0A: + switch (sub) + { + case 0x00: + return "Generic Docking Station"; + case 0x80: + return "Unknown Docking Station"; + default: + return "Docking Station"; + } + case 0x0B: + switch (sub) + { + case 0x00: + return "386 Processor"; + case 0x01: + return "486 Processor"; + case 0x02: + return "Pentium Processor"; + case 0x10: + return "Alpha Processor"; + case 0x20: + return "PowerPC Processor"; + case 0x30: + return "MIPS Processor"; + case 0x40: + return "Co-Processor"; + default: + return "Processor"; + } + case 0x0C: + switch (sub) + { + case 0x00: + switch (progIf) + { + case 0x00: + return "IEEE 1394 Controller (FireWire)"; + case 0x10: + return "IEEE 1394 Controller (1394 OpenHCI Spec)"; + default: + return "IEEE Controller"; + } + case 0x01: + return "ACCESS.bus"; + case 0x02: + return "SSA"; + case 0x03: + switch (progIf) + { + case 0x00: + return "USB (Universal Host Controller Spec)"; + case 0x10: + return "USB (Open Host Controller Spec)"; + case 0x20: + return "USB2 Host Controller (Intel Enhanced Host Controller Interface)"; + case 0x30: + return "USB3 XHCI Controller"; + case 0x80: + return "Unspecified USB Controller"; + case 0xFE: + return "USB (Not Host Controller)"; + default: + return "USB"; + } + case 0x04: + return "Fibre Channel"; + case 0x05: + return "SMBus"; + case 0x06: + return "InfiniBand"; + case 0x07: + switch (progIf) + { + case 0x00: + return "IPMI SMIC Interface"; + case 0x01: + return "IPMI Kybd Controller Style Interface"; + case 0x02: + return "IPMI Block Transfer Interface"; + default: + return "IPMI SMIC Interface"; + } + case 0x08: + return "SERCOS Interface Standard (IEC 61491)"; + case 0x09: + return "CANbus"; + default: + return "Serial Bus Controller"; + } + case 0x0D: + switch (sub) + { + case 0x00: + return "iRDA Compatible Controller"; + case 0x01: + return "Consumer IR Controller"; + case 0x10: + return "RF Controller"; + case 0x11: + return "Bluetooth Controller"; + case 0x12: + return "Broadband Controller"; + case 0x20: + return "Ethernet Controller (802.11a)"; + case 0x21: + return "Ethernet Controller (802.11b)"; + case 0x80: + return "Unknown Wireless Controller"; + default: + return "Wireless Controller"; + } + case 0x0E: + switch (sub) + { + case 0x00: + return "Message FIFO"; + default: + return "Intelligent I/O Controller"; + } + case 0x0F: + switch (sub) + { + case 0x01: + return "TV Controller"; + case 0x02: + return "Audio Controller"; + case 0x03: + return "Voice Controller"; + case 0x04: + return "Data Controller"; + default: + return "Satellite Communication Controller"; + } + case 0x10: + switch (sub) + { + case 0x00: + return "Network and Computing Encrpytion/Decryption"; + case 0x10: + return "Entertainment Encryption/Decryption"; + case 0x80: + return "Unknown Encryption/Decryption"; + default: + return "Encryption/Decryption Controller"; + } + case 0x11: + switch (sub) + { + case 0x00: + return "DPIO Modules"; + case 0x01: + return "Performance Counters"; + case 0x10: + return "Communications Syncrhonization Plus Time and Frequency Test/Measurment"; + case 0x20: + return "Management Card"; + case 0x80: + return "Unknown Data Acquisition/Signal Processing Controller"; + default: + return "Data Acquisition and Signal Processing Controller"; + } + default: + return "Unknown device type"; + } + } + } +} diff --git a/SRC/Aura_OS/System/Utils/SerialTextWriter.cs b/SRC/Aura_OS/System/Utils/SerialTextWriter.cs new file mode 100644 index 000000000..94bea422c --- /dev/null +++ b/SRC/Aura_OS/System/Utils/SerialTextWriter.cs @@ -0,0 +1,102 @@ +/* +* PROJECT: Aura Operating System Development +* CONTENT: TextWriter that sends Console output to the serial log +* PROGRAMMERS: Valentin Charbonnier +*/ + +using System; +using System.IO; +using Cosmos.Kernel.System.Diagnostics; + +namespace Aura_OS.System.Utils +{ + /// + /// Installed as Console.Out/Error (Kernel.GuiSink) once the GUI owns the canvas: the gen3 KernelConsole + /// draws on the same canvas, so un-redirected Console output would paint over the desktop. + /// Everything goes to the serial log. Never throws (an exception escaping a writer installed with + /// Console.SetOut would leave the SyncTextWriter monitor held). + /// + public sealed class SerialTextWriter : TextWriter + { + public override global::System.Text.Encoding Encoding => global::System.Text.Encoding.UTF8; + + public override void Write(char value) + { + try + { + Log.WriteString(value.ToString()); + } + catch (Exception) + { + } + } + + public override void Write(string value) + { + if (value == null) + { + return; + } + + try + { + Log.WriteString(value); + } + catch (Exception) + { + } + } + + public override void Write(char[] buffer, int index, int count) + { + if (buffer == null || index < 0 || count <= 0 || index + count > buffer.Length) + { + return; + } + + try + { + Log.WriteString(new string(buffer, index, count)); + } + catch (Exception) + { + } + } + + public override void Write(ReadOnlySpan buffer) + { + if (buffer.IsEmpty) + { + return; + } + + try + { + Log.WriteString(new string(buffer)); + } + catch (Exception) + { + } + } + + public override void WriteLine(string value) + { + try + { + if (value != null) + { + Log.WriteString(value); + } + + Log.WriteString("\n"); + } + catch (Exception) + { + } + } + + public override void Flush() + { + } + } +} diff --git a/SRC/Aura_OS/System/Utils/Time.cs b/SRC/Aura_OS/System/Utils/Time.cs index 5945af299..84a15cafa 100644 --- a/SRC/Aura_OS/System/Utils/Time.cs +++ b/SRC/Aura_OS/System/Utils/Time.cs @@ -6,111 +6,119 @@ * Alexy DA CRUZ */ -using Cosmos.HAL; +using System; namespace Aura_OS.System { public static class Time { - static int Hour() { return RTC.Hour; } + // Each public method reads DateTime.Now once and passes the snapshot down, + // so the fields of one string all come from the same instant. + // GEN3-GAP(tz-rtc): firmware clock as-is, no timezone. - static int Minute() { return RTC.Minute; } + static int Hour(DateTime now) { return now.Hour; } - static int Second() { return RTC.Second; } + static int Minute(DateTime now) { return now.Minute; } - static int Century() { return RTC.Century; } + static int Second(DateTime now) { return now.Second; } - static int Year() { return RTC.Year; } + static int Century(DateTime now) { return now.Year / 100; } - static int Month() { return RTC.Month; } + // 4-digit year (the gen2 RTC year was 2-digit). + static int Year(DateTime now) { return now.Year; } - static int DayOfMonth() { return RTC.DayOfTheMonth; } + static int Month(DateTime now) { return now.Month; } - static int DayOfWeek() { return RTC.DayOfTheWeek; } + static int DayOfMonth(DateTime now) { return now.Day; } - static string getTime24(bool hour, bool min, bool sec) + // 0 = Sunday (the gen2 RTC day of week was 1-based). + static int DayOfWeek(DateTime now) { return (int)now.DayOfWeek; } + + static string getTime24(DateTime now, bool hour, bool min, bool sec) { string timeStr = ""; if (hour) { - if (Hour().ToString().Length == 1) + if (Hour(now).ToString().Length == 1) { - timeStr += "0" + Hour().ToString(); + timeStr += "0" + Hour(now).ToString(); } else { - timeStr += Hour().ToString(); + timeStr += Hour(now).ToString(); } } if (min) { - if (Minute().ToString().Length == 1) + if (Minute(now).ToString().Length == 1) { timeStr += ":"; - timeStr += "0" + Minute().ToString(); + timeStr += "0" + Minute(now).ToString(); } else { timeStr += ":"; - timeStr += Minute().ToString(); + timeStr += Minute(now).ToString(); } } if (sec) { - if (Second().ToString().Length == 1) + if (Second(now).ToString().Length == 1) { timeStr += ":"; - timeStr += "0" + Second().ToString(); + timeStr += "0" + Second(now).ToString(); } else { timeStr += ":"; - timeStr += Second().ToString(); + timeStr += Second(now).ToString(); } } return timeStr; } - static string getTime12(bool hour, bool min, bool sec) + static string getTime12(DateTime now, bool hour, bool min, bool sec) { string timeStr = ""; if (hour) { - if (Hour() > 12) - timeStr += Hour() - 12; + if (Hour(now) > 12) + timeStr += Hour(now) - 12; + else if (Hour(now) == 0) + timeStr += 12; else - timeStr += Hour(); + timeStr += Hour(now); } if (min) { - if (Minute().ToString().Length == 1) + if (Minute(now).ToString().Length == 1) { timeStr += ":"; - timeStr += "0" + Minute().ToString(); + timeStr += "0" + Minute(now).ToString(); } else { timeStr += ":"; - timeStr += Minute().ToString(); + timeStr += Minute(now).ToString(); } } if (sec) { - if (Second().ToString().Length == 1) + if (Second(now).ToString().Length == 1) { timeStr += ":"; - timeStr += "0" + Second().ToString(); + timeStr += "0" + Second(now).ToString(); } else { timeStr += ":"; - timeStr += Second().ToString(); + timeStr += Second(now).ToString(); } } if (hour) { - if (Hour() > 12) + if (Hour(now) >= 12) timeStr += " PM"; else timeStr += " AM"; @@ -124,18 +132,20 @@ static string getTime12(bool hour, bool min, bool sec) /// Actual Hour public static string TimeString(bool hour, bool min, bool sec) { + DateTime now = DateTime.Now; + switch (Kernel.langSelected) { case "fr_FR": - return getTime24(hour, min, sec); + return getTime24(now, hour, min, sec); case "en_US": - return getTime12(hour, min, sec); + return getTime12(now, hour, min, sec); case "nl_NL": - return getTime24(hour, min, sec); + return getTime24(now, hour, min, sec); case "it_IT": - return getTime12(hour, min, sec); + return getTime12(now, hour, min, sec); default: - return getTime12(hour, min, sec); + return getTime12(now, hour, min, sec); } } @@ -145,7 +155,7 @@ public static string TimeString(bool hour, bool min, bool sec) /// Actual Year public static string YearString() { - int intyear = Year(); + int intyear = Year(DateTime.Now); string stringyear = intyear.ToString(); if (stringyear.Length == 2) @@ -161,7 +171,7 @@ public static string YearString() /// Actual Month public static string MonthString() { - int intmonth = Month(); + int intmonth = Month(DateTime.Now); string stringmonth = intmonth.ToString(); if (stringmonth.Length == 1) @@ -177,7 +187,7 @@ public static string MonthString() /// Actual Day public static string DayString() { - int intday = DayOfMonth(); + int intday = DayOfMonth(DateTime.Now); string stringday = intday.ToString(); if (stringday.Length == 1) diff --git a/SRC/Aura_Plugs/Aura_Plugs.csproj b/SRC/Aura_Plugs/Aura_Plugs.csproj deleted file mode 100644 index d35d67d19..000000000 --- a/SRC/Aura_Plugs/Aura_Plugs.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - net6.0 - True - - - - - - - - - - - - - XSharp.dll - - - - diff --git a/SRC/Aura_Plugs/DebuggerImpl.cs b/SRC/Aura_Plugs/DebuggerImpl.cs deleted file mode 100644 index 71d73f097..000000000 --- a/SRC/Aura_Plugs/DebuggerImpl.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Aura_OS; -using Aura_OS.System; -using Aura_OS.System.Graphics.UI.GUI; -using Cosmos.Debug.Kernel; -using IL2CPU.API.Attribs; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Aura_Plugs -{ - [Plug(Target = typeof(Debugger))] - public class DebuggerImpl - { - public static void DoSend(string aText) - { - Logs.DoKernelLog(aText); - } - } -} diff --git a/SRC/Aura_Plugs/DirectBitmapImpl.cs b/SRC/Aura_Plugs/DirectBitmapImpl.cs deleted file mode 100644 index efbf4b283..000000000 --- a/SRC/Aura_Plugs/DirectBitmapImpl.cs +++ /dev/null @@ -1,368 +0,0 @@ -/* -* PROJECT: Aura Operating System Development -* CONTENT: Direct bitmap plugs (used for compositing) -* PROGRAMMERS: Valentin Charbonnier -* https://github.com/sswroom/SClass -*/ - -using System; -using XSharp.Assembler; -using XSharp; -using IL2CPU.API.Attribs; -using Aura_OS.System.Graphics.UI.GUI; - -namespace Cosmos.System_Plugs.System.Drawing -{ - [Plug(Target = typeof(DirectBitmap))] - public unsafe static class DrawImageAlphaImpl - { - [PlugMethod(Assembler = typeof(AlphaBltSSE2ASM))] - public static void AlphaBlendSSE(uint* dest, int dbpl, uint* src, int sbpl, int width, int height) => throw new NotImplementedException(); - [PlugMethod(Assembler = typeof(AlphaBltSSEASM))] - public static void AlphaBltSSE2(byte* dst, byte* src, int w, int h, int wmul4) => throw new NotImplementedException(); - [PlugMethod(Assembler = typeof(BrightnessASM))] - public static void OpacitySSE(uint* pixelPtr, int w, int h, int bpl, uint a) => throw new NotImplementedException(); - } - - public class AlphaBltSSE2ASM : AssemblerMethod - { - // public static void AlphaBltSSE2(uint* dest, int dbpl, uint* src, int sbpl, int width, int height) - public override void AssembleNew(Assembler aAssembler, object aMethodInfo) - { - XS.LiteralCode(" push ebp"); - XS.LiteralCode(" push ebx"); - XS.LiteralCode(" push esi"); - XS.LiteralCode(" push edi"); - XS.LiteralCode("mov eax,dword [ebp+12]"); // width - XS.LiteralCode(" shl eax,2"); - XS.LiteralCode("sub dword [ebp+16],eax"); // sbpl - XS.LiteralCode("sub dword [ebp+24],eax"); // dbpl - XS.LiteralCode(" test eax,15"); - XS.LiteralCode(" jnz iadbldstart"); - XS.LiteralCode("test dword [ebp+28],15"); // dest - XS.LiteralCode(" jnz iadbld4start"); - XS.LiteralCode("test dword [ebp+24],15"); // dbpl - XS.LiteralCode(" jnz iadbld4start"); - XS.LiteralCode(" jmp iadbld4astart"); - XS.LiteralCode(" align 16"); - XS.LiteralCode("iadbldstart:"); - XS.LiteralCode(" mov ebx,0x10101010"); - XS.LiteralCode(" pxor xmm2,xmm2"); - XS.LiteralCode(" movd xmm4,ebx"); - XS.LiteralCode(" punpcklbw xmm4, xmm2"); - XS.LiteralCode("mov edi,dword [ebp+28]"); // dest - XS.LiteralCode("mov esi,dword [ebp+20]"); // src - XS.LiteralCode("mov edx,dword [ebp+8]"); // height - XS.LiteralCode(" ALIGN 16"); - XS.LiteralCode("iadbldlop:"); - XS.LiteralCode("mov ecx,dword [ebp+12]"); // width - XS.LiteralCode(" align 16"); - XS.LiteralCode("iadbldlop2:"); - XS.LiteralCode(" mov bl,byte [esi+3]"); - XS.LiteralCode(" mov bh,bl"); - XS.LiteralCode(" movzx eax,bx"); - XS.LiteralCode(" shl ebx,16"); - XS.LiteralCode(" or eax,ebx"); - XS.LiteralCode(" movd xmm0,eax"); - XS.LiteralCode(" mov ebx,0xffffffff"); - XS.LiteralCode(" sub ebx,eax"); - XS.LiteralCode(" or ebx,0xff000000"); - XS.LiteralCode(" movd xmm3,ebx"); - XS.LiteralCode(" movd xmm1,dword [esi]"); - XS.LiteralCode(" punpcklbw xmm0, xmm2"); - XS.LiteralCode(" punpcklbw xmm1, xmm2"); - XS.LiteralCode(" pmullw xmm0,xmm1"); - XS.LiteralCode(" movdqa xmm1,xmm0"); - XS.LiteralCode(" movd xmm0,dword [edi]"); - XS.LiteralCode(" punpcklbw xmm3, xmm2"); - XS.LiteralCode(" punpcklbw xmm0, xmm2"); - XS.LiteralCode(" pmullw xmm0,xmm3"); - XS.LiteralCode(" paddusw xmm0,xmm1"); - XS.LiteralCode(" movdqa xmm1,xmm0"); - XS.LiteralCode(" psrlw xmm1,8"); - XS.LiteralCode(" paddusw xmm0,xmm1"); - XS.LiteralCode(" paddusw xmm0,xmm4"); - XS.LiteralCode(" psrlw xmm0,8"); - XS.LiteralCode(" packuswb xmm0,xmm2"); - XS.LiteralCode(" movd dword [edi],xmm0"); - XS.LiteralCode(" lea esi,[esi+4]"); - XS.LiteralCode(" lea edi,[edi+4]"); - XS.LiteralCode(" dec ecx"); - XS.LiteralCode(" jnz iadbldlop2"); - XS.LiteralCode("add esi,dword [ebp+16]"); // sAdd - XS.LiteralCode("add edi,dword [ebp+24]"); // dAdd - XS.LiteralCode(" dec edx"); - XS.LiteralCode(" jnz iadbldlop"); - XS.LiteralCode(" jmp iadbldexit"); - XS.LiteralCode(" align 16"); - XS.LiteralCode("iadbld4start:"); - XS.LiteralCode("shr dword [ebp+12],2"); // width - XS.LiteralCode(" mov ebx,0x10101010"); - XS.LiteralCode(" pxor xmm2,xmm2"); - XS.LiteralCode(" movd xmm4,ebx"); - XS.LiteralCode(" punpckldq xmm4, xmm4"); - XS.LiteralCode(" punpcklbw xmm4, xmm2"); - XS.LiteralCode(" mov ebx,0xffffffff"); - XS.LiteralCode(" movd xmm6,ebx"); - XS.LiteralCode(" mov ebx,0xff000000"); - XS.LiteralCode(" movd xmm7,ebx"); - XS.LiteralCode(" punpckldq xmm6,xmm6"); - XS.LiteralCode(" punpckldq xmm7,xmm7"); - XS.LiteralCode("mov edi,dword [ebp+28]"); // dest - XS.LiteralCode("mov esi,dword [ebp+20]"); // src - XS.LiteralCode("mov edx,dword [ebp+8]"); // height - XS.LiteralCode(" ALIGN 16"); - XS.LiteralCode("iadbld4lop:"); - XS.LiteralCode("mov ecx,dword [ebp+12]"); // width - XS.LiteralCode(" align 16"); - XS.LiteralCode("iadbld4lop2:"); - XS.LiteralCode(" movzx eax,byte [esi+3]"); - XS.LiteralCode(" mov ah,byte [esi+7]"); - XS.LiteralCode(" movd xmm0,eax"); - XS.LiteralCode(" punpcklbw xmm0,xmm0"); - XS.LiteralCode(" punpcklwd xmm0,xmm0"); - XS.LiteralCode(" movdqa xmm3,xmm6"); - XS.LiteralCode(" psubd xmm3,xmm0"); - XS.LiteralCode(" por xmm3,xmm7"); - XS.LiteralCode(" movq xmm1,[esi]"); - XS.LiteralCode(" punpcklbw xmm0, xmm2"); - XS.LiteralCode(" punpcklbw xmm1, xmm2"); - XS.LiteralCode(" pmullw xmm0,xmm1"); - XS.LiteralCode(" movdqa xmm1,xmm0"); - XS.LiteralCode(" movq xmm0,[edi]"); - XS.LiteralCode(" punpcklbw xmm3, xmm2"); - XS.LiteralCode(" punpcklbw xmm0, xmm2"); - XS.LiteralCode(" pmullw xmm0,xmm3"); - XS.LiteralCode(" paddusw xmm0,xmm1"); - XS.LiteralCode(" movdqa xmm1,xmm0"); - XS.LiteralCode(" psrlw xmm1,8"); - XS.LiteralCode(" paddusw xmm0,xmm1"); - XS.LiteralCode(" paddusw xmm0,xmm4"); - XS.LiteralCode(" movzx eax,byte [esi+11]"); - XS.LiteralCode(" mov ah,byte [esi+15]"); - XS.LiteralCode(" movd xmm5,eax"); - XS.LiteralCode(" punpcklbw xmm5,xmm5"); - XS.LiteralCode(" punpcklwd xmm5,xmm5"); - XS.LiteralCode(" movdqa xmm3,xmm6"); - XS.LiteralCode(" psubd xmm3,xmm5"); - XS.LiteralCode(" por xmm3,xmm7"); - XS.LiteralCode(" movq xmm1,[esi+8]"); - XS.LiteralCode(" punpcklbw xmm5,xmm2"); - XS.LiteralCode(" punpcklbw xmm1,xmm2"); - XS.LiteralCode(" pmullw xmm5,xmm1"); - XS.LiteralCode(" movdqa xmm1,xmm5"); - XS.LiteralCode(" movq xmm5,[edi+8]"); - XS.LiteralCode(" punpcklbw xmm3,xmm2"); - XS.LiteralCode(" punpcklbw xmm5,xmm2"); - XS.LiteralCode(" pmullw xmm5,xmm3"); - XS.LiteralCode(" paddusw xmm5,xmm1"); - XS.LiteralCode(" movdqa xmm1,xmm5"); - XS.LiteralCode(" psrlw xmm1,8"); - XS.LiteralCode(" paddusw xmm5,xmm1"); - XS.LiteralCode(" paddusw xmm5,xmm4"); - XS.LiteralCode(" psrlw xmm0,8"); - XS.LiteralCode(" psrlw xmm5,8"); - XS.LiteralCode(" packuswb xmm0,xmm5"); - XS.LiteralCode(" movdqu [edi],xmm0"); - XS.LiteralCode(" lea esi,[esi+16]"); - XS.LiteralCode(" lea edi,[edi+16]"); - XS.LiteralCode(" dec ecx"); - XS.LiteralCode(" jnz iadbld4lop2"); - XS.LiteralCode("add esi,dword [ebp+16]"); // sAdd - XS.LiteralCode("add edi,dword [ebp+24]"); // dAdd - XS.LiteralCode(" dec edx"); - XS.LiteralCode(" jnz iadbld4lop"); - XS.LiteralCode(" jmp iadbldexit"); - XS.LiteralCode(" align 16"); - XS.LiteralCode("iadbld4astart:"); - XS.LiteralCode("shr dword [ebp+12],2"); // width - XS.LiteralCode(" mov ebx,0x10101010"); - XS.LiteralCode(" pxor xmm2,xmm2"); - XS.LiteralCode(" movd xmm4,ebx"); - XS.LiteralCode(" punpckldq xmm4, xmm4"); - XS.LiteralCode(" punpcklbw xmm4, xmm2"); - XS.LiteralCode(" mov ebx,0xffffffff"); - XS.LiteralCode(" movd xmm6,ebx"); - XS.LiteralCode(" mov ebx,0xff000000"); - XS.LiteralCode(" movd xmm7,ebx"); - XS.LiteralCode(" punpckldq xmm6,xmm6"); - XS.LiteralCode(" punpckldq xmm7,xmm7"); - XS.LiteralCode("mov edi,dword [ebp+28]"); // dest - XS.LiteralCode("mov esi,dword [ebp+20]"); // src - XS.LiteralCode("mov edx,dword [ebp+8]"); // height - XS.LiteralCode(" ALIGN 16"); - XS.LiteralCode("iadbld4alop:"); - XS.LiteralCode("mov ecx,dword [ebp+12]"); // width - XS.LiteralCode(" align 16"); - XS.LiteralCode("iadbld4alop2:"); - XS.LiteralCode(" movzx eax,byte [esi+3]"); - XS.LiteralCode(" mov ah,byte [esi+7]"); - XS.LiteralCode(" movd xmm0,eax"); - XS.LiteralCode(" punpcklbw xmm0,xmm0"); - XS.LiteralCode(" punpcklwd xmm0,xmm0"); - XS.LiteralCode(" movdqa xmm3,xmm6"); - XS.LiteralCode(" psubd xmm3,xmm0"); - XS.LiteralCode(" por xmm3,xmm7"); - XS.LiteralCode(" movq xmm1,[esi]"); - XS.LiteralCode(" punpcklbw xmm0, xmm2"); - XS.LiteralCode(" punpcklbw xmm1, xmm2"); - XS.LiteralCode(" pmullw xmm0,xmm1"); - XS.LiteralCode(" movdqa xmm1,xmm0"); - XS.LiteralCode(" movq xmm0,[edi]"); - XS.LiteralCode(" punpcklbw xmm3, xmm2"); - XS.LiteralCode(" punpcklbw xmm0, xmm2"); - XS.LiteralCode(" pmullw xmm0,xmm3"); - XS.LiteralCode(" paddusw xmm0,xmm1"); - XS.LiteralCode(" movdqa xmm1,xmm0"); - XS.LiteralCode(" psrlw xmm1,8"); - XS.LiteralCode(" paddusw xmm0,xmm1"); - XS.LiteralCode(" paddusw xmm0,xmm4"); - XS.LiteralCode(" movzx eax,byte [esi+11]"); - XS.LiteralCode(" mov ah,byte [esi+15]"); - XS.LiteralCode(" movd xmm5,eax"); - XS.LiteralCode(" punpcklbw xmm5,xmm5"); - XS.LiteralCode(" punpcklwd xmm5,xmm5"); - XS.LiteralCode(" movdqa xmm3,xmm6"); - XS.LiteralCode(" psubd xmm3,xmm5"); - XS.LiteralCode(" por xmm3,xmm7"); - XS.LiteralCode(" movq xmm1,[esi+8]"); - XS.LiteralCode(" punpcklbw xmm5,xmm2"); - XS.LiteralCode(" punpcklbw xmm1,xmm2"); - XS.LiteralCode(" pmullw xmm5,xmm1"); - XS.LiteralCode(" movdqa xmm1,xmm5"); - XS.LiteralCode(" movq xmm5,[edi+8]"); - XS.LiteralCode(" punpcklbw xmm3,xmm2"); - XS.LiteralCode(" punpcklbw xmm5,xmm2"); - XS.LiteralCode(" pmullw xmm5,xmm3"); - XS.LiteralCode(" paddusw xmm5,xmm1"); - XS.LiteralCode(" movdqa xmm1,xmm5"); - XS.LiteralCode(" psrlw xmm1,8"); - XS.LiteralCode(" paddusw xmm5,xmm1"); - XS.LiteralCode(" paddusw xmm5,xmm4"); - XS.LiteralCode(" psrlw xmm0,8"); - XS.LiteralCode(" psrlw xmm5,8"); - XS.LiteralCode(" packuswb xmm0,xmm5"); - XS.LiteralCode(" movntdq [edi],xmm0"); - XS.LiteralCode(" lea esi,[esi+16]"); - XS.LiteralCode(" lea edi,[edi+16]"); - XS.LiteralCode(" dec ecx"); - XS.LiteralCode(" jnz iadbld4alop2"); - XS.LiteralCode("add esi,dword [ebp+16]"); // sAdd - XS.LiteralCode("add edi,dword [ebp+24]"); // dAdd - XS.LiteralCode(" dec edx"); - XS.LiteralCode(" jnz iadbld4alop"); - XS.LiteralCode(" align 16"); - - XS.LiteralCode("iadbldexit:"); - - // Fix 0x00 alpha - XS.LiteralCode(" mov eax, [ebp+12]"); - XS.LiteralCode(" mul dword [ebp+8]"); - XS.LiteralCode(" mov ecx, eax"); - XS.LiteralCode("alpha_loop:"); - XS.LiteralCode(" movzx edx, byte [esi+3]"); - XS.LiteralCode(" cmp edx, 0"); - XS.LiteralCode(" jne next_pixel"); - XS.LiteralCode("next_pixel:"); - XS.LiteralCode(" add esi, 4"); - XS.LiteralCode(" add edi, 4"); - XS.LiteralCode(" dec ecx"); - XS.LiteralCode(" jnz alpha_loop"); - - XS.LiteralCode(" pop edi"); - XS.LiteralCode(" pop esi"); - XS.LiteralCode(" pop ebx"); - XS.LiteralCode(" pop ebp"); - } - } - - public class BrightnessASM : AssemblerMethod - { - private const int AlphaDisplacement = 8; // Déplacement pour l'argument alpha - private const int LenDisplacement = 12; - private const int ImgDisplacement = 16; - - //public static void OpacitySSE(uint* pixelPtr, int w, int h, int bpl, uint a) - public override void AssembleNew(Assembler aAssembler, object aMethodInfo) - { - XS.LiteralCode(" push edi"); - XS.LiteralCode(" push eax"); - XS.LiteralCode(" mov eax,dword [ebp+20]"); // w - XS.LiteralCode(" shl eax,2"); - XS.LiteralCode(" sub dword [ebp+12],eax"); // bpl - - XS.LiteralCode(" mov edi,dword [ebp+24]"); // pixelPtr - XS.LiteralCode(" mov edx,dword [ebp+16]"); // h - XS.LiteralCode(" mov al,byte [ebp+8]"); // a - XS.LiteralCode(" align 16"); - - XS.LiteralCode("ifa32lop:"); - XS.LiteralCode(" mov ecx,dword [ebp+20]"); // w - XS.LiteralCode(" align 16"); - XS.LiteralCode("ifa32lop2:"); - XS.LiteralCode(" cmp byte [edi+3], 0x00"); - XS.LiteralCode(" je skip_alpha_adjustment"); - XS.LiteralCode(" mov byte [edi+3], al"); - XS.LiteralCode("skip_alpha_adjustment:"); - XS.LiteralCode(" add edi,4"); - XS.LiteralCode(" dec ecx"); - XS.LiteralCode(" jnz ifa32lop2"); - XS.LiteralCode(" add edi,dword [ebp+12]"); // bpl - XS.LiteralCode(" dec edx"); - XS.LiteralCode(" jnz ifa32lop"); - XS.LiteralCode(" pop eax"); - XS.LiteralCode(" pop edi"); - } - } - - public class AlphaBltSSEASM : AssemblerMethod - { - // public static void AlphaBltSSE(byte* dst, byte* src, int w, int h, int wmul4) - public override void AssembleNew(Assembler aAssembler, object aMethodInfo) - { - XS.LiteralCode(" mov edi, [ebp + 24]"); // Move the address of index 0 of dst (unsigned char*(Because this is a pointer, it's an int, being compiled as x86, so 32 bits, or 4 bytes)) into EDI destination index register, for string operations - XS.LiteralCode(" mov esi, [ebp + 20]"); // Move the address of index 0 of src (unsigned char*(Because this is a pointer, it's an int, being compiled as x86, so 32 bits, or 4 bytes)) into ESI source index register, for string operations - XS.LiteralCode(" mov edx, [ebp + 12]"); // Move the address of h (int, 32 bits(4 bytes)) into 32-bit(4 byte) EDX register. EDX now points to h. - XS.LiteralCode(" pxor mm6,mm6"); // Performs a logical XOR operation on mm6 and mm6, then stores the result in mm6, a 64 bit MMX register. Because XORing itself, this initializes to 0. - XS.LiteralCode(" pxor mm7,mm7"); // Performs a logical XOR operation on mm7 and mm7, then stores the result in mm7, a 64 bit MMX register. Because XORing itself, this initializes to 0. - XS.LiteralCode(" xor eax,eax"); // Performs a logical XOR operation on eax and eax, then stores the result in eax, a 32 bit x86 register. Because XORing itself, this initializes to 0. - XS.LiteralCode("scan_loop:"); // Label this line to be jumped to. - XS.LiteralCode(" mov ecx, [ebp + 16]"); // Move address of w into ECX 32 bit(4 byte) register. ECX is our count register, it will decrement while looping. ECX now points to w. - XS.LiteralCode(" xor ebx, ebx"); // Performs a logical XOR operation on EBX and EBX, then stores the result in EBX, a 32 bit x86 register. Because XORing itself, this initializes to 0. - XS.LiteralCode("pix_loop:"); // Label this line to be jumped to. - XS.LiteralCode(" movq mm4,[esi + ebx * 8]"); // mm0 = src (RG BA RG BA) // Moves a quadword(8 bytes) of data from address of esi+ebx*8 to mm4. ESI is src's starting address+EBX which is an offset counter, of 8 bytes. EBX is a counter. - XS.LiteralCode(" movq mm5,[edi + ebx * 8]"); // mm1 = dst (RG BA RG BA) // Moves a quadword(8 bytes) of data from address of edi+ebx*8 to mm5. ESD is dst's starting address+EBX which is an offset counter, of 8 bytes. EBX is a counter. - // FIRST PIXEL - XS.LiteralCode(" movq mm0, mm4"); // mm0 = 00 00 RG BA // Moves the quadword(8 bytes) contents of mm4 into mm0. This will be RGBA, with each channel being 2 bytes, with a value of 0-255. - XS.LiteralCode(" movq mm1, mm5"); // mm1 = 00 00 RG BA // Moves the quadword(8 bytes) contents of mm5 into mm1. This will be RGBA, with each channel being 2 bytes, with a value of 0-255. - XS.LiteralCode(" punpcklbw mm0, mm6"); // mm0 = (0R 0G 0B 0A) // Interleaves low order bytes of mm0 and mm6 together, into mm0. http://qcd.phys.cmu.edu/QCDcluster/intel/vtune/reference/vc265.htm - XS.LiteralCode(" punpcklbw mm1, mm7"); // mm0 = (0R 0G 0B 0A) // Interleaves low order bytes of mm1 and mm7 together, into mm1. http://qcd.phys.cmu.edu/QCDcluster/intel/vtune/reference/vc265.htm - XS.LiteralCode(" pshufw mm2, mm0,0ffh"); // mm2 = 0A 0A 0A 0A // Shuffles the words(2 bytes) from mm0 into mm2 using the third operand to define their placement in mm2. http://qcd.phys.cmu.edu/QCDcluster/intel/vtune/reference/vc254.htm -- Uses mm1 instead of mm2 for Question 2. - XS.LiteralCode(" movq mm3,mm1"); // mm3 = mm1 // Moves the quadword(8 bytes) contents of mm1 to mm3. - XS.LiteralCode(" psubw mm0,mm1"); // mm0 = mm0 - mm1 // Subtract packed word integers in mm1 from packed word integers in mm0. https://www.felixcloutier.com/x86/psubb:psubw:psubd - XS.LiteralCode(" psllw mm3,8"); // mm3 = mm1 * 256 // Shift bits in mm3 left 8 places (Multiply by 256). https://www.felixcloutier.com/x86/psllw:pslld:psllq - XS.LiteralCode(" pmullw mm0, mm2"); // mm0 = (src-dst)*alpha // Multiply mm2 and mm0, and store low order bits of result in mm0 https://docs.oracle.com/cd/E19120-01/open.solaris/817-5477/eojdc/index.html - XS.LiteralCode(" paddw mm0, mm3"); // mm0 = (src-dst)*alpha+dst*256 // Add packed word integers mm3 and mm0, into mm0. https://www.felixcloutier.com/x86/paddb:paddw:paddd:paddq - XS.LiteralCode(" psrlw mm0,8"); // mm0 = ((src - dst) * alpha + dst * 256) / 256 // Shift words in mm0 right by 8 (Divide by 256). https://www.felixcloutier.com/x86/psrlw:psrld:psrlq - // SECOND PIXEL - XS.LiteralCode(" punpckhbw mm5, mm7"); // mm5 = (0R 0G 0B 0A) // Unpack and interleave high-order bytes from mm5 and mm7 into mm5. https://www.felixcloutier.com/x86/punpckhbw:punpckhwd:punpckhdq:punpckhqdq - XS.LiteralCode(" punpckhbw mm4, mm6"); // mm4 = (0R 0G 0B 0A) // Unpack and interleave high-order bytes from mm4 and mm6 into mm4. https://www.felixcloutier.com/x86/punpckhbw:punpckhwd:punpckhdq:punpckhqdq - XS.LiteralCode(" movq mm3, mm5"); // mm3 = mm5 // Moves the quadword(8 bytes) contents of mm5 to mm3. - XS.LiteralCode(" pshufw mm2, mm4,0ffh"); // mm2 = 0A 0A 0A 0A // Shuffles the words(2 bytes) from mm4 into mm2 using the third operand to define their placement in mm2. http://qcd.phys.cmu.edu/QCDcluster/intel/vtune/reference/vc254.htm -- Uses mm5 instead of mm4 for Question 2. - XS.LiteralCode(" psllw mm3,8"); // mm3 = mm5 * 256 // Shift bits in mm3 left 8 places (Multiply by 256). https://www.felixcloutier.com/x86/psllw:pslld:psllq - XS.LiteralCode(" psubw mm4, mm5"); // mm4 = mm4 - mm5 // Subtract packed word integers in mm5 from packed word integers in mm4. https://www.felixcloutier.com/x86/psubb:psubw:psubd - XS.LiteralCode(" pmullw mm4, mm2"); // mm4 = (src-dst)*alpha // Multiply mm2 and mm4, and store low order bits of result in mm4 https://docs.oracle.com/cd/E19120-01/open.solaris/817-5477/eojdc/index.html - XS.LiteralCode(" paddw mm4, mm3"); // mm4 = (src-dst)*alpha+dst*256 // Add packed word integers mm4 and mm3, into mm4. https://www.felixcloutier.com/x86/paddb:paddw:paddd:paddq - XS.LiteralCode(" psrlw mm4,8"); // mm4 = ((src - dst) * alpha + dst * 256) / 256 // Shift words in mm4 right by 8 (Divide by 256). https://www.felixcloutier.com/x86/psrlw:psrld:psrlq - XS.LiteralCode(" packuswb mm0, mm4"); // mm0 = RG BA RG BA // Converts 4 signed word integers from mm0 and 4 signed word integers from mm4 into 8 unsigned byte integers in mm0 using unsigned saturation. (Set to min of range if below, set to max of range if above) - XS.LiteralCode(" movq[edi + ebx * 8],mm0"); // dst = mm0 // Moves the quadword(8 bytes) contents of mm0 to address indicated by edi+ebx*8. EDI is dst's starting address+EBX which is an offset counter, of 8 bytes. EBX is a counter. - XS.LiteralCode(" inc ebx"); // increment the value stored at the address of ebx // Increment EBX - XS.LiteralCode(" loop pix_loop"); // loop back to pix_loop label. https://docs.oracle.com/cd/E19455-01/806-3773/instructionset-72/index.html Loop also decrements ECX, and continues without looping if that register is zero. - XS.LiteralCode(" mov ebx, [ebp + 8]"); // Move the address of wmul4 into ebx, creating a pointer to wmul4 in ebx. - XS.LiteralCode(" add esi, ebx"); // Add the contents of EBX into ESI - XS.LiteralCode(" add edi, ebx"); // Add the contents of EBX into EDI - XS.LiteralCode(" dec edx"); // Decrement EDX - XS.LiteralCode(" jnz scan_loop"); // Jump to label if zero flag is not set. Not entirely sure how and where the zero flag is being set or cleared here. - } - } -} diff --git a/SRC/Aura_Plugs/Global.cs b/SRC/Aura_Plugs/Global.cs deleted file mode 100644 index cb93fdb0d..000000000 --- a/SRC/Aura_Plugs/Global.cs +++ /dev/null @@ -1,48 +0,0 @@ -/* -* PROJECT: Aura Operating System Development -* CONTENT: Plug of Cosmos.System.Global -* PROGRAMMERS: Valentin Charbonnier -*/ - -using IL2CPU.API.Attribs; -using Cosmos.HAL; -using System.IO; -using Cosmos.System; - -namespace Aura_OS.System.Plugs -{ - - [Plug(Target = typeof(Cosmos.System.Global))] - public static class Global - { - // TODO: continue adding exceptions to the list, as HAL and Core would be documented. - /// - /// Initializes the console, screen and keyboard. - /// - /// A screen device. - public static void Init(TextScreenBase textScreen, bool initScrollWheel = true, bool initPS2 = true, bool initNetwork = true, bool ideInit = true) - { - // We must init Console before calling Inits. - // This is part of the "minimal" boot to allow output. - Cosmos.System.Global.Console = new Console(textScreen); - - Kernel.TextmodeConsole = new Graphics.UI.CUI.Console(textScreen); - - CustomConsole.WriteLineInfo("Starting Aura Operating System v" + Kernel.Version + "-" + Kernel.Revision); - - CustomConsole.WriteLineInfo("Initializing the Hardware Abstraction Layer (HAL)..."); - Cosmos.HAL.Global.Init(textScreen, initScrollWheel, initPS2, initNetwork, ideInit); - - // TODO: @ascpixi: The end-user should have an option to exclude parts of - // Cosmos, such as the network stack, when they are not needed. As of - // now, these modules will *always* be included, as they're referenced - // by the initialization code. - CustomConsole.WriteLineInfo("Initializing the network stack..."); - Cosmos.System.Network.NetworkStack.Initialize(); - - Cosmos.System.Global.NumLock = false; - Cosmos.System.Global.CapsLock = false; - Cosmos.System.Global.ScrollLock = false; - } - } -} \ No newline at end of file diff --git a/SRC/Aura_Plugs/INTs.cs b/SRC/Aura_Plugs/INTs.cs deleted file mode 100644 index 64c4325e5..000000000 --- a/SRC/Aura_Plugs/INTs.cs +++ /dev/null @@ -1,41 +0,0 @@ -/* -* PROJECT: Aura Operating System Development -* CONTENT: CPU Exceptions. -* PROGRAMMERS: Valentin Charbonnier -*/ - -using IL2CPU.API.Attribs; -using static Cosmos.Core.INTs; - -namespace Aura_Plugs -{ - [Plug(Target = typeof(Cosmos.Core.INTs))] - - public class INTs - { - public static void HandleException(uint aEIP, string aDescription, string aName, ref IRQContext ctx, uint lastKnownAddressValue = 0) - { - const string xHex = "0123456789ABCDEF"; - - string ctxinterrupt = ""; - ctxinterrupt = ctxinterrupt + xHex[(int)((ctx.Interrupt >> 4) & 0xF)]; - ctxinterrupt = ctxinterrupt + xHex[(int)(ctx.Interrupt & 0xF)]; - - string lastsknowaddress = ""; - - if (lastKnownAddressValue != 0) - { - lastsknowaddress = lastsknowaddress + xHex[(int)((lastKnownAddressValue >> 28) & 0xF)]; - lastsknowaddress = lastsknowaddress + xHex[(int)((lastKnownAddressValue >> 24) & 0xF)]; - lastsknowaddress = lastsknowaddress + xHex[(int)((lastKnownAddressValue >> 20) & 0xF)]; - lastsknowaddress = lastsknowaddress + xHex[(int)((lastKnownAddressValue >> 16) & 0xF)]; - lastsknowaddress = lastsknowaddress + xHex[(int)((lastKnownAddressValue >> 12) & 0xF)]; - lastsknowaddress = lastsknowaddress + xHex[(int)((lastKnownAddressValue >> 8) & 0xF)]; - lastsknowaddress = lastsknowaddress + xHex[(int)((lastKnownAddressValue >> 4) & 0xF)]; - lastsknowaddress = lastsknowaddress + xHex[(int)(lastKnownAddressValue & 0xF)]; - } - - Aura_OS.System.Crash.StopKernel(aName, aDescription, lastsknowaddress, ctxinterrupt); - } - } -} \ No newline at end of file diff --git a/SRC/Aura_Plugs/SVGAIICanvas.cs b/SRC/Aura_Plugs/SVGAIICanvas.cs deleted file mode 100644 index 6ebc579a3..000000000 --- a/SRC/Aura_Plugs/SVGAIICanvas.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Cosmos.HAL.Drivers.Video.SVGAII; -using Cosmos.System.Graphics; -using IL2CPU.API.Attribs; - -namespace Aura_Plugs -{ - [Plug(Target = typeof(SVGAIICanvas))] - internal class SVGAIICanvasImpl - { - public static void DrawImage(SVGAIICanvas aThis, Image image, int x, int y, [FieldAccess(Name = "Cosmos.HAL.Drivers.Video.SVGAII.VMWareSVGAII Cosmos.System.Graphics.SVGAIICanvas.driver")] ref VMWareSVGAII driver) - { - var width = (int)image.Width; - var height = (int)image.Height; - var data = image.RawData; - - for (int i = 0; i < height; i++) - { - driver.videoMemory.Copy(aThis.GetPointOffset(x, y + i), data, i * width, width); - } - } - - public static void Display(SVGAIICanvas aThis, [FieldAccess(Name = "Cosmos.HAL.Drivers.Video.SVGAII.VMWareSVGAII Cosmos.System.Graphics.SVGAIICanvas.driver")] ref VMWareSVGAII driver) - { - driver.Update(0, 0, aThis.Mode.Width, aThis.Mode.Height); - } - } -} diff --git a/SRC/Aura_Plugs/XSharp.dll b/SRC/Aura_Plugs/XSharp.dll deleted file mode 100644 index 70d81d70d..000000000 Binary files a/SRC/Aura_Plugs/XSharp.dll and /dev/null differ diff --git a/global.json b/global.json new file mode 100644 index 000000000..faa07a753 --- /dev/null +++ b/global.json @@ -0,0 +1,4 @@ +{ + "sdk": { "version": "10.0.201", "rollForward": "latestFeature" }, + "msbuild-sdks": { "Cosmos.Sdk": "3.0.89.20261002" } +}