# Path: VM/ctypes_types.py

# 
# Path: VM/kernel/kernel.py
# class KernelMeta(type):   
# class Kernel(metaclass=KernelMeta):
#     def register(cls, syscall_number: int):
#         def actually_register(function: Callable[..., int]):
#     def __init__(self, cpu):
#     def __getitem__(self, syscall_number: int):
#     def kernel_read_string(self, address: int) -> bytes:


import os
import logging
    import enum
from io import UnsupportedOperation
from ..ctypes_types import udword, ctypes
from .kernel import Kernel, Int, Uint

    logger.info('\tsys_read: [SUCC] read %r from fd %u', data, fd)

    l = len(data)
    kernel.cpu.mem.set_bytes(data_addr, l, data)

    return l


@Kernel.register(0x04)
def sys_write(kernel: Kernel, fd: Uint, buf_addr: Uint, count: Uint):
    """
    Arguments: (unsigned int fd, const char * buf, size_t count)
    """

    buf = kernel.cpu.mem.get_bytes(buf_addr, count)

    logger.info('sys_write(%d, 0x%08x(%s), %d)', fd, buf_addr, buf, count)
    try:
        fileno = kernel.cpu.descriptors[fd].fileno()
        ret = os.write(fileno, buf)
        # os.fsync(fileno)
    except (AttributeError, UnsupportedOperation):
        ret = kernel.cpu.descriptors[fd].write(buf.decode('ascii'))
        kernel.cpu.descriptors[fd].flush()

    return ret if ret is not None else count


@Kernel.register(0x92)

# Path: VM/ctypes_types.py

# 
# Path: VM/kernel/kernel.py
# class KernelMeta(type):   
# class Kernel(metaclass=KernelMeta):
#     def register(cls, syscall_number: int):
#         def actually_register(function: Callable[..., int]):
#     def __init__(self, cpu):
#     def __getitem__(self, syscall_number: int):
#     def kernel_read_string(self, address: int) -> bytes:


# Path: VM/kernel/kernel_filesystem.py
import os
import logging
    import enum
from io import UnsupportedOperation
from ..ctypes_types import udword, ctypes
from .kernel import Kernel, Int, Uint


    logger.info('\tsys_read: [SUCC] read %r from fd %u', data, fd)

    l = len(data)
    kernel.cpu.mem.set_bytes(data_addr, l, data)

    return l


@Kernel.register(0x04)
def sys_write(kernel: Kernel, fd: Uint, buf_addr: Uint, count: Uint):
    """
    Arguments: (unsigned int fd, const char * buf, size_t count)
    """

    buf = kernel.cpu.mem.get_bytes(buf_addr, count)

    logger.info('sys_write(%d, 0x%08x(%s), %d)', fd, buf_addr, buf, count)
    try:
        fileno = kernel.cpu.descriptors[fd].fileno()
        ret = os.write(fileno, buf)
        # os.fsync(fileno)
    except (AttributeError, UnsupportedOperation):
        ret = kernel.cpu.descriptors[fd].write(buf.decode('ascii'))
        kernel.cpu.descriptors[fd].flush()

    return ret if ret is not None else count


@Kernel.register(0x92)

def sys_writev(kernel: Kernel, fd: Int, iov_addr: Uint, iovcnt: Int):