garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /kernel/src/syscall.rs

raw

//! System calls: `svc #0` from a program (or a kernel task), the number in
//! x8 (`pinnacle_abi::call`), arguments from x0, results in x0–x2.
//!
//! A call that must wait (`receive`, `sleep_until`) rewinds the program's
//! return address to its `svc` and blocks: when the task is woken it makes
//! the same call again, and finds what it waited for.

use crate::exceptions::Frame;
use crate::mm::PAGE;
use crate::mm::space::Access;
use crate::object::{self, Endpoint, Memory, Message, Object};
use crate::sched;
use alloc::sync::Arc;
use alloc::vec::Vec;
use pinnacle_abi::{CLOSED, ERROR, MAX_COPY, MAX_MESSAGE, MAX_MESSAGE_HANDLES, TIMEOUT, call};

/// What a call answers in x0, x1 and x2.
type Answer = (u64, u64, u64);
const FAILED: Answer = (ERROR, 0, 0);

pub fn handle(frame: *mut Frame) -> *mut Frame {
    // Timed per call when the profiler runs: a tick during a call fires
    // only after it, so the samples count a call to its caller.
    #[cfg(target_arch = "aarch64")]
    if crate::profile::on() {
        // SAFETY: as below.
        let number = unsafe { (*frame).call() };
        let start = crate::profile::counter();
        let next = handle_call(frame);
        crate::profile::called(number, start);
        return next;
    }
    handle_call(frame)
}

