dm_test_spi_flash() picks up its SPI emulator with
uclass_first_device_err(UCLASS_SPI_EMUL), which assumes the sandbox SPI
flash emulator is the only device in that uclass. That holds today only
because the flash emulator is bound lazily, on the first transfer.

As soon as a second SPI emulator is described in the device tree it is
bound during the devicetree scan and so comes first in the uclass. The
test then hands a foreign device to sandbox_sf_set_block_protect(),
which casts its private data to struct sandbox_spi_flash and writes
past the end of it, corrupting the heap.

Ask for the emulator attached to this particular slave instead, which
is what the test means, and which stays correct however many SPI
emulators exist.

Signed-off-by: João Loureiro <[email protected]>
---
 test/dm/sf.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/test/dm/sf.c b/test/dm/sf.c
index 3684d021709..0ec02ac694b 100644
--- a/test/dm/sf.c
+++ b/test/dm/sf.c
@@ -50,8 +50,13 @@ static int dm_test_spi_flash(struct unit_test_state *uts)
        ut_assertok(spi_flash_read_dm(dev, 0, size, dst));
        ut_asserteq_mem(src, dst, size);
 
-       /* Try the write-protect stuff */
-       ut_assertok(uclass_first_device_err(UCLASS_SPI_EMUL, &emul));
+       /*
+        * Try the write-protect stuff. Ask for the emulator attached to this
+        * particular slave rather than the first one in the uclass, since
+        * other SPI emulators may be present.
+        */
+       ut_assertok(sandbox_spi_get_emul(state_get_current(), dev->parent, dev,
+                                        &emul));
        ut_asserteq(0, spl_flash_get_sw_write_prot(dev));
        sandbox_sf_set_block_protect(emul, 1);
        ut_asserteq(1, spl_flash_get_sw_write_prot(dev));
-- 
2.55.0

Reply via email to