import errno
import fcntl
import mmap
import os
import struct

fd = os.open('/dev/amifl', os.O_RDWR)
try:
    for command in (0x4160, 0x4161):
        try:
            fcntl.ioctl(fd, command, 1)
        except OSError as error:
            assert error.errno == errno.EFAULT, error
        else:
            raise AssertionError('invalid user pointer accepted')
    for size in (-1, 0, 128 * 1024 + 1):
        data = bytearray(struct.pack('<qQQQQ', size, 0, 0, 0, 0))
        try:
            fcntl.ioctl(fd, 0x4160, data, True)
        except OSError as error:
            assert error.errno == errno.EINVAL, error
        else:
            raise AssertionError('invalid allocation size accepted')
    data = bytearray(struct.pack('<qQQQQ', 65536, 0, 0, 0, 0))
    fcntl.ioctl(fd, 0x4160, data, True)
    try:
        size, _, _, virtual, physical = struct.unpack('<qQQQQ', data)
        assert size == 65536 and virtual and physical
        with mmap.mmap(fd, 65536, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ) as mapping:
            assert struct.unpack('<4I', mapping[:16]) == tuple(range(0xAFD00000, 0xAFD00004))
    finally:
        fcntl.ioctl(fd, 0x4161, data, True)
    print('LEGACY_DRIVER_CHECK_OK: invalid pointers/sizes rejected; allocated, mapped, read and freed 64 KiB')
finally:
    os.close(fd)