fn handle_call(frame: *mut Frame) -> *mut Frame {
    // SAFETY: the vector stub just wrote this frame, and nothing else holds it.
    let f = unsafe { &mut *frame };
    let a = f.args();
    let answer = match f.call() {
        call::YIELD => return sched::switch(frame),
        // Kernel code going to sleep (`sched::sleep`): the frame is EL1's,
        // and resumes where it was. A program asking gets an error.
        call::BLOCK if f.is_kernel() => return sched::block(frame, None),
        call::EXIT => return sched::exit(frame, a[0]),
        call::EXIT_PROCESS => return sched::exit_process(frame, a[0]),
        call::SLEEP_UNTIL => {
            if crate::timer::now_ms() >= a[0] {
                (0, 0, 0)
            } else {
                f.repeat_call();
                return sched::block(frame, Some(a[0]));
            }
        }
        call::RECEIVE => match receive(a) {
            Received::Now(answer) => answer,
            Received::Wait(deadline) => {
                f.repeat_call();
                return sched::block(frame, deadline);
            }
        },
        call::WAIT => match wait(a) {
            Received::Now(answer) => answer,
            Received::Wait(deadline) => {
                f.repeat_call();
                return sched::block(frame, deadline);
            }
        },
        call::FUTEX_WAIT => return crate::futex::wait(frame, a[0], a[1] as u32, (a[2] != 0).then_some(a[2])),
        call::FUTEX_WAKE => (crate::futex::wake(a[0], a[1]), 0, 0),
        call::WRITE => (write(a[0] as usize, a[1] as usize), 0, 0),
        call::PID => (sched::current() as u64, 0, 0),
        call::TIME => (crate::timer::now_ms(), 0, 0),
        call::MAP_MEMORY => map_memory(a[0] as usize),
        call::CHANNEL => {
            let (one, other) = Endpoint::pair();
            sched::with_process(|p| {
                (
                    p.add_handle(Object::Channel(one)),
                    p.add_handle(Object::Channel(other)),
                    0,
                )
            })
            .unwrap_or(FAILED)
        }
        call::SEND => send(a),
        call::CLOSE => {
            // Dropped outside the task lock: closing may wake the peer.
            let object = sched::with_process(|p| p.take_handle(a[0])).flatten();
            if object.is_some() { (0, 0, 0) } else { FAILED }
        }
        call::MEMORY => match Memory::new(a[0] as usize) {
            Some(memory) => add(Object::Memory(memory)),
            None => FAILED,
        },
        call::MAP => map(a[0]),
        call::UNMAP => unmap(a[0]),
        call::KILL => kill(a[0]),
        call::REGISTER => register(a),
        call::CONNECT => {
            // A service named `system-…` is for system programs: an
            // installed app may not reach it (the p2p service's commands
            // on other devices, run in the person's name).
            let name = read_user(a[0] as usize, a[1] as usize)
                .filter(|name| !(name.starts_with(b"system-") && confined()) && !sealed());
            match name.and_then(|name| object::connect(&name)) {
                Some(end) => add(Object::Channel(end)),
                None => FAILED,
            }
        }
        call::SPAWN => spawn(a),
        call::FRAMEBUFFER => framebuffer(a[0] as u32, a[1] as u32),
        call::INPUT => input(),
        call::FLUSH_SCREEN if privileged() => {
            crate::drivers::display::flush(a[0] as i32, a[1] as i32, a[2] as i32, a[3] as i32);
            (0, 0, 0)
        }
        call::READ_FILE => read_file(a),
        call::CONNECT_TCP | call::CONNECT_TCP6 | call::RESOLVE | call::UDP_BIND | call::LISTEN_TCP
            if !networked() =>
        {
            FAILED
        }
        call::LISTEN_TCP => match crate::drivers::net::listen(a[0] as u16) {
            Some(end) => add(Object::Channel(end)),
            None => FAILED,
        },
        call::CONNECT_TCP => match crate::drivers::net::connect(
            pinnacle_net::IpAddr::V4((a[0] as u32).to_be_bytes()),
            a[1] as u16,
        ) {
            Some(end) => add(Object::Channel(end)),
            None => FAILED,
        },
        call::CONNECT_TCP6 => {
            let mut ip = [0u8; 16];
            ip[..8].copy_from_slice(&a[0].to_be_bytes());
            ip[8..].copy_from_slice(&a[1].to_be_bytes());
            match crate::drivers::net::connect(pinnacle_net::IpAddr::from_mapped(ip), a[2] as u16) {
                Some(end) => add(Object::Channel(end)),
                None => FAILED,
            }
        }
        call::RESOLVE => {
            let name = read_user(a[0] as usize, a[1] as usize).filter(|n| n.len() <= 253);
            match name
                .as_deref()
                .and_then(|n| core::str::from_utf8(n).ok())
                .and_then(crate::drivers::net::resolve)
            {
                Some(end) => add(Object::Channel(end)),
                None => FAILED,
            }
        }
        call::AUDIO_PLAY => match crate::drivers::sound::open_player(a[0] as u32, a[1] as u32) {
            Some(end) => add(Object::Channel(end)),
            None => FAILED,
        },
        call::AUDIO_RECORD => match crate::drivers::sound::open_recorder(a[0] as u32, a[1] as u32) {
            Some(end) => add(Object::Channel(end)),
            None => FAILED,
        },
        call::BLUETOOTH_PORT => match crate::drivers::serial::open(crate::drivers::serial::Port::Bluetooth) {
            Some(end) if !confined() => add(Object::Channel(end)),
            _ => FAILED,
        },
        call::MODEM_PORT => match crate::drivers::serial::open(crate::drivers::serial::Port::Modem) {
            Some(end) if !confined() => add(Object::Channel(end)),
            _ => FAILED,
        },
        call::WIFI_PORT => match crate::drivers::serial::open(crate::drivers::serial::Port::Wifi) {
            Some(end) if !confined() => add(Object::Channel(end)),
            _ => FAILED,
        },
        call::PROGRAM => program(a[0] as usize, a[1] as usize),
        call::UNMAP_MEMORY => unmap_memory(a[0] as usize),
        call::GPU if !gpu_granted() => FAILED,
        call::GPU => match crate::drivers::gpu3d::open() {
            Some(end) => add(Object::Channel(end)),
            None => FAILED,
        },
        call::AUDIO_VOLUME => match crate::drivers::sound::volume(a[0]) {
            Some(before) => (before, 0, 0),
            None => FAILED,
        },
        call::UDP_BIND => match crate::drivers::net::udp_bind(a[0] as u16) {
            Some((end, port)) => {
                let (handle, ..) = add(Object::Channel(end));
                (handle, u64::from(port), 0)
            }
            None => FAILED,
        },
        call::THREAD => match sched::spawn_thread(a[0], a[1], a[2]) {
            Some(id) => (id as u64, 0, 0),
            None => FAILED,
        },
        call::RANDOM => {
            let mut bytes = alloc::vec![0u8; (a[1] as usize).min(4096)];
            crate::drivers::random::fill(&mut bytes);
            if write_user(a[0] as usize, &bytes) {
                (bytes.len() as u64, 0, 0)
            } else {
                FAILED
            }
        }
        call::NET_INFO6 => match crate::drivers::net::info6() {
            Some(info) if a[1] as usize >= info.len() && write_user(a[0] as usize, &info) => {
                (info.len() as u64, 0, 0)
            }
            _ => FAILED,
        },
        call::NET_INFO => match crate::drivers::net::info() {
            Some((ip, router, dns)) => (
                u32::from_be_bytes(ip).into(),
                u32::from_be_bytes(router).into(),
                u32::from_be_bytes(dns).into(),
            ),
            None => FAILED,
        },
        call::SYSTEM => match a[0] {
            0 => {
                let text = crate::chain::describe();
                let n = text.len().min(a[2] as usize);
                if write_user(a[1] as usize, &text.as_bytes()[..n]) {
                    (n as u64, 0, 0)
                } else {
                    FAILED
                }
            }
            1 if !confined() => crate::chain::restart(),
            _ => FAILED,
        },
        call::INSTALL if !confined() => install(a),
        call::NET_SWITCH => match a[0] {
            0 => (crate::drivers::net::state(), 0, 0),
            1 | 2 if !confined() => {
                crate::drivers::net::switch(a[0] == 1);
                (crate::drivers::net::state(), 0, 0)
            }
            _ => FAILED,
        },
        call::WRITE_FILE => match (
            read_user(a[0] as usize, a[1] as usize),
            read_user(a[2] as usize, a[3] as usize),
        ) {
            (Some(path), Some(data)) => file_op(&path, |fs, p| fs.write(p, &data).map(|()| 0)),
            _ => FAILED,
        },
        call::LIST => list(a),
        call::READ_AT => read_at(a),
        call::WRITE_AT => match (
            read_user(a[0] as usize, a[1] as usize),
            read_user(a[3] as usize, a[4] as usize),
        ) {
            (Some(path), Some(data)) => file_op(&path, |fs, p| fs.write_at(p, a[2], &data).map(|()| 0)),
            _ => FAILED,
        },
        call::STAT => stat(a),
        call::OPEN_FILE => open_file(a),
        call::FILE => file(a),
        // Changing the passphrase asks for the old one: Settings may too.
        call::VAULT if privileged() || a[0] == 4 && !confined() => vault(a),
        call::CPU_FEATURES => (crate::arch::isar0(), 0, 0),
        call::DISK => match read_user(a[0] as usize, a[1] as usize) {
            Some(label) if !confined() => {
                let label = alloc::format!("{}:/", core::str::from_utf8(&label).unwrap_or(""));
                let block = pinnacle_fs::BLOCK as u64;
                crate::drivers::block::with_disk(&label, |fs, _| {
                    (u64::from(fs.capacity()) * block, u64::from(fs.free()) * block, 0)
                })
                .unwrap_or(FAILED)
            }
            _ => FAILED,
        },
        call::REMOVE => match read_user(a[0] as usize, a[1] as usize) {
            Some(path) => file_op(&path, |fs, p| fs.remove_all(p).map(|()| 0)),
            None => FAILED,
        },
        call::CREATE_DIR => match read_user(a[0] as usize, a[1] as usize) {
            Some(path) => file_op(&path, |fs, p| fs.create_dir(p).map(|()| 0)),
            None => FAILED,
        },
        call::CLOCK => match a[0] {
            0 => {
                let (ms, source) = crate::clock::now_ms();
                (ms / 1000, source, ms % 1000)
            }
            1 if !confined() => {
                crate::clock::set(a[1]);
                (0, 0, 0)
            }
            _ => FAILED,
        },
        call::PROGRAMS => {
            let names = crate::programs::names();
            let len = names.len().min(a[1] as usize);
            if write_user(a[0] as usize, &names[..len]) {
                (len as u64, 0, 0)
            } else {
                FAILED
            }
        }
        call::DEVICES => {
            let mut text = alloc::string::String::new();
            for d in crate::device::all() {
                let (driver, class) = d
                    .driver
                    .map_or(("-", "-"), |(driver, class)| (driver, class.name()));
                let firmware = crate::device::firmware(&d.name).unwrap_or_else(|| "-".into());
                text += &alloc::format!(
                    "{class}\t{driver}\t{}\t{}\t{firmware}\n",
                    d.name,
                    d.compatible.join(",")
                );
            }
            let len = text.len().min(a[1] as usize);
            if write_user(a[0] as usize, &text.as_bytes()[..len]) {
                (len as u64, 0, 0)
            } else {
                FAILED
            }
        }
        call::POWER if confined() => FAILED,
        call::POWER => {
            #[cfg(target_arch = "x86_64")]
            let text = crate::power::status();
            #[cfg(not(target_arch = "x86_64"))]
            let text = alloc::string::String::new();
            let len = text.len().min(a[1] as usize);
            if write_user(a[0] as usize, &text.as_bytes()[..len]) {
                (len as u64, 0, 0)
            } else {
                FAILED
            }
        }
        call::BRIGHTNESS if confined() => FAILED,
        call::BRIGHTNESS => {
            let level = match a[0] {
                0 => crate::drivers::backlight::level(),
                1 => crate::drivers::backlight::set(a[1].min(100) as u8),
                _ => None,
            };
            level.map_or(FAILED, |l| (u64::from(l), 0, 0))
        }
        call::PROCESSES | call::KILL_ID | call::LOG if confined() => FAILED,
        call::PROCESSES => processes(a[0], a[1] as usize, a[2] as usize),
        call::KILL_ID => kill_id(a[0]),
        call::LOG => {
            let mut kept = Vec::with_capacity(crate::console::KEPT);
            crate::console::CONSOLE.lock().kept(&mut kept);
            // The newest part, when the buffer is smaller.
            let from = kept.len().saturating_sub(a[1] as usize);
            if write_user(a[0] as usize, &kept[from..]) {
                ((kept.len() - from) as u64, 0, 0)
            } else {
                FAILED
            }
        }
        call::INFO => {
            let (free, _) = crate::mm::pages::stats();
            let ram = crate::mm::ram_size();
            (
                u64::from(crate::smp::online().count_ones()),
                ram as u64,
                (free * PAGE) as u64,
            )
        }
        _ => FAILED,
    };
    f.set_result(answer);
    frame
}

