foxygit / fake-08-xbox360 Log in
main xbox360 commits tags

/platform/xex/runtime/fs.c · 17.56 KB

raw
/*
 * newlib file system calls and dirent for GCC-built Xbox 360 titles, on the
 * kernel's Nt* file API.
 *
 * Paths: "dev:/dir/file" or "dev:\dir\file" (dev = game, usb0..usb2, hdd, or
 * any other symbolic link), relative paths are relative to "game:". They
 * become the object name "\??\dev:\dir\file". Kernel paths starting with
 * '\' are passed through unchanged.
 */
#include <errno.h>
#include <fcntl.h>
#include <reent.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>

#include <xbox360/xboxkrnl.h>

#include "xex_runtime.h"

#define STATUS_END_OF_FILE              0xC0000011
#define STATUS_NO_MORE_FILES            0x80000006
#define STATUS_NO_SUCH_FILE             0xC000000F
#define STATUS_OBJECT_NAME_NOT_FOUND    0xC0000034
#define STATUS_OBJECT_NAME_COLLISION    0xC0000035
#define STATUS_OBJECT_PATH_NOT_FOUND    0xC000003A
#define STATUS_ACCESS_DENIED            0xC0000022
#define STATUS_FILE_IS_A_DIRECTORY      0xC00000BA
#define STATUS_NOT_A_DIRECTORY          0xC0000103
#define STATUS_NO_SUCH_DEVICE           0xC000000E
#define STATUS_DISK_FULL                0xC000007F
#define STATUS_SHARING_VIOLATION        0xC0000043
#define STATUS_CANNOT_DELETE            0xC0000121

#ifndef FILE_LIST_DIRECTORY
#define FILE_LIST_DIRECTORY 0x00000001
#endif
#ifndef FILE_READ_ATTRIBUTES
#define FILE_READ_ATTRIBUTES 0x00000080
#endif

#define XEX_PATH_MAX 512
#define MAX_FDS      64
#define FIRST_FD     3

typedef struct {
    HANDLE handle;
    long long pos;
    int append;
    int used;
} xex_file;

static xex_file files[MAX_FDS];

/* ------------------------------------------------------------------------ */

static int status_to_errno(NTSTATUS status)
{
    switch ((unsigned)status) {
    case STATUS_NO_SUCH_FILE:
    case STATUS_OBJECT_NAME_NOT_FOUND:
    case STATUS_OBJECT_PATH_NOT_FOUND:
    case STATUS_NO_SUCH_DEVICE:
        return ENOENT;
    case STATUS_OBJECT_NAME_COLLISION:
        return EEXIST;
    case STATUS_ACCESS_DENIED:
        return EACCES;
    case STATUS_FILE_IS_A_DIRECTORY:
        return EISDIR;
    case STATUS_NOT_A_DIRECTORY:
        return ENOTDIR;
    case STATUS_DISK_FULL:
        return ENOSPC;
    case STATUS_SHARING_VIOLATION:
    case STATUS_CANNOT_DELETE:
        return EBUSY;
    default:
        return EIO;
    }
}

static int nt_ok(NTSTATUS status)
{
    return (int)status >= 0;
}

/* "usb0:/a/b" -> "\??\usb0:\a\b"; relative -> "\??\game:\..." */
int xex_kernel_path(const char *in, char *out, size_t size)
{
    size_t o = 0;
    const char *p = in;

    if (!in || !*in) {
        return -1;
    }

    if (in[0] == '\\') {                      /* already a kernel path */
        if (strlen(in) + 1 > size) return -1;
        strcpy(out, in);
        return 0;
    }

    const char *colon = strchr(in, ':');
    const char *prefix = "\\??\\";
    for (const char *s = prefix; *s; s++) out[o++] = *s;
    if (!colon) {
        const char *game = "game:\\";
        for (const char *s = game; *s; s++) out[o++] = *s;
    }

    char last = 0;
    for (; *p && o + 2 < size; p++) {
        char c = (*p == '/') ? '\\' : *p;
        if (c == '\\' && last == '\\') continue;   /* collapse "//" */
        out[o++] = c;
        last = c;
    }
    if (*p) return -1;

    /* "dev:" -> "dev:\" (root), strip other trailing separators */
    if (o > 0 && out[o - 1] == ':') {
        out[o++] = '\\';
    } else {
        while (o > 1 && out[o - 1] == '\\' && out[o - 2] != ':') o--;
    }
    out[o] = 0;
    return 0;
}

