Skip to content

Commit

Permalink
boot: Read files in small chunks on broken firmware
Browse files Browse the repository at this point in the history
Fixes: #25911
  • Loading branch information
medhefgo committed Mar 24, 2023
1 parent cfac791 commit d2ab1a4
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
7 changes: 4 additions & 3 deletions src/boot/efi/boot.c
Original file line number Diff line number Diff line change
Expand Up @@ -2311,12 +2311,13 @@ static EFI_STATUS initrd_prepare(
if (info->FileSize == 0) /* Automatically skip over empty files */
continue;

size_t new_size, read_size = info->FileSize;
if (__builtin_add_overflow(size, read_size, &new_size))
size_t new_size, read_size;
if (__builtin_add_overflow(size, info->FileSize, &new_size))
return EFI_OUT_OF_RESOURCES;
initrd = xrealloc(initrd, size, new_size);

err = handle->Read(handle, &read_size, initrd + size);
void *read_buf = initrd + size;
err = file_read(root, *i, 0, info->FileSize, &read_buf, &read_size);
if (err != EFI_SUCCESS)
return err;

Expand Down
39 changes: 38 additions & 1 deletion src/boot/efi/util.c
Original file line number Diff line number Diff line change
Expand Up @@ -333,9 +333,46 @@ EFI_STATUS file_read(EFI_FILE *dir, const char16_t *name, size_t off, size_t siz
}

err = handle->Read(handle, &size, read_buf);
if (err != EFI_SUCCESS)
if (!IN_SET(err, EFI_SUCCESS, EFI_BAD_BUFFER_SIZE))
return err;

/* Some firmwares cannot handle large file reads and will instead return EFI_BAD_BUFFER_SIZE.
* As a workaround, read such files in small chunks.
*
* https://github.com/systemd/systemd/issues/25911 */
if (err == EFI_BAD_BUFFER_SIZE) {
/* Handle is probably in a permanent bad state. Re-open the file. */
(void) handle->Close(handle);
handle = NULL;

err = dir->Open(dir, &handle, (char16_t *) name, EFI_FILE_MODE_READ, 0);
if (err != EFI_SUCCESS)
return err;

if (off > 0) {
err = handle->SetPosition(handle, off);
if (err != EFI_SUCCESS)
return err;
}

size_t remaining = size;
size = 0;
while (remaining > 0) {
size_t chunk = MIN(1024U * 1024U, remaining);

err = handle->Read(handle, &chunk, (uint8_t *) read_buf + size);
if (err != EFI_SUCCESS)
return err;
if (chunk == 0)
/* Caller requested more bytes than are in file. */
break;

assert(chunk <= remaining);
size += chunk;
remaining -= chunk;
}
}

if (buf_owned) {
/* Note that handle->Read() changes size to reflect the actually bytes read. */
memset((uint8_t *) read_buf + size, 0, extra);
Expand Down

0 comments on commit d2ab1a4

Please sign in to comment.