fn add(object: Object) -> Answer {
    sched::with_process(|p| (p.add_handle(object), 0, 0)).unwrap_or(FAILED)
}

/// A copy of `len` bytes of the caller's memory at `address`, if they are
/// the caller's to read.
fn read_user(address: usize, len: usize) -> Option<Vec<u8>> {
    if len > MAX_COPY || !sched::with_process(|p| p.space.allows(address, len, false))? {
        return None;
    }
    if len == 0 {
        return Some(Vec::new());
    }
    // SAFETY: the caller's space maps these bytes readable, and TTBR0
    // holds it during its call.
    Some(unsafe { core::slice::from_raw_parts(address as *const u8, len) }.to_vec())
}

/// Copies `bytes` to the caller's memory at `address`, if it is the
/// caller's to write.
fn write_user(address: usize, bytes: &[u8]) -> bool {
    if !sched::with_process(|p| p.space.allows(address, bytes.len(), true)).unwrap_or(false) {
        return false;
    }
    if bytes.is_empty() {
        return true;
    }
    // SAFETY: as in `read_user`, writable.
    unsafe { core::ptr::copy_nonoverlapping(bytes.as_ptr(), address as *mut u8, bytes.len()) };
    true
}

fn u64s(bytes: &[u8]) -> impl Iterator<Item = u64> + '_ {
    bytes.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c))
}

/// Puts a program's bytes on the console.
fn write(address: usize, len: usize) -> u64 {
    match read_user(address, len.min(MAX_MESSAGE)) {
        Some(bytes) => {
            crate::console::CONSOLE.lock().write_bytes(&bytes);
            bytes.len() as u64
        }
        None => ERROR,
    }
}

