fix(bitscrambler): clean up loopback create failures

Clear the returned handle on loopback creation failure and route
initialized objects through bitscrambler_free so channel ownership and
extra cleanup state cannot leak after partial setup errors. Add a
regression test for the failed create path.
This commit is contained in:
morris
2026-08-03 10:18:29 +08:00
parent 7105b85101
commit a68dbf4033
2 changed files with 23 additions and 5 deletions
@@ -72,11 +72,13 @@ esp_err_t bitscrambler_loopback_create(bitscrambler_handle_t *handle, int attach
if (!handle) {
return ESP_ERR_INVALID_ARG;
}
*handle = NULL;
if (attach_to < 0 || attach_to > SOC_BITSCRAMBLER_ATTACH_MAX) {
return ESP_ERR_INVALID_ARG;
}
esp_err_t ret = ESP_OK;
bool bs_initialized = false;
bitscrambler_loopback_t *bs = calloc(1, sizeof(bitscrambler_loopback_t));
if (!bs) {
return ESP_ERR_NO_MEM;
@@ -88,14 +90,13 @@ esp_err_t bitscrambler_loopback_create(bitscrambler_handle_t *handle, int attach
.attach_to = attach_to
};
ESP_GOTO_ON_ERROR(bitscrambler_init_loopback(&bs->bs, &cfg), err, TAG, "failed bitscrambler init for loopback");
bs_initialized = true;
// register extra cleanup function to free loopback resources
bitscrambler_register_extra_clean_up(&bs->bs, bitscrambler_loopback_cleanup, bs);
bs->sema_done = xSemaphoreCreateBinary();
if (!bs->sema_done) {
goto err;
}
ESP_GOTO_ON_FALSE(bs->sema_done, ESP_ERR_NO_MEM, err, TAG, "failed to create semaphore");
bs->max_transfer_sz_bytes = max_transfer_sz_bytes;
size_t desc_ct = esp_dma_calculate_node_count(max_transfer_sz_bytes, 4, DMA_DESCRIPTOR_BUFFER_MAX_SIZE);
@@ -137,8 +138,11 @@ esp_err_t bitscrambler_loopback_create(bitscrambler_handle_t *handle, int attach
return ESP_OK;
err:
bitscrambler_loopback_free(bs);
free(bs);
if (bs_initialized) {
bitscrambler_free(&bs->bs);
} else {
free(bs);
}
return ret;
}