ESP32: `spi:close/1` crashes the VM with a double free

Open Beginner friendly
#2,429 0 comments 1 reaction 0 assignees View on GitHub

Maintainers usually reply within 3 days

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
85/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
c, erlang
Domain
embedded-iot

Research direction

Start with src/platforms/esp32/components/avm_builtins/spi_driver.c at spidriver_close, then check src/libAtomVM/context.c at context_destroy to follow the second free. Reproduce with the ESP32-C6 example in the issue; done means closing the SPI device no longer triggers the heap assertion or reboot.

Written by the indexing model from the issue text.

Description

Description

Calling spi:close/1 on an ESP32 aborts the VM with a heap assertion.

spidriver_close frees the port's platform data but leaves ctx->platform_data pointing at it:

https://github.com/atomvm/AtomVM/blob/main/src/platforms/esp32/components/avm_builtins/spi_driver.c#L337

spidriver_consume_mailbox then returns NativeTerminate, and context_destroy frees ctx->platform_data a second time:

https://github.com/atomvm/AtomVM/blob/main/src/libAtomVM/context.c#L307

To reproduce

On an ESP32-C6 running v0.7.0-beta.0, which is also present on main:

SPI = spi:open([
    {bus_config, [{mosi, 1}, {sclk, 23}, {peripheral, "spi2"}]},
    {device_config, [{leds, [{clock_speed_hz, 2500000}, {mode, 0}, {cs, -1}, {address_len_bits, 0}]}]}
]),
ok = spi:write(SPI, leds, #{write_data => <<0>>}),
spi:close(SPI).

The log shows Removed SPI device. and Stopped SPI Bus., then assert failed: 0x4002838e and a reboot.

Suggested fix

Set ctx->platform_data = NULL; after free(spi_data); in spidriver_close, so context_destroy doesn't free it again.

Dominant language
Erlang
Stars
2.3k
Forks
171
Avg merge
4d 11h
Merged PRs (30d)
20

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from atomvm/AtomVM

All issues in atomvm/AtomVM

Similar issues

More Embedded & IoT issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.