fn map_memory(size: usize) -> Answer {
    // No more than the machine has: a request past it is a mistake, not a
    // wait (Cartopolis asks for 260 MiB at once).
    if size == 0 || size > crate::mm::ram_size() {
        return FAILED;
    }
    let pages = size.div_ceil(PAGE);
    sched::with_process(|p| {
        let at = p.reserve(pages * PAGE);
        for page in 0..pages {
            let frame = crate::mm::pages::alloc(0)?;
            // SAFETY: just allocated, ours alone.
            unsafe { core::ptr::write_bytes(frame as *mut u8, 0, PAGE) };
            p.space.map(at + page * PAGE, frame, Access::ReadWrite).ok()?;
        }
        p.private.insert(at, pages);
        Some((at as u64, 0, 0))
    })
    .flatten()
    .unwrap_or(FAILED)
}

/// Gives back the memory `map_memory` answered `address` for: its pages,
/// and the addresses for a later mapping.
fn unmap_memory(address: usize) -> Answer {
    sched::with_process(|p| {
        let &pages = p.private.get(&address)?;
        if !p.space.unmap_private(address, pages) {
            return None;
        }
        p.private.remove(&address);
        p.release(address, pages * PAGE);
        Some((0, 0, 0))
    })
    .flatten()
    .unwrap_or(FAILED)
}

fn map(handle: u64) -> Answer {
    sched::with_process(|p| {
        let Some(Object::Memory(memory)) = p.handle(handle).cloned() else {
            return None;
        };
        let at = p.reserve(memory.size);
        p.space.map_shared(at, memory.address, memory.size / PAGE).ok()?;
        let size = memory.size;
        p.mapped.push((at, memory));
        Some((at as u64, size as u64, 0))
    })
    .flatten()
    .unwrap_or(FAILED)
}

/// Unmaps the shared memory mapped at `address`; its pages go back once no
/// program maps it and no handle names it.
fn unmap(address: u64) -> Answer {
    let memory = sched::with_process(|p| {
        let i = p.mapped.iter().position(|(at, _)| *at as u64 == address)?;
        let pages = p.mapped[i].1.size / PAGE;
        if !p.space.unmap_shared(address as usize, pages) {
            return None;
        }
        p.release(address as usize, pages * PAGE);
        Some(p.mapped.remove(i).1)
    })
    .flatten();
    // Dropped here, outside the program's lock: perhaps the last hold.
    match memory {
        Some(memory) => {
            drop(memory);
            (0, 0, 0)
        }
        None => FAILED,
    }
}

fn send([handle, bytes, len, handles, count, ..]: [u64; 7]) -> Answer {
    let (len, count) = (len as usize, count as usize);
    if len > MAX_MESSAGE || count > MAX_MESSAGE_HANDLES {
        return FAILED;
    }
    let Some(bytes) = read_user(bytes as usize, len) else {
        return FAILED;
    };
    let Some(numbers) = read_user(handles as usize, count * 8) else {
        return FAILED;
    };
    let taken = sched::with_process(|p| {
        let Some(Object::Channel(end)) = p.handle(handle).cloned() else {
            return None;
        };
        let numbers: Vec<u64> = u64s(&numbers).collect();
        if numbers.iter().any(|&n| n == handle || p.handle(n).is_none()) {
            return None;
        }
        Some((
            end,
            numbers
                .iter()
                .map(|&n| p.take_handle(n).unwrap())
                .collect::<Vec<_>>(),
        ))
    })
    .flatten();
    let Some((end, handles)) = taken else {
        return FAILED;
    };
    if end.send(Message { bytes, handles }) {
        (0, 0, 0)
    } else {
        FAILED
    }
}

enum Received {
    Now(Answer),
    /// Nothing yet: block until woken or the deadline.
    Wait(Option<u64>),
}

fn receive([handles, count, buffer, len, handles_out, max, deadline]: [u64; 7]) -> Received {
    let fail = Received::Now(FAILED);
    let Some(numbers) = read_user(handles as usize, count as usize * 8) else {
        return fail;
    };
    let ends = sched::with_process(|p| {
        u64s(&numbers)
            .map(|n| match p.handle(n) {
                Some(Object::Channel(end)) => Some(end.clone()),
                _ => None,
            })
            .collect::<Option<Vec<Arc<Endpoint>>>>()
    })
    .flatten();
    let Some(ends) = ends else { return fail };
    let me = sched::current();
    for (index, end) in ends.iter().enumerate() {
        let mut inbox = end.inbox.lock();
        if let Some(message) = inbox.messages.front() {
            if message.bytes.len() > len as usize || message.handles.len() > max as usize {
                return fail;
            }
            let message = inbox.messages.pop_front().unwrap();
            drop(inbox);
            if !write_user(buffer as usize, &message.bytes) {
                return fail;
            }
            let numbers: Vec<u8> = sched::with_process(|p| {
                message
                    .handles
                    .into_iter()
                    .flat_map(|object| p.add_handle(object).to_le_bytes())
                    .collect()
            })
            .unwrap_or_default();
            if !write_user(handles_out as usize, &numbers) {
                return fail;
            }
            return Received::Now((index as u64, message.bytes.len() as u64, numbers.len() as u64 / 8));
        }
        if inbox.closed {
            return Received::Now((index as u64, CLOSED, 0));
        }
        if !inbox.waiters.contains(&me) {
            inbox.waiters.push(me);
        }
    }
    match deadline {
        0 => Received::Wait(None),
        d if crate::timer::now_ms() >= d => Received::Now((TIMEOUT, 0, 0)),
        d => Received::Wait(Some(d)),
    }
}