static void init_attributes(OBJECT_ATTRIBUTES *attributes, STRING *name, char *path)
{
    size_t len = strlen(path);
    name->Length = (USHORT)len;
    name->MaximumLength = (USHORT)(len + 1);
    name->Buffer = path;
    attributes->RootDirectory = NULL;
    attributes->ObjectName = name;
    attributes->Attributes = OBJ_CASE_INSENSITIVE;
}

static NTSTATUS open_path(const char *path, HANDLE *handle, ACCESS_MASK access,
                          ULONG disposition, ULONG options)
{
    char kpath[XEX_PATH_MAX];
    STRING name;
    OBJECT_ATTRIBUTES attributes;
    IO_STATUS_BLOCK iosb;

    if (xex_kernel_path(path, kpath, sizeof(kpath)) != 0) {
        return STATUS_OBJECT_PATH_NOT_FOUND;
    }
    init_attributes(&attributes, &name, kpath);
    return NtCreateFile(handle, access | SYNCHRONIZE, &attributes, &iosb, NULL,
                        FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE,
                        (CREATE_DISPOSITION)disposition,
                        options | FILE_SYNCHRONOUS_IO_NONALERT);
}

static xex_file *get_file(int fd)
{
    if (fd < FIRST_FD || fd >= MAX_FDS || !files[fd].used) {
        return NULL;
    }
    return &files[fd];
}

/* FileStandardInformation: supported by every NT-style kernel. */
typedef struct {
    LARGE_INTEGER AllocationSize;
    LARGE_INTEGER EndOfFile;
    ULONG NumberOfLinks;
    BOOLEAN DeletePending;
    BOOLEAN Directory;
} XEX_FILE_STANDARD_INFORMATION;

/* Size and attributes of an open file. Tries FileStandardInformation
 * first (FileNetworkOpenInformation is not available on every kernel). */
static int query_file(HANDLE handle, long long *size, ULONG *attributes)
{
    IO_STATUS_BLOCK iosb;
    XEX_FILE_STANDARD_INFORMATION standard;
    if (nt_ok(NtQueryInformationFile(handle, &iosb, &standard, sizeof(standard), FileStandardInformation))) {
        *size = standard.EndOfFile.QuadPart;
        *attributes = standard.Directory ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL;
        return 0;
    }
    FILE_NETWORK_OPEN_INFORMATION info;
    if (nt_ok(NtQueryInformationFile(handle, &iosb, &info, sizeof(info), FileNetworkOpenInformation))) {
        *size = info.EndOfFile.QuadPart;
        *attributes = info.FileAttributes;
        return 0;
    }
    return -1;
}

static long long file_size(HANDLE handle)
{
    long long size;
    ULONG attributes;
    return query_file(handle, &size, &attributes) == 0 ? size : -1;
}

/* ------------------------------------------------------------------------ */
/* newlib system calls                                                      */

int _open_r(struct _reent *r, const char *path, int flags, int mode)
{
    (void)mode;
    int fd;
    for (fd = FIRST_FD; fd < MAX_FDS && files[fd].used; fd++) {}
    if (fd == MAX_FDS) {
        r->_errno = EMFILE;
        return -1;
    }

    ACCESS_MASK access = FILE_READ_ATTRIBUTES;
    switch (flags & O_ACCMODE) {
    case O_RDONLY: access |= GENERIC_READ; break;
    case O_WRONLY: access |= GENERIC_WRITE; break;
    default:       access |= GENERIC_READ | GENERIC_WRITE; break;
    }

    ULONG disposition;
    if ((flags & O_CREAT) && (flags & O_EXCL))       disposition = FILE_CREATE;
    else if ((flags & O_CREAT) && (flags & O_TRUNC)) disposition = FILE_OVERWRITE_IF;
    else if (flags & O_CREAT)                        disposition = FILE_OPEN_IF;
    else if (flags & O_TRUNC)                        disposition = FILE_OVERWRITE;
    else                                             disposition = FILE_OPEN;

    HANDLE handle;
    NTSTATUS status = open_path(path, &handle, access, disposition, FILE_NON_DIRECTORY_FILE);
    if (!nt_ok(status)) {
        r->_errno = status_to_errno(status);
        return -1;
    }

    files[fd].handle = handle;
    files[fd].pos = 0;
    files[fd].append = (flags & O_APPEND) != 0;
    files[fd].used = 1;
    return fd;
}

