conversions of malloc/calloc/free to g_malloc/g_new/g_free etc

The QEMU project has generally standardized on using the glib g_malloc/g_free operations instead of plain malloc/free for memory allocation. There are a few remaining uses of malloc/free that could do with being converted to g_malloc/g_free for consistency.

What needs to be done:

  • Look at the coding style guide to find out what our recommendations for memory allocation are: https://www.qemu.org/docs/master/devel/style.html#low-level-memory-management.
  • Only tackle one data structure at a time, because an allocation with malloc or calloc must be freed with free but an allocation with g_malloc must be freed with g_free. So you need to do a bit of analysis of the code to see where an allocation may be later freed.
  • Put each conversion in its own patch; don't put several unrelated conversions in a single patch.
  • If you've got a patch that converts handling for one data structure, send that, so you can get code review on it. Don't try to do lots of conversions at once and send a big series.
  • Look for uses of malloc, and convert them to g_new or similar (see the coding style guide for more details on allocation interface usage). For allocations that are large or where the guest can control the allocation size, g_try_malloc may be better.
  • Likewise, convert calloc to g_new0 and friends.
  • Drop return value checks unless using g_try_new/g_try_new0.
  • Ignore uses of malloc in standalone test cases and in third party libraries. Notably, you should ignore uses in:
    • subprojects/
    • tests/tcg/
    • libdecnumber/
    • pc-bios/
    • target/xtensa/xtensa-isa.c
  • Ignore bsd-user/elfload.c for the moment -- the bsd-user maintainers are trying to upstream a large quantity of downstream changes currently, and unnecessary changes to upstream make it harder for them.
  • A few places in the code must deliberately use malloc -- these will have a comment near the callsite explaining why. You can ignore these ones.

The main remaining sites to be converted from use of malloc are:

  • a few uses in disas/ (m68k, sparc, nios2)
  • hw/audio/fmopl.c
  • target/xtensa/translate.c
  • contrib/elf2dmp/

And for calloc:

  • hw/xtensa/mx_pic.c
  • linux-user/main.c
  • tests/vhost-user-bridge.c
Edited by Peter Maydell