/// WAIT: which of the ends has a message, or its peer gone, without taking
/// it; else as RECEIVE waits.
fn wait([handles, count, deadline, ..]: [u64; 7]) -> Received {
    let Some(numbers) = read_user(handles as usize, count as usize * 8) else {
        return Received::Now(FAILED);
    };
    let ends = sched::with_process(|p| {
        u64s(&numbers)
            .map(|n| match p.handle(n) {
                Some(Object::Channel(end)) => Some(end.clone()),
                _ => None,
            })
            .collect::<Option<Vec<Arc<Endpoint>>>>()
    })
    .flatten();
    let Some(ends) = ends else {
        return Received::Now(FAILED);
    };
    let me = sched::current();
    for (index, end) in ends.iter().enumerate() {
        let mut inbox = end.inbox.lock();
        if let Some(message) = inbox.messages.front() {
            return Received::Now((
                index as u64,
                message.bytes.len() as u64,
                message.handles.len() as u64,
            ));
        }
        if inbox.closed {
            return Received::Now((index as u64, CLOSED, 0));
        }
        if !inbox.waiters.contains(&me) {
            inbox.waiters.push(me);
        }
    }
    match deadline {
        0 => Received::Wait(None),
        d if crate::timer::now_ms() >= d => Received::Now((TIMEOUT, 0, 0)),
        d => Received::Wait(Some(d)),
    }
}

/// Whether the caller is an installed app, confined (see [`may`]).
/// An installed app, or a sealed program: neither may register a
/// service, reach a `system-…` one, start programs or read the disks' sizes.
/// `install`: the disks, starting an installation, how it goes.
fn install(a: [u64; 7]) -> (u64, u64, u64) {
    use crate::drivers::block::{self, Holds};
    use crate::install::{self, State};
    let answer = |text: &str| {
        let n = text.len().min(a[2] as usize);
        if write_user(a[1] as usize, &text.as_bytes()[..n]) {
            (n as u64, 0, 0)
        } else {
            FAILED
        }
    };
    match a[0] {
        0 => {
            let possible = install::possible();
            let least = install::min_bytes();
            let mut text = alloc::string::String::new();
            for d in block::disks() {
                let free = block::free_controller(&d.name).is_some();
                let holds = match d.holds {
                    Holds::Pinnacle => "pinnacle",
                    Holds::Other => "other",
                    Holds::Unknown => "unknown",
                    Holds::Empty => "empty",
                };
                let installable = possible && free && d.bytes >= least;
                text += &alloc::format!(
                    "{}|{}|{}|{}|{holds}|{}\n",
                    d.name,
                    d.model.replace('|', " "),
                    d.bytes,
                    u8::from(d.removable),
                    u8::from(installable)
                );
            }
            answer(&text)
        }
        1 => match read_user(a[3] as usize, a[4] as usize) {
            Some(name) if install::start(core::str::from_utf8(&name).unwrap_or("")) => (0, 0, 0),
            _ => FAILED,
        },
        2 => answer(&match install::state() {
            State::Idle => alloc::string::String::from("idle"),
            State::Running(what) => alloc::format!("running|{what}"),
            State::Done(what) => alloc::format!("done|{what}"),
            State::Failed(why) => alloc::format!("failed|{why}"),
        }),
        _ => FAILED,
    }
}

fn confined() -> bool {
    sched::with_process(|p| p.confined.is_some() || p.sealed).unwrap_or(false)
}

fn sealed() -> bool {
    sched::with_process(|p| p.sealed).unwrap_or(false)
}

/// The path of the program the caller runs, into its buffer: an installed
/// app's file (`system:/apps/<name>/program`); a program built in has none.
fn program(buffer: usize, len: usize) -> Answer {
    let Some(app) = sched::with_process(|p| p.confined.clone()).flatten() else {
        return FAILED;
    };
    let path = alloc::format!("system:/apps/{app}/program");
    if path.len() > len || !write_user(buffer, path.as_bytes()) {
        return FAILED;
    }
    (path.len() as u64, 0, 0)
}

/// Whether the caller may use the 3D GPU: a program the system started, or
/// an app whose manifest says `gpu=yes`.
fn gpu_granted() -> bool {
    if sealed() {
        return false;
    }
    let Some(app) = sched::with_process(|p| p.confined.clone()).flatten() else {
        return true;
    };
    let path = alloc::format!("/apps/{app}/manifest");
    crate::drivers::block::with_disk(&path, |fs, p| fs.read(p))
        .and_then(Result::ok)
        .is_some_and(|m| manifest_grants(&m, "gpu"))
}

/// Whether the caller may use the network: a program the system started,
/// or an app whose manifest says `network=yes`.
fn networked() -> bool {
    sched::with_process(|p| p.network).unwrap_or(false)
}

/// Offers a service by name. An installed app may not: it could take a
/// name a system service is about to claim.
fn register([name, len, handle, ..]: [u64; 7]) -> Answer {
    if confined() {
        return FAILED;
    }
    let Some(name) = read_user(name as usize, len as usize) else {
        return FAILED;
    };
    let end = sched::with_process(|p| match p.handle(handle) {
        Some(Object::Channel(end)) => Some(end.clone()),
        _ => None,
    })
    .flatten();
    if end.is_some_and(|end| object::register(&name, end)) {
        (0, 0, 0)
    } else {
        FAILED
    }
}