int _close_r(struct _reent *r, int fd)
{
    xex_file *f = get_file(fd);
    if (!f) {
        if (fd >= 0 && fd < FIRST_FD) return 0;
        r->_errno = EBADF;
        return -1;
    }
    NtClose(f->handle);
    f->used = 0;
    return 0;
}

_ssize_t _read_r(struct _reent *r, int fd, void *buf, size_t len)
{
    xex_file *f = get_file(fd);
    if (!f) {
        r->_errno = EBADF;
        return -1;
    }
    if (len == 0) return 0;

    IO_STATUS_BLOCK iosb;
    LARGE_INTEGER offset;
    offset.QuadPart = f->pos;
    NTSTATUS status = NtReadFile(f->handle, NULL, NULL, NULL, &iosb, buf, (ULONG)len, &offset);
    if ((unsigned)status == STATUS_END_OF_FILE) {
        return 0;
    }
    if (!nt_ok(status)) {
        r->_errno = status_to_errno(status);
        return -1;
    }
    f->pos += iosb.Information;
    return (_ssize_t)iosb.Information;
}

_ssize_t _write_r(struct _reent *r, int fd, const void *buf, size_t len)
{
    if (fd == 1 || fd == 2) {
        xex_debug_write(buf, len);
        return (_ssize_t)len;
    }

    xex_file *f = get_file(fd);
    if (!f) {
        r->_errno = EBADF;
        return -1;
    }
    if (len == 0) return 0;

    if (f->append) {
        long long size = file_size(f->handle);
        if (size >= 0) f->pos = size;
    }

    IO_STATUS_BLOCK iosb;
    LARGE_INTEGER offset;
    offset.QuadPart = f->pos;
    NTSTATUS status = NtWriteFile(f->handle, NULL, NULL, NULL, &iosb, (PVOID)buf, (ULONG)len, &offset);
    if (!nt_ok(status)) {
        r->_errno = status_to_errno(status);
        return -1;
    }
    f->pos += iosb.Information;
    return (_ssize_t)iosb.Information;
}

_off_t _lseek_r(struct _reent *r, int fd, _off_t off, int whence)
{
    xex_file *f = get_file(fd);
    if (!f) {
        r->_errno = EBADF;
        return -1;
    }
    long long base;
    switch (whence) {
    case SEEK_SET: base = 0; break;
    case SEEK_CUR: base = f->pos; break;
    case SEEK_END:
        base = file_size(f->handle);
        if (base < 0) {
            r->_errno = EIO;
            return -1;
        }
        break;
    default:
        r->_errno = EINVAL;
        return -1;
    }
    if (base + off < 0) {
        r->_errno = EINVAL;
        return -1;
    }
    f->pos = base + off;
    return (_off_t)f->pos;
}

static void fill_stat(struct stat *st, ULONG attributes, long long size)
{
    memset(st, 0, sizeof(*st));
    st->st_mode = (attributes & FILE_ATTRIBUTE_DIRECTORY) ? (S_IFDIR | 0777) : (S_IFREG | 0666);
    st->st_size = (off_t)size;
    st->st_nlink = 1;
    st->st_blksize = 4096;
}

int _fstat_r(struct _reent *r, int fd, struct stat *st)
{
    if (fd >= 0 && fd < FIRST_FD) {
        memset(st, 0, sizeof(*st));
        st->st_mode = S_IFCHR;
        return 0;
    }
    xex_file *f = get_file(fd);
    if (!f) {
        r->_errno = EBADF;
        return -1;
    }
    long long size;
    ULONG attributes;
    if (query_file(f->handle, &size, &attributes) != 0) {
        r->_errno = EIO;
        return -1;
    }
    fill_stat(st, attributes, size);
    return 0;
}

