cbfstool: Add helper function `buffer_from_file_aligned_size`
This change adds a helper function `buffer_from_file_aligned_size` that loads a file into memory buffer by creating a memory buffer of size rounded up to the provided `size_granularity` parameter. BUG=b:189177186,b:189167923 Change-Id: Iad3430d476abcdad850505ac50e36cd5d5deecb4 Signed-off-by: Furquan Shaikh <furquan@google.com> Reviewed-on: https://review.coreboot.org/c/coreboot/+/55989 Tested-by: build bot (Jenkins) <no-reply@coreboot.org> Reviewed-by: Felix Held <felix-coreboot@felixheld.de> Reviewed-by: Tim Wawrzynczak <twawrzynczak@chromium.org>
This commit is contained in:
parent
967730f565
commit
2bfef8d856
|
@ -49,7 +49,8 @@ int buffer_create(struct buffer *buffer, size_t size, const char *name)
|
|||
return (buffer->data == NULL);
|
||||
}
|
||||
|
||||
int buffer_from_file(struct buffer *buffer, const char *filename)
|
||||
int buffer_from_file_aligned_size(struct buffer *buffer, const char *filename,
|
||||
size_t size_granularity)
|
||||
{
|
||||
FILE *fp = fopen(filename, "rb");
|
||||
if (!fp) {
|
||||
|
@ -63,20 +64,29 @@ int buffer_from_file(struct buffer *buffer, const char *filename)
|
|||
fclose(fp);
|
||||
return -1;
|
||||
}
|
||||
buffer->size = file_size;
|
||||
buffer->size = ALIGN_UP(file_size, size_granularity);
|
||||
buffer->name = strdup(filename);
|
||||
buffer->data = (char *)malloc(buffer->size);
|
||||
assert(buffer->data);
|
||||
if (fread(buffer->data, 1, buffer->size, fp) != buffer->size) {
|
||||
if (fread(buffer->data, 1, file_size, fp) != (size_t)file_size) {
|
||||
fprintf(stderr, "incomplete read: %s\n", filename);
|
||||
fclose(fp);
|
||||
buffer_delete(buffer);
|
||||
return -1;
|
||||
}
|
||||
fclose(fp);
|
||||
|
||||
if (buffer->size > (size_t)file_size)
|
||||
memset(buffer->data + file_size, 0xff, buffer->size - file_size);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int buffer_from_file(struct buffer *buffer, const char *filename)
|
||||
{
|
||||
return buffer_from_file_aligned_size(buffer, filename, 1);
|
||||
}
|
||||
|
||||
int buffer_write_file(struct buffer *buffer, const char *filename)
|
||||
{
|
||||
FILE *fp = fopen(filename, "wb");
|
||||
|
|
|
@ -132,6 +132,11 @@ int buffer_create(struct buffer *buffer, size_t size, const char *name);
|
|||
/* Loads a file into memory buffer. Returns 0 on success, otherwise non-zero. */
|
||||
int buffer_from_file(struct buffer *buffer, const char *filename);
|
||||
|
||||
/* Loads a file into memory buffer (with buffer size rounded up to a multiple of
|
||||
size_granularity). Returns 0 on success, otherwise non-zero. */
|
||||
int buffer_from_file_aligned_size(struct buffer *buffer, const char *filename,
|
||||
size_t size_granularity);
|
||||
|
||||
/* Writes memory buffer content into file.
|
||||
* Returns 0 on success, otherwise non-zero. */
|
||||
int buffer_write_file(struct buffer *buffer, const char *filename);
|
||||
|
|
Loading…
Reference in New Issue