/// Starts a program: one built in, or an installed app
/// (`/apps/<name>/program` on the system disk), which runs confined to its
/// own folder, made here. An installed app may not start programs: it asks
/// the display server to.
fn spawn([name, len, argument, handles, count, flags, ..]: [u64; 7]) -> Answer {
    if confined() {
        return FAILED;
    }
    let Some(name) = read_user(name as usize, len as usize) else {
        return FAILED;
    };
    let path;
    let mut app = None;
    // Built in, or installed: then read from its disk as it loads, a range
    // at a time (a large program does not fit in one allocation).
    let mut built_in;
    let mut on_disk;
    let elf: &mut dyn crate::process::Image = match crate::programs::find(&name) {
        Some(elf) => {
            built_in = elf;
            &mut built_in
        }
        None => {
            let Ok(name) = core::str::from_utf8(&name) else {
                return FAILED;
            };
            if name.is_empty() || name.contains(['/', ':', '.']) {
                return FAILED;
            }
            path = alloc::format!("/apps/{name}/program");
            if crate::drivers::block::with_disk(&path, |fs, p| fs.stat(p))
                .and_then(Result::ok)
                .is_none()
            {
                return FAILED;
            }
            // Its folder, in the data vault once that is open; already there
            // after its first run.
            let folder = app_folder(name);
            let _ = crate::drivers::block::with_disk(&folder, |fs, p| fs.create_dir(p));
            app = Some(alloc::string::String::from(name));
            on_disk = crate::process::OnDisk(&path);
            &mut on_disk
        }
    };
    if count as usize > MAX_MESSAGE_HANDLES {
        return FAILED;
    }
    let Some(numbers) = read_user(handles as usize, count as usize * 8) else {
        return FAILED;
    };
    let given = sched::with_process(|p| {
        let numbers: Vec<u64> = u64s(&numbers).collect();
        if numbers.iter().any(|&n| p.handle(n).is_none()) {
            return None;
        }
        Some(
            numbers
                .iter()
                .map(|&n| p.take_handle(n).unwrap())
                .collect::<Vec<_>>(),
        )
    })
    .flatten();
    let Some(given) = given else { return FAILED };
    // What the app's manifest grants it, read before it runs.
    let network = app.as_deref().is_some_and(|name| {
        let path = alloc::format!("/apps/{name}/manifest");
        crate::drivers::block::with_disk(&path, |fs, p| fs.read(p))
            .and_then(Result::ok)
            .is_some_and(|m| manifest_grants(&m, "network"))
    });
    let network = network || app.is_none();
    // Asked to know how it ends: the starter's end of a channel its code
    // arrives on, the program holding the other from before it runs.
    let (watcher, watch) = if flags & pinnacle_abi::SPAWN_WATCH != 0 {
        let (watcher, watch) = Endpoint::pair();
        (Some(watcher), Some(watch))
    } else {
        (None, None)
    };
    let sealed = flags & pinnacle_abi::SPAWN_SEALED != 0;
    let Ok(id) =
        sched::spawn_program_watched(elf, argument, given, false, false, app, network, sealed, watch)
    else {
        return FAILED;
    };
    sched::name(id, &name);
    let watcher = watcher.map_or(0, |w| add(Object::Channel(w)).0);
    match sched::process_of(id) {
        Some(process) => (id as u64, add(Object::Process(process)).0, watcher),
        // It ended already.
        None => (id as u64, 0, watcher),
    }
}

/// Whether a manifest (`key=value` lines) has `<key>=yes`.
pub fn manifest_grants(manifest: &[u8], key: &str) -> bool {
    core::str::from_utf8(manifest).is_ok_and(|text| {
        text.lines().any(|line| {
            line.strip_prefix(key)
                .and_then(|r| r.strip_prefix('='))
                .is_some_and(|v| v.trim() == "yes")
        })
    })
}

fn privileged() -> bool {
    sched::with_process(|p| p.privileged).unwrap_or(false)
}

/// The screen: its framebuffer's handle, width and height. Asked with a
/// width and height other than the screen's (and possible), the screen
/// changes to that size first: a rotation, or a different display.
fn framebuffer(width: u32, height: u32) -> Answer {
    if !privileged() {
        return FAILED;
    }
    let current = crate::drivers::display::DISPLAY
        .lock()
        .as_ref()
        .map(|d| (d.width, d.height));
    if width != 0 && height != 0 && current.is_some_and(|c| c != (width, height)) {
        // Kept as it is when the new size cannot be had.
        crate::drivers::display::init(width, height);
    }
    let lent = crate::drivers::display::DISPLAY
        .lock()
        .as_ref()
        .map(|d| (d.memory.clone(), d.width, d.height));
    match lent {
        Some((memory, width, height)) => {
            let (handle, ..) = add(Object::Memory(memory));
            (handle, u64::from(width), u64::from(height))
        }
        None => FAILED,
    }
}

fn input() -> Answer {
    if !privileged() {
        return FAILED;
    }
    match crate::drivers::input::subscribe() {
        Some(end) => add(Object::Channel(end)),
        None => FAILED,
    }
}

type Disk = pinnacle_fs::Fs<crate::drivers::block::Store>;

/// An installed app's own folder: in the data vault once it is open, else
/// on the system disk.
fn app_folder(name: &str) -> alloc::string::String {
    if crate::drivers::block::mounted("data") {
        alloc::format!("data:/apps/{name}")
    } else {
        alloc::format!("system:/data/{name}")
    }
}

