AUTHORS, util/: Drop individual copyright notices
[coreboot.git] / util / cbfstool / cbfs_image.c
bloba0b2a82d8e652661ecadfa2a54451a07b44784bf
1 /* CBFS Image Manipulation */
2 /*
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; version 2 of the License.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
13 #include <inttypes.h>
14 #include <libgen.h>
15 #include <stddef.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <strings.h>
20 #include <commonlib/endian.h>
21 #include <vb2_sha.h>
23 #include "common.h"
24 #include "cbfs_image.h"
25 #include "elfparsing.h"
26 #include "rmodule.h"
28 /* Even though the file-adding functions---cbfs_add_entry() and
29 * cbfs_add_entry_at()---perform their sizing checks against the beginning of
30 * the subsequent section rather than a stable recorded value such as an empty
31 * file header's len field, it's possible to prove two interesting properties
32 * about their behavior:
33 * - Placing a new file within an empty entry located below an existing file
34 * entry will never leave an aligned flash address containing neither the
35 * beginning of a file header nor part of a file.
36 * - Placing a new file in an empty entry at the very end of the image such
37 * that it fits, but leaves no room for a final header, is guaranteed not to
38 * change the total amount of space for entries, even if that new file is
39 * later removed from the CBFS.
40 * These properties are somewhat nonobvious from the implementation, so the
41 * reader is encouraged to blame this comment and examine the full proofs
42 * in the commit message before making significant changes that would risk
43 * removing said guarantees.
46 /* The file name align is not defined in CBFS spec -- only a preference by
47 * (old) cbfstool. */
48 #define CBFS_FILENAME_ALIGN (16)
50 static const char *lookup_name_by_type(const struct typedesc_t *desc, uint32_t type,
51 const char *default_value)
53 int i;
54 for (i = 0; desc[i].name; i++)
55 if (desc[i].type == type)
56 return desc[i].name;
57 return default_value;
60 static int lookup_type_by_name(const struct typedesc_t *desc, const char *name)
62 int i;
63 for (i = 0; desc[i].name && strcasecmp(name, desc[i].name); ++i);
64 return desc[i].name ? (int)desc[i].type : -1;
67 static const char *get_cbfs_entry_type_name(uint32_t type)
69 return lookup_name_by_type(filetypes, type, "(unknown)");
72 int cbfs_parse_comp_algo(const char *name)
74 return lookup_type_by_name(types_cbfs_compression, name);
77 static const char *get_hash_attr_name(uint16_t hash_type)
79 return lookup_name_by_type(types_cbfs_hash, hash_type, "(invalid)");
82 int cbfs_parse_hash_algo(const char *name)
84 return lookup_type_by_name(types_cbfs_hash, name);
87 /* CBFS image */
89 size_t cbfs_calculate_file_header_size(const char *name)
91 return (sizeof(struct cbfs_file) +
92 align_up(strlen(name) + 1, CBFS_FILENAME_ALIGN));
95 /* Only call on legacy CBFSes possessing a master header. */
96 static int cbfs_fix_legacy_size(struct cbfs_image *image, char *hdr_loc)
98 assert(image);
99 assert(cbfs_is_legacy_cbfs(image));
100 // A bug in old cbfstool may produce extra few bytes (by alignment) and
101 // cause cbfstool to overwrite things after free space -- which is
102 // usually CBFS header on x86. We need to workaround that.
103 // Except when we run across a file that contains the actual header,
104 // in which case this image is a safe, new-style
105 // `cbfstool add-master-header` based image.
107 struct cbfs_file *entry, *first = NULL, *last = NULL;
108 for (first = entry = cbfs_find_first_entry(image);
109 entry && cbfs_is_valid_entry(image, entry);
110 entry = cbfs_find_next_entry(image, entry)) {
111 /* Is the header guarded by a CBFS file entry? Then exit */
112 if (((char *)entry) + ntohl(entry->offset) == hdr_loc) {
113 return 0;
115 last = entry;
117 if ((char *)first < (char *)hdr_loc &&
118 (char *)entry > (char *)hdr_loc) {
119 WARN("CBFS image was created with old cbfstool with size bug. "
120 "Fixing size in last entry...\n");
121 last->len = htonl(ntohl(last->len) - image->header.align);
122 DEBUG("Last entry has been changed from 0x%x to 0x%x.\n",
123 cbfs_get_entry_addr(image, entry),
124 cbfs_get_entry_addr(image,
125 cbfs_find_next_entry(image, last)));
127 return 0;
130 void cbfs_put_header(void *dest, const struct cbfs_header *header)
132 struct buffer outheader;
134 outheader.data = dest;
135 outheader.size = 0;
137 xdr_be.put32(&outheader, header->magic);
138 xdr_be.put32(&outheader, header->version);
139 xdr_be.put32(&outheader, header->romsize);
140 xdr_be.put32(&outheader, header->bootblocksize);
141 xdr_be.put32(&outheader, header->align);
142 xdr_be.put32(&outheader, header->offset);
143 xdr_be.put32(&outheader, header->architecture);
146 static void cbfs_decode_payload_segment(struct cbfs_payload_segment *output,
147 struct cbfs_payload_segment *input)
149 struct buffer seg = {
150 .data = (void *)input,
151 .size = sizeof(*input),
153 output->type = xdr_be.get32(&seg);
154 output->compression = xdr_be.get32(&seg);
155 output->offset = xdr_be.get32(&seg);
156 output->load_addr = xdr_be.get64(&seg);
157 output->len = xdr_be.get32(&seg);
158 output->mem_len = xdr_be.get32(&seg);
159 assert(seg.size == 0);
162 static int cbfs_file_get_compression_info(struct cbfs_file *entry,
163 uint32_t *decompressed_size)
165 unsigned int compression = CBFS_COMPRESS_NONE;
166 if (decompressed_size)
167 *decompressed_size = ntohl(entry->len);
168 for (struct cbfs_file_attribute *attr = cbfs_file_first_attr(entry);
169 attr != NULL;
170 attr = cbfs_file_next_attr(entry, attr)) {
171 if (ntohl(attr->tag) == CBFS_FILE_ATTR_TAG_COMPRESSION) {
172 struct cbfs_file_attr_compression *ac =
173 (struct cbfs_file_attr_compression *)attr;
174 compression = ntohl(ac->compression);
175 if (decompressed_size)
176 *decompressed_size =
177 ntohl(ac->decompressed_size);
180 return compression;
183 static struct cbfs_file_attr_hash *cbfs_file_get_next_hash(
184 struct cbfs_file *entry, struct cbfs_file_attr_hash *cur)
186 struct cbfs_file_attribute *attr = (struct cbfs_file_attribute *)cur;
187 if (attr == NULL) {
188 attr = cbfs_file_first_attr(entry);
189 if (attr == NULL)
190 return NULL;
191 if (ntohl(attr->tag) == CBFS_FILE_ATTR_TAG_HASH)
192 return (struct cbfs_file_attr_hash *)attr;
194 while ((attr = cbfs_file_next_attr(entry, attr)) != NULL) {
195 if (ntohl(attr->tag) == CBFS_FILE_ATTR_TAG_HASH)
196 return (struct cbfs_file_attr_hash *)attr;
198 return NULL;
201 void cbfs_get_header(struct cbfs_header *header, void *src)
203 struct buffer outheader;
205 outheader.data = src; /* We're not modifying the data */
206 outheader.size = 0;
208 header->magic = xdr_be.get32(&outheader);
209 header->version = xdr_be.get32(&outheader);
210 header->romsize = xdr_be.get32(&outheader);
211 header->bootblocksize = xdr_be.get32(&outheader);
212 header->align = xdr_be.get32(&outheader);
213 header->offset = xdr_be.get32(&outheader);
214 header->architecture = xdr_be.get32(&outheader);
217 int cbfs_image_create(struct cbfs_image *image, size_t entries_size)
219 assert(image);
220 assert(image->buffer.data);
222 size_t empty_header_len = cbfs_calculate_file_header_size("");
223 uint32_t entries_offset = 0;
224 uint32_t align = CBFS_ENTRY_ALIGNMENT;
225 if (image->has_header) {
226 entries_offset = image->header.offset;
228 if (entries_offset > image->buffer.size) {
229 ERROR("CBFS file entries are located outside CBFS itself\n");
230 return -1;
233 align = image->header.align;
236 // This attribute must be given in order to prove that this module
237 // correctly preserves certain CBFS properties. See the block comment
238 // near the top of this file (and the associated commit message).
239 if (align < empty_header_len) {
240 ERROR("CBFS must be aligned to at least %zu bytes\n",
241 empty_header_len);
242 return -1;
245 if (entries_size > image->buffer.size - entries_offset) {
246 ERROR("CBFS doesn't have enough space to fit its file entries\n");
247 return -1;
250 if (empty_header_len > entries_size) {
251 ERROR("CBFS is too small to fit any header\n");
252 return -1;
254 struct cbfs_file *entry_header =
255 (struct cbfs_file *)(image->buffer.data + entries_offset);
256 // This alignment is necessary in order to prove that this module
257 // correctly preserves certain CBFS properties. See the block comment
258 // near the top of this file (and the associated commit message).
259 entries_size -= entries_size % align;
261 size_t capacity = entries_size - empty_header_len;
262 LOG("Created CBFS (capacity = %zu bytes)\n", capacity);
263 return cbfs_create_empty_entry(entry_header, CBFS_COMPONENT_NULL,
264 capacity, "");
267 int cbfs_legacy_image_create(struct cbfs_image *image,
268 uint32_t architecture,
269 uint32_t align,
270 struct buffer *bootblock,
271 uint32_t bootblock_offset,
272 uint32_t header_offset,
273 uint32_t entries_offset)
275 assert(image);
276 assert(image->buffer.data);
277 assert(bootblock);
279 int32_t *rel_offset;
280 uint32_t cbfs_len;
281 void *header_loc;
282 size_t size = image->buffer.size;
284 DEBUG("cbfs_image_create: bootblock=0x%x+0x%zx, "
285 "header=0x%x+0x%zx, entries_offset=0x%x\n",
286 bootblock_offset, bootblock->size, header_offset,
287 sizeof(image->header), entries_offset);
289 // Adjust legacy top-aligned address to ROM offset.
290 if (IS_TOP_ALIGNED_ADDRESS(entries_offset))
291 entries_offset = size + (int32_t)entries_offset;
292 if (IS_TOP_ALIGNED_ADDRESS(bootblock_offset))
293 bootblock_offset = size + (int32_t)bootblock_offset;
294 if (IS_TOP_ALIGNED_ADDRESS(header_offset))
295 header_offset = size + (int32_t)header_offset;
297 DEBUG("cbfs_create_image: (real offset) bootblock=0x%x, "
298 "header=0x%x, entries_offset=0x%x\n",
299 bootblock_offset, header_offset, entries_offset);
301 // Prepare bootblock
302 if (bootblock_offset + bootblock->size > size) {
303 ERROR("Bootblock (0x%x+0x%zx) exceed ROM size (0x%zx)\n",
304 bootblock_offset, bootblock->size, size);
305 return -1;
307 if (entries_offset > bootblock_offset &&
308 entries_offset < bootblock->size) {
309 ERROR("Bootblock (0x%x+0x%zx) overlap CBFS data (0x%x)\n",
310 bootblock_offset, bootblock->size, entries_offset);
311 return -1;
313 memcpy(image->buffer.data + bootblock_offset, bootblock->data,
314 bootblock->size);
316 // Prepare header
317 if (header_offset + sizeof(image->header) > size - sizeof(int32_t)) {
318 ERROR("Header (0x%x+0x%zx) exceed ROM size (0x%zx)\n",
319 header_offset, sizeof(image->header), size);
320 return -1;
322 image->header.magic = CBFS_HEADER_MAGIC;
323 image->header.version = CBFS_HEADER_VERSION;
324 image->header.romsize = size;
325 image->header.bootblocksize = bootblock->size;
326 image->header.align = align;
327 image->header.offset = entries_offset;
328 image->header.architecture = architecture;
330 header_loc = (image->buffer.data + header_offset);
331 cbfs_put_header(header_loc, &image->header);
332 image->has_header = true;
334 // The last 4 byte of the image contain the relative offset from the end
335 // of the image to the master header as a 32-bit signed integer. x86
336 // relies on this also being its (memory-mapped, top-aligned) absolute
337 // 32-bit address by virtue of how two's complement numbers work.
338 assert(size % sizeof(int32_t) == 0);
339 rel_offset = (int32_t *)(image->buffer.data + size - sizeof(int32_t));
340 *rel_offset = header_offset - size;
342 // Prepare entries
343 if (align_up(entries_offset, align) != entries_offset) {
344 ERROR("Offset (0x%x) must be aligned to 0x%x.\n",
345 entries_offset, align);
346 return -1;
348 // To calculate available length, find
349 // e = min(bootblock, header, rel_offset) where e > entries_offset.
350 cbfs_len = size - sizeof(int32_t);
351 if (bootblock_offset > entries_offset && bootblock_offset < cbfs_len)
352 cbfs_len = bootblock_offset;
353 if (header_offset > entries_offset && header_offset < cbfs_len)
354 cbfs_len = header_offset;
356 if (cbfs_image_create(image, cbfs_len - entries_offset))
357 return -1;
358 return 0;
361 int cbfs_image_from_buffer(struct cbfs_image *out, struct buffer *in,
362 uint32_t offset)
364 assert(out);
365 assert(in);
366 assert(in->data);
368 buffer_clone(&out->buffer, in);
369 out->has_header = false;
371 if (cbfs_is_valid_cbfs(out)) {
372 return 0;
375 void *header_loc = cbfs_find_header(in->data, in->size, offset);
376 if (header_loc) {
377 cbfs_get_header(&out->header, header_loc);
378 out->has_header = true;
379 cbfs_fix_legacy_size(out, header_loc);
380 return 0;
381 } else if (offset != ~0u) {
382 ERROR("The -H switch is only valid on legacy images having CBFS master headers.\n");
383 return 1;
385 ERROR("Selected image region is not a valid CBFS.\n");
386 return 1;
389 int cbfs_copy_instance(struct cbfs_image *image, struct buffer *dst)
391 assert(image);
393 struct cbfs_file *src_entry, *dst_entry;
394 size_t align;
395 ssize_t last_entry_size;
397 size_t copy_end = buffer_size(dst);
399 align = CBFS_ENTRY_ALIGNMENT;
401 dst_entry = (struct cbfs_file *)buffer_get(dst);
403 /* Copy non-empty files */
404 for (src_entry = cbfs_find_first_entry(image);
405 src_entry && cbfs_is_valid_entry(image, src_entry);
406 src_entry = cbfs_find_next_entry(image, src_entry)) {
407 size_t entry_size;
409 if ((src_entry->type == htonl(CBFS_COMPONENT_NULL)) ||
410 (src_entry->type == htonl(CBFS_COMPONENT_CBFSHEADER)) ||
411 (src_entry->type == htonl(CBFS_COMPONENT_DELETED)))
412 continue;
414 entry_size = htonl(src_entry->len) + htonl(src_entry->offset);
415 memcpy(dst_entry, src_entry, entry_size);
416 dst_entry = (struct cbfs_file *)(
417 (uintptr_t)dst_entry + align_up(entry_size, align));
419 if ((size_t)((uint8_t *)dst_entry - (uint8_t *)buffer_get(dst))
420 >= copy_end) {
421 ERROR("Ran out of room in copy region.\n");
422 return 1;
426 /* Last entry size is all the room above it, except for top 4 bytes
427 * which may be used by the master header pointer. This messes with
428 * the ability to stash something "top-aligned" into the region, but
429 * keeps things simpler. */
430 last_entry_size = copy_end -
431 ((uint8_t *)dst_entry - (uint8_t *)buffer_get(dst)) -
432 cbfs_calculate_file_header_size("") - sizeof(int32_t);
434 if (last_entry_size < 0)
435 WARN("No room to create the last entry!\n")
436 else
437 cbfs_create_empty_entry(dst_entry, CBFS_COMPONENT_NULL,
438 last_entry_size, "");
440 return 0;
443 int cbfs_expand_to_region(struct buffer *region)
445 if (buffer_get(region) == NULL)
446 return 1;
448 struct cbfs_image image;
449 memset(&image, 0, sizeof(image));
450 if (cbfs_image_from_buffer(&image, region, 0)) {
451 ERROR("reading CBFS failed!\n");
452 return 1;
455 uint32_t region_sz = buffer_size(region);
457 struct cbfs_file *entry;
458 for (entry = buffer_get(region);
459 cbfs_is_valid_entry(&image, entry);
460 entry = cbfs_find_next_entry(&image, entry)) {
461 /* just iterate through */
464 /* entry now points to the first aligned address after the last valid
465 * file header. That's either outside the image or exactly the place
466 * where we need to create a new file.
468 int last_entry_size = region_sz -
469 ((uint8_t *)entry - (uint8_t *)buffer_get(region)) -
470 cbfs_calculate_file_header_size("") - sizeof(int32_t);
472 if (last_entry_size > 0) {
473 cbfs_create_empty_entry(entry, CBFS_COMPONENT_NULL,
474 last_entry_size, "");
475 /* If the last entry was an empty file, merge them. */
476 cbfs_walk(&image, cbfs_merge_empty_entry, NULL);
479 return 0;
482 int cbfs_truncate_space(struct buffer *region, uint32_t *size)
484 if (buffer_get(region) == NULL)
485 return 1;
487 struct cbfs_image image;
488 memset(&image, 0, sizeof(image));
489 if (cbfs_image_from_buffer(&image, region, 0)) {
490 ERROR("reading CBFS failed!\n");
491 return 1;
494 struct cbfs_file *entry, *trailer;
495 for (trailer = entry = buffer_get(region);
496 cbfs_is_valid_entry(&image, entry);
497 trailer = entry,
498 entry = cbfs_find_next_entry(&image, entry)) {
499 /* just iterate through */
502 /* trailer now points to the last valid CBFS entry's header.
503 * If that file is empty, remove it and report its header's offset as
504 * maximum size.
506 if ((strlen(trailer->filename) != 0) &&
507 (trailer->type != htonl(CBFS_COMPONENT_NULL)) &&
508 (trailer->type != htonl(CBFS_COMPONENT_DELETED))) {
509 /* nothing to truncate. Return de-facto CBFS size in case it
510 * was already truncated. */
511 *size = (uint8_t *)entry - (uint8_t *)buffer_get(region);
512 return 0;
514 *size = (uint8_t *)trailer - (uint8_t *)buffer_get(region);
515 memset(trailer, 0xff, buffer_size(region) - *size);
517 return 0;
520 static size_t cbfs_file_entry_metadata_size(const struct cbfs_file *f)
522 return ntohl(f->offset);
525 static size_t cbfs_file_entry_data_size(const struct cbfs_file *f)
527 return ntohl(f->len);
530 static size_t cbfs_file_entry_size(const struct cbfs_file *f)
532 return cbfs_file_entry_metadata_size(f) + cbfs_file_entry_data_size(f);
535 int cbfs_compact_instance(struct cbfs_image *image)
537 assert(image);
539 struct cbfs_file *prev;
540 struct cbfs_file *cur;
542 /* The prev entry will always be an empty entry. */
543 prev = NULL;
546 * Note: this function does not honor alignment or fixed location files.
547 * It's behavior is akin to cbfs_copy_instance() in that it expects
548 * the caller to understand the ramifications of compacting a
549 * fragmented CBFS image.
552 for (cur = cbfs_find_first_entry(image);
553 cur && cbfs_is_valid_entry(image, cur);
554 cur = cbfs_find_next_entry(image, cur)) {
555 size_t prev_size;
556 size_t cur_size;
557 size_t empty_metadata_size;
558 size_t spill_size;
559 uint32_t type = htonl(cur->type);
561 /* Current entry is empty. Kepp track of it. */
562 if ((type == htonl(CBFS_COMPONENT_NULL)) ||
563 (type == htonl(CBFS_COMPONENT_DELETED))) {
564 prev = cur;
565 continue;
568 /* Need to ensure the previous entry is an empty one. */
569 if (prev == NULL)
570 continue;
572 /* At this point prev is an empty entry. Put the non-empty
573 * file in prev's location. Then add a new empty entry. This
574 * essentialy bubbles empty entries towards the end. */
576 prev_size = cbfs_file_entry_size(prev);
577 cur_size = cbfs_file_entry_size(cur);
580 * Adjust the empty file size by the actual space occupied
581 * bewtween the beginning of the empty file and the non-empty
582 * file.
584 prev_size += (cbfs_get_entry_addr(image, cur) -
585 cbfs_get_entry_addr(image, prev)) - prev_size;
587 /* Move the non-empty file over the empty file. */
588 memmove(prev, cur, cur_size);
591 * Get location of the empty file. Note that since prev was
592 * overwritten with the non-empty file the previously moved
593 * file needs to be used to calculate the empty file's location.
595 cur = cbfs_find_next_entry(image, prev);
598 * The total space to work with for swapping the 2 entries
599 * consists of the 2 files' sizes combined. However, the
600 * cbfs_file entries start on CBFS_ALIGNMENT boundaries.
601 * Because of this the empty file size may end up smaller
602 * because of the non-empty file's metadata and data length.
604 * Calculate the spill size which is the amount of data lost
605 * due to the alignment constraints after moving the non-empty
606 * file.
608 spill_size = (cbfs_get_entry_addr(image, cur) -
609 cbfs_get_entry_addr(image, prev)) - cur_size;
611 empty_metadata_size = cbfs_calculate_file_header_size("");
613 /* Check if new empty size can contain the metadata. */
614 if (empty_metadata_size + spill_size > prev_size) {
615 ERROR("Unable to swap '%s' with prev empty entry.\n",
616 prev->filename);
617 return 1;
620 /* Update the empty file's size. */
621 prev_size -= spill_size + empty_metadata_size;
623 /* Create new empty file. */
624 cbfs_create_empty_entry(cur, CBFS_COMPONENT_NULL,
625 prev_size, "");
627 /* Merge any potential empty entries together. */
628 cbfs_walk(image, cbfs_merge_empty_entry, NULL);
631 * Since current switched to an empty file keep track of it.
632 * Even if any empty files were merged the empty entry still
633 * starts at previously calculated location.
635 prev = cur;
638 return 0;
641 int cbfs_image_delete(struct cbfs_image *image)
643 if (image == NULL)
644 return 0;
646 buffer_delete(&image->buffer);
647 return 0;
650 /* Tries to add an entry with its data (CBFS_SUBHEADER) at given offset. */
651 static int cbfs_add_entry_at(struct cbfs_image *image,
652 struct cbfs_file *entry,
653 const void *data,
654 uint32_t content_offset,
655 const struct cbfs_file *header,
656 const size_t len_align)
658 struct cbfs_file *next = cbfs_find_next_entry(image, entry);
659 uint32_t addr = cbfs_get_entry_addr(image, entry),
660 addr_next = cbfs_get_entry_addr(image, next);
661 uint32_t min_entry_size = cbfs_calculate_file_header_size("");
662 uint32_t len, header_offset;
663 uint32_t align = image->has_header ? image->header.align :
664 CBFS_ENTRY_ALIGNMENT;
665 uint32_t header_size = ntohl(header->offset);
667 header_offset = content_offset - header_size;
668 if (header_offset % align)
669 header_offset -= header_offset % align;
670 if (header_offset < addr) {
671 ERROR("No space to hold cbfs_file header.");
672 return -1;
675 // Process buffer BEFORE content_offset.
676 if (header_offset - addr > min_entry_size) {
677 DEBUG("|min|...|header|content|... <create new entry>\n");
678 len = header_offset - addr - min_entry_size;
679 cbfs_create_empty_entry(entry, CBFS_COMPONENT_NULL, len, "");
680 if (verbose > 1) cbfs_print_entry_info(image, entry, stderr);
681 entry = cbfs_find_next_entry(image, entry);
682 addr = cbfs_get_entry_addr(image, entry);
685 len = content_offset - addr - header_size;
686 memcpy(entry, header, header_size);
687 if (len != 0) {
688 /* the header moved backwards a bit to accommodate cbfs_file
689 * alignment requirements, so patch up ->offset to still point
690 * to file data.
692 DEBUG("|..|header|content|... <use offset to create entry>\n");
693 DEBUG("before: offset=0x%x\n", ntohl(entry->offset));
694 // TODO reset expanded name buffer to 0xFF.
695 entry->offset = htonl(ntohl(entry->offset) + len);
696 DEBUG("after: offset=0x%x\n", ntohl(entry->len));
699 // Ready to fill data into entry.
700 DEBUG("content_offset: 0x%x, entry location: %x\n",
701 content_offset, (int)((char*)CBFS_SUBHEADER(entry) -
702 image->buffer.data));
703 assert((char*)CBFS_SUBHEADER(entry) - image->buffer.data ==
704 (ptrdiff_t)content_offset);
705 memcpy(CBFS_SUBHEADER(entry), data, ntohl(entry->len));
706 if (verbose > 1) cbfs_print_entry_info(image, entry, stderr);
708 // Align the length to a multiple of len_align
709 if (len_align &&
710 ((ntohl(entry->offset) + ntohl(entry->len)) % len_align)) {
711 size_t off = (ntohl(entry->offset) + ntohl(entry->len)) % len_align;
712 entry->len = htonl(ntohl(entry->len) + len_align - off);
715 // Process buffer AFTER entry.
716 entry = cbfs_find_next_entry(image, entry);
717 addr = cbfs_get_entry_addr(image, entry);
718 if (addr == addr_next)
719 return 0;
721 assert(addr < addr_next);
722 if (addr_next - addr < min_entry_size) {
723 DEBUG("No need for new \"empty\" entry\n");
724 /* No need to increase the size of the just
725 * stored file to extend to next file. Alignment
726 * of next file takes care of this.
728 return 0;
731 len = addr_next - addr - min_entry_size;
732 /* keep space for master header pointer */
733 if ((uint8_t *)entry + min_entry_size + len >
734 (uint8_t *)buffer_get(&image->buffer) +
735 buffer_size(&image->buffer) - sizeof(int32_t)) {
736 len -= sizeof(int32_t);
738 cbfs_create_empty_entry(entry, CBFS_COMPONENT_NULL, len, "");
739 if (verbose > 1) cbfs_print_entry_info(image, entry, stderr);
740 return 0;
743 int cbfs_add_entry(struct cbfs_image *image, struct buffer *buffer,
744 uint32_t content_offset,
745 struct cbfs_file *header,
746 const size_t len_align)
748 assert(image);
749 assert(buffer);
750 assert(buffer->data);
751 assert(!IS_TOP_ALIGNED_ADDRESS(content_offset));
753 const char *name = header->filename;
755 uint32_t entry_type;
756 uint32_t addr, addr_next;
757 struct cbfs_file *entry, *next;
758 uint32_t need_size;
759 uint32_t header_size = ntohl(header->offset);
761 need_size = header_size + buffer->size;
762 DEBUG("cbfs_add_entry('%s'@0x%x) => need_size = %u+%zu=%u\n",
763 name, content_offset, header_size, buffer->size, need_size);
765 // Merge empty entries.
766 DEBUG("(trying to merge empty entries...)\n");
767 cbfs_walk(image, cbfs_merge_empty_entry, NULL);
769 for (entry = cbfs_find_first_entry(image);
770 entry && cbfs_is_valid_entry(image, entry);
771 entry = cbfs_find_next_entry(image, entry)) {
773 entry_type = ntohl(entry->type);
774 if (entry_type != CBFS_COMPONENT_NULL)
775 continue;
777 addr = cbfs_get_entry_addr(image, entry);
778 next = cbfs_find_next_entry(image, entry);
779 addr_next = cbfs_get_entry_addr(image, next);
781 DEBUG("cbfs_add_entry: space at 0x%x+0x%x(%d) bytes\n",
782 addr, addr_next - addr, addr_next - addr);
784 /* Will the file fit? Don't yet worry if we have space for a new
785 * "empty" entry. We take care of that later.
787 if (addr + need_size > addr_next)
788 continue;
790 // Test for complicated cases
791 if (content_offset > 0) {
792 if (addr_next < content_offset) {
793 DEBUG("Not for specified offset yet");
794 continue;
795 } else if (addr > content_offset) {
796 DEBUG("Exceed specified content_offset.");
797 break;
798 } else if (addr + header_size > content_offset) {
799 ERROR("Not enough space for header.\n");
800 break;
801 } else if (content_offset + buffer->size > addr_next) {
802 ERROR("Not enough space for content.\n");
803 break;
807 // TODO there are more few tricky cases that we may
808 // want to fit by altering offset.
810 if (content_offset == 0) {
811 // we tested every condition earlier under which
812 // placing the file there might fail
813 content_offset = addr + header_size;
816 DEBUG("section 0x%x+0x%x for content_offset 0x%x.\n",
817 addr, addr_next - addr, content_offset);
819 if (cbfs_add_entry_at(image, entry, buffer->data,
820 content_offset, header, len_align) == 0) {
821 return 0;
823 break;
826 ERROR("Could not add [%s, %zd bytes (%zd KB)@0x%x]; too big?\n",
827 buffer->name, buffer->size, buffer->size / 1024, content_offset);
828 return -1;
831 struct cbfs_file *cbfs_get_entry(struct cbfs_image *image, const char *name)
833 struct cbfs_file *entry;
834 for (entry = cbfs_find_first_entry(image);
835 entry && cbfs_is_valid_entry(image, entry);
836 entry = cbfs_find_next_entry(image, entry)) {
837 if (strcasecmp(entry->filename, name) == 0) {
838 DEBUG("cbfs_get_entry: found %s\n", name);
839 return entry;
842 return NULL;
845 static int cbfs_stage_decompress(struct cbfs_stage *stage, struct buffer *buff)
847 struct buffer reader;
848 char *orig_buffer;
849 char *new_buffer;
850 size_t new_buff_sz;
851 decomp_func_ptr decompress;
853 buffer_clone(&reader, buff);
855 /* The stage metadata is in little endian. */
856 stage->compression = xdr_le.get32(&reader);
857 stage->entry = xdr_le.get64(&reader);
858 stage->load = xdr_le.get64(&reader);
859 stage->len = xdr_le.get32(&reader);
860 stage->memlen = xdr_le.get32(&reader);
862 /* Create a buffer just with the uncompressed program now that the
863 * struct cbfs_stage has been peeled off. */
864 if (stage->compression == CBFS_COMPRESS_NONE) {
865 new_buff_sz = buffer_size(buff) - sizeof(struct cbfs_stage);
867 orig_buffer = buffer_get(buff);
868 new_buffer = calloc(1, new_buff_sz);
869 memcpy(new_buffer, orig_buffer + sizeof(struct cbfs_stage),
870 new_buff_sz);
871 buffer_init(buff, buff->name, new_buffer, new_buff_sz);
872 free(orig_buffer);
873 return 0;
876 decompress = decompression_function(stage->compression);
877 if (decompress == NULL)
878 return -1;
880 orig_buffer = buffer_get(buff);
882 /* This can be too big of a buffer needed, but there's no current
883 * field indicating decompressed size of data. */
884 new_buff_sz = stage->memlen;
885 new_buffer = calloc(1, new_buff_sz);
887 if (decompress(orig_buffer + sizeof(struct cbfs_stage),
888 (int)(buffer_size(buff) - sizeof(struct cbfs_stage)),
889 new_buffer, (int)new_buff_sz, &new_buff_sz)) {
890 ERROR("Couldn't decompress stage.\n");
891 free(new_buffer);
892 return -1;
895 /* Include correct size for full stage info. */
896 buffer_init(buff, buff->name, new_buffer, new_buff_sz);
898 /* True decompressed size is just the data size -- no metadata. */
899 stage->len = new_buff_sz;
900 /* Stage is not compressed. */
901 stage->compression = CBFS_COMPRESS_NONE;
903 free(orig_buffer);
905 return 0;
908 static int cbfs_payload_decompress(struct cbfs_payload_segment *segments,
909 struct buffer *buff, int num_seg)
911 struct buffer new_buffer;
912 struct buffer seg_buffer;
913 size_t new_buff_sz;
914 char *in_ptr;
915 char *out_ptr;
916 size_t new_offset;
917 decomp_func_ptr decompress;
919 new_offset = num_seg * sizeof(*segments);
920 new_buff_sz = num_seg * sizeof(*segments);
922 /* Find out and allocate the amount of memory occupied
923 * by the binary data */
924 for (int i = 0; i < num_seg; i++)
925 new_buff_sz += segments[i].mem_len;
927 if (buffer_create(&new_buffer, new_buff_sz, "decompressed_buff"))
928 return -1;
930 in_ptr = buffer_get(buff) + new_offset;
931 out_ptr = buffer_get(&new_buffer) + new_offset;
933 for (int i = 0; i < num_seg; i++) {
934 struct buffer tbuff;
935 size_t decomp_size;
937 /* Segments BSS and ENTRY do not have binary data. */
938 if (segments[i].type == PAYLOAD_SEGMENT_BSS ||
939 segments[i].type == PAYLOAD_SEGMENT_ENTRY) {
940 continue;
941 } else if (segments[i].type == PAYLOAD_SEGMENT_PARAMS) {
942 memcpy(out_ptr, in_ptr, segments[i].len);
943 segments[i].offset = new_offset;
944 new_offset += segments[i].len;
945 in_ptr += segments[i].len;
946 out_ptr += segments[i].len;
947 segments[i].compression = CBFS_COMPRESS_NONE;
948 continue;
951 /* The payload uses an unknown compression algorithm. */
952 decompress = decompression_function(segments[i].compression);
953 if (decompress == NULL) {
954 ERROR("Unknown decompression algorithm: %u\n",
955 segments[i].compression);
956 return -1;
959 if (buffer_create(&tbuff, segments[i].mem_len, "segment")) {
960 buffer_delete(&new_buffer);
961 return -1;
964 if (decompress(in_ptr, segments[i].len, buffer_get(&tbuff),
965 (int) buffer_size(&tbuff),
966 &decomp_size)) {
967 ERROR("Couldn't decompress payload segment %u\n", i);
968 buffer_delete(&new_buffer);
969 buffer_delete(&tbuff);
970 return -1;
973 memcpy(out_ptr, buffer_get(&tbuff), decomp_size);
975 in_ptr += segments[i].len;
977 /* Update the offset of the segment. */
978 segments[i].offset = new_offset;
979 /* True decompressed size is just the data size. No metadata */
980 segments[i].len = decomp_size;
981 /* Segment is not compressed. */
982 segments[i].compression = CBFS_COMPRESS_NONE;
984 /* Update the offset and output buffer pointer. */
985 new_offset += decomp_size;
986 out_ptr += decomp_size;
988 buffer_delete(&tbuff);
991 buffer_splice(&seg_buffer, &new_buffer, 0, 0);
992 xdr_segs(&seg_buffer, segments, num_seg);
994 buffer_delete(buff);
995 *buff = new_buffer;
997 return 0;
1000 static int init_elf_from_arch(Elf64_Ehdr *ehdr, uint32_t cbfs_arch)
1002 int endian;
1003 int nbits;
1004 int machine;
1006 switch (cbfs_arch) {
1007 case CBFS_ARCHITECTURE_X86:
1008 endian = ELFDATA2LSB;
1009 nbits = ELFCLASS32;
1010 machine = EM_386;
1011 break;
1012 case CBFS_ARCHITECTURE_ARM:
1013 endian = ELFDATA2LSB;
1014 nbits = ELFCLASS32;
1015 machine = EM_ARM;
1016 break;
1017 case CBFS_ARCHITECTURE_AARCH64:
1018 endian = ELFDATA2LSB;
1019 nbits = ELFCLASS64;
1020 machine = EM_AARCH64;
1021 break;
1022 case CBFS_ARCHITECTURE_MIPS:
1023 endian = ELFDATA2LSB;
1024 nbits = ELFCLASS32;
1025 machine = EM_MIPS;
1026 break;
1027 case CBFS_ARCHITECTURE_RISCV:
1028 endian = ELFDATA2LSB;
1029 nbits = ELFCLASS32;
1030 machine = EM_RISCV;
1031 break;
1032 default:
1033 ERROR("Unsupported arch: %x\n", cbfs_arch);
1034 return -1;
1037 elf_init_eheader(ehdr, machine, nbits, endian);
1038 return 0;
1041 static int cbfs_stage_make_elf(struct buffer *buff, uint32_t arch)
1043 Elf64_Ehdr ehdr;
1044 Elf64_Shdr shdr;
1045 struct cbfs_stage stage;
1046 struct elf_writer *ew;
1047 struct buffer elf_out;
1048 size_t empty_sz;
1049 int rmod_ret;
1051 if (arch == CBFS_ARCHITECTURE_UNKNOWN) {
1052 ERROR("You need to specify -m ARCH.\n");
1053 return -1;
1056 if (cbfs_stage_decompress(&stage, buff)) {
1057 ERROR("Failed to decompress stage.\n");
1058 return -1;
1061 if (init_elf_from_arch(&ehdr, arch))
1062 return -1;
1064 ehdr.e_entry = stage.entry;
1066 /* Attempt rmodule translation first. */
1067 rmod_ret = rmodule_stage_to_elf(&ehdr, buff);
1069 if (rmod_ret < 0) {
1070 ERROR("rmodule parsing failed\n");
1071 return -1;
1072 } else if (rmod_ret == 0)
1073 return 0;
1075 /* Rmodule couldn't do anything with the data. Continue on with SELF. */
1077 ew = elf_writer_init(&ehdr);
1078 if (ew == NULL) {
1079 ERROR("Unable to init ELF writer.\n");
1080 return -1;
1083 memset(&shdr, 0, sizeof(shdr));
1084 shdr.sh_type = SHT_PROGBITS;
1085 shdr.sh_flags = SHF_WRITE | SHF_ALLOC | SHF_EXECINSTR;
1086 shdr.sh_addr = stage.load;
1087 shdr.sh_size = stage.len;
1088 empty_sz = stage.memlen - stage.len;
1090 if (elf_writer_add_section(ew, &shdr, buff, ".program")) {
1091 ERROR("Unable to add ELF section: .program\n");
1092 elf_writer_destroy(ew);
1093 return -1;
1096 if (empty_sz != 0) {
1097 struct buffer b;
1099 buffer_init(&b, NULL, NULL, 0);
1100 memset(&shdr, 0, sizeof(shdr));
1101 shdr.sh_type = SHT_NOBITS;
1102 shdr.sh_flags = SHF_WRITE | SHF_ALLOC;
1103 shdr.sh_addr = stage.load + stage.len;
1104 shdr.sh_size = empty_sz;
1105 if (elf_writer_add_section(ew, &shdr, &b, ".empty")) {
1106 ERROR("Unable to add ELF section: .empty\n");
1107 elf_writer_destroy(ew);
1108 return -1;
1112 if (elf_writer_serialize(ew, &elf_out)) {
1113 ERROR("Unable to create ELF file from stage.\n");
1114 elf_writer_destroy(ew);
1115 return -1;
1118 /* Flip buffer with the created ELF one. */
1119 buffer_delete(buff);
1120 *buff = elf_out;
1122 elf_writer_destroy(ew);
1124 return 0;
1127 static int cbfs_payload_make_elf(struct buffer *buff, uint32_t arch)
1129 Elf64_Ehdr ehdr;
1130 Elf64_Shdr shdr;
1131 struct cbfs_payload_segment *segs = NULL;
1132 struct elf_writer *ew = NULL;
1133 struct buffer elf_out;
1134 int segments = 0;
1135 int retval = -1;
1137 if (arch == CBFS_ARCHITECTURE_UNKNOWN) {
1138 ERROR("You need to specify -m ARCH.\n");
1139 goto out;
1142 /* Count the number of segments inside buffer */
1143 while (true) {
1144 uint32_t payload_type = 0;
1146 struct cbfs_payload_segment *seg;
1148 seg = buffer_get(buff);
1149 payload_type = read_be32(&seg[segments].type);
1151 if (payload_type == PAYLOAD_SEGMENT_CODE) {
1152 segments++;
1153 } else if (payload_type == PAYLOAD_SEGMENT_DATA) {
1154 segments++;
1155 } else if (payload_type == PAYLOAD_SEGMENT_BSS) {
1156 segments++;
1157 } else if (payload_type == PAYLOAD_SEGMENT_PARAMS) {
1158 segments++;
1159 } else if (payload_type == PAYLOAD_SEGMENT_ENTRY) {
1160 /* The last segment in a payload is always ENTRY as
1161 * specified by the parse_elf_to_payload() function.
1162 * Therefore there is no need to continue looking for
1163 * segments.*/
1164 segments++;
1165 break;
1166 } else {
1167 ERROR("Unknown payload segment type: %x\n",
1168 payload_type);
1169 goto out;
1173 segs = malloc(segments * sizeof(*segs));
1175 /* Decode xdr segments */
1176 for (int i = 0; i < segments; i++) {
1177 struct cbfs_payload_segment *serialized_seg = buffer_get(buff);
1178 xdr_get_seg(&segs[i], &serialized_seg[i]);
1181 if (cbfs_payload_decompress(segs, buff, segments)) {
1182 ERROR("Failed to decompress payload.\n");
1183 goto out;
1186 if (init_elf_from_arch(&ehdr, arch))
1187 goto out;
1189 ehdr.e_entry = segs[segments-1].load_addr;
1191 ew = elf_writer_init(&ehdr);
1192 if (ew == NULL) {
1193 ERROR("Unable to init ELF writer.\n");
1194 goto out;
1197 for (int i = 0; i < segments; i++) {
1198 struct buffer tbuff;
1199 size_t empty_sz = 0;
1201 memset(&shdr, 0, sizeof(shdr));
1202 char *name = NULL;
1204 if (segs[i].type == PAYLOAD_SEGMENT_CODE) {
1205 shdr.sh_type = SHT_PROGBITS;
1206 shdr.sh_flags = SHF_WRITE | SHF_ALLOC | SHF_EXECINSTR;
1207 shdr.sh_addr = segs[i].load_addr;
1208 shdr.sh_size = segs[i].len;
1209 empty_sz = segs[i].mem_len - segs[i].len;
1210 name = strdup(".text");
1211 buffer_splice(&tbuff, buff, segs[i].offset,
1212 segs[i].len);
1213 } else if (segs[i].type == PAYLOAD_SEGMENT_DATA) {
1214 shdr.sh_type = SHT_PROGBITS;
1215 shdr.sh_flags = SHF_ALLOC | SHF_WRITE;
1216 shdr.sh_addr = segs[i].load_addr;
1217 shdr.sh_size = segs[i].len;
1218 empty_sz = segs[i].mem_len - segs[i].len;
1219 name = strdup(".data");
1220 buffer_splice(&tbuff, buff, segs[i].offset,
1221 segs[i].len);
1222 } else if (segs[i].type == PAYLOAD_SEGMENT_BSS) {
1223 shdr.sh_type = SHT_NOBITS;
1224 shdr.sh_flags = SHF_ALLOC | SHF_WRITE;
1225 shdr.sh_addr = segs[i].load_addr;
1226 shdr.sh_size = segs[i].len;
1227 name = strdup(".bss");
1228 buffer_splice(&tbuff, buff, 0, 0);
1229 } else if (segs[i].type == PAYLOAD_SEGMENT_PARAMS) {
1230 shdr.sh_type = SHT_NOTE;
1231 shdr.sh_flags = 0;
1232 shdr.sh_size = segs[i].len;
1233 name = strdup(".note.pinfo");
1234 buffer_splice(&tbuff, buff, segs[i].offset,
1235 segs[i].len);
1236 } else if (segs[i].type == PAYLOAD_SEGMENT_ENTRY) {
1237 break;
1238 } else {
1239 ERROR("unknown ELF segment type\n");
1240 goto out;
1243 if (!name) {
1244 ERROR("out of memory\n");
1245 goto out;
1248 if (elf_writer_add_section(ew, &shdr, &tbuff, name)) {
1249 ERROR("Unable to add ELF section: %s\n", name);
1250 free(name);
1251 goto out;
1253 free(name);
1255 if (empty_sz != 0) {
1256 struct buffer b;
1258 buffer_init(&b, NULL, NULL, 0);
1259 memset(&shdr, 0, sizeof(shdr));
1260 shdr.sh_type = SHT_NOBITS;
1261 shdr.sh_flags = SHF_WRITE | SHF_ALLOC;
1262 shdr.sh_addr = segs[i].load_addr + segs[i].len;
1263 shdr.sh_size = empty_sz;
1264 name = strdup(".empty");
1265 if (!name) {
1266 ERROR("out of memory\n");
1267 goto out;
1269 if (elf_writer_add_section(ew, &shdr, &b, name)) {
1270 ERROR("Unable to add ELF section: %s\n", name);
1271 free(name);
1272 goto out;
1274 free(name);
1278 if (elf_writer_serialize(ew, &elf_out)) {
1279 ERROR("Unable to create ELF file from stage.\n");
1280 goto out;
1283 /* Flip buffer with the created ELF one. */
1284 buffer_delete(buff);
1285 *buff = elf_out;
1286 retval = 0;
1288 out:
1289 free(segs);
1290 elf_writer_destroy(ew);
1291 return retval;
1294 int cbfs_export_entry(struct cbfs_image *image, const char *entry_name,
1295 const char *filename, uint32_t arch, bool do_processing)
1297 struct cbfs_file *entry = cbfs_get_entry(image, entry_name);
1298 struct buffer buffer;
1299 if (!entry) {
1300 ERROR("File not found: %s\n", entry_name);
1301 return -1;
1304 unsigned int compressed_size = ntohl(entry->len);
1305 unsigned int decompressed_size = 0;
1306 unsigned int compression = cbfs_file_get_compression_info(entry,
1307 &decompressed_size);
1308 unsigned int buffer_len;
1309 decomp_func_ptr decompress;
1311 if (do_processing) {
1312 decompress = decompression_function(compression);
1313 if (!decompress) {
1314 ERROR("looking up decompression routine failed\n");
1315 return -1;
1317 buffer_len = decompressed_size;
1318 } else {
1319 /* Force nop decompression */
1320 decompress = decompression_function(CBFS_COMPRESS_NONE);
1321 buffer_len = compressed_size;
1324 LOG("Found file %.30s at 0x%x, type %.12s, compressed %d, size %d\n",
1325 entry_name, cbfs_get_entry_addr(image, entry),
1326 get_cbfs_entry_type_name(ntohl(entry->type)), compressed_size,
1327 decompressed_size);
1329 buffer_init(&buffer, strdup("(cbfs_export_entry)"), NULL, 0);
1330 buffer.data = malloc(buffer_len);
1331 buffer.size = buffer_len;
1333 if (decompress(CBFS_SUBHEADER(entry), compressed_size,
1334 buffer.data, buffer.size, NULL)) {
1335 ERROR("decompression failed for %s\n", entry_name);
1336 buffer_delete(&buffer);
1337 return -1;
1341 * The stage metadata is never compressed proper for cbfs_stage
1342 * files. The contents of the stage data can be though. Therefore
1343 * one has to do a second pass for stages to potentially decompress
1344 * the stage data to make it more meaningful.
1346 if (do_processing) {
1347 int (*make_elf)(struct buffer *, uint32_t) = NULL;
1348 switch (ntohl(entry->type)) {
1349 case CBFS_COMPONENT_STAGE:
1350 make_elf = cbfs_stage_make_elf;
1351 break;
1352 case CBFS_COMPONENT_SELF:
1353 make_elf = cbfs_payload_make_elf;
1354 break;
1356 if (make_elf && make_elf(&buffer, arch)) {
1357 ERROR("Failed to write %s into %s.\n",
1358 entry_name, filename);
1359 buffer_delete(&buffer);
1360 return -1;
1364 if (buffer_write_file(&buffer, filename) != 0) {
1365 ERROR("Failed to write %s into %s.\n",
1366 entry_name, filename);
1367 buffer_delete(&buffer);
1368 return -1;
1371 buffer_delete(&buffer);
1372 INFO("Successfully dumped the file to: %s\n", filename);
1373 return 0;
1376 int cbfs_remove_entry(struct cbfs_image *image, const char *name)
1378 struct cbfs_file *entry;
1379 entry = cbfs_get_entry(image, name);
1380 if (!entry) {
1381 ERROR("CBFS file %s not found.\n", name);
1382 return -1;
1384 DEBUG("cbfs_remove_entry: Removed %s @ 0x%x\n",
1385 entry->filename, cbfs_get_entry_addr(image, entry));
1386 entry->type = htonl(CBFS_COMPONENT_DELETED);
1387 cbfs_walk(image, cbfs_merge_empty_entry, NULL);
1388 return 0;
1391 int cbfs_print_header_info(struct cbfs_image *image)
1393 char *name = strdup(image->buffer.name);
1394 assert(image);
1395 printf("%s: %zd kB, bootblocksize %d, romsize %d, offset 0x%x\n"
1396 "alignment: %d bytes, architecture: %s\n\n",
1397 basename(name),
1398 image->buffer.size / 1024,
1399 image->header.bootblocksize,
1400 image->header.romsize,
1401 image->header.offset,
1402 image->header.align,
1403 arch_to_string(image->header.architecture));
1404 free(name);
1405 return 0;
1408 static int cbfs_print_stage_info(struct cbfs_stage *stage, FILE* fp)
1410 fprintf(fp,
1411 " %s compression, entry: 0x%" PRIx64 ", load: 0x%" PRIx64 ", "
1412 "length: %d/%d\n",
1413 lookup_name_by_type(types_cbfs_compression,
1414 stage->compression, "(unknown)"),
1415 stage->entry,
1416 stage->load,
1417 stage->len,
1418 stage->memlen);
1419 return 0;
1422 static int cbfs_print_decoded_payload_segment_info(
1423 struct cbfs_payload_segment *seg, FILE *fp)
1425 /* The input (seg) must be already decoded by
1426 * cbfs_decode_payload_segment.
1428 switch (seg->type) {
1429 case PAYLOAD_SEGMENT_CODE:
1430 case PAYLOAD_SEGMENT_DATA:
1431 fprintf(fp, " %s (%s compression, offset: 0x%x, "
1432 "load: 0x%" PRIx64 ", length: %d/%d)\n",
1433 (seg->type == PAYLOAD_SEGMENT_CODE ?
1434 "code " : "data"),
1435 lookup_name_by_type(types_cbfs_compression,
1436 seg->compression,
1437 "(unknown)"),
1438 seg->offset, seg->load_addr, seg->len,
1439 seg->mem_len);
1440 break;
1442 case PAYLOAD_SEGMENT_ENTRY:
1443 fprintf(fp, " entry (0x%" PRIx64 ")\n",
1444 seg->load_addr);
1445 break;
1447 case PAYLOAD_SEGMENT_BSS:
1448 fprintf(fp, " BSS (address 0x%016" PRIx64 ", "
1449 "length 0x%x)\n",
1450 seg->load_addr, seg->len);
1451 break;
1453 case PAYLOAD_SEGMENT_PARAMS:
1454 fprintf(fp, " parameters\n");
1455 break;
1457 default:
1458 fprintf(fp, " 0x%x (%s compression, offset: 0x%x, "
1459 "load: 0x%" PRIx64 ", length: %d/%d\n",
1460 seg->type,
1461 lookup_name_by_type(types_cbfs_compression,
1462 seg->compression,
1463 "(unknown)"),
1464 seg->offset, seg->load_addr, seg->len,
1465 seg->mem_len);
1466 break;
1468 return 0;
1471 int cbfs_print_entry_info(struct cbfs_image *image, struct cbfs_file *entry,
1472 void *arg)
1474 const char *name = entry->filename;
1475 struct cbfs_payload_segment *payload;
1476 FILE *fp = (FILE *)arg;
1478 if (!cbfs_is_valid_entry(image, entry)) {
1479 ERROR("cbfs_print_entry_info: Invalid entry at 0x%x\n",
1480 cbfs_get_entry_addr(image, entry));
1481 return -1;
1483 if (!fp)
1484 fp = stdout;
1486 unsigned int decompressed_size = 0;
1487 unsigned int compression = cbfs_file_get_compression_info(entry,
1488 &decompressed_size);
1489 const char *compression_name = lookup_name_by_type(
1490 types_cbfs_compression, compression, "????");
1492 if (compression == CBFS_COMPRESS_NONE)
1493 fprintf(fp, "%-30s 0x%-8x %-12s %8d %-4s\n",
1494 *name ? name : "(empty)",
1495 cbfs_get_entry_addr(image, entry),
1496 get_cbfs_entry_type_name(ntohl(entry->type)),
1497 ntohl(entry->len),
1498 compression_name
1500 else
1501 fprintf(fp, "%-30s 0x%-8x %-12s %8d %-4s (%d decompressed)\n",
1502 *name ? name : "(empty)",
1503 cbfs_get_entry_addr(image, entry),
1504 get_cbfs_entry_type_name(ntohl(entry->type)),
1505 ntohl(entry->len),
1506 compression_name,
1507 decompressed_size
1510 struct cbfs_file_attr_hash *hash = NULL;
1511 while ((hash = cbfs_file_get_next_hash(entry, hash)) != NULL) {
1512 unsigned int hash_type = ntohl(hash->hash_type);
1513 if (hash_type >= CBFS_NUM_SUPPORTED_HASHES) {
1514 fprintf(fp, "invalid hash type %d\n", hash_type);
1515 break;
1517 size_t hash_len = widths_cbfs_hash[hash_type];
1518 char *hash_str = bintohex(hash->hash_data, hash_len);
1519 uint8_t local_hash[hash_len];
1520 if (vb2_digest_buffer(CBFS_SUBHEADER(entry),
1521 ntohl(entry->len), hash_type, local_hash,
1522 hash_len) != VB2_SUCCESS) {
1523 fprintf(fp, "failed to hash '%s'\n", name);
1524 free(hash_str);
1525 break;
1527 int valid = memcmp(local_hash, hash->hash_data, hash_len) == 0;
1528 const char *valid_str = valid ? "valid" : "invalid";
1530 fprintf(fp, " hash %s:%s %s\n",
1531 get_hash_attr_name(hash_type),
1532 hash_str, valid_str);
1533 free(hash_str);
1536 if (!verbose)
1537 return 0;
1539 DEBUG(" cbfs_file=0x%x, offset=0x%x, content_address=0x%x+0x%x\n",
1540 cbfs_get_entry_addr(image, entry), ntohl(entry->offset),
1541 cbfs_get_entry_addr(image, entry) + ntohl(entry->offset),
1542 ntohl(entry->len));
1544 /* note the components of the subheader may be in host order ... */
1545 switch (ntohl(entry->type)) {
1546 case CBFS_COMPONENT_STAGE:
1547 cbfs_print_stage_info((struct cbfs_stage *)
1548 CBFS_SUBHEADER(entry), fp);
1549 break;
1551 case CBFS_COMPONENT_SELF:
1552 payload = (struct cbfs_payload_segment *)
1553 CBFS_SUBHEADER(entry);
1554 while (payload) {
1555 struct cbfs_payload_segment seg;
1556 cbfs_decode_payload_segment(&seg, payload);
1557 cbfs_print_decoded_payload_segment_info(
1558 &seg, fp);
1559 if (seg.type == PAYLOAD_SEGMENT_ENTRY)
1560 break;
1561 else
1562 payload ++;
1564 break;
1565 default:
1566 break;
1568 return 0;
1571 static int cbfs_print_parseable_entry_info(struct cbfs_image *image,
1572 struct cbfs_file *entry, void *arg)
1574 FILE *fp = (FILE *)arg;
1575 const char *name;
1576 const char *type;
1577 size_t offset;
1578 size_t metadata_size;
1579 size_t data_size;
1580 const char *sep = "\t";
1582 if (!cbfs_is_valid_entry(image, entry)) {
1583 ERROR("cbfs_print_entry_info: Invalid entry at 0x%x\n",
1584 cbfs_get_entry_addr(image, entry));
1585 return -1;
1588 name = entry->filename;
1589 if (*name == '\0')
1590 name = "(empty)";
1591 type = get_cbfs_entry_type_name(ntohl(entry->type)),
1592 metadata_size = ntohl(entry->offset);
1593 data_size = ntohl(entry->len);
1594 offset = cbfs_get_entry_addr(image, entry);
1596 fprintf(fp, "%s%s", name, sep);
1597 fprintf(fp, "0x%zx%s", offset, sep);
1598 fprintf(fp, "%s%s", type, sep);
1599 fprintf(fp, "0x%zx%s", metadata_size, sep);
1600 fprintf(fp, "0x%zx%s", data_size, sep);
1601 fprintf(fp, "0x%zx\n", metadata_size + data_size);
1603 return 0;
1606 int cbfs_print_directory(struct cbfs_image *image)
1608 if (cbfs_is_legacy_cbfs(image))
1609 cbfs_print_header_info(image);
1610 printf("%-30s %-10s %-12s Size Comp\n", "Name", "Offset", "Type");
1611 cbfs_walk(image, cbfs_print_entry_info, NULL);
1612 return 0;
1615 int cbfs_print_parseable_directory(struct cbfs_image *image)
1617 size_t i;
1618 const char *header[] = {
1619 "Name",
1620 "Offset",
1621 "Type",
1622 "Metadata Size",
1623 "Data Size",
1624 "Total Size",
1626 const char *sep = "\t";
1628 for (i = 0; i < ARRAY_SIZE(header) - 1; i++)
1629 fprintf(stdout, "%s%s", header[i], sep);
1630 fprintf(stdout, "%s\n", header[i]);
1631 cbfs_walk(image, cbfs_print_parseable_entry_info, stdout);
1632 return 0;
1635 int cbfs_merge_empty_entry(struct cbfs_image *image, struct cbfs_file *entry,
1636 unused void *arg)
1638 struct cbfs_file *next;
1639 uint32_t next_addr = 0;
1641 /* We don't return here even if this entry is already empty because we
1642 want to merge the empty entries following after it. */
1644 /* Loop until non-empty entry is found, starting from the current entry.
1645 After the loop, next_addr points to the next non-empty entry. */
1646 next = entry;
1647 while (ntohl(next->type) == CBFS_COMPONENT_DELETED ||
1648 ntohl(next->type) == CBFS_COMPONENT_NULL) {
1649 next = cbfs_find_next_entry(image, next);
1650 if (!next)
1651 break;
1652 next_addr = cbfs_get_entry_addr(image, next);
1653 if (!cbfs_is_valid_entry(image, next))
1654 /* 'next' could be the end of cbfs */
1655 break;
1658 if (!next_addr)
1659 /* Nothing to empty */
1660 return 0;
1662 /* We can return here if we find only a single empty entry.
1663 For simplicity, we just proceed (and make it empty again). */
1665 /* We're creating one empty entry for combined empty spaces */
1666 uint32_t addr = cbfs_get_entry_addr(image, entry);
1667 size_t len = next_addr - addr - cbfs_calculate_file_header_size("");
1668 DEBUG("join_empty_entry: [0x%x, 0x%x) len=%zu\n", addr, next_addr, len);
1669 cbfs_create_empty_entry(entry, CBFS_COMPONENT_NULL, len, "");
1671 return 0;
1674 int cbfs_walk(struct cbfs_image *image, cbfs_entry_callback callback,
1675 void *arg)
1677 int count = 0;
1678 struct cbfs_file *entry;
1679 for (entry = cbfs_find_first_entry(image);
1680 entry && cbfs_is_valid_entry(image, entry);
1681 entry = cbfs_find_next_entry(image, entry)) {
1682 count ++;
1683 if (callback(image, entry, arg) != 0)
1684 break;
1686 return count;
1689 static int cbfs_header_valid(struct cbfs_header *header)
1691 if ((ntohl(header->magic) == CBFS_HEADER_MAGIC) &&
1692 ((ntohl(header->version) == CBFS_HEADER_VERSION1) ||
1693 (ntohl(header->version) == CBFS_HEADER_VERSION2)) &&
1694 (ntohl(header->offset) < ntohl(header->romsize)))
1695 return 1;
1696 return 0;
1699 struct cbfs_header *cbfs_find_header(char *data, size_t size,
1700 uint32_t forced_offset)
1702 size_t offset;
1703 int found = 0;
1704 int32_t rel_offset;
1705 struct cbfs_header *header, *result = NULL;
1707 if (forced_offset < (size - sizeof(struct cbfs_header))) {
1708 /* Check if the forced header is valid. */
1709 header = (struct cbfs_header *)(data + forced_offset);
1710 if (cbfs_header_valid(header))
1711 return header;
1712 return NULL;
1715 // Try finding relative offset of master header at end of file first.
1716 rel_offset = *(int32_t *)(data + size - sizeof(int32_t));
1717 offset = size + rel_offset;
1718 DEBUG("relative offset: %#zx(-%#zx), offset: %#zx\n",
1719 (size_t)rel_offset, (size_t)-rel_offset, offset);
1721 if (offset >= size - sizeof(*header) ||
1722 !cbfs_header_valid((struct cbfs_header *)(data + offset))) {
1723 // Some use cases append non-CBFS data to the end of the ROM.
1724 DEBUG("relative offset seems wrong, scanning whole image...\n");
1725 offset = 0;
1728 for (; offset + sizeof(*header) < size; offset++) {
1729 header = (struct cbfs_header *)(data + offset);
1730 if (!cbfs_header_valid(header))
1731 continue;
1732 if (!found++)
1733 result = header;
1735 if (found > 1)
1736 // Top-aligned images usually have a working relative offset
1737 // field, so this is more likely to happen on bottom-aligned
1738 // ones (where the first header is the "outermost" one)
1739 WARN("Multiple (%d) CBFS headers found, using the first one.\n",
1740 found);
1741 return result;
1745 struct cbfs_file *cbfs_find_first_entry(struct cbfs_image *image)
1747 assert(image);
1748 if (image->has_header)
1749 /* header.offset is relative to start of flash, not
1750 * start of region, so use it with the full image.
1752 return (struct cbfs_file *)
1753 (buffer_get_original_backing(&image->buffer) +
1754 image->header.offset);
1755 else
1756 return (struct cbfs_file *)buffer_get(&image->buffer);
1759 struct cbfs_file *cbfs_find_next_entry(struct cbfs_image *image,
1760 struct cbfs_file *entry)
1762 uint32_t addr = cbfs_get_entry_addr(image, entry);
1763 int align = image->has_header ? image->header.align :
1764 CBFS_ENTRY_ALIGNMENT;
1765 assert(entry && cbfs_is_valid_entry(image, entry));
1766 addr += ntohl(entry->offset) + ntohl(entry->len);
1767 addr = align_up(addr, align);
1768 return (struct cbfs_file *)(image->buffer.data + addr);
1771 uint32_t cbfs_get_entry_addr(struct cbfs_image *image, struct cbfs_file *entry)
1773 assert(image && image->buffer.data && entry);
1774 return (int32_t)((char *)entry - image->buffer.data);
1777 int cbfs_is_valid_cbfs(struct cbfs_image *image)
1779 return buffer_check_magic(&image->buffer, CBFS_FILE_MAGIC,
1780 strlen(CBFS_FILE_MAGIC));
1783 int cbfs_is_legacy_cbfs(struct cbfs_image *image)
1785 return image->has_header;
1788 int cbfs_is_valid_entry(struct cbfs_image *image, struct cbfs_file *entry)
1790 uint32_t offset = cbfs_get_entry_addr(image, entry);
1792 if (offset >= image->buffer.size)
1793 return 0;
1795 struct buffer entry_data;
1796 buffer_clone(&entry_data, &image->buffer);
1797 buffer_seek(&entry_data, offset);
1798 return buffer_check_magic(&entry_data, CBFS_FILE_MAGIC,
1799 strlen(CBFS_FILE_MAGIC));
1802 struct cbfs_file *cbfs_create_file_header(int type,
1803 size_t len, const char *name)
1805 struct cbfs_file *entry = malloc(MAX_CBFS_FILE_HEADER_BUFFER);
1806 memset(entry, CBFS_CONTENT_DEFAULT_VALUE, MAX_CBFS_FILE_HEADER_BUFFER);
1807 memcpy(entry->magic, CBFS_FILE_MAGIC, sizeof(entry->magic));
1808 entry->type = htonl(type);
1809 entry->len = htonl(len);
1810 entry->attributes_offset = 0;
1811 entry->offset = htonl(cbfs_calculate_file_header_size(name));
1812 memset(entry->filename, 0, ntohl(entry->offset) - sizeof(*entry));
1813 strcpy(entry->filename, name);
1814 return entry;
1817 int cbfs_create_empty_entry(struct cbfs_file *entry, int type,
1818 size_t len, const char *name)
1820 struct cbfs_file *tmp = cbfs_create_file_header(type, len, name);
1821 memcpy(entry, tmp, ntohl(tmp->offset));
1822 free(tmp);
1823 memset(CBFS_SUBHEADER(entry), CBFS_CONTENT_DEFAULT_VALUE, len);
1824 return 0;
1827 struct cbfs_file_attribute *cbfs_file_first_attr(struct cbfs_file *file)
1829 /* attributes_offset should be 0 when there is no attribute, but all
1830 * values that point into the cbfs_file header are invalid, too. */
1831 if (ntohl(file->attributes_offset) <= sizeof(*file))
1832 return NULL;
1834 /* There needs to be enough space for the file header and one
1835 * attribute header for this to make sense. */
1836 if (ntohl(file->offset) <=
1837 sizeof(*file) + sizeof(struct cbfs_file_attribute))
1838 return NULL;
1840 return (struct cbfs_file_attribute *)
1841 (((uint8_t *)file) + ntohl(file->attributes_offset));
1844 struct cbfs_file_attribute *cbfs_file_next_attr(struct cbfs_file *file,
1845 struct cbfs_file_attribute *attr)
1847 /* ex falso sequitur quodlibet */
1848 if (attr == NULL)
1849 return NULL;
1851 /* Is there enough space for another attribute? */
1852 if ((uint8_t *)attr + ntohl(attr->len) +
1853 sizeof(struct cbfs_file_attribute) >
1854 (uint8_t *)file + ntohl(file->offset))
1855 return NULL;
1857 struct cbfs_file_attribute *next = (struct cbfs_file_attribute *)
1858 (((uint8_t *)attr) + ntohl(attr->len));
1859 /* If any, "unused" attributes must come last. */
1860 if (ntohl(next->tag) == CBFS_FILE_ATTR_TAG_UNUSED)
1861 return NULL;
1862 if (ntohl(next->tag) == CBFS_FILE_ATTR_TAG_UNUSED2)
1863 return NULL;
1865 return next;
1868 struct cbfs_file_attribute *cbfs_add_file_attr(struct cbfs_file *header,
1869 uint32_t tag,
1870 uint32_t size)
1872 struct cbfs_file_attribute *attr, *next;
1873 next = cbfs_file_first_attr(header);
1874 do {
1875 attr = next;
1876 next = cbfs_file_next_attr(header, attr);
1877 } while (next != NULL);
1878 uint32_t header_size = ntohl(header->offset) + size;
1879 if (header_size > MAX_CBFS_FILE_HEADER_BUFFER) {
1880 DEBUG("exceeding allocated space for cbfs_file headers");
1881 return NULL;
1883 /* attr points to the last valid attribute now.
1884 * If NULL, we have to create the first one. */
1885 if (attr == NULL) {
1886 /* New attributes start where the header ends.
1887 * header->offset is later set to accommodate the
1888 * additional structure.
1889 * No endianness translation necessary here, because both
1890 * fields are encoded the same way. */
1891 header->attributes_offset = header->offset;
1892 attr = (struct cbfs_file_attribute *)
1893 (((uint8_t *)header) +
1894 ntohl(header->attributes_offset));
1895 } else {
1896 attr = (struct cbfs_file_attribute *)
1897 (((uint8_t *)attr) +
1898 ntohl(attr->len));
1900 header->offset = htonl(header_size);
1901 memset(attr, CBFS_CONTENT_DEFAULT_VALUE, size);
1902 attr->tag = htonl(tag);
1903 attr->len = htonl(size);
1904 return attr;
1907 int cbfs_add_file_hash(struct cbfs_file *header, struct buffer *buffer,
1908 enum vb2_hash_algorithm hash_type)
1910 uint32_t hash_index = hash_type;
1912 if (hash_index >= CBFS_NUM_SUPPORTED_HASHES)
1913 return -1;
1915 unsigned hash_size = widths_cbfs_hash[hash_type];
1916 if (hash_size == 0)
1917 return -1;
1919 struct cbfs_file_attr_hash *attrs =
1920 (struct cbfs_file_attr_hash *)cbfs_add_file_attr(header,
1921 CBFS_FILE_ATTR_TAG_HASH,
1922 sizeof(struct cbfs_file_attr_hash) + hash_size);
1924 if (attrs == NULL)
1925 return -1;
1927 attrs->hash_type = htonl(hash_type);
1928 if (vb2_digest_buffer(buffer_get(buffer), buffer_size(buffer),
1929 hash_type, attrs->hash_data, hash_size) != VB2_SUCCESS)
1930 return -1;
1932 return 0;
1935 /* Finds a place to hold whole data in same memory page. */
1936 static int is_in_same_page(uint32_t start, uint32_t size, uint32_t page)
1938 if (!page)
1939 return 1;
1940 return (start / page) == (start + size - 1) / page;
1943 /* Tests if data can fit in a range by given offset:
1944 * start ->| metadata_size | offset (+ size) |<- end
1946 static int is_in_range(size_t start, size_t end, size_t metadata_size,
1947 size_t offset, size_t size)
1949 return (offset >= start + metadata_size && offset + size <= end);
1952 static size_t absolute_align(const struct cbfs_image *image, size_t val,
1953 size_t align)
1955 const size_t region_offset = buffer_offset(&image->buffer);
1956 /* To perform alignment on absolute address, take the region offset */
1957 /* of the image into account. */
1958 return align_up(val + region_offset, align) - region_offset;
1962 int32_t cbfs_locate_entry(struct cbfs_image *image, size_t size,
1963 size_t page_size, size_t align, size_t metadata_size)
1965 struct cbfs_file *entry;
1966 size_t need_len;
1967 size_t addr, addr_next, addr2, addr3, offset;
1969 /* Default values: allow fitting anywhere in ROM. */
1970 if (!page_size)
1971 page_size = image->has_header ? image->header.romsize :
1972 image->buffer.size;
1973 if (!align)
1974 align = 1;
1976 if (size > page_size)
1977 ERROR("Input file size (%zd) greater than page size (%zd).\n",
1978 size, page_size);
1980 size_t image_align = image->has_header ? image->header.align :
1981 CBFS_ENTRY_ALIGNMENT;
1982 if (page_size % image_align)
1983 WARN("%s: Page size (%#zx) not aligned with CBFS image (%#zx).\n",
1984 __func__, page_size, image_align);
1986 need_len = metadata_size + size;
1988 // Merge empty entries to build get max available space.
1989 cbfs_walk(image, cbfs_merge_empty_entry, NULL);
1991 /* Three cases of content location on memory page:
1992 * case 1.
1993 * | PAGE 1 | PAGE 2 |
1994 * | <header><content>| Fit. Return start of content.
1996 * case 2.
1997 * | PAGE 1 | PAGE 2 |
1998 * | <header><content> | Fits when we shift content to align
1999 * shift-> | <header>|<content> | at starting of PAGE 2.
2001 * case 3. (large content filling whole page)
2002 * | PAGE 1 | PAGE 2 | PAGE 3 |
2003 * | <header>< content > | Can't fit. If we shift content to
2004 * |trial-> <header>< content > | PAGE 2, header can't fit in free
2005 * | shift-> <header><content> space, so we must use PAGE 3.
2007 * The returned address can be then used as "base-address" (-b) in add-*
2008 * commands (will be re-calculated and positioned by cbfs_add_entry_at).
2009 * For stage targets, the address is also used to re-link stage before
2010 * being added into CBFS.
2012 for (entry = cbfs_find_first_entry(image);
2013 entry && cbfs_is_valid_entry(image, entry);
2014 entry = cbfs_find_next_entry(image, entry)) {
2016 uint32_t type = ntohl(entry->type);
2017 if (type != CBFS_COMPONENT_NULL)
2018 continue;
2020 addr = cbfs_get_entry_addr(image, entry);
2021 addr_next = cbfs_get_entry_addr(image, cbfs_find_next_entry(
2022 image, entry));
2023 if (addr_next - addr < need_len)
2024 continue;
2026 offset = absolute_align(image, addr + metadata_size, align);
2027 if (is_in_same_page(offset, size, page_size) &&
2028 is_in_range(addr, addr_next, metadata_size, offset, size)) {
2029 DEBUG("cbfs_locate_entry: FIT (PAGE1).");
2030 return offset;
2033 addr2 = align_up(addr, page_size);
2034 offset = absolute_align(image, addr2, align);
2035 if (is_in_range(addr, addr_next, metadata_size, offset, size)) {
2036 DEBUG("cbfs_locate_entry: OVERLAP (PAGE2).");
2037 return offset;
2040 /* Assume page_size >= metadata_size so adding one page will
2041 * definitely provide the space for header. */
2042 assert(page_size >= metadata_size);
2043 addr3 = addr2 + page_size;
2044 offset = absolute_align(image, addr3, align);
2045 if (is_in_range(addr, addr_next, metadata_size, offset, size)) {
2046 DEBUG("cbfs_locate_entry: OVERLAP+ (PAGE3).");
2047 return offset;
2050 return -1;