pci-pc: add NULL check for qpci_free_pc
PATCH 1/1 pci-pc: add NULL check for qpci_free_pc
The current layout of struct QPCIBusPC provides only one field, QPCIBus bus, so passing a NULL pointer to qpci_free_pc() makes container_of(NULL, QPCIBusPC, bus)
returning 0 (NULL), that is correctly handled by g_free(). This is bad practice, allowing the caller to think that it's okay to always pass NULL to the function, even though this is just a particular case.
In facts, qpci_free_pc() happens to return NULL only because container_of computes the subtraction between the given NULL
pointer and offsetof(QPCIBus, bus), with the latter returning 0 too, since bus is the first element of the struct and there is no offset betwen itself and QPCIBusPC.
However, if in future the bus field changes its position, for example becoming the second field, offsetof will return a number > 0, since there is some offset between the beginning of the struct and the bus field.
Therefore passing a NULL pointer to the container_of macro will return a negative number, that will be translated into an invalid address passed to g_free() and causing a seg fault.
Adding a preventive safety check that returns from the function if the given pointer is NULL solves the problem.
--- tests/libqos/pci-pc.c | 4 ++++ 1 file changed, 4 insertions(+)
tests/libqos/pci-pc.c +4 -0
@@ -152,6 +152,10 @@ QPCIBus *qpci_init_pc(QTestState *qts, QGuestAllocator *alloc)void qpci_free_pc (QPCIBus *bus) { +if (!bus) { +return ; + } +QPCIBusPC *s =container_of (bus, QPCIBusPC, bus);g_free (s);
Signature · 1 line
2.17.1
Quoted 20 lines · Emanuele Giuseppe Esposito
The current layout of struct QPCIBusPC provides only one field, QPCIBus bus, so passing a NULL pointer to
qpci_free_pc()makescontainer_of(NULL, QPCIBusPC, bus)
returning 0 (NULL), that is correctly handled byg_free(). This is bad practice, allowing the caller to think that it's okay to always pass NULL to the function, even though this is just a particular case.
In facts,qpci_free_pc()happens to return NULL only becausecontainer_ofcomputes the subtraction between the given NULL
pointer andoffsetof(QPCIBus, bus), with the latter returning 0 too, since bus is the first element of the struct and there is no offset betwen itself and QPCIBusPC.However, if in future the bus field changes its position, for example becoming the second field, offsetof will return a number > 0, since there is some offset between the beginning of the struct and the bus field.
Therefore passing a NULL pointer to thecontainer_ofmacro will return a negative number, that will be translated into an invalid address passed tog_free()and causing a seg fault.
Quoted 7 lines
Adding a preventive safety check that returns from the function if the given pointer is NULL solves the problem.
Signed-off-by Emanuele Giuseppe Esposito <[email protected]>--- tests/libqos/pci-pc.c | 4 ++++ 1 file changed, 4 insertions(+)