/// The path a call means, if the caller may reach it (read it, or with
/// `write` change it). `app:/…` is the calling app's own folder, wherever
/// it is: an app need not know whether the person's data is in a vault.
/// Programs the system starts may touch any file. An installed app `name`
/// is confined: it reads its own package (`/apps/<name>`), the fonts, the
/// TLS roots, the time zones and what the person chose of zone and keyboard
/// (`/locale`) on the system disk, and reads and writes its own folder;
/// nothing else, and no path that climbs with `..`.
fn checked(path: &str, write: bool) -> Option<alloc::string::String> {
    if sealed() {
        return None;
    }
    let confined = sched::with_process(|p| p.confined.clone()).flatten();
    if confined.is_some() && path.split('/').any(|c| c == ".." || c == ".") {
        return None;
    }
    let path = match path.strip_prefix("app:") {
        Some(rest) => {
            let folder = app_folder(confined.as_deref()?);
            let rest = rest.trim_start_matches('/');
            if rest.is_empty() {
                folder
            } else {
                alloc::format!("{folder}/{rest}")
            }
        }
        // No label: the system disk.
        None if !path.contains(':') => alloc::format!("system:{path}"),
        None => path.into(),
    };
    let Some(name) = confined else {
        return Some(path);
    };
    let under = |dir: &str| path == dir || path.strip_prefix(dir).is_some_and(|rest| rest.starts_with('/'));
    let allowed = under(&app_folder(&name))
        || !write
            && (under(&alloc::format!("system:/apps/{name}"))
                || under("system:/fonts")
                || under("system:/certificates")
                || under("system:/zoneinfo")
                || under("system:/locale"));
    allowed.then_some(path)
}

/// A call that changes the disk at `path`, if the caller may.
fn file_op(path: &[u8], f: impl FnOnce(&mut Disk, &str) -> Result<u64, pinnacle_fs::Error>) -> Answer {
    let Some(path) = core::str::from_utf8(path).ok().and_then(|p| checked(p, true)) else {
        return FAILED;
    };
    match crate::drivers::block::with_disk(&path, f) {
        Some(Ok(value)) => (value, 0, 0),
        _ => FAILED,
    }
}

fn read_file([path, len, buffer, size, ..]: [u64; 7]) -> Answer {
    let Some(path) = readable(path, len) else {
        return FAILED;
    };
    let read = |fs: &mut Disk, p: &str| {
        let length = fs.stat(p)?.size;
        // Only what fits is read: a file can be far larger than memory.
        if length > size.min(MAX_COPY as u64) {
            return Ok(Err(length));
        }
        fs.read(p).map(Ok)
    };
    match crate::drivers::block::with_disk(&path, read) {
        Some(Ok(Err(length))) => (length, 0, 0),
        Some(Ok(Ok(data))) if data.len() as u64 <= size => {
            if write_user(buffer as usize, &data) {
                (data.len() as u64, 0, 0)
            } else {
                FAILED
            }
        }
        Some(Ok(Ok(data))) => (data.len() as u64, 0, 0),
        _ => FAILED,
    }
}

/// The path a call names, if the caller may read it ([`checked`]).
fn readable(path: u64, len: u64) -> Option<alloc::string::String> {
    let path = read_user(path as usize, len as usize)?;
    checked(core::str::from_utf8(&path).ok()?, false)
}

fn read_at([path, len, offset, buffer, size, ..]: [u64; 7]) -> Answer {
    let Some(path) = readable(path, len) else {
        return FAILED;
    };
    let size = size.min(MAX_COPY as u64);
    match crate::drivers::block::with_disk(&path, |fs, p| fs.read_at(p, offset, size)) {
        Some(Ok(data)) if write_user(buffer as usize, &data) => (data.len() as u64, 0, 0),
        _ => FAILED,
    }
}

fn stat([path, len, ..]: [u64; 7]) -> Answer {
    let Some(path) = readable(path, len) else {
        return FAILED;
    };
    match crate::drivers::block::with_disk(&path, |fs, p| fs.stat(p)) {
        Some(Ok(stat)) => (stat.size, stat.kind as u64, stat.modified),
        _ => FAILED,
    }
}

/// A handle to one file, with the rights asked for if the caller may have
/// them ([`checked`]): reading needs only read access, writing or adding
/// needs write access, and makes the file when it is missing.
fn open_file([path, len, rights, ..]: [u64; 7]) -> Answer {
    use pinnacle_abi::file::{APPEND, READ, WRITE};
    let changes = rights & (WRITE | APPEND) != 0;
    if rights == 0 || rights & !(READ | WRITE | APPEND) != 0 {
        return FAILED;
    }
    let Some(path) = read_user(path as usize, len as usize)
        .and_then(|p| alloc::string::String::from_utf8(p).ok())
        .and_then(|p| checked(&p, changes))
    else {
        return FAILED;
    };
    let is_file = crate::drivers::block::with_disk(&path, |fs, p| match fs.stat(p) {
        Ok(stat) => Ok(stat.kind == pinnacle_fs::Kind::File),
        Err(_) if changes => fs.write_at(p, 0, &[]).map(|()| true),
        Err(e) => Err(e),
    });
    match is_file {
        Some(Ok(true)) => add(Object::File(Arc::new(object::OpenFile { path, rights }))),
        _ => FAILED,
    }
}

