extmod/moddeflate: Keep DeflateIO state consistent on window alloc fail.

Allocation of a large compression window may fail, and in that case keep
the `DeflateIO` state consistent so its other methods (such as `close()`)
still work.  Consistency is kept by only updating the `self->write` member
if the window allocation succeeds.

Thanks to @jimmo for finding the bug.

Signed-off-by: Damien George <damien@micropython.org>
This commit is contained in:
Damien George
2025-03-18 00:34:20 +11:00
parent fdc0c6f8f6
commit fa42487e45
4 changed files with 50 additions and 4 deletions

View File

@@ -168,16 +168,20 @@ static bool deflateio_init_write(mp_obj_deflateio_t *self) {
const mp_stream_p_t *stream = mp_get_stream_raise(self->stream, MP_STREAM_OP_WRITE);
self->write = m_new_obj(mp_obj_deflateio_write_t);
self->write->input_len = 0;
int wbits = self->window_bits;
if (wbits == 0) {
// Same default wbits for all formats.
wbits = DEFLATEIO_DEFAULT_WBITS;
}
// Allocate the large window before allocating the mp_obj_deflateio_write_t, in case the
// window allocation fails the mp_obj_deflateio_t object will remain in a consistent state.
size_t window_len = 1 << wbits;
self->write->window = m_new(uint8_t, window_len);
uint8_t *window = m_new(uint8_t, window_len);
self->write = m_new_obj(mp_obj_deflateio_write_t);
self->write->window = window;
self->write->input_len = 0;
uzlib_lz77_init(&self->write->lz77, self->write->window, window_len);
self->write->lz77.dest_write_data = self;