int _stat_r(struct _reent *r, const char *path, struct stat *st)
{
    char kpath[XEX_PATH_MAX];
    STRING name;
    OBJECT_ATTRIBUTES attributes;
    FILE_NETWORK_OPEN_INFORMATION info;

    if (xex_kernel_path(path, kpath, sizeof(kpath)) != 0) {
        r->_errno = ENAMETOOLONG;
        return -1;
    }
    init_attributes(&attributes, &name, kpath);
    NTSTATUS status = NtQueryFullAttributesFile(&attributes, &info);
    if (!nt_ok(status)) {
        /* No attributes by name (volume roots like "usb0:\", or kernels
         * without the call): open it and ask the handle. */
        HANDLE handle;
        NTSTATUS open_status = open_path(path, &handle, FILE_READ_ATTRIBUTES, FILE_OPEN, 0);
        if (!nt_ok(open_status)) {
            open_status = open_path(path, &handle, FILE_LIST_DIRECTORY, FILE_OPEN, FILE_DIRECTORY_FILE);
        }
        if (!nt_ok(open_status)) {
            r->_errno = status_to_errno(status);
            return -1;
        }
        long long size = 0;
        ULONG file_attributes = FILE_ATTRIBUTE_DIRECTORY;
        query_file(handle, &size, &file_attributes);
        NtClose(handle);
        fill_stat(st, file_attributes, size);
        return 0;
    }
    fill_stat(st, info.FileAttributes, info.EndOfFile.QuadPart);
    return 0;
}

int _isatty_r(struct _reent *r, int fd)
{
    (void)r;
    return fd >= 0 && fd < FIRST_FD;
}

#ifndef DELETE
#define DELETE 0x00010000
#endif

/* Deletes through FileDispositionInformation on an open handle: the
 * standard NT way, used when NtDeleteFile fails. */
static NTSTATUS delete_by_handle(const char *path, ULONG options)
{
    HANDLE handle;
    NTSTATUS status = open_path(path, &handle, DELETE, FILE_OPEN, options);
    if (!nt_ok(status)) return status;
    IO_STATUS_BLOCK iosb;
    BOOLEAN delete_file = TRUE;
    status = NtSetInformationFile(handle, &iosb, &delete_file, sizeof(delete_file), FileDispositionInformation);
    NtClose(handle);
    return status;
}

static int delete_path(const char *path, ULONG options)
{
    char kpath[XEX_PATH_MAX];
    STRING name;
    OBJECT_ATTRIBUTES attributes;
    if (xex_kernel_path(path, kpath, sizeof(kpath)) != 0) {
        errno = ENAMETOOLONG;
        return -1;
    }
    init_attributes(&attributes, &name, kpath);
    NTSTATUS status = NtDeleteFile(&attributes);
    if (!nt_ok(status)) {
        status = delete_by_handle(path, options);
    }
    if (!nt_ok(status)) {
        errno = status_to_errno(status);
        return -1;
    }
    return 0;
}

int _unlink_r(struct _reent *r, const char *path)
{
    if (delete_path(path, FILE_NON_DIRECTORY_FILE) != 0) {
        r->_errno = errno;
        return -1;
    }
    return 0;
}

int rmdir(const char *path)
{
    return delete_path(path, FILE_DIRECTORY_FILE);
}

int _link_r(struct _reent *r, const char *existing, const char *new_path)
{
    (void)existing; (void)new_path;
    r->_errno = ENOSYS;
    return -1;
}

int _rename_r(struct _reent *r, const char *old_path, const char *new_path)
{
    (void)old_path; (void)new_path;
    r->_errno = ENOSYS;
    return -1;
}

int mkdir(const char *path, mode_t mode)
{
    (void)mode;
    HANDLE handle;
    NTSTATUS status = open_path(path, &handle, FILE_LIST_DIRECTORY, FILE_CREATE, FILE_DIRECTORY_FILE);
    if (!nt_ok(status)) {
        errno = status_to_errno(status);
        return -1;
    }
    NtClose(handle);
    return 0;
}

int chdir(const char *path)
{
    (void)path;
    errno = ENOSYS;
    return -1;
}

/* ------------------------------------------------------------------------ */
/* dirent                                                                   */

struct __xex_dir {
    HANDLE handle;
    struct dirent entry;
    ULONG offset;        /* offset of the next entry in buffer, or ~0 */
    int restart;
    unsigned char buffer[8192] __attribute__((aligned(8)));
};