/// An operation on a file handle (`pinnacle_abi::file`).
fn file([handle, op, offset, buffer, len, ..]: [u64; 7]) -> Answer {
    use pinnacle_abi::file::*;
    let Some(Some(Object::File(file))) = sched::with_process(|p| p.handle(handle).cloned()) else {
        return FAILED;
    };
    let may = |right: u64| file.rights & right != 0;
    let on_disk = |f: &mut dyn FnMut(&mut Disk, &str) -> Result<Answer, pinnacle_fs::Error>| {
        match crate::drivers::block::with_disk(&file.path, |fs, p| f(fs, p)) {
            Some(Ok(answer)) => answer,
            _ => FAILED,
        }
    };
    match op {
        OP_READ if may(READ) => {
            let len = len.min(MAX_COPY as u64);
            match crate::drivers::block::with_disk(&file.path, |fs, p| fs.read_at(p, offset, len)) {
                Some(Ok(data)) if write_user(buffer as usize, &data) => (data.len() as u64, 0, 0),
                _ => FAILED,
            }
        }
        OP_WRITE | OP_APPEND if op == OP_WRITE && may(WRITE) || op == OP_APPEND && may(WRITE | APPEND) => {
            let Some(data) = read_user(buffer as usize, len as usize) else {
                return FAILED;
            };
            on_disk(&mut |fs, p| {
                // Finding the end and writing there happen under the disk's
                // lock, so two holders adding at once each get their own.
                let at = if op == OP_APPEND { fs.stat(p)?.size } else { offset };
                fs.write_at(p, at, &data)?;
                Ok((at, 0, 0))
            })
        }
        OP_REPLACE if may(WRITE) => {
            let Some(data) = read_user(buffer as usize, len as usize) else {
                return FAILED;
            };
            on_disk(&mut |fs, p| fs.write(p, &data).map(|()| (0, 0, 0)))
        }
        OP_STAT => on_disk(&mut |fs, p| {
            let stat = fs.stat(p)?;
            Ok((stat.size, stat.kind as u64, stat.modified))
        }),
        OP_NARROW if offset != 0 && offset & !file.rights == 0 => {
            add(Object::File(Arc::new(object::OpenFile {
                path: file.path.clone(),
                rights: offset,
            })))
        }
        OP_RIGHTS => (file.rights, 0, 0),
        _ => FAILED,
    }
}

fn list([path, len, buffer, size, ..]: [u64; 7]) -> Answer {
    let Some(path) = readable(path, len) else {
        return FAILED;
    };
    match crate::drivers::block::with_disk(&path, |fs, p| fs.list(p)) {
        Some(Ok(names)) => {
            let mut out = Vec::new();
            for name in names {
                out.extend_from_slice(name.as_bytes());
                out.push(b'\n');
            }
            out.truncate(size as usize);
            if write_user(buffer as usize, &out) {
                (out.len() as u64, 0, 0)
            } else {
                FAILED
            }
        }
        _ => FAILED,
    }
}

/// Ends the program `handle` names, if it still runs.
fn kill(handle: u64) -> Answer {
    let target = sched::with_process(|p| match p.handle(handle) {
        Some(Object::Process(process)) => process.upgrade(),
        _ => None,
    })
    .flatten();
    let Some(target) = target else {
        return FAILED;
    };
    // A program ends itself with EXIT_PROCESS, which leaves no thread behind.
    if sched::current_process().is_some_and(|me| Arc::ptr_eq(&me, &target)) {
        return FAILED;
    }
    sched::kill(&target);
    (0, 0, 0)
}

/// The programs that run (op 0) or the services registered (op 1), as text
/// into the caller's `buffer`.
fn processes(op: u64, buffer: usize, len: usize) -> Answer {
    use core::fmt::Write as _;
    let mut text = alloc::string::String::new();
    match op {
        0 => {
            for p in sched::processes() {
                let kind = match () {
                    _ if p.privileged => "display",
                    _ if p.sealed => "sealed",
                    _ if p.app => "app",
                    _ => "system",
                };
                // A name has no `|` or line break: it is a program's.
                let name: alloc::string::String =
                    p.name.chars().filter(|c| !matches!(c, '|' | '\n')).collect();
                let _ = writeln!(
                    text,
                    "{}|{name}|{}|{}|{}|{kind}",
                    p.id, p.threads, p.memory, p.started
                );
            }
        }
        1 => {
            for name in object::services() {
                text.push_str(&alloc::string::String::from_utf8_lossy(&name));
                text.push('\n');
            }
        }
        _ => return FAILED,
    }
    let bytes = &text.as_bytes()[..text.len().min(len)];
    if write_user(buffer, bytes) {
        (bytes.len() as u64, 0, 0)
    } else {
        FAILED
    }
}

/// Ends the program numbered `id`: not the display server, nor the caller.
fn kill_id(id: u64) -> Answer {
    let Some(target) = sched::process_by_id(id) else {
        return FAILED;
    };
    // Its lock let go before the task lock is taken, which `end_threads`
    // takes the other way round.
    let privileged = target.lock().privileged;
    if privileged || sched::current_process().is_some_and(|me| Arc::ptr_eq(&me, &target)) {
        return FAILED;
    }
    sched::kill(&target);
    (0, 0, 0)
}

/// The disk that waits for a passphrase: its state, opening it, or making
/// it a vault.
fn vault([op, passphrase, len, new, new_len, ..]: [u64; 7]) -> Answer {
    use crate::drivers::block;
    if op == 0 {
        return (block::vault_state(), 0, 0);
    }
    let Some(passphrase) = read_user(passphrase as usize, len as usize) else {
        return FAILED;
    };
    let Ok(passphrase) = core::str::from_utf8(&passphrase) else {
        return FAILED;
    };
    let done = match op {
        1 => block::open_vault(passphrase),
        2 => block::create_vault(passphrase),
        3 => block::check_vault(passphrase),
        4 => read_user(new as usize, new_len as usize)
            .and_then(|new| alloc::string::String::from_utf8(new).ok())
            .is_some_and(|new| block::change_vault_passphrase(passphrase, &new)),
        _ => false,
    };
    if done { (0, 0, 0) } else { FAILED }
}