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>
diff --git a/util/cbfstool/common.c b/util/cbfstool/common.c
index 539d0ba..5889e2a 100644
--- a/util/cbfstool/common.c
+++ b/util/cbfstool/common.c
@@ -49,7 +49,8 @@
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 @@
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");
diff --git a/util/cbfstool/common.h b/util/cbfstool/common.h
index 07ffdf8..b23c8d2 100644
--- a/util/cbfstool/common.h
+++ b/util/cbfstool/common.h
@@ -132,6 +132,11 @@
/* 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);