Debian Codegraph @

util/cbfstool/cbfstool.c

raw symbols SCIP
1 /* cbfstool, CLI utility for CBFS file manipulation */
2 /* SPDX-License-Identifier: GPL-2.0-only */
3
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <strings.h>
8 #include <ctype.h>
9 #include <unistd.h>
10 #include <getopt.h>
11 #include "common.h"
12 #include "cbfs.h"
13 #include "cbfs_image.h"
14 #include "cbfs_sections.h"
15 #include "elfparsing.h"
16 #include "partitioned_file.h"
17 #include "lz4/lib/xxhash.h"
18 #include <commonlib/bsd/cbfs_private.h>
19 #include <commonlib/bsd/compression.h>
20 #include <commonlib/bsd/metadata_hash.h>
21 #include <commonlib/fsp.h>
22 #include <commonlib/endian.h>
23 #include <commonlib/helpers.h>
24 #include <commonlib/region.h>
25 #include <vboot_host.h>
26
27 struct command {
28 const char *name;
29 const char *optstring;
30 int (*function) (void);
31 // Whether to populate param.image_region before invoking function
32 bool accesses_region;
33 // This set to true means two things:
34 // - in case of a command operating on a region, the region's contents
35 // will be written back to image_file at the end
36 // - write access to the file is required
37 bool modifies_region;
38 };
39
40 static struct param {
41 partitioned_file_t *image_file;
42 struct buffer *image_region;
43 const char *name;
44 const char *filename;
45 const char *fmap;
46 const char *region_name;
47 const char *source_region;
48 const char *bootblock;
49 const char *ignore_sections;
50 const char *ucode_region;
51 uint64_t u64val;
52 uint32_t type;
53 uint32_t baseaddress;
54 /*
55 * Input can be negative. It will be transformed to offset from start of region (if
56 * negative) and stored in baseaddress.
57 */
58 long long int baseaddress_input;
59 uint32_t baseaddress_assigned;
60 uint64_t loadaddress;
61 uint32_t headeroffset;
62 /*
63 * Input can be negative. It will be transformed to offset from start of region (if
64 * negative) and stored in baseaddress.
65 */
66 long long int headeroffset_input;
67 uint32_t headeroffset_assigned;
68 uint64_t entrypoint;
69 uint32_t size;
70 uint32_t alignment;
71 uint32_t pagesize;
72 uint32_t cbfsoffset;
73 /*
74 * Input can be negative. It will be transformed to corresponding region offset (if
75 * negative) and stored in baseaddress.
76 */
77 long long int cbfsoffset_input;
78 uint32_t cbfsoffset_assigned;
79 uint32_t arch;
80 uint32_t padding;
81 uint32_t topswap_size;
82 bool u64val_assigned;
83 bool fill_partial_upward;
84 bool fill_partial_downward;
85 bool show_immutable;
86 bool stage_xip;
87 bool force_pow2_pagesize;
88 bool autogen_attr;
89 bool machine_parseable;
90 bool unprocessed;
91 bool ibb;
92 enum cbfs_compression compression;
93 int precompression;
94 enum vb2_hash_algorithm hash;
95 /* For linux payloads */
96 char *initrd;
97 char *cmdline;
98 int force;
99 /*
100 * Base and size of extended window for decoding SPI flash greater than 16MiB in host
101 * address space on x86 platforms. The assumptions here are:
102 * 1. Top 16MiB is still decoded in the fixed decode window just below 4G boundary.
103 * 2. Rest of the SPI flash below the top 16MiB is mapped at the top of extended
104 * window. Even though the platform might support a larger extended window, the SPI
105 * flash part used by the mainboard might not be large enough to be mapped in the entire
106 * window. In such cases, the mapping is assumed to be in the top part of the extended
107 * window with the bottom part remaining unused.
108 */
109 uint32_t ext_win_base;
110 uint32_t ext_win_size;
111 } param = {
112 /* All variables not listed are initialized as zero. */
113 .arch = CBFS_ARCHITECTURE_UNKNOWN,
114 .compression = CBFS_COMPRESS_NONE,
115 .hash = VB2_HASH_INVALID,
116 .headeroffset = HEADER_OFFSET_UNKNOWN,
117 .region_name = SECTION_NAME_PRIMARY_CBFS,
118 .u64val = -1,
119 };
120
121 /*
122 * This "metadata_hash cache" caches the value and location of the CBFS metadata
123 * hash embedded in the bootblock when CBFS verification is enabled. The first
124 * call to get_mh_cache() searches for the cache by scanning the whole bootblock
125 * for its 8-byte signature, later calls will just return the previously found
126 * information again. If the cbfs_hash.algo member in the result is
127 * VB2_HASH_INVALID, that means no metadata hash was found and this image does
128 * not use CBFS verification.
129 */
130 struct mh_cache {
131 const char *region;
132 size_t offset;
133 struct vb2_hash cbfs_hash;
134 platform_fixup_func fixup;
135 bool initialized;
136 };
137
138 static struct mh_cache *get_mh_cache(void)
139 {
140 static struct mh_cache mhc;
141
142 if (mhc.initialized)
143 return &mhc;
144
145 mhc.initialized = true;
146
147 const struct fmap *fmap = partitioned_file_get_fmap(param.image_file);
148 if (!fmap)
149 goto no_metadata_hash;
150
151 /* Find the metadata_hash container. If there is a "BOOTBLOCK" FMAP section, it's
152 there. If not, it's a normal file in the primary CBFS section. */
153 size_t offset, size;
154 struct buffer buffer;
155 if (fmap_find_area(fmap, SECTION_NAME_BOOTBLOCK)) {
156 if (!partitioned_file_read_region(&buffer, param.image_file,
157 SECTION_NAME_BOOTBLOCK))
158 goto no_metadata_hash;
159 mhc.region = SECTION_NAME_BOOTBLOCK;
160 offset = 0;
161 size = buffer.size;
162 } else {
163 struct cbfs_image cbfs;
164 struct cbfs_file *mh_container;
165 if (!partitioned_file_read_region(&buffer, param.image_file,
166 SECTION_NAME_PRIMARY_CBFS))
167 goto no_metadata_hash;
168 mhc.region = SECTION_NAME_PRIMARY_CBFS;
169 if (cbfs_image_from_buffer(&cbfs, &buffer, param.headeroffset))
170 goto no_metadata_hash;
171 mh_container = cbfs_get_entry(&cbfs, "bootblock");
172 if (!mh_container || be32toh(mh_container->type) != CBFS_TYPE_BOOTBLOCK) {
173 /* Check for apu/amdfw file */
174 mh_container = cbfs_get_entry(&cbfs, "apu/amdfw");
175 if (!mh_container || be32toh(mh_container->type) != CBFS_TYPE_AMDFW)
176 goto no_metadata_hash;
177 }
178
179 offset = (void *)mh_container + be32toh(mh_container->offset) -
180 buffer_get(&cbfs.buffer);
181 size = be32toh(mh_container->len);
182 }
183
184 /* Find and validate the metadata hash anchor inside the containing file and
185 record its exact byte offset from the start of the FMAP region. */
186 struct metadata_hash_anchor *anchor = memmem(buffer_get(&buffer) + offset,
187 size, METADATA_HASH_ANCHOR_MAGIC, sizeof(anchor->magic));
188 if (anchor) {
189 if (!vb2_digest_size(anchor->cbfs_hash.algo)) {
190 ERROR("Unknown CBFS metadata hash type: %d\n",
191 anchor->cbfs_hash.algo);
192 goto no_metadata_hash;
193 }
194 mhc.cbfs_hash = anchor->cbfs_hash;
195 mhc.offset = (void *)anchor - buffer_get(&buffer);
196 mhc.fixup = platform_fixups_probe(&buffer, mhc.offset,
197 mhc.region);
198 return &mhc;
199 }
200
201 no_metadata_hash:
202 mhc.cbfs_hash.algo = VB2_HASH_INVALID;
203 return &mhc;
204 }
205
206 static void update_and_info(const char *name, void *dst, void *src, size_t size)
207 {
208 if (!memcmp(dst, src, size))
209 return;
210 char *src_str = bintohex(src, size);
211 char *dst_str = bintohex(dst, size);
212 INFO("Updating %s from %s to %s\n", name, dst_str, src_str);
213 memcpy(dst, src, size);
214 free(src_str);
215 free(dst_str);
216 }
217
218 static int update_anchor(struct mh_cache *mhc, uint8_t *fmap_hash)
219 {
220 struct buffer buffer;
221 if (!partitioned_file_read_region(&buffer, param.image_file,
222 mhc->region))
223 return -1;
224 struct metadata_hash_anchor *anchor = buffer_get(&buffer) + mhc->offset;
225 /* The metadata hash anchor should always still be where we left it. */
226 assert(!memcmp(anchor->magic, METADATA_HASH_ANCHOR_MAGIC,
227 sizeof(anchor->magic)) &&
228 anchor->cbfs_hash.algo == mhc->cbfs_hash.algo);
229 update_and_info("CBFS metadata hash", anchor->cbfs_hash.raw,
230 mhc->cbfs_hash.raw, vb2_digest_size(anchor->cbfs_hash.algo));
231 if (fmap_hash) {
232 update_and_info("FMAP hash",
233 metadata_hash_anchor_fmap_hash(anchor), fmap_hash,
234 vb2_digest_size(anchor->cbfs_hash.algo));
235 }
236 if (mhc->fixup && mhc->fixup(&buffer, mhc->offset) != 0)
237 return -1;
238 if (!partitioned_file_write_region(param.image_file, &buffer))
239 return -1;
240 return 0;
241
242 }
243
244 /* This should be called after every time CBFS metadata might have changed. It
245 will recalculate and update the metadata hash in the bootblock if needed. */
246 static int maybe_update_metadata_hash(struct cbfs_image *cbfs)
247 {
248 if (strcmp(param.region_name, SECTION_NAME_PRIMARY_CBFS))
249 return 0; /* Metadata hash only embedded in primary CBFS. */
250
251 struct mh_cache *mhc = get_mh_cache();
252 if (mhc->cbfs_hash.algo == VB2_HASH_INVALID)
253 return 0;
254
255 enum cb_err err = cbfs_walk(cbfs, NULL, NULL, &mhc->cbfs_hash,
256 CBFS_WALK_WRITEBACK_HASH);
257 if (err != CB_CBFS_NOT_FOUND) {
258 ERROR("Unexpected cbfs_walk() error %d\n", err);
259 return -1;
260 }
261
262 return update_anchor(mhc, NULL);
263 }
264
265 /* This should be called after every time the FMAP or the bootblock itself might
266 have changed, and will write the new FMAP hash into the metadata hash anchor
267 in the bootblock if required (usually when the bootblock is first added). */
268 static int maybe_update_fmap_hash(void)
269 {
270 if (strcmp(param.region_name, SECTION_NAME_BOOTBLOCK) &&
271 strcmp(param.region_name, SECTION_NAME_FMAP) &&
272 param.type != CBFS_TYPE_BOOTBLOCK &&
273 param.type != CBFS_TYPE_AMDFW)
274 return 0; /* FMAP and bootblock didn't change. */
275
276 struct mh_cache *mhc = get_mh_cache();
277 if (mhc->cbfs_hash.algo == VB2_HASH_INVALID)
278 return 0;
279
280 struct vb2_hash fmap_hash;
281 const struct fmap *fmap = partitioned_file_get_fmap(param.image_file);
282 if (!fmap || vb2_hash_calculate(false, fmap, fmap_size(fmap),
283 mhc->cbfs_hash.algo, &fmap_hash))
284 return -1;
285 return update_anchor(mhc, fmap_hash.raw);
286 }
287
288 static bool verification_exclude(enum cbfs_type type)
289 {
290 switch (type) {
291 case CBFS_TYPE_BOOTBLOCK:
292 case CBFS_TYPE_CBFSHEADER:
293 case CBFS_TYPE_INTEL_FIT:
294 case CBFS_TYPE_AMDFW:
295 return true;
296 default:
297 return false;
298 }
299 }
300
301 static bool region_is_flashmap(const char *region)
302 {
303 return partitioned_file_region_check_magic(param.image_file, region,
304 FMAP_SIGNATURE, strlen(FMAP_SIGNATURE));
305 }
306
307 /* @return Same as cbfs_is_valid_cbfs(), but for a named region. */
308 static bool region_is_modern_cbfs(const char *region)
309 {
310 return partitioned_file_region_check_magic(param.image_file, region,
311 CBFS_FILE_MAGIC, strlen(CBFS_FILE_MAGIC));
312 }
313
314 /* This describes a window from the SPI flash address space into the host address space. */
315 struct mmap_window {
316 struct region flash_space;
317 struct region host_space;
318 };
319
320 /* Should be enough for now */
321 #define MMAP_MAX_WINDOWS 3
322
323 /* Table of all the decode windows supported by the platform. */
324 static int mmap_window_table_size;
325 static struct mmap_window mmap_window_table[MMAP_MAX_WINDOWS];
326
327 static int add_mmap_window(unsigned long flash_offset, unsigned long host_offset, unsigned long window_size)
328 {
329 if (mmap_window_table_size >= MMAP_MAX_WINDOWS) {
330 ERROR("Too many memory map windows\n");
331 return 1;
332 }
333
334 if (region_create_untrusted(
335 &mmap_window_table[mmap_window_table_size].flash_space,
336 flash_offset, window_size) != CB_SUCCESS ||
337 region_create_untrusted(
338 &mmap_window_table[mmap_window_table_size].host_space,
339 host_offset, window_size) != CB_SUCCESS) {
340 ERROR("Invalid mmap window size %lu.\n", window_size);
341 return 1;
342 }
343
344 mmap_window_table_size++;
345 return 0;
346 }
347
348
349 static int decode_mmap_arg(char *arg)
350 {
351 if (arg == NULL)
352 return 1;
353
354 union {
355 unsigned long array[3];
356 struct {
357 unsigned long flash_base;
358 unsigned long mmap_base;
359 unsigned long mmap_size;
360 };
361 } mmap_args;
362 char *suffix = NULL;
363 char *substring = strtok(arg, ":");
364 for (size_t i = 0; i < ARRAY_SIZE(mmap_args.array); i++) {
365 if (!substring) {
366 ERROR("Invalid mmap arguments '%s'.\n",
367 arg);
368 return 1;
369 }
370 mmap_args.array[i] = strtol(substring, &suffix, 0);
371 if (suffix && *suffix) {
372 ERROR("Invalid mmap arguments '%s'.\n",
373 arg);
374 return 1;
375 }
376 substring = strtok(NULL, ":");
377 }
378
379 if (substring != NULL) {
380 ERROR("Invalid argument, too many substrings '%s'.\n",
381 arg);
382
383 return 1;
384 }
385
386 if (add_mmap_window(mmap_args.flash_base, mmap_args.mmap_base, mmap_args.mmap_size))
387 return 1;
388
389 return 0;
390 }
391
392 #define DEFAULT_DECODE_WINDOW_TOP (4ULL * GiB)
393 #define DEFAULT_DECODE_WINDOW_MAX_SIZE (16 * MiB)
394
395 static bool create_mmap_windows(void)
396 {
397 static bool done;
398
399 if (done)
400 return done;
401
402 // No memory map provided, use a default one
403 if (mmap_window_table_size == 0) {
404 const size_t image_size = partitioned_file_total_size(param.image_file);
405 printf("Image SIZE %zu\n", image_size);
406 const size_t std_window_size = MIN(DEFAULT_DECODE_WINDOW_MAX_SIZE, image_size);
407 const size_t std_window_flash_offset = image_size - std_window_size;
408
409 /*
410 * Default decode window lives just below 4G boundary in host space and maps up to a
411 * maximum of 16MiB. If the window is smaller than 16MiB, the SPI flash window is mapped
412 * at the top of the host window just below 4G.
413 */
414 if (add_mmap_window(std_window_flash_offset, DEFAULT_DECODE_WINDOW_TOP - std_window_size, std_window_size))
415 return false;
416 } else {
417 /*
418 * Check provided memory map
419 */
420 for (int i = 0; i < mmap_window_table_size; i++) {
421 for (int j = i + 1; j < mmap_window_table_size; j++) {
422 if (region_overlap(&mmap_window_table[i].flash_space,
423 &mmap_window_table[j].flash_space)) {
424 ERROR("Flash space windows (base=0x%zx, limit=0x%zx) and (base=0x%zx, limit=0x%zx) overlap!\n",
425 region_offset(&mmap_window_table[i].flash_space),
426 region_last(&mmap_window_table[i].flash_space),
427 region_offset(&mmap_window_table[j].flash_space),
428 region_last(&mmap_window_table[j].flash_space));
429 return false;
430 }
431
432 if (region_overlap(&mmap_window_table[i].host_space,
433 &mmap_window_table[j].host_space)) {
434 ERROR("Host space windows (base=0x%zx, limit=0x%zx) and (base=0x%zx, limit=0x%zx) overlap!\n",
435 region_offset(&mmap_window_table[i].flash_space),
436 region_last(&mmap_window_table[i].flash_space),
437 region_offset(&mmap_window_table[j].flash_space),
438 region_last(&mmap_window_table[j].flash_space));
439 return false;
440 }
441 }
442 }
443 }
444
445 done = true;
446 return done;
447 }
448
449 static unsigned int convert_address(const struct region *to, const struct region *from,
450 unsigned int addr)
451 {
452 /*
453 * Calculate the offset in the "from" region and use that offset to calculate
454 * corresponding address in the "to" region.
455 */
456 size_t offset = addr - region_offset(from);
457 return region_offset(to) + offset;
458 }
459
460 enum mmap_addr_type {
461 HOST_SPACE_ADDR,
462 FLASH_SPACE_ADDR,
463 };
464
465 static int find_mmap_window(enum mmap_addr_type addr_type, unsigned int addr)
466 {
467 size_t i;
468
469 for (i = 0; i < ARRAY_SIZE(mmap_window_table); i++) {
470 const struct region *reg;
471
472 if (addr_type == HOST_SPACE_ADDR)
473 reg = &mmap_window_table[i].host_space;
474 else
475 reg = &mmap_window_table[i].flash_space;
476
477 if (region_offset(reg) <= addr &&
478 ((uint64_t)region_offset(reg) + (uint64_t)region_sz(reg) - 1) >= addr)
479 return i;
480 }
481
482 return -1;
483 }
484
485 static unsigned int convert_host_to_flash(const struct buffer *region, unsigned int addr)
486 {
487 int idx;
488 const struct region *to, *from;
489
490 idx = find_mmap_window(HOST_SPACE_ADDR, addr);
491 if (idx == -1) {
492 ERROR("Host address(%x) not in any mmap window!\n", addr);
493 return 0;
494 }
495
496 to = &mmap_window_table[idx].flash_space;
497 from = &mmap_window_table[idx].host_space;
498
499 /* region->offset is subtracted because caller expects offset in the given region. */
500 return convert_address(to, from, addr) - region->offset;
501 }
502
503 static unsigned int convert_flash_to_host(const struct buffer *region, unsigned int addr)
504 {
505 int idx;
506 const struct region *to, *from;
507
508 /*
509 * region->offset is added because caller provides offset in the given region. This is
510 * converted to an absolute address in the SPI flash space. This is done before the
511 * conversion as opposed to after in convert_host_to_flash() above because the address
512 * is actually an offset within the region. So, it needs to be converted into an
513 * absolute address in the SPI flash space before converting into an address in host
514 * space.
515 */
516 addr += region->offset;
517 idx = find_mmap_window(FLASH_SPACE_ADDR, addr);
518
519 if (idx == -1) {
520 ERROR("SPI flash address(%x) not in any mmap window!\n", addr);
521 return 0;
522 }
523
524 to = &mmap_window_table[idx].host_space;
525 from = &mmap_window_table[idx].flash_space;
526
527 return convert_address(to, from, addr);
528 }
529
530 static unsigned int convert_addr_space(const struct buffer *region, unsigned int addr)
531 {
532 assert(region);
533
534 assert(create_mmap_windows());
535
536 if (IS_HOST_SPACE_ADDRESS(addr))
537 return convert_host_to_flash(region, addr);
538 else
539 return convert_flash_to_host(region, addr);
540 }
541
542 /*
543 * This function takes offset value which represents the offset from one end of the region and
544 * converts it to offset from the other end of the region. offset is expected to be positive.
545 */
546 static int convert_region_offset(unsigned int offset, uint32_t *region_offset)
547 {
548 size_t size;
549
550 if (param.size) {
551 size = param.size;
552 } else {
553 assert(param.image_region);
554 size = param.image_region->size;
555 }
556
557 if (size < offset) {
558 ERROR("Cannot convert region offset (size=0x%zx, offset=0x%x)\n", size, offset);
559 return 1;
560 }
561
562 *region_offset = size - offset;
563 return 0;
564 }
565
566 static int do_cbfs_locate(uint32_t *cbfs_addr, size_t data_size)
567 {
568 uint32_t metadata_size = 0;
569
570 if (!param.name) {
571 ERROR("You need to specify -n/--name.\n");
572 return 1;
573 }
574
575 struct cbfs_image image;
576 if (cbfs_image_from_buffer(&image, param.image_region,
577 param.headeroffset))
578 return 1;
579
580 if (cbfs_get_entry(&image, param.name))
581 WARN("'%s' already in CBFS.\n", param.name);
582
583 if (!data_size) {
584 ERROR("File '%s' is empty?\n", param.name);
585 return 1;
586 }
587
588 /* Compute required page size */
589 if (param.force_pow2_pagesize) {
590 param.pagesize = 1;
591 while (param.pagesize < data_size)
592 param.pagesize <<= 1;
593 DEBUG("Page size is %d (0x%x)\n", param.pagesize, param.pagesize);
594 }
595
596 /* Include cbfs_file size along with space for with name. */
597 metadata_size += cbfs_calculate_file_header_size(param.name);
598 /* Adjust metadata_size if additional attributes were added */
599 if (param.autogen_attr) {
600 if (param.alignment)
601 metadata_size += sizeof(struct cbfs_file_attr_align);
602 if (param.baseaddress_assigned || param.stage_xip)
603 metadata_size += sizeof(struct cbfs_file_attr_position);
604 }
605 if (param.precompression || param.compression != CBFS_COMPRESS_NONE)
606 metadata_size += sizeof(struct cbfs_file_attr_compression);
607 if (param.type == CBFS_TYPE_STAGE)
608 metadata_size += sizeof(struct cbfs_file_attr_stageheader);
609
610 /* Take care of the hash attribute if it is used */
611 if (param.hash != VB2_HASH_INVALID)
612 metadata_size += cbfs_file_attr_hash_size(param.hash);
613
614 int32_t address = cbfs_locate_entry(&image, data_size, param.pagesize,
615 param.alignment, metadata_size);
616
617 if (address < 0) {
618 ERROR("'%s'(%u + %zu) can't fit in CBFS for page-size %#x, align %#x.\n",
619 param.name, metadata_size, data_size, param.pagesize, param.alignment);
620 return 1;
621 }
622
623 *cbfs_addr = address;
624 return 0;
625 }
626
627 typedef int (*convert_buffer_t)(struct buffer *buffer, uint32_t *offset,
628 struct cbfs_file *header);
629
630 static int cbfs_add_integer_component(const char *name,
631 uint64_t u64val,
632 uint32_t offset,
633 uint32_t headeroffset) {
634 struct cbfs_image image;
635 struct cbfs_file *header = NULL;
636 struct buffer buffer;
637 int i, ret = 1;
638
639 if (!name) {
640 ERROR("You need to specify -n/--name.\n");
641 return 1;
642 }
643
644 if (buffer_create(&buffer, 8, name) != 0)
645 return 1;
646
647 for (i = 0; i < 8; i++)
648 buffer.data[i] = (u64val >> i*8) & 0xff;
649
650 if (cbfs_image_from_buffer(&image, param.image_region, headeroffset)) {
651 ERROR("Selected image region is not a CBFS.\n");
652 goto done;
653 }
654
655 if (cbfs_get_entry(&image, name)) {
656 if (cbfs_remove_entry(&image, name) != 0) {
657 ERROR("Removing file '%s' failed.\n", name);
658 goto done;
659 }
660 }
661
662 header = cbfs_create_file_header(CBFS_TYPE_RAW,
663 buffer.size, name);
664 if (!header)
665 goto done;
666
667 enum vb2_hash_algorithm algo = get_mh_cache()->cbfs_hash.algo;
668 if (algo != VB2_HASH_INVALID)
669 if (cbfs_add_file_hash(header, &buffer, algo)) {
670 ERROR("couldn't add hash for '%s'\n", name);
671 goto done;
672 }
673
674 if (cbfs_add_entry(&image, &buffer, offset, header, 0) != 0) {
675 ERROR("Failed to add %llu into ROM image as '%s'.\n",
676 (long long unsigned)u64val, name);
677 goto done;
678 }
679
680 ret = maybe_update_metadata_hash(&image);
681
682 done:
683 free(header);
684 buffer_delete(&buffer);
685 return ret;
686 }
687
688 static int is_valid_topswap(void)
689 {
690 switch (param.topswap_size) {
691 case (64 * KiB):
692 case (128 * KiB):
693 case (256 * KiB):
694 case (512 * KiB):
695 case (1 * MiB):
696 break;
697 default:
698 ERROR("Invalid topswap_size %d, topswap can be 64K|128K|256K|512K|1M\n",
699 param.topswap_size);
700 return 0;
701 }
702 return 1;
703 }
704
705 static void fill_header_offset(void *location, uint32_t offset)
706 {
707 // TODO: When we have a BE target, we'll need to store this as BE
708 write_le32(location, offset);
709 }
710
711 static int update_master_header_loc_topswap(struct cbfs_image *image,
712 void *h_loc, uint32_t header_offset)
713 {
714 struct cbfs_file *entry;
715 void *ts_h_loc = h_loc;
716
717 entry = cbfs_get_entry(image, "bootblock");
718 if (entry == NULL) {
719 ERROR("Bootblock not in ROM image?!?\n");
720 return 1;
721 }
722
723 /*
724 * Check if the existing topswap boundary matches with
725 * the one provided.
726 */
727 if (param.topswap_size != be32toh(entry->len)/2) {
728 ERROR("Top swap boundary does not match\n");
729 return 1;
730 }
731
732 ts_h_loc -= param.topswap_size;
733 fill_header_offset(ts_h_loc, header_offset);
734
735 return 0;
736 }
737
738 static int cbfs_add_master_header(void)
739 {
740 const char * const name = "cbfs master header";
741 struct cbfs_image image;
742 struct cbfs_file *header = NULL;
743 struct buffer buffer;
744 int ret = 1;
745 size_t offset;
746 size_t size;
747 void *h_loc;
748
749 if (cbfs_image_from_buffer(&image, param.image_region,
750 param.headeroffset)) {
751 ERROR("Selected image region is not a CBFS.\n");
752 return 1;
753 }
754
755 if (cbfs_get_entry(&image, name)) {
756 ERROR("'%s' already in ROM image.\n", name);
757 return 1;
758 }
759
760 if (buffer_create(&buffer, sizeof(struct cbfs_header), name) != 0)
761 return 1;
762
763 struct cbfs_header *h = (struct cbfs_header *)buffer.data;
764 h->magic = htobe32(CBFS_HEADER_MAGIC);
765 h->version = htobe32(CBFS_HEADER_VERSION);
766 /* The 4 bytes are left out for two reasons:
767 * 1. the cbfs master header pointer resides there
768 * 2. some cbfs implementations assume that an image that resides
769 * below 4GB has a bootblock and get confused when the end of the
770 * image is at 4GB == 0.
771 */
772 h->bootblocksize = htobe32(4);
773 h->align = htobe32(CBFS_ALIGNMENT);
774 /* The offset and romsize fields within the master header are absolute
775 * values within the boot media. As such, romsize needs to relfect
776 * the end 'offset' for a CBFS. To achieve that the current buffer
777 * representing the CBFS region's size is added to the offset of
778 * the region within a larger image.
779 */
780 offset = buffer_get(param.image_region) -
781 buffer_get_original_backing(param.image_region);
782 size = buffer_size(param.image_region);
783 h->romsize = htobe32(size + offset);
784 h->offset = htobe32(offset);
785 h->architecture = htobe32(CBFS_ARCHITECTURE_UNKNOWN);
786
787 /* Never add a hash attribute to the master header. */
788 header = cbfs_create_file_header(CBFS_TYPE_CBFSHEADER,
789 buffer_size(&buffer), name);
790 if (!header)
791 goto done;
792 if (cbfs_add_entry(&image, &buffer, 0, header, 0) != 0) {
793 ERROR("Failed to add cbfs master header into ROM image.\n");
794 goto done;
795 }
796
797 struct cbfs_file *entry;
798 if ((entry = cbfs_get_entry(&image, name)) == NULL) {
799 ERROR("'%s' not in ROM image?!?\n", name);
800 goto done;
801 }
802
803 uint32_t header_offset = CBFS_SUBHEADER(entry) -
804 buffer_get(&image.buffer);
805 header_offset = -(buffer_size(&image.buffer) - header_offset);
806
807 h_loc = (void *)(buffer_get(&image.buffer) +
808 buffer_size(&image.buffer) - 4);
809 fill_header_offset(h_loc, header_offset);
810 /*
811 * If top swap present, update the header
812 * location in secondary bootblock
813 */
814 if (param.topswap_size) {
815 if (update_master_header_loc_topswap(&image, h_loc,
816 header_offset))
817 goto done;
818 }
819
820 ret = maybe_update_metadata_hash(&image);
821
822 done:
823 free(header);
824 buffer_delete(&buffer);
825 return ret;
826 }
827
828 static int add_topswap_bootblock(struct buffer *buffer, uint32_t *offset)
829 {
830 size_t bb_buf_size = buffer_size(buffer);
831
832 if (bb_buf_size > param.topswap_size) {
833 ERROR("Bootblock bigger than the topswap boundary\n");
834 ERROR("size = %zd, ts = %d\n", bb_buf_size,
835 param.topswap_size);
836 return 1;
837 }
838
839 /*
840 * Allocate topswap_size*2 bytes for bootblock to
841 * accommodate the second bootblock.
842 */
843 struct buffer new_bootblock, bb1, bb2;
844 if (buffer_create(&new_bootblock, 2 * param.topswap_size,
845 buffer->name))
846 return 1;
847
848 buffer_splice(&bb1, &new_bootblock, param.topswap_size - bb_buf_size,
849 bb_buf_size);
850 buffer_splice(&bb2, &new_bootblock,
851 buffer_size(&new_bootblock) - bb_buf_size,
852 bb_buf_size);
853
854 /* Copy to first bootblock */
855 memcpy(buffer_get(&bb1), buffer_get(buffer), bb_buf_size);
856 /* Copy to second bootblock */
857 memcpy(buffer_get(&bb2), buffer_get(buffer), bb_buf_size);
858
859 buffer_delete(buffer);
860 buffer_clone(buffer, &new_bootblock);
861
862 /* Update the location (offset) of bootblock in the region */
863 return convert_region_offset(buffer_size(buffer), offset);
864 }
865
866 static int cbfs_add_component(const char *filename,
867 const char *name,
868 uint32_t headeroffset,
869 convert_buffer_t convert)
870 {
871 /*
872 * The steps used to determine the final placement offset in CBFS, in order:
873 *
874 * 1. If --base-address was passed, that value is used. If it was passed in the host
875 * address space, convert it to flash address space. (After that, |*offset| is always
876 * in the flash address space.)
877 *
878 * 2. The convert() function may write a location back to |offset|, usually by calling
879 * do_cbfs_locate(). In this case, it needs to ensure that the location found can fit
880 * the CBFS file in its final form (after any compression and conversion).
881 *
882 * 3. If --align was passed and the offset is still undecided at this point,
883 * do_cbfs_locate() is called to find an appropriately aligned location.
884 *
885 * 4. If |offset| is still 0 at the end, cbfs_add_entry() will find the first available
886 * location that fits.
887 */
888 uint32_t offset = param.baseaddress_assigned ? param.baseaddress : 0;
889 size_t len_align = 0;
890
891 if (param.alignment && param.baseaddress_assigned) {
892 ERROR("Cannot specify both alignment and base address\n");
893 return 1;
894 }
895
896 if (param.stage_xip && param.compression != CBFS_COMPRESS_NONE) {
897 ERROR("Cannot specify compression for XIP.\n");
898 return 1;
899 }
900
901 if (!filename) {
902 ERROR("You need to specify -f/--filename.\n");
903 return 1;
904 }
905
906 if (!name) {
907 ERROR("You need to specify -n/--name.\n");
908 return 1;
909 }
910
911 if (param.type == 0) {
912 ERROR("You need to specify a valid -t/--type.\n");
913 return 1;
914 }
915
916 struct cbfs_image image;
917 if (cbfs_image_from_buffer(&image, param.image_region, headeroffset))
918 return 1;
919
920 if (cbfs_get_entry(&image, name)) {
921 ERROR("'%s' already in ROM image.\n", name);
922 return 1;
923 }
924
925 struct buffer buffer;
926 if (buffer_from_file(&buffer, filename) != 0) {
927 ERROR("Could not load file '%s'.\n", filename);
928 return 1;
929 }
930
931 struct cbfs_file *header =
932 cbfs_create_file_header(param.type, buffer.size, name);
933 if (!header)
934 goto error;
935
936 /* Bootblock and CBFS header should never have file hashes. When adding
937 the bootblock it is important that we *don't* look up the metadata
938 hash yet (before it is added) or we'll cache an outdated result. */
939 if (!verification_exclude(param.type)) {
940 enum vb2_hash_algorithm mh_algo = get_mh_cache()->cbfs_hash.algo;
941 if (mh_algo != VB2_HASH_INVALID && param.hash != mh_algo) {
942 if (param.hash == VB2_HASH_INVALID) {
943 param.hash = mh_algo;
944 } else {
945 ERROR("Cannot specify hash %s that's different from metadata hash algorithm %s\n",
946 vb2_get_hash_algorithm_name(param.hash),
947 vb2_get_hash_algorithm_name(mh_algo));
948 goto error;
949 }
950 }
951 }
952
953 /*
954 * Check if Intel CPU topswap is specified this will require a
955 * second bootblock to be added.
956 */
957 if (param.type == CBFS_TYPE_BOOTBLOCK && param.topswap_size)
958 if (add_topswap_bootblock(&buffer, &offset))
959 goto error;
960
961 /* With --base-address we allow host space addresses -- if so, convert it here. */
962 if (IS_HOST_SPACE_ADDRESS(offset))
963 offset = convert_addr_space(param.image_region, offset);
964
965 if (convert && convert(&buffer, &offset, header) != 0) {
966 ERROR("Failed to parse file '%s'.\n", filename);
967 goto error;
968 }
969
970 /* This needs to run after convert() to take compression into account. */
971 if (!offset && param.alignment)
972 if (do_cbfs_locate(&offset, buffer_size(&buffer)))
973 goto error;
974
975 /* This needs to run after convert() to hash the actual final file data. */
976 if (param.hash != VB2_HASH_INVALID &&
977 cbfs_add_file_hash(header, &buffer, param.hash) == -1) {
978 ERROR("couldn't add hash for '%s'\n", name);
979 goto error;
980 }
981
982 if (param.autogen_attr) {
983 /* Add position attribute if assigned */
984 if (param.baseaddress_assigned || param.stage_xip) {
985 struct cbfs_file_attr_position *attrs =
986 (struct cbfs_file_attr_position *)
987 cbfs_add_file_attr(header,
988 CBFS_FILE_ATTR_TAG_POSITION,
989 sizeof(struct cbfs_file_attr_position));
990 if (attrs == NULL)
991 goto error;
992 attrs->position = htobe32(offset);
993 }
994 /* Add alignment attribute if used */
995 if (param.alignment) {
996 struct cbfs_file_attr_align *attrs =
997 (struct cbfs_file_attr_align *)
998 cbfs_add_file_attr(header,
999 CBFS_FILE_ATTR_TAG_ALIGNMENT,
1000 sizeof(struct cbfs_file_attr_align));
1001 if (attrs == NULL)
1002 goto error;
1003 attrs->alignment = htobe32(param.alignment);
1004 }
1005 }
1006
1007 if (param.ibb) {
1008 /* Mark as Initial Boot Block */
1009 struct cbfs_file_attribute *attrs = cbfs_add_file_attr(header,
1010 CBFS_FILE_ATTR_TAG_IBB,
1011 sizeof(struct cbfs_file_attribute));
1012 if (attrs == NULL)
1013 goto error;
1014 /* For Intel TXT minimum align is 16 */
1015 len_align = 16;
1016 }
1017
1018 if (param.padding) {
1019 const uint32_t hs = sizeof(struct cbfs_file_attribute);
1020 uint32_t size = ALIGN_UP(MAX(hs, param.padding),
1021 CBFS_ATTRIBUTE_ALIGN);
1022 INFO("Padding %d bytes\n", size);
1023 struct cbfs_file_attribute *attr =
1024 (struct cbfs_file_attribute *)cbfs_add_file_attr(
1025 header, CBFS_FILE_ATTR_TAG_PADDING,
1026 size);
1027 if (attr == NULL)
1028 goto error;
1029 }
1030
1031 if (cbfs_add_entry(&image, &buffer, offset, header, len_align) != 0) {
1032 ERROR("Failed to add '%s' into ROM image.\n", filename);
1033 goto error;
1034 }
1035
1036 free(header);
1037 buffer_delete(&buffer);
1038
1039 return maybe_update_metadata_hash(&image) || maybe_update_fmap_hash();
1040
1041 error:
1042 free(header);
1043 buffer_delete(&buffer);
1044 return 1;
1045 }
1046
1047 static int cbfstool_convert_raw(struct buffer *buffer,
1048 unused uint32_t *offset, struct cbfs_file *header)
1049 {
1050 char *compressed;
1051 int decompressed_size, compressed_size;
1052 comp_func_ptr compress;
1053
1054 decompressed_size = buffer->size;
1055 if (param.precompression) {
1056 param.compression = read_le32(buffer->data);
1057 decompressed_size = read_le32(buffer->data + sizeof(uint32_t));
1058 compressed_size = buffer->size - 8;
1059 compressed = malloc(compressed_size);
1060 if (!compressed)
1061 return -1;
1062 memcpy(compressed, buffer->data + 8, compressed_size);
1063 } else {
1064 if (param.compression == CBFS_COMPRESS_NONE)
1065 goto out;
1066
1067 compress = compression_function(param.compression);
1068 if (!compress)
1069 return -1;
1070 compressed = calloc(buffer->size, 1);
1071 if (!compressed)
1072 return -1;
1073
1074 if (compress(buffer->data, buffer->size,
1075 compressed, &compressed_size)) {
1076 WARN("Compression failed - disabled\n");
1077 free(compressed);
1078 goto out;
1079 }
1080 }
1081
1082 struct cbfs_file_attr_compression *attrs =
1083 (struct cbfs_file_attr_compression *)
1084 cbfs_add_file_attr(header,
1085 CBFS_FILE_ATTR_TAG_COMPRESSION,
1086 sizeof(struct cbfs_file_attr_compression));
1087 if (attrs == NULL) {
1088 free(compressed);
1089 return -1;
1090 }
1091 attrs->compression = htobe32(param.compression);
1092 attrs->decompressed_size = htobe32(decompressed_size);
1093
1094 free(buffer->data);
1095 buffer->data = compressed;
1096 buffer->size = compressed_size;
1097
1098 out:
1099 header->len = htobe32(buffer->size);
1100 return 0;
1101 }
1102
1103 static int cbfstool_convert_fsp(struct buffer *buffer,
1104 uint32_t *offset, struct cbfs_file *header)
1105 {
1106 uint32_t address;
1107 struct buffer fsp;
1108
1109 /*
1110 * There are 4 different cases here:
1111 *
1112 * 1. --xip and --base-address: we need to place the binary at the given base address
1113 * in the CBFS image and relocate it to that address. *offset was already filled in,
1114 * but we need to convert it to the host address space for relocation.
1115 *
1116 * 2. --xip but no --base-address: we implicitly force a 4K minimum alignment so that
1117 * relocation can occur. Call do_cbfs_locate() here to find an appropriate *offset.
1118 * This also needs to be converted to the host address space for relocation.
1119 *
1120 * 3. No --xip but a --base-address: special case where --base-address does not have its
1121 * normal meaning, instead we use it as the relocation target address. We explicitly
1122 * reset *offset to 0 so that the file will be placed wherever it fits in CBFS.
1123 *
1124 * 4. No --xip and no --base-address: this means that the FSP was pre-linked and should
1125 * not be relocated. Just chain directly to convert_raw() for compression.
1126 */
1127
1128 if (param.stage_xip) {
1129 if (!param.baseaddress_assigned) {
1130 param.alignment = 4*1024;
1131 if (do_cbfs_locate(offset, buffer_size(buffer)))
1132 return -1;
1133 }
1134 assert(!IS_HOST_SPACE_ADDRESS(*offset));
1135 address = convert_addr_space(param.image_region, *offset);
1136 } else {
1137 if (param.baseaddress_assigned == 0) {
1138 INFO("Honoring pre-linked FSP module, no relocation.\n");
1139 return cbfstool_convert_raw(buffer, offset, header);
1140 } else {
1141 address = param.baseaddress;
1142 *offset = 0;
1143 }
1144 }
1145
1146 /* Create a copy of the buffer to attempt relocation. */
1147 if (buffer_create(&fsp, buffer_size(buffer), "fsp"))
1148 return -1;
1149
1150 memcpy(buffer_get(&fsp), buffer_get(buffer), buffer_size(buffer));
1151
1152 /* Replace the buffer contents w/ the relocated ones on success. */
1153 if (fsp_component_relocate(address, buffer_get(&fsp), buffer_size(&fsp))
1154 > 0) {
1155 buffer_delete(buffer);
1156 buffer_clone(buffer, &fsp);
1157 } else {
1158 buffer_delete(&fsp);
1159 WARN("Invalid FSP variant.\n");
1160 }
1161
1162 /* Let the raw path handle all the cbfs metadata logic. */
1163 return cbfstool_convert_raw(buffer, offset, header);
1164 }
1165
1166 static int cbfstool_convert_mkstage(struct buffer *buffer, uint32_t *offset,
1167 struct cbfs_file *header)
1168 {
1169 struct buffer output;
1170 int ret;
1171
1172 /*
1173 * We need a final location for XIP parsing, so we need to call do_cbfs_locate() early
1174 * here. That is okay because XIP stages may not be compressed, so their size cannot
1175 * change anymore at a later point.
1176 */
1177 if (param.stage_xip) {
1178 size_t data_size, alignment;
1179 if (elf_program_file_size_align(buffer, &data_size, &alignment) < 0) {
1180 ERROR("Could not obtain ELF size & alignment\n");
1181 return 1;
1182 }
1183
1184 param.alignment = MAX(alignment, param.alignment);
1185
1186 if (do_cbfs_locate(offset, data_size)) {
1187 ERROR("Could not find location for stage.\n");
1188 return 1;
1189 }
1190 }
1191
1192 struct cbfs_file_attr_stageheader *stageheader = (void *)
1193 cbfs_add_file_attr(header, CBFS_FILE_ATTR_TAG_STAGEHEADER,
1194 sizeof(struct cbfs_file_attr_stageheader));
1195 if (!stageheader)
1196 return -1;
1197
1198 if (param.stage_xip) {
1199 uint32_t host_space_address = convert_addr_space(param.image_region, *offset);
1200 assert(IS_HOST_SPACE_ADDRESS(host_space_address));
1201 ret = parse_elf_to_xip_stage(buffer, &output, host_space_address,
1202 param.ignore_sections, stageheader);
1203 } else {
1204 ret = parse_elf_to_stage(buffer, &output, param.ignore_sections,
1205 stageheader);
1206 }
1207 if (ret != 0)
1208 return -1;
1209
1210 /* Store a hash of original uncompressed stage to compare later. */
1211 size_t decmp_size = buffer_size(&output);
1212 uint32_t decmp_hash = XXH32(buffer_get(&output), decmp_size, 0);
1213
1214 /* Chain to base conversion routine to handle compression. */
1215 ret = cbfstool_convert_raw(&output, offset, header);
1216 if (ret != 0)
1217 goto fail;
1218
1219 /* Special care must be taken for LZ4-compressed stages that the BSS is
1220 large enough to provide scratch space for in-place decompression. */
1221 if (!param.precompression && param.compression == CBFS_COMPRESS_LZ4) {
1222 size_t memlen = be32toh(stageheader->memlen);
1223 size_t compressed_size = buffer_size(&output);
1224 uint8_t *compare_buffer = malloc(memlen);
1225 uint8_t *start = compare_buffer + memlen - compressed_size;
1226 if (!compare_buffer) {
1227 ERROR("Out of memory\n");
1228 goto fail;
1229 }
1230 memcpy(start, buffer_get(&output), compressed_size);
1231 ret = ulz4fn(start, compressed_size, compare_buffer, memlen);
1232 if (ret == 0) {
1233 ERROR("Not enough scratch space to decompress LZ4 in-place -- increase BSS size or disable compression!\n");
1234 free(compare_buffer);
1235 goto fail;
1236 } else if (ret != (int)decmp_size ||
1237 decmp_hash != XXH32(compare_buffer, decmp_size, 0)) {
1238 ERROR("LZ4 compression BUG! Report to mailing list.\n");
1239 free(compare_buffer);
1240 goto fail;
1241 }
1242 free(compare_buffer);
1243 }
1244
1245 buffer_delete(buffer);
1246 buffer_clone(buffer, &output);
1247 return 0;
1248
1249 fail:
1250 buffer_delete(&output);
1251 return -1;
1252 }
1253
1254 static int cbfstool_convert_mkpayload(struct buffer *buffer,
1255 unused uint32_t *offset, struct cbfs_file *header)
1256 {
1257 struct buffer output;
1258 int ret;
1259 /* Per default, try and see if payload is an ELF binary */
1260 ret = parse_elf_to_payload(buffer, &output, param.compression);
1261
1262 /* If it's not an ELF, see if it's a FIT */
1263 if (ret != 0) {
1264 ret = parse_fit_to_payload(buffer, &output, param.compression);
1265 if (ret == 0)
1266 header->type = htobe32(CBFS_TYPE_FIT_PAYLOAD);
1267 }
1268
1269 /* If it's not an FIT, see if it's a UEFI FV */
1270 if (ret != 0)
1271 ret = parse_fv_to_payload(buffer, &output, param.compression);
1272
1273 /* If it's neither ELF nor UEFI Fv, try bzImage */
1274 if (ret != 0)
1275 ret = parse_bzImage_to_payload(buffer, &output,
1276 param.initrd, param.cmdline, param.compression);
1277
1278 /* Not a supported payload type */
1279 if (ret != 0) {
1280 ERROR("Not a supported payload type (ELF / FV).\n");
1281 buffer_delete(buffer);
1282 return -1;
1283 }
1284
1285 buffer_delete(buffer);
1286 // Direct assign, no dupe.
1287 memcpy(buffer, &output, sizeof(*buffer));
1288 header->len = htobe32(output.size);
1289 return 0;
1290 }
1291
1292 static int cbfstool_convert_mkflatpayload(struct buffer *buffer,
1293 unused uint32_t *offset, struct cbfs_file *header)
1294 {
1295 struct buffer output;
1296 if (parse_flat_binary_to_payload(buffer, &output,
1297 param.loadaddress,
1298 param.entrypoint,
1299 param.compression) != 0) {
1300 return -1;
1301 }
1302 buffer_delete(buffer);
1303 // Direct assign, no dupe.
1304 memcpy(buffer, &output, sizeof(*buffer));
1305 header->len = htobe32(output.size);
1306 return 0;
1307 }
1308
1309 static int cbfs_add(void)
1310 {
1311 convert_buffer_t convert = cbfstool_convert_raw;
1312
1313 if (param.type == CBFS_TYPE_FSP) {
1314 convert = cbfstool_convert_fsp;
1315 } else if (param.type == CBFS_TYPE_STAGE) {
1316 ERROR("stages can only be added with cbfstool add-stage\n");
1317 return 1;
1318 } else if (param.stage_xip) {
1319 ERROR("cbfstool add supports xip only for FSP component type\n");
1320 return 1;
1321 }
1322
1323 return cbfs_add_component(param.filename,
1324 param.name,
1325 param.headeroffset,
1326 convert);
1327 }
1328
1329 static int cbfs_add_stage(void)
1330 {
1331 if (param.stage_xip && param.baseaddress_assigned) {
1332 ERROR("Cannot specify base address for XIP.\n");
1333 return 1;
1334 }
1335 param.type = CBFS_TYPE_STAGE;
1336
1337 return cbfs_add_component(param.filename,
1338 param.name,
1339 param.headeroffset,
1340 cbfstool_convert_mkstage);
1341 }
1342
1343 static int cbfs_add_payload(void)
1344 {
1345 param.type = CBFS_TYPE_SELF;
1346 return cbfs_add_component(param.filename,
1347 param.name,
1348 param.headeroffset,
1349 cbfstool_convert_mkpayload);
1350 }
1351
1352 static int cbfs_add_flat_binary(void)
1353 {
1354 if (param.loadaddress == 0) {
1355 ERROR("You need to specify a valid "
1356 "-l/--load-address.\n");
1357 return 1;
1358 }
1359 if (param.entrypoint == 0) {
1360 ERROR("You need to specify a valid "
1361 "-e/--entry-point.\n");
1362 return 1;
1363 }
1364 param.type = CBFS_TYPE_SELF;
1365 return cbfs_add_component(param.filename,
1366 param.name,
1367 param.headeroffset,
1368 cbfstool_convert_mkflatpayload);
1369 }
1370
1371 static int cbfs_add_integer(void)
1372 {
1373 if (!param.u64val_assigned) {
1374 ERROR("You need to specify a value to write.\n");
1375 return 1;
1376 }
1377 return cbfs_add_integer_component(param.name,
1378 param.u64val,
1379 param.baseaddress,
1380 param.headeroffset);
1381 }
1382
1383 static int cbfs_remove(void)
1384 {
1385 if (!param.name) {
1386 ERROR("You need to specify -n/--name.\n");
1387 return 1;
1388 }
1389
1390 struct cbfs_image image;
1391 if (cbfs_image_from_buffer(&image, param.image_region,
1392 param.headeroffset))
1393 return 1;
1394
1395 if (cbfs_remove_entry(&image, param.name) != 0) {
1396 ERROR("Removing file '%s' failed.\n",
1397 param.name);
1398 return 1;
1399 }
1400
1401 return maybe_update_metadata_hash(&image);
1402 }
1403
1404 static int cbfs_create(void)
1405 {
1406 struct cbfs_image image;
1407 memset(&image, 0, sizeof(image));
1408 buffer_clone(&image.buffer, param.image_region);
1409
1410 if (param.fmap) {
1411 if (param.arch != CBFS_ARCHITECTURE_UNKNOWN || param.size ||
1412 param.baseaddress_assigned ||
1413 param.headeroffset_assigned ||
1414 param.cbfsoffset_assigned ||
1415 param.bootblock) {
1416 ERROR("Since -M was provided, -m, -s, -b, -o, -H, and -B should be omitted\n");
1417 return 1;
1418 }
1419
1420 return cbfs_image_create(&image, image.buffer.size);
1421 }
1422
1423 if (param.arch == CBFS_ARCHITECTURE_UNKNOWN) {
1424 ERROR("You need to specify -m/--machine arch.\n");
1425 return 1;
1426 }
1427
1428 struct buffer bootblock;
1429 if (!param.bootblock) {
1430 DEBUG("-B not given, creating image without bootblock.\n");
1431 if (buffer_create(&bootblock, 0, "(dummy)") != 0)
1432 return 1;
1433 } else if (buffer_from_file(&bootblock, param.bootblock)) {
1434 return 1;
1435 }
1436
1437 if (!param.alignment)
1438 param.alignment = CBFS_ALIGNMENT;
1439
1440 // Set default offsets. x86, as usual, needs to be a special snowflake.
1441 if (!param.baseaddress_assigned) {
1442 if (param.arch == CBFS_ARCHITECTURE_X86) {
1443 // Make sure there's at least enough room for rel_offset
1444 param.baseaddress = param.size -
1445 MAX(bootblock.size, sizeof(int32_t));
1446 DEBUG("x86 -> bootblock lies at end of ROM (%#x).\n",
1447 param.baseaddress);
1448 } else {
1449 param.baseaddress = 0;
1450 DEBUG("bootblock starts at address 0x0.\n");
1451 }
1452 }
1453 if (!param.headeroffset_assigned) {
1454 if (param.arch == CBFS_ARCHITECTURE_X86) {
1455 param.headeroffset = param.baseaddress -
1456 sizeof(struct cbfs_header);
1457 DEBUG("x86 -> CBFS header before bootblock (%#x).\n",
1458 param.headeroffset);
1459 } else {
1460 param.headeroffset = align_up(param.baseaddress +
1461 bootblock.size, sizeof(uint32_t));
1462 DEBUG("CBFS header placed behind bootblock (%#x).\n",
1463 param.headeroffset);
1464 }
1465 }
1466 if (!param.cbfsoffset_assigned) {
1467 if (param.arch == CBFS_ARCHITECTURE_X86) {
1468 param.cbfsoffset = 0;
1469 DEBUG("x86 -> CBFS entries start at address 0x0.\n");
1470 } else {
1471 param.cbfsoffset = align_up(param.headeroffset +
1472 sizeof(struct cbfs_header),
1473 CBFS_ALIGNMENT);
1474 DEBUG("CBFS entries start beind master header (%#x).\n",
1475 param.cbfsoffset);
1476 }
1477 }
1478
1479 int ret = cbfs_legacy_image_create(&image,
1480 param.arch,
1481 CBFS_ALIGNMENT,
1482 &bootblock,
1483 param.baseaddress,
1484 param.headeroffset,
1485 param.cbfsoffset);
1486 buffer_delete(&bootblock);
1487 return ret;
1488 }
1489
1490 static int cbfs_layout(void)
1491 {
1492 const struct fmap *fmap = partitioned_file_get_fmap(param.image_file);
1493 if (!fmap) {
1494 LOG("This is a legacy image composed entirely of a single CBFS.\n");
1495 return 1;
1496 }
1497
1498 printf("This image contains the following sections that can be %s with this tool:\n",
1499 param.show_immutable ? "accessed" : "manipulated");
1500 puts("");
1501 for (unsigned i = 0; i < fmap->nareas; ++i) {
1502 const struct fmap_area *current = fmap->areas + i;
1503
1504 bool readonly = partitioned_file_fmap_count(param.image_file,
1505 partitioned_file_fmap_select_children_of, current) ||
1506 region_is_flashmap((const char *)current->name);
1507 if (!param.show_immutable && readonly)
1508 continue;
1509
1510 printf("'%s'", current->name);
1511
1512 // Detect consecutive sections that describe the same region and
1513 // show them as aliases. This cannot find equivalent entries
1514 // that aren't adjacent; however, fmaptool doesn't generate
1515 // FMAPs with such sections, so this convenience feature works
1516 // for all but the strangest manually created FMAP binaries.
1517 // TODO: This could be done by parsing the FMAP into some kind
1518 // of tree that had duplicate lists in addition to child lists,
1519 // which would allow covering that weird, unlikely case as well.
1520 unsigned lookahead;
1521 for (lookahead = 1; i + lookahead < fmap->nareas;
1522 ++lookahead) {
1523 const struct fmap_area *consecutive =
1524 fmap->areas + i + lookahead;
1525 if (consecutive->offset != current->offset ||
1526 consecutive->size != current->size)
1527 break;
1528 printf(", '%s'", consecutive->name);
1529 }
1530 if (lookahead > 1)
1531 fputs(" are aliases for the same region", stdout);
1532
1533 const char *qualifier = "";
1534 if (readonly)
1535 qualifier = "read-only, ";
1536 else if (region_is_modern_cbfs((const char *)current->name))
1537 qualifier = "CBFS, ";
1538 else if (current->flags & FMAP_AREA_PRESERVE)
1539 qualifier = "preserve, ";
1540 printf(" (%ssize %u, offset %u)\n", qualifier, current->size,
1541 current->offset);
1542
1543 i += lookahead - 1;
1544 }
1545 puts("");
1546
1547 if (param.show_immutable) {
1548 puts("It is at least possible to perform the read action on every section listed above.");
1549 } else {
1550 puts("It is possible to perform either the write action or the CBFS add/remove actions on every section listed above.");
1551 puts("To see the image's read-only sections as well, rerun with the -w option.");
1552 }
1553
1554 return 0;
1555 }
1556
1557 static enum cb_err verify_walker(__always_unused cbfs_dev_t dev, size_t offset,
1558 const union cbfs_mdata *mdata, size_t already_read, void *arg)
1559 {
1560 uint32_t type = be32toh(mdata->h.type);
1561 uint32_t data_offset = be32toh(mdata->h.offset);
1562 if (verification_exclude(type))
1563 return CB_CBFS_NOT_FOUND;
1564 assert(already_read == data_offset);
1565 const struct vb2_hash *hash = cbfs_file_hash(mdata);
1566 if (!hash)
1567 return CB_ERR;
1568 void *file_data = arg + offset + data_offset;
1569 if (vb2_hash_verify(false, file_data, be32toh(mdata->h.len), hash) != VB2_SUCCESS)
1570 return CB_CBFS_HASH_MISMATCH;
1571 return CB_CBFS_NOT_FOUND;
1572 }
1573
1574 static int cbfs_print(void)
1575 {
1576 struct cbfs_image image;
1577 if (cbfs_image_from_buffer(&image, param.image_region,
1578 param.headeroffset))
1579 return 1;
1580 if (param.machine_parseable) {
1581 if (verbose)
1582 printf("[FMAP REGION]\t%s\n", param.region_name);
1583 cbfs_print_parseable_directory(&image);
1584 } else {
1585 printf("FMAP REGION: %s\n", param.region_name);
1586 cbfs_print_directory(&image);
1587 }
1588
1589 if (verbose) {
1590 const char *verification_state = "fully valid";
1591 struct mh_cache *mhc = get_mh_cache();
1592 if (mhc->cbfs_hash.algo == VB2_HASH_INVALID)
1593 return 0;
1594
1595 struct vb2_hash real_hash = { .algo = mhc->cbfs_hash.algo };
1596 enum cb_err err = cbfs_walk(&image, verify_walker, buffer_get(&image.buffer),
1597 &real_hash, CBFS_WALK_WRITEBACK_HASH);
1598 if (err == CB_CBFS_HASH_MISMATCH)
1599 verification_state = "invalid file hashes";
1600 else if (err != CB_CBFS_NOT_FOUND)
1601 verification_state = "missing file hashes";
1602 char *hash_str = bintohex(real_hash.raw,
1603 vb2_digest_size(real_hash.algo));
1604 printf("[METADATA HASH]\t%s:%s",
1605 vb2_get_hash_algorithm_name(real_hash.algo), hash_str);
1606 if (!strcmp(param.region_name, SECTION_NAME_PRIMARY_CBFS)) {
1607 if (!memcmp(mhc->cbfs_hash.raw, real_hash.raw,
1608 vb2_digest_size(real_hash.algo))) {
1609 printf(":valid");
1610 } else {
1611 printf(":invalid");
1612 verification_state = "invalid metadata hash";
1613 }
1614 }
1615 printf("\n");
1616 printf("[CBFS VERIFICATION (%s)]\t%s\n", param.region_name, verification_state);
1617 free(hash_str);
1618 }
1619
1620 return 0;
1621 }
1622
1623 static int cbfs_extract(void)
1624 {
1625 if (!param.filename) {
1626 ERROR("You need to specify -f/--filename.\n");
1627 return 1;
1628 }
1629
1630 if (!param.name) {
1631 ERROR("You need to specify -n/--name.\n");
1632 return 1;
1633 }
1634
1635 struct cbfs_image image;
1636 if (cbfs_image_from_buffer(&image, param.image_region,
1637 param.headeroffset))
1638 return 1;
1639
1640 return cbfs_export_entry(&image, param.name, param.filename,
1641 param.arch, !param.unprocessed);
1642 }
1643
1644 static int cbfs_write(void)
1645 {
1646 if (!param.filename) {
1647 ERROR("You need to specify a valid input -f/--file.\n");
1648 return 1;
1649 }
1650 if (!partitioned_file_is_partitioned(param.image_file)) {
1651 ERROR("This operation isn't valid on legacy images having CBFS master headers\n");
1652 return 1;
1653 }
1654
1655 if (!param.force && region_is_modern_cbfs(param.region_name)) {
1656 ERROR("Target image region '%s' is a CBFS and must be manipulated using add and remove\n",
1657 param.region_name);
1658 return 1;
1659 }
1660
1661 struct buffer new_content;
1662 if (buffer_from_file(&new_content, param.filename))
1663 return 1;
1664
1665 if (buffer_check_magic(&new_content, FMAP_SIGNATURE,
1666 strlen(FMAP_SIGNATURE))) {
1667 ERROR("File '%s' appears to be an FMAP and cannot be added to an existing image\n",
1668 param.filename);
1669 buffer_delete(&new_content);
1670 return 1;
1671 }
1672 if (!param.force && buffer_check_magic(&new_content, CBFS_FILE_MAGIC,
1673 strlen(CBFS_FILE_MAGIC))) {
1674 ERROR("File '%s' appears to be a CBFS and cannot be inserted into a raw region\n",
1675 param.filename);
1676 buffer_delete(&new_content);
1677 return 1;
1678 }
1679
1680 unsigned offset = 0;
1681 if (param.fill_partial_upward && param.fill_partial_downward) {
1682 ERROR("You may only specify one of -u and -d.\n");
1683 buffer_delete(&new_content);
1684 return 1;
1685 } else if (!param.fill_partial_upward && !param.fill_partial_downward) {
1686 if (new_content.size != param.image_region->size) {
1687 ERROR("File to add is %zu bytes and would not fill %zu-byte target region (did you mean to pass either -u or -d?)\n",
1688 new_content.size, param.image_region->size);
1689 buffer_delete(&new_content);
1690 return 1;
1691 }
1692 } else {
1693 if (new_content.size > param.image_region->size) {
1694 ERROR("File to add is %zu bytes and would overflow %zu-byte target region\n",
1695 new_content.size, param.image_region->size);
1696 buffer_delete(&new_content);
1697 return 1;
1698 }
1699 if (param.u64val == (uint64_t)-1) {
1700 WARN("Written area will abut %s of target region: any unused space will keep its current contents\n",
1701 param.fill_partial_upward ? "bottom" : "top");
1702 } else if (param.u64val > 0xff) {
1703 ERROR("given fill value (%x) is larger than a byte\n", (unsigned)(param.u64val & 0xff));
1704 buffer_delete(&new_content);
1705 return 1;
1706 } else {
1707 memset(buffer_get(param.image_region),
1708 param.u64val & 0xff,
1709 buffer_size(param.image_region));
1710 }
1711 if (param.fill_partial_downward)
1712 offset = param.image_region->size - new_content.size;
1713 }
1714
1715 memcpy(param.image_region->data + offset, new_content.data,
1716 new_content.size);
1717 buffer_delete(&new_content);
1718
1719 return maybe_update_fmap_hash();
1720 }
1721
1722 static int cbfs_read(void)
1723 {
1724 if (!param.filename) {
1725 ERROR("You need to specify a valid output -f/--file.\n");
1726 return 1;
1727 }
1728 if (!partitioned_file_is_partitioned(param.image_file)) {
1729 ERROR("This operation isn't valid on legacy images having CBFS master headers\n");
1730 return 1;
1731 }
1732
1733 return buffer_write_file(param.image_region, param.filename);
1734 }
1735
1736 static int cbfs_copy(void)
1737 {
1738 struct cbfs_image src_image;
1739 struct buffer src_buf;
1740
1741 if (!param.source_region) {
1742 ERROR("You need to specify -R/--source-region.\n");
1743 return 1;
1744 }
1745
1746 /* Obtain the source region and convert it to a cbfs_image. */
1747 if (!partitioned_file_read_region(&src_buf, param.image_file,
1748 param.source_region)) {
1749 ERROR("Region not found in image: %s\n", param.source_region);
1750 return 1;
1751 }
1752
1753 if (cbfs_image_from_buffer(&src_image, &src_buf, param.headeroffset))
1754 return 1;
1755
1756 return cbfs_copy_instance(&src_image, param.image_region);
1757 }
1758
1759 static int cbfs_compact(void)
1760 {
1761 struct cbfs_image image;
1762 if (cbfs_image_from_buffer(&image, param.image_region,
1763 param.headeroffset))
1764 return 1;
1765 WARN("Compacting a CBFS doesn't honor alignment or fixed addresses!\n");
1766 return cbfs_compact_instance(&image);
1767 }
1768
1769 static int cbfs_expand(void)
1770 {
1771 struct buffer src_buf;
1772
1773 /* Obtain the source region. */
1774 if (!partitioned_file_read_region(&src_buf, param.image_file,
1775 param.region_name)) {
1776 ERROR("Region not found in image: %s\n", param.source_region);
1777 return 1;
1778 }
1779
1780 return cbfs_expand_to_region(param.image_region);
1781 }
1782
1783 static int cbfs_truncate(void)
1784 {
1785 struct buffer src_buf;
1786
1787 /* Obtain the source region. */
1788 if (!partitioned_file_read_region(&src_buf, param.image_file,
1789 param.region_name)) {
1790 ERROR("Region not found in image: %s\n", param.source_region);
1791 return 1;
1792 }
1793
1794 uint32_t size;
1795 int result = cbfs_truncate_space(param.image_region, &size);
1796 if (!result)
1797 printf("0x%x\n", size);
1798 return result;
1799 }
1800
1801 static const struct command commands[] = {
1802 {"add", "H:r:f:n:t:c:b:a:p:yvA:j:gh?", cbfs_add, true, true},
1803 {"add-flat-binary", "H:r:f:n:l:e:c:b:p:vA:gh?", cbfs_add_flat_binary,
1804 true, true},
1805 {"add-payload", "H:r:f:n:c:b:a:C:I:p:vA:gh?", cbfs_add_payload,
1806 true, true},
1807 {"add-stage", "a:H:r:f:n:t:c:b:P:QS:p:yvA:gh?", cbfs_add_stage,
1808 true, true},
1809 {"add-int", "H:r:i:n:b:vgh?", cbfs_add_integer, true, true},
1810 {"add-master-header", "H:r:vh?j:", cbfs_add_master_header, true, true},
1811 {"compact", "r:h?", cbfs_compact, true, true},
1812 {"copy", "r:R:h?", cbfs_copy, true, true},
1813 {"create", "M:r:s:B:b:H:o:m:vh?", cbfs_create, true, true},
1814 {"extract", "H:r:m:n:f:Uvh?", cbfs_extract, true, false},
1815 {"layout", "wvh?", cbfs_layout, false, false},
1816 {"print", "H:r:vkh?", cbfs_print, true, false},
1817 {"read", "r:f:vh?", cbfs_read, true, false},
1818 {"remove", "H:r:n:vh?", cbfs_remove, true, true},
1819 {"write", "r:f:i:Fudvh?", cbfs_write, true, true},
1820 {"expand", "r:h?", cbfs_expand, true, true},
1821 {"truncate", "r:h?", cbfs_truncate, true, true},
1822 };
1823
1824 enum {
1825 /* begin after ASCII characters */
1826 LONGOPT_START = 256,
1827 LONGOPT_IBB = LONGOPT_START,
1828 LONGOPT_MMAP,
1829 LONGOPT_END,
1830 };
1831
1832 static struct option long_options[] = {
1833 {"alignment", required_argument, 0, 'a' },
1834 {"base-address", required_argument, 0, 'b' },
1835 {"bootblock", required_argument, 0, 'B' },
1836 {"cmdline", required_argument, 0, 'C' },
1837 {"compression", required_argument, 0, 'c' },
1838 {"topswap-size", required_argument, 0, 'j' },
1839 {"empty-fits", required_argument, 0, 'x' },
1840 {"entry-point", required_argument, 0, 'e' },
1841 {"file", required_argument, 0, 'f' },
1842 {"fill-downward", no_argument, 0, 'd' },
1843 {"fill-upward", no_argument, 0, 'u' },
1844 {"flashmap", required_argument, 0, 'M' },
1845 {"fmap-regions", required_argument, 0, 'r' },
1846 {"force", no_argument, 0, 'F' },
1847 {"source-region", required_argument, 0, 'R' },
1848 {"hash-algorithm",required_argument, 0, 'A' },
1849 {"header-offset", required_argument, 0, 'H' },
1850 {"help", no_argument, 0, 'h' },
1851 {"ignore-sec", required_argument, 0, 'S' },
1852 {"initrd", required_argument, 0, 'I' },
1853 {"int", required_argument, 0, 'i' },
1854 {"load-address", required_argument, 0, 'l' },
1855 {"machine", required_argument, 0, 'm' },
1856 {"name", required_argument, 0, 'n' },
1857 {"offset", required_argument, 0, 'o' },
1858 {"padding", required_argument, 0, 'p' },
1859 {"pow2page", no_argument, 0, 'Q' },
1860 {"ucode-region", required_argument, 0, 'q' },
1861 {"size", required_argument, 0, 's' },
1862 {"type", required_argument, 0, 't' },
1863 {"verbose", no_argument, 0, 'v' },
1864 {"with-readonly", no_argument, 0, 'w' },
1865 {"xip", no_argument, 0, 'y' },
1866 {"gen-attribute", no_argument, 0, 'g' },
1867 {"mach-parseable",no_argument, 0, 'k' },
1868 {"unprocessed", no_argument, 0, 'U' },
1869 {"ibb", no_argument, 0, LONGOPT_IBB },
1870 {"mmap", required_argument, 0, LONGOPT_MMAP },
1871 {NULL, 0, 0, 0 }
1872 };
1873
1874 static int get_region_offset(long long int offset, uint32_t *region_offset)
1875 {
1876 /* If offset is not negative, no transformation required. */
1877 if (offset >= 0) {
1878 *region_offset = offset;
1879 return 0;
1880 }
1881
1882 /* Calculate offset from start of region. */
1883 return convert_region_offset(-offset, region_offset);
1884 }
1885
1886 static int calculate_region_offsets(void)
1887 {
1888 int ret = 0;
1889
1890 if (param.baseaddress_assigned)
1891 ret |= get_region_offset(param.baseaddress_input, &param.baseaddress);
1892 if (param.headeroffset_assigned)
1893 ret |= get_region_offset(param.headeroffset_input, &param.headeroffset);
1894 if (param.cbfsoffset_assigned)
1895 ret |= get_region_offset(param.cbfsoffset_input, &param.cbfsoffset);
1896
1897 return ret;
1898 }
1899
1900 static int dispatch_command(struct command command)
1901 {
1902 if (command.accesses_region) {
1903 assert(param.image_file);
1904
1905 if (partitioned_file_is_partitioned(param.image_file)) {
1906 INFO("Performing operation on '%s' region...\n",
1907 param.region_name);
1908 }
1909 if (!partitioned_file_read_region(param.image_region,
1910 param.image_file, param.region_name)) {
1911 ERROR("The image will be left unmodified.\n");
1912 return 1;
1913 }
1914
1915 if (command.modifies_region) {
1916 // We (intentionally) don't support overwriting the FMAP
1917 // section. If you find yourself wanting to do this,
1918 // consider creating a new image rather than performing
1919 // whatever hacky transformation you were planning.
1920 if (region_is_flashmap(param.region_name)) {
1921 ERROR("Image region '%s' is read-only because it contains the FMAP.\n",
1922 param.region_name);
1923 ERROR("The image will be left unmodified.\n");
1924 return 1;
1925 }
1926 // We don't allow writing raw data to regions that
1927 // contain nested regions, since doing so would
1928 // overwrite all such subregions.
1929 if (partitioned_file_region_contains_nested(
1930 param.image_file, param.region_name)) {
1931 ERROR("Image region '%s' is read-only because it contains nested regions.\n",
1932 param.region_name);
1933 ERROR("The image will be left unmodified.\n");
1934 return 1;
1935 }
1936 }
1937
1938 /*
1939 * Once image region is read, input offsets can be adjusted accordingly if the
1940 * inputs are provided as negative integers i.e. offsets from end of region.
1941 */
1942 if (calculate_region_offsets())
1943 return 1;
1944 }
1945
1946 if (command.function()) {
1947 if (partitioned_file_is_partitioned(param.image_file)) {
1948 ERROR("Failed while operating on '%s' region!\n",
1949 param.region_name);
1950 ERROR("The image will be left unmodified.\n");
1951 }
1952 return 1;
1953 }
1954
1955 return 0;
1956 }
1957
1958 static void usage(char *name)
1959 {
1960 printf
1961 ("cbfstool: Management utility for CBFS formatted ROM images\n\n"
1962 "USAGE:\n" " %s [-h]\n"
1963 " %s FILE COMMAND [-v] [PARAMETERS]...\n\n" "OPTIONs:\n"
1964 " -H header_offset Do not search for header; use this offset*\n"
1965 " -T Output top-aligned memory address\n"
1966 " -u Accept short data; fill upward/from bottom\n"
1967 " -d Accept short data; fill downward/from top\n"
1968 " -F Force action\n"
1969 " -g Generate position and alignment arguments\n"
1970 " -U Unprocessed; don't decompress or make ELF\n"
1971 " -v Provide verbose output (-v=INFO -vv=DEBUG output)\n"
1972 " -h Display this help message\n\n"
1973 "COMMANDs:\n"
1974 " add [-r image,regions] -f FILE -n NAME -t TYPE [-A hash] \\\n"
1975 " [-c compression] [-b base-address | -a alignment] \\\n"
1976 " [-p padding size] [-y|--xip if TYPE is FSP] \\\n"
1977 " [-j topswap-size] (Intel CPUs only) [--ibb] \\\n"
1978 " [--mmap flash-base:mmio-base:size] "
1979 "Add a component\n"
1980 " "
1981 " -j valid size: 0x10000 0x20000 0x40000 0x80000 0x100000 \n"
1982 " add-payload [-r image,regions] -f FILE -n NAME [-A hash] \\\n"
1983 " [-c compression] [-b base-address] \\\n"
1984 " (linux specific: [-C cmdline] [-I initrd]) "
1985 "Add a payload to the ROM\n"
1986 " add-stage [-r image,regions] -f FILE -n NAME [-A hash] \\\n"
1987 " [-c compression] [-b base] \\\n"
1988 " [-S comma-separated-section(s)-to-ignore] \\\n"
1989 " [-a alignment] [-Q|--pow2page] \\\n"
1990 " [-y|--xip] [--ibb] \\\n"
1991 " [--mmap flash-base:mmio-base:size] "
1992 "Add a stage to the ROM\n"
1993 " add-flat-binary [-r image,regions] -f FILE -n NAME \\\n"
1994 " [-A hash] -l load-address -e entry-point \\\n"
1995 " [-c compression] [-b base] "
1996 "Add a 32bit flat mode binary\n"
1997 " add-int [-r image,regions] -i INTEGER -n NAME [-b base] "
1998 "Add a raw 64-bit integer value\n"
1999 " add-master-header [-r image,regions] \\ \n"
2000 " [-j topswap-size] (Intel CPUs only) "
2001 "Add a legacy CBFS master header\n"
2002 " remove [-r image,regions] -n NAME "
2003 "Remove a component\n"
2004 " compact -r image,regions "
2005 "Defragment CBFS image.\n"
2006 " copy -r image,regions -R source-region "
2007 "Create a copy (duplicate) cbfs instance in fmap\n"
2008 " create -m ARCH -s size [-b bootblock offset] \\\n"
2009 " [-o CBFS offset] [-H header offset] [-B bootblock] "
2010 "Create a legacy ROM file with CBFS master header*\n"
2011 " create -M flashmap [-r list,of,regions,containing,cbfses] "
2012 "Create a new-style partitioned firmware image\n"
2013 " layout [-w] "
2014 "List mutable (or, with -w, readable) image regions\n"
2015 " print [-r image,regions] [-k] "
2016 "Show the contents of the ROM\n"
2017 " extract [-r image,regions] [-m ARCH] -n NAME -f FILE [-U] "
2018 "Extracts a file from ROM\n"
2019 " write [-F] -r image,regions -f file [-u | -d] [-i int] "
2020 "Write file into same-size [or larger] raw region\n"
2021 " read [-r fmap-region] -f file "
2022 "Extract raw region contents into binary file\n"
2023 " truncate [-r fmap-region] "
2024 "Truncate CBFS and print new size on stdout\n"
2025 " expand [-r fmap-region] "
2026 "Expand CBFS to span entire region\n"
2027 "OFFSETs:\n"
2028 " Numbers accompanying -b, -H, and -o switches* may be provided\n"
2029 " in two possible formats: if their value is greater than\n"
2030 " 0x80000000, they are interpreted as a top-aligned x86 memory\n"
2031 " address; otherwise, they are treated as an offset into flash.\n"
2032 "ARCHes:\n", name, name
2033 );
2034 print_supported_architectures();
2035
2036 printf("TYPEs:\n");
2037 print_supported_filetypes();
2038 printf(
2039 "\n* Note that these actions and switches are only valid when\n"
2040 " working with legacy images whose structure is described\n"
2041 " primarily by a CBFS master header. New-style images, in\n"
2042 " contrast, exclusively make use of an FMAP to describe their\n"
2043 " layout: this must minimally contain an '%s' section\n"
2044 " specifying the location of this FMAP itself and a '%s'\n"
2045 " section describing the primary CBFS. It should also be noted\n"
2046 " that, when working with such images, the -F and -r switches\n"
2047 " default to '%s' for convenience, and the -b switch becomes\n"
2048 " relative to the selected CBFS region's lowest address.\n"
2049 " The one exception to this rule is the top-aligned address,\n"
2050 " which is always relative to the end of the entire image\n"
2051 " rather than relative to the local region; this is true for\n"
2052 " for both input (sufficiently large) and output (-T) data.\n",
2053 SECTION_NAME_FMAP, SECTION_NAME_PRIMARY_CBFS,
2054 SECTION_NAME_PRIMARY_CBFS
2055 );
2056 }
2057
2058 static bool valid_opt(size_t i, int c)
2059 {
2060 /* Check if it is one of the optstrings supported by the command. */
2061 if (strchr(commands[i].optstring, c))
2062 return true;
2063
2064 /*
2065 * Check if it is one of the non-ASCII characters. Currently, the
2066 * non-ASCII characters are only checked against the valid list
2067 * irrespective of the command.
2068 */
2069 if (c >= LONGOPT_START && c < LONGOPT_END)
2070 return true;
2071
2072 return false;
2073 }
2074
2075 int main(int argc, char **argv)
2076 {
2077 size_t i;
2078 int c;
2079
2080 if (argc < 3) {
2081 usage(argv[0]);
2082 return 1;
2083 }
2084
2085 char *image_name = argv[1];
2086 char *cmd = argv[2];
2087 optind += 2;
2088
2089 for (i = 0; i < ARRAY_SIZE(commands); i++) {
2090 if (strcmp(cmd, commands[i].name) != 0)
2091 continue;
2092
2093 while (1) {
2094 char *suffix = NULL;
2095 int option_index = 0;
2096
2097 c = getopt_long(argc, argv, commands[i].optstring,
2098 long_options, &option_index);
2099 if (c == -1) {
2100 if (optind < argc) {
2101 ERROR("%s: excessive argument -- '%s'"
2102 "\n", argv[0], argv[optind]);
2103 return 1;
2104 }
2105 break;
2106 }
2107
2108 /* Filter out illegal long options */
2109 if (!valid_opt(i, c)) {
2110 ERROR("%s: invalid option -- '%d'\n",
2111 argv[0], c);
2112 c = '?';
2113 }
2114
2115 switch(c) {
2116 case 'n':
2117 param.name = optarg;
2118 break;
2119 case 't':
2120 if (intfiletype(optarg) != ((uint64_t) - 1))
2121 param.type = intfiletype(optarg);
2122 else
2123 param.type = strtoul(optarg, NULL, 0);
2124 if (param.type == 0)
2125 WARN("Unknown type '%s' ignored\n",
2126 optarg);
2127 break;
2128 case 'c': {
2129 if (strcmp(optarg, "precompression") == 0) {
2130 param.precompression = 1;
2131 break;
2132 }
2133 int algo = cbfs_parse_comp_algo(optarg);
2134 if (algo >= 0)
2135 param.compression = algo;
2136 else
2137 WARN("Unknown compression '%s' ignored.\n",
2138 optarg);
2139 break;
2140 }
2141 case 'A': {
2142 if (!vb2_lookup_hash_alg(optarg, &param.hash)) {
2143 ERROR("Unknown hash algorithm '%s'.\n",
2144 optarg);
2145 return 1;
2146 }
2147 break;
2148 }
2149 case 'M':
2150 param.fmap = optarg;
2151 break;
2152 case 'r':
2153 param.region_name = optarg;
2154 break;
2155 case 'R':
2156 param.source_region = optarg;
2157 break;
2158 case 'b':
2159 param.baseaddress_input = strtoll(optarg, &suffix, 0);
2160 if (!*optarg || (suffix && *suffix)) {
2161 ERROR("Invalid base address '%s'.\n",
2162 optarg);
2163 return 1;
2164 }
2165 // baseaddress may be zero on non-x86, so we
2166 // need an explicit "baseaddress_assigned".
2167 param.baseaddress_assigned = 1;
2168 break;
2169 case 'l':
2170 param.loadaddress = strtoull(optarg, &suffix, 0);
2171 if (!*optarg || (suffix && *suffix)) {
2172 ERROR("Invalid load address '%s'.\n",
2173 optarg);
2174 return 1;
2175 }
2176 break;
2177 case 'e':
2178 param.entrypoint = strtoull(optarg, &suffix, 0);
2179 if (!*optarg || (suffix && *suffix)) {
2180 ERROR("Invalid entry point '%s'.\n",
2181 optarg);
2182 return 1;
2183 }
2184 break;
2185 case 's':
2186 param.size = strtoul(optarg, &suffix, 0);
2187 if (!*optarg) {
2188 ERROR("Empty size specified.\n");
2189 return 1;
2190 }
2191 switch (tolower((int)suffix[0])) {
2192 case 'k':
2193 param.size *= 1024;
2194 break;
2195 case 'm':
2196 param.size *= 1024 * 1024;
2197 break;
2198 case '\0':
2199 break;
2200 default:
2201 ERROR("Invalid suffix for size '%s'.\n",
2202 optarg);
2203 return 1;
2204 }
2205 break;
2206 case 'B':
2207 param.bootblock = optarg;
2208 break;
2209 case 'H':
2210 param.headeroffset_input = strtoll(optarg, &suffix, 0);
2211 if (!*optarg || (suffix && *suffix)) {
2212 ERROR("Invalid header offset '%s'.\n",
2213 optarg);
2214 return 1;
2215 }
2216 param.headeroffset_assigned = 1;
2217 break;
2218 case 'a':
2219 param.alignment = strtoul(optarg, &suffix, 0);
2220 if (!*optarg || (suffix && *suffix)) {
2221 ERROR("Invalid alignment '%s'.\n",
2222 optarg);
2223 return 1;
2224 }
2225 break;
2226 case 'p':
2227 param.padding = strtoul(optarg, &suffix, 0);
2228 if (!*optarg || (suffix && *suffix)) {
2229 ERROR("Invalid pad size '%s'.\n",
2230 optarg);
2231 return 1;
2232 }
2233 break;
2234 case 'Q':
2235 param.force_pow2_pagesize = 1;
2236 break;
2237 case 'o':
2238 param.cbfsoffset_input = strtoll(optarg, &suffix, 0);
2239 if (!*optarg || (suffix && *suffix)) {
2240 ERROR("Invalid cbfs offset '%s'.\n",
2241 optarg);
2242 return 1;
2243 }
2244 param.cbfsoffset_assigned = 1;
2245 break;
2246 case 'f':
2247 param.filename = optarg;
2248 break;
2249 case 'F':
2250 param.force = 1;
2251 break;
2252 case 'i':
2253 param.u64val = strtoull(optarg, &suffix, 0);
2254 param.u64val_assigned = 1;
2255 if (!*optarg || (suffix && *suffix)) {
2256 ERROR("Invalid int parameter '%s'.\n",
2257 optarg);
2258 return 1;
2259 }
2260 break;
2261 case 'u':
2262 param.fill_partial_upward = true;
2263 break;
2264 case 'd':
2265 param.fill_partial_downward = true;
2266 break;
2267 case 'w':
2268 param.show_immutable = true;
2269 break;
2270 case 'j':
2271 param.topswap_size = strtol(optarg, NULL, 0);
2272 if (!is_valid_topswap())
2273 return 1;
2274 break;
2275 case 'q':
2276 param.ucode_region = optarg;
2277 break;
2278 case 'v':
2279 verbose++;
2280 break;
2281 case 'm':
2282 param.arch = string_to_arch(optarg);
2283 break;
2284 case 'I':
2285 param.initrd = optarg;
2286 break;
2287 case 'C':
2288 param.cmdline = optarg;
2289 break;
2290 case 'S':
2291 param.ignore_sections = optarg;
2292 break;
2293 case 'y':
2294 param.stage_xip = true;
2295 break;
2296 case 'g':
2297 param.autogen_attr = true;
2298 break;
2299 case 'k':
2300 param.machine_parseable = true;
2301 break;
2302 case 'U':
2303 param.unprocessed = true;
2304 break;
2305 case LONGOPT_IBB:
2306 param.ibb = true;
2307 break;
2308 case LONGOPT_MMAP:
2309 if (decode_mmap_arg(optarg))
2310 return 1;
2311 break;
2312 case 'h':
2313 case '?':
2314 usage(argv[0]);
2315 return 1;
2316 default:
2317 break;
2318 }
2319 }
2320
2321 if (commands[i].function == cbfs_create) {
2322 if (param.fmap) {
2323 struct buffer flashmap;
2324 if (buffer_from_file(&flashmap, param.fmap))
2325 return 1;
2326 param.image_file = partitioned_file_create(
2327 image_name, &flashmap);
2328 buffer_delete(&flashmap);
2329 } else if (param.size) {
2330 param.image_file = partitioned_file_create_flat(
2331 image_name, param.size);
2332 } else {
2333 ERROR("You need to specify a valid -M/--flashmap or -s/--size.\n");
2334 return 1;
2335 }
2336 } else {
2337 bool write_access = commands[i].modifies_region;
2338
2339 param.image_file =
2340 partitioned_file_reopen(image_name,
2341 write_access);
2342 }
2343 if (!param.image_file)
2344 return 1;
2345
2346 unsigned num_regions = 1;
2347 for (const char *list = strchr(param.region_name, ','); list;
2348 list = strchr(list + 1, ','))
2349 ++num_regions;
2350
2351 // If the action needs to read an image region, as indicated by
2352 // having accesses_region set in its command struct, that
2353 // region's buffer struct will be stored here and the client
2354 // will receive a pointer to it via param.image_region. It
2355 // need not write the buffer back to the image file itself,
2356 // since this behavior can be requested via its modifies_region
2357 // field. Additionally, it should never free the region buffer,
2358 // as that is performed automatically once it completes.
2359 struct buffer image_regions[num_regions];
2360 memset(image_regions, 0, sizeof(image_regions));
2361
2362 bool seen_primary_cbfs = false;
2363 char region_name_scratch[strlen(param.region_name) + 1];
2364 strcpy(region_name_scratch, param.region_name);
2365 param.region_name = strtok(region_name_scratch, ",");
2366 for (unsigned region = 0; region < num_regions; ++region) {
2367 if (!param.region_name) {
2368 ERROR("Encountered illegal degenerate region name in -r list\n");
2369 ERROR("The image will be left unmodified.\n");
2370 partitioned_file_close(param.image_file);
2371 return 1;
2372 }
2373
2374 if (strcmp(param.region_name, SECTION_NAME_PRIMARY_CBFS)
2375 == 0)
2376 seen_primary_cbfs = true;
2377
2378 param.image_region = image_regions + region;
2379 if (dispatch_command(commands[i])) {
2380 partitioned_file_close(param.image_file);
2381 return 1;
2382 }
2383
2384 param.region_name = strtok(NULL, ",");
2385 }
2386
2387 if (commands[i].function == cbfs_create && !seen_primary_cbfs) {
2388 ERROR("The creation -r list must include the mandatory '%s' section.\n",
2389 SECTION_NAME_PRIMARY_CBFS);
2390 ERROR("The image will be left unmodified.\n");
2391 partitioned_file_close(param.image_file);
2392 return 1;
2393 }
2394
2395 if (commands[i].modifies_region) {
2396 assert(param.image_file);
2397 for (unsigned region = 0; region < num_regions;
2398 ++region) {
2399
2400 if (!partitioned_file_write_region(
2401 param.image_file,
2402 image_regions + region)) {
2403 partitioned_file_close(
2404 param.image_file);
2405 return 1;
2406 }
2407 }
2408 }
2409
2410 partitioned_file_close(param.image_file);
2411 return 0;
2412 }
2413
2414 ERROR("Unknown command '%s'.\n", cmd);
2415 usage(argv[0]);
2416 return 1;
2417 }