DIR *opendir(const char *path)
{
    HANDLE handle;
    NTSTATUS status = open_path(path, &handle, FILE_LIST_DIRECTORY, FILE_OPEN, FILE_DIRECTORY_FILE);
    if (!nt_ok(status)) {
        errno = status_to_errno(status);
        return NULL;
    }
    DIR *dir = (DIR *)malloc(sizeof(DIR));
    if (!dir) {
        NtClose(handle);
        errno = ENOMEM;
        return NULL;
    }
    dir->handle = handle;
    dir->offset = ~0u;
    dir->restart = 1;
    return dir;
}

struct dirent *readdir(DIR *dir)
{
    if (!dir) {
        errno = EBADF;
        return NULL;
    }
    if (dir->offset == ~0u) {
        IO_STATUS_BLOCK iosb;
        NTSTATUS status = NtQueryDirectoryFile(dir->handle, NULL, NULL, NULL, &iosb,
                                               dir->buffer, sizeof(dir->buffer), NULL,
                                               dir->restart ? TRUE : FALSE);
        dir->restart = 0;
        if (!nt_ok(status) || (unsigned)status == STATUS_NO_MORE_FILES) {
            return NULL;
        }
        dir->offset = 0;
    }

    FILE_DIRECTORY_INFORMATION *info = (FILE_DIRECTORY_INFORMATION *)(dir->buffer + dir->offset);
    ULONG len = info->FileNameLength;
    if (len > sizeof(dir->entry.d_name) - 1) len = sizeof(dir->entry.d_name) - 1;
    memcpy(dir->entry.d_name, info->FileName, len);
    dir->entry.d_name[len] = 0;
    dir->entry.d_type = (info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? DT_DIR : DT_REG;
    dir->entry.d_ino = 0;

    dir->offset = info->NextEntryOffset ? dir->offset + info->NextEntryOffset : ~0u;
    return &dir->entry;
}

void rewinddir(DIR *dir)
{
    if (dir) {
        dir->offset = ~0u;
        dir->restart = 1;
    }
}

int closedir(DIR *dir)
{
    if (!dir) {
        errno = EBADF;
        return -1;
    }
    NtClose(dir->handle);
    free(dir);
    return 0;
}

/* ------------------------------------------------------------------------ */
/* Mount points                                                             */

static NTSTATUS link_device(const char *link, const char *device)
{
    char link_buf[64], device_buf[96];
    STRING link_name, device_name;
    strcpy(link_buf, link);
    strcpy(device_buf, device);
    link_name.Length = (USHORT)strlen(link_buf);
    link_name.MaximumLength = link_name.Length + 1;
    link_name.Buffer = link_buf;
    device_name.Length = (USHORT)strlen(device_buf);
    device_name.MaximumLength = device_name.Length + 1;
    device_name.Buffer = device_buf;
    return ObCreateSymbolicLink(&link_name, &device_name);
}

/* name "usbX" -> "\??\usbX:" */
static void link_name_of(const char *name, char *out, size_t size)
{
    size_t n = strlen(name);
    if (n > 0 && name[n - 1] == ':') n--;
    snprintf(out, size, "\\??\\%.*s:", (int)n, name);
}

int xex_mount(const char *name, const char *device)
{
    char link[64];
    link_name_of(name, link, sizeof(link));
    NTSTATUS status = link_device(link, device);
    if (!nt_ok(status)) {
        errno = status_to_errno(status);
        return -1;
    }
    return 0;
}

int xex_unmount(const char *name)
{
    char link[64];
    STRING link_name;
    link_name_of(name, link, sizeof(link));
    link_name.Length = (USHORT)strlen(link);
    link_name.MaximumLength = link_name.Length + 1;
    link_name.Buffer = link;
    return nt_ok(ObDeleteSymbolicLink(&link_name)) ? 0 : -1;
}

void xex_mount_devices(void)
{
    link_device("\\??\\usb0:", "\\Device\\Mass0");
    link_device("\\??\\usb1:", "\\Device\\Mass1");
    link_device("\\??\\usb2:", "\\Device\\Mass2");
    link_device("\\??\\hdd:", "\\Device\\Harddisk0\\Partition1");
}