memory_region_init_ram_ptr() (and memory_region_init_ram_device_ptr())
create a MemoryRegion backed by a lump of memory provided by the caller.
They do this by calling qemu_ram_alloc_from_ptr(), passing the size
and pointer along. However, qemu_ram_alloc_from_ptr() does this,
regardless of whether it was given a host pointer or not:

    align = qemu_real_host_page_size();
    align = MAX(align, TARGET_PAGE_SIZE);
    size = ROUND_UP(size, align);
    max_size = ROUND_UP(max_size, align);

The result is that if the caller passed us a lump of memory that's
not a multiple of both the host and target page sizes then we create
a RAMBlock whose used_length and max_length fields claim that it's
larger than the actual backing memory. Any user of RAMBlocks that
trusts that information (such as the migration code) will then
happily read or write off the end of the backing memory.

This obviously isn't right, but is the problem:
 * that qemu_ram_alloc_from_ptr() shouldn't align if it's given
   a host pointer, and all users of RAMBlock need to be able to
   cope with unaligned base pointers and sizes?
 * that qemu_ram_alloc_from_ptr() should complain (assert?) about
   unaligned base pointers and sizes, and all callers trying to
   use it for smaller MRs need to be fixed?

This came to my attention via
 https://gitlab.com/qemu-project/qemu/-/work_items/4877
which reports that trying to migrate the AVR 'uno' machine runs
into this because it creates an "sram-as-io" MemoryRegion backed
by a local allocation which is less than a page.

Related is
 https://gitlab.com/qemu-project/qemu/-/work_items/4663
which reports that the tpm-tis-device doesn't work under hvf, because
that device creates a non-aligned RAM MR with memory_region_init_ram_ptr(),
and the hvf code fails with an error when it sees a non-aligned
lump of RAM.

I'm not sure which direction we should be going in trying to fix these.

thanks
-- PMM

Reply via email to