blob: 9bf3688304904c673790d899deb6761cd4b88fb6 [file] [log] [blame]
Hung-Te Lineab2c812013-01-29 01:56:17 +08001/*
2 * CBFS Image Manipulation
3 *
4 * Copyright (C) 2013 The Chromium OS Authors. All rights reserved.
Werner Zeh95bfcae2016-01-25 12:47:20 +01005 * Copyright (C) 2016 Siemens AG. All rights reserved.
Philipp Deppenwiese7ba58712018-11-20 13:54:49 +01006 * Copyright (C) 2019 9elements Agency GmbH
7 * Copyright (C) 2019 Facebook Inc.
Hung-Te Lineab2c812013-01-29 01:56:17 +08008 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; version 2 of the License.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
Hung-Te Lineab2c812013-01-29 01:56:17 +080017 */
18
Hung-Te Lin3bb035b2013-01-29 02:15:49 +080019#include <inttypes.h>
20#include <libgen.h>
Patrick Georgicccc9d42015-04-28 13:09:36 +020021#include <stddef.h>
Hung-Te Lineab2c812013-01-29 01:56:17 +080022#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
Sol Boucher0e539312015-03-05 15:38:03 -080025#include <strings.h>
Antonello Dettorifda691e2016-06-09 12:35:36 +020026#include <commonlib/endian.h>
Joel Kitching2eb89c82019-04-25 17:45:12 +080027#include <vb2_sha.h>
Hung-Te Lineab2c812013-01-29 01:56:17 +080028
29#include "common.h"
30#include "cbfs_image.h"
Aaron Durbin5a1e85c2015-10-27 21:02:30 -050031#include "elfparsing.h"
Aaron Durbin694fd132015-10-28 11:39:34 -050032#include "rmodule.h"
Hung-Te Lineab2c812013-01-29 01:56:17 +080033
Sol Boucher636cc852015-04-03 09:13:04 -070034/* Even though the file-adding functions---cbfs_add_entry() and
35 * cbfs_add_entry_at()---perform their sizing checks against the beginning of
36 * the subsequent section rather than a stable recorded value such as an empty
37 * file header's len field, it's possible to prove two interesting properties
38 * about their behavior:
39 * - Placing a new file within an empty entry located below an existing file
40 * entry will never leave an aligned flash address containing neither the
41 * beginning of a file header nor part of a file.
42 * - Placing a new file in an empty entry at the very end of the image such
43 * that it fits, but leaves no room for a final header, is guaranteed not to
44 * change the total amount of space for entries, even if that new file is
45 * later removed from the CBFS.
46 * These properties are somewhat nonobvious from the implementation, so the
47 * reader is encouraged to blame this comment and examine the full proofs
48 * in the commit message before making significant changes that would risk
49 * removing said guarantees.
50 */
51
Hung-Te Lineab2c812013-01-29 01:56:17 +080052/* The file name align is not defined in CBFS spec -- only a preference by
53 * (old) cbfstool. */
54#define CBFS_FILENAME_ALIGN (16)
55
Ronald G. Minnichaa2f7392013-12-03 11:13:35 -080056static const char *lookup_name_by_type(const struct typedesc_t *desc, uint32_t type,
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -070057 const char *default_value)
58{
Hung-Te Lin3bb035b2013-01-29 02:15:49 +080059 int i;
60 for (i = 0; desc[i].name; i++)
61 if (desc[i].type == type)
62 return desc[i].name;
63 return default_value;
64}
65
Sol Boucherec424862015-05-07 21:00:05 -070066static int lookup_type_by_name(const struct typedesc_t *desc, const char *name)
67{
68 int i;
69 for (i = 0; desc[i].name && strcasecmp(name, desc[i].name); ++i);
70 return desc[i].name ? (int)desc[i].type : -1;
71}
72
Stefan Reinauer2dd161f2015-03-04 00:55:03 +010073static const char *get_cbfs_entry_type_name(uint32_t type)
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -070074{
Patrick Georgidc37dab2015-09-09 16:46:00 +020075 return lookup_name_by_type(filetypes, type, "(unknown)");
Hung-Te Lin3bb035b2013-01-29 02:15:49 +080076}
77
Sol Boucherec424862015-05-07 21:00:05 -070078int cbfs_parse_comp_algo(const char *name)
79{
80 return lookup_type_by_name(types_cbfs_compression, name);
81}
82
Patrick Georgi89f20342015-10-01 15:54:04 +020083static const char *get_hash_attr_name(uint16_t hash_type)
84{
85 return lookup_name_by_type(types_cbfs_hash, hash_type, "(invalid)");
86}
87
88int cbfs_parse_hash_algo(const char *name)
89{
90 return lookup_type_by_name(types_cbfs_hash, name);
91}
92
Hung-Te Linc03d9b02013-01-29 02:38:40 +080093/* CBFS image */
94
Patrick Georgi11ee08f2015-08-11 15:10:02 +020095size_t cbfs_calculate_file_header_size(const char *name)
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -070096{
Hung-Te Linc03d9b02013-01-29 02:38:40 +080097 return (sizeof(struct cbfs_file) +
98 align_up(strlen(name) + 1, CBFS_FILENAME_ALIGN));
99}
100
Sol Boucher67a0a862015-03-18 12:36:27 -0700101/* Only call on legacy CBFSes possessing a master header. */
Alexandru Gagniucc1d1fd82014-02-05 01:10:08 -0600102static int cbfs_fix_legacy_size(struct cbfs_image *image, char *hdr_loc)
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -0700103{
Sol Boucher67a0a862015-03-18 12:36:27 -0700104 assert(image);
105 assert(cbfs_is_legacy_cbfs(image));
Hung-Te Lin49fcd752013-01-29 03:16:20 +0800106 // A bug in old cbfstool may produce extra few bytes (by alignment) and
107 // cause cbfstool to overwrite things after free space -- which is
108 // usually CBFS header on x86. We need to workaround that.
Patrick Georgi343ea082016-02-10 18:07:52 +0100109 // Except when we run across a file that contains the actual header,
110 // in which case this image is a safe, new-style
111 // `cbfstool add-master-header` based image.
Hung-Te Lin49fcd752013-01-29 03:16:20 +0800112
113 struct cbfs_file *entry, *first = NULL, *last = NULL;
114 for (first = entry = cbfs_find_first_entry(image);
Hung-Te Lin408aefd2013-02-09 10:38:55 +0800115 entry && cbfs_is_valid_entry(image, entry);
Hung-Te Lin49fcd752013-01-29 03:16:20 +0800116 entry = cbfs_find_next_entry(image, entry)) {
Patrick Georgi343ea082016-02-10 18:07:52 +0100117 /* Is the header guarded by a CBFS file entry? Then exit */
118 if (((char *)entry) + ntohl(entry->offset) == hdr_loc) {
119 return 0;
120 }
Hung-Te Lin49fcd752013-01-29 03:16:20 +0800121 last = entry;
122 }
Alexandru Gagniucc1d1fd82014-02-05 01:10:08 -0600123 if ((char *)first < (char *)hdr_loc &&
124 (char *)entry > (char *)hdr_loc) {
Hung-Te Lin49fcd752013-01-29 03:16:20 +0800125 WARN("CBFS image was created with old cbfstool with size bug. "
126 "Fixing size in last entry...\n");
Sol Boucher3e060ed2015-05-05 15:40:15 -0700127 last->len = htonl(ntohl(last->len) - image->header.align);
Hung-Te Lin49fcd752013-01-29 03:16:20 +0800128 DEBUG("Last entry has been changed from 0x%x to 0x%x.\n",
129 cbfs_get_entry_addr(image, entry),
130 cbfs_get_entry_addr(image,
131 cbfs_find_next_entry(image, last)));
132 }
133 return 0;
134}
135
Ronald G. Minnichb5adeee2014-01-06 08:38:15 -0800136void cbfs_put_header(void *dest, const struct cbfs_header *header)
137{
138 struct buffer outheader;
139
140 outheader.data = dest;
141 outheader.size = 0;
142
143 xdr_be.put32(&outheader, header->magic);
144 xdr_be.put32(&outheader, header->version);
145 xdr_be.put32(&outheader, header->romsize);
146 xdr_be.put32(&outheader, header->bootblocksize);
147 xdr_be.put32(&outheader, header->align);
148 xdr_be.put32(&outheader, header->offset);
149 xdr_be.put32(&outheader, header->architecture);
150}
Alexandru Gagniucc1d1fd82014-02-05 01:10:08 -0600151
Hung-Te Lin0780d672014-05-16 10:14:05 +0800152static void cbfs_decode_payload_segment(struct cbfs_payload_segment *output,
153 struct cbfs_payload_segment *input)
154{
155 struct buffer seg = {
156 .data = (void *)input,
157 .size = sizeof(*input),
158 };
159 output->type = xdr_be.get32(&seg);
160 output->compression = xdr_be.get32(&seg);
161 output->offset = xdr_be.get32(&seg);
162 output->load_addr = xdr_be.get64(&seg);
163 output->len = xdr_be.get32(&seg);
164 output->mem_len = xdr_be.get32(&seg);
165 assert(seg.size == 0);
166}
167
Patrick Georgia71c83f2015-08-26 12:23:26 +0200168static int cbfs_file_get_compression_info(struct cbfs_file *entry,
169 uint32_t *decompressed_size)
170{
171 unsigned int compression = CBFS_COMPRESS_NONE;
Patrick Georgia2ce7102016-12-14 16:08:52 +0100172 if (decompressed_size)
173 *decompressed_size = ntohl(entry->len);
Patrick Georgia71c83f2015-08-26 12:23:26 +0200174 for (struct cbfs_file_attribute *attr = cbfs_file_first_attr(entry);
175 attr != NULL;
176 attr = cbfs_file_next_attr(entry, attr)) {
177 if (ntohl(attr->tag) == CBFS_FILE_ATTR_TAG_COMPRESSION) {
178 struct cbfs_file_attr_compression *ac =
179 (struct cbfs_file_attr_compression *)attr;
180 compression = ntohl(ac->compression);
181 if (decompressed_size)
182 *decompressed_size =
183 ntohl(ac->decompressed_size);
184 }
185 }
186 return compression;
187}
188
Patrick Georgi89f20342015-10-01 15:54:04 +0200189static struct cbfs_file_attr_hash *cbfs_file_get_next_hash(
190 struct cbfs_file *entry, struct cbfs_file_attr_hash *cur)
191{
192 struct cbfs_file_attribute *attr = (struct cbfs_file_attribute *)cur;
193 if (attr == NULL) {
194 attr = cbfs_file_first_attr(entry);
195 if (attr == NULL)
196 return NULL;
197 if (ntohl(attr->tag) == CBFS_FILE_ATTR_TAG_HASH)
198 return (struct cbfs_file_attr_hash *)attr;
199 }
200 while ((attr = cbfs_file_next_attr(entry, attr)) != NULL) {
201 if (ntohl(attr->tag) == CBFS_FILE_ATTR_TAG_HASH)
202 return (struct cbfs_file_attr_hash *)attr;
203 };
204 return NULL;
205}
206
Sol Boucher0e539312015-03-05 15:38:03 -0800207void cbfs_get_header(struct cbfs_header *header, void *src)
Alexandru Gagniucc1d1fd82014-02-05 01:10:08 -0600208{
209 struct buffer outheader;
210
Sol Boucher0e539312015-03-05 15:38:03 -0800211 outheader.data = src; /* We're not modifying the data */
Alexandru Gagniucc1d1fd82014-02-05 01:10:08 -0600212 outheader.size = 0;
213
214 header->magic = xdr_be.get32(&outheader);
215 header->version = xdr_be.get32(&outheader);
216 header->romsize = xdr_be.get32(&outheader);
217 header->bootblocksize = xdr_be.get32(&outheader);
218 header->align = xdr_be.get32(&outheader);
219 header->offset = xdr_be.get32(&outheader);
220 header->architecture = xdr_be.get32(&outheader);
221}
222
Sol Boucher67a0a862015-03-18 12:36:27 -0700223int cbfs_image_create(struct cbfs_image *image, size_t entries_size)
224{
225 assert(image);
226 assert(image->buffer.data);
227
228 size_t empty_header_len = cbfs_calculate_file_header_size("");
229 uint32_t entries_offset = 0;
230 uint32_t align = CBFS_ENTRY_ALIGNMENT;
231 if (image->has_header) {
232 entries_offset = image->header.offset;
233
234 if (entries_offset > image->buffer.size) {
235 ERROR("CBFS file entries are located outside CBFS itself\n");
236 return -1;
237 }
238
239 align = image->header.align;
240 }
241
242 // This attribute must be given in order to prove that this module
243 // correctly preserves certain CBFS properties. See the block comment
244 // near the top of this file (and the associated commit message).
245 if (align < empty_header_len) {
246 ERROR("CBFS must be aligned to at least %zu bytes\n",
247 empty_header_len);
248 return -1;
249 }
250
251 if (entries_size > image->buffer.size - entries_offset) {
252 ERROR("CBFS doesn't have enough space to fit its file entries\n");
253 return -1;
254 }
255
256 if (empty_header_len > entries_size) {
257 ERROR("CBFS is too small to fit any header\n");
258 return -1;
259 }
260 struct cbfs_file *entry_header =
261 (struct cbfs_file *)(image->buffer.data + entries_offset);
262 // This alignment is necessary in order to prove that this module
263 // correctly preserves certain CBFS properties. See the block comment
264 // near the top of this file (and the associated commit message).
265 entries_size -= entries_size % align;
266
267 size_t capacity = entries_size - empty_header_len;
268 LOG("Created CBFS (capacity = %zu bytes)\n", capacity);
Patrick Georgiedf25d92015-08-12 09:12:06 +0200269 return cbfs_create_empty_entry(entry_header, CBFS_COMPONENT_NULL,
270 capacity, "");
Sol Boucher67a0a862015-03-18 12:36:27 -0700271}
272
273int cbfs_legacy_image_create(struct cbfs_image *image,
274 uint32_t architecture,
275 uint32_t align,
276 struct buffer *bootblock,
277 uint32_t bootblock_offset,
278 uint32_t header_offset,
279 uint32_t entries_offset)
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800280{
Sol Bouchere3260a02015-03-25 13:40:08 -0700281 assert(image);
282 assert(image->buffer.data);
283 assert(bootblock);
284
Julius Wernerefcee762014-11-10 13:14:24 -0800285 int32_t *rel_offset;
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800286 uint32_t cbfs_len;
Alexandru Gagniucc1d1fd82014-02-05 01:10:08 -0600287 void *header_loc;
Sol Bouchere3260a02015-03-25 13:40:08 -0700288 size_t size = image->buffer.size;
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800289
290 DEBUG("cbfs_image_create: bootblock=0x%x+0x%zx, "
291 "header=0x%x+0x%zx, entries_offset=0x%x\n",
Sol Boucher5bad3952015-05-05 20:35:26 -0700292 bootblock_offset, bootblock->size, header_offset,
293 sizeof(image->header), entries_offset);
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800294
Sol Boucher67a0a862015-03-18 12:36:27 -0700295 // Adjust legacy top-aligned address to ROM offset.
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800296 if (IS_TOP_ALIGNED_ADDRESS(entries_offset))
Sol Boucher0e539312015-03-05 15:38:03 -0800297 entries_offset = size + (int32_t)entries_offset;
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800298 if (IS_TOP_ALIGNED_ADDRESS(bootblock_offset))
Sol Boucher0e539312015-03-05 15:38:03 -0800299 bootblock_offset = size + (int32_t)bootblock_offset;
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800300 if (IS_TOP_ALIGNED_ADDRESS(header_offset))
Sol Boucher0e539312015-03-05 15:38:03 -0800301 header_offset = size + (int32_t)header_offset;
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800302
303 DEBUG("cbfs_create_image: (real offset) bootblock=0x%x, "
304 "header=0x%x, entries_offset=0x%x\n",
305 bootblock_offset, header_offset, entries_offset);
306
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800307 // Prepare bootblock
308 if (bootblock_offset + bootblock->size > size) {
309 ERROR("Bootblock (0x%x+0x%zx) exceed ROM size (0x%zx)\n",
310 bootblock_offset, bootblock->size, size);
311 return -1;
312 }
Hung-Te Linc5ff6482013-02-06 12:41:49 +0800313 if (entries_offset > bootblock_offset &&
314 entries_offset < bootblock->size) {
315 ERROR("Bootblock (0x%x+0x%zx) overlap CBFS data (0x%x)\n",
316 bootblock_offset, bootblock->size, entries_offset);
317 return -1;
318 }
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800319 memcpy(image->buffer.data + bootblock_offset, bootblock->data,
320 bootblock->size);
321
322 // Prepare header
Sol Boucher5bad3952015-05-05 20:35:26 -0700323 if (header_offset + sizeof(image->header) > size - sizeof(int32_t)) {
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800324 ERROR("Header (0x%x+0x%zx) exceed ROM size (0x%zx)\n",
Sol Boucher5bad3952015-05-05 20:35:26 -0700325 header_offset, sizeof(image->header), size);
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800326 return -1;
327 }
Sol Boucher3e060ed2015-05-05 15:40:15 -0700328 image->header.magic = CBFS_HEADER_MAGIC;
329 image->header.version = CBFS_HEADER_VERSION;
330 image->header.romsize = size;
331 image->header.bootblocksize = bootblock->size;
332 image->header.align = align;
333 image->header.offset = entries_offset;
334 image->header.architecture = architecture;
Alexandru Gagniucc1d1fd82014-02-05 01:10:08 -0600335
336 header_loc = (image->buffer.data + header_offset);
Sol Boucher3e060ed2015-05-05 15:40:15 -0700337 cbfs_put_header(header_loc, &image->header);
Sol Boucher67a0a862015-03-18 12:36:27 -0700338 image->has_header = true;
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800339
Julius Wernerefcee762014-11-10 13:14:24 -0800340 // The last 4 byte of the image contain the relative offset from the end
341 // of the image to the master header as a 32-bit signed integer. x86
342 // relies on this also being its (memory-mapped, top-aligned) absolute
343 // 32-bit address by virtue of how two's complement numbers work.
344 assert(size % sizeof(int32_t) == 0);
345 rel_offset = (int32_t *)(image->buffer.data + size - sizeof(int32_t));
346 *rel_offset = header_offset - size;
347
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800348 // Prepare entries
349 if (align_up(entries_offset, align) != entries_offset) {
350 ERROR("Offset (0x%x) must be aligned to 0x%x.\n",
351 entries_offset, align);
352 return -1;
353 }
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800354 // To calculate available length, find
Julius Wernerefcee762014-11-10 13:14:24 -0800355 // e = min(bootblock, header, rel_offset) where e > entries_offset.
356 cbfs_len = size - sizeof(int32_t);
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800357 if (bootblock_offset > entries_offset && bootblock_offset < cbfs_len)
358 cbfs_len = bootblock_offset;
359 if (header_offset > entries_offset && header_offset < cbfs_len)
360 cbfs_len = header_offset;
Sol Boucher67a0a862015-03-18 12:36:27 -0700361
362 if (cbfs_image_create(image, cbfs_len - entries_offset))
363 return -1;
Hung-Te Linf56c73f2013-01-29 09:45:12 +0800364 return 0;
365}
366
Sol Bouchere3260a02015-03-25 13:40:08 -0700367int cbfs_image_from_buffer(struct cbfs_image *out, struct buffer *in,
368 uint32_t offset)
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -0700369{
Sol Bouchere3260a02015-03-25 13:40:08 -0700370 assert(out);
371 assert(in);
372 assert(in->data);
Alexandru Gagniucc1d1fd82014-02-05 01:10:08 -0600373
Sol Bouchere3260a02015-03-25 13:40:08 -0700374 buffer_clone(&out->buffer, in);
Sol Boucher67a0a862015-03-18 12:36:27 -0700375 out->has_header = false;
376
Patrick Georgi2f953d32015-09-11 18:34:39 +0200377 if (cbfs_is_valid_cbfs(out)) {
378 return 0;
379 }
380
Sol Bouchere3260a02015-03-25 13:40:08 -0700381 void *header_loc = cbfs_find_header(in->data, in->size, offset);
382 if (header_loc) {
383 cbfs_get_header(&out->header, header_loc);
Sol Boucher67a0a862015-03-18 12:36:27 -0700384 out->has_header = true;
Sol Bouchere3260a02015-03-25 13:40:08 -0700385 cbfs_fix_legacy_size(out, header_loc);
Patrick Georgi2f953d32015-09-11 18:34:39 +0200386 return 0;
Sol Boucher67a0a862015-03-18 12:36:27 -0700387 } else if (offset != ~0u) {
388 ERROR("The -H switch is only valid on legacy images having CBFS master headers.\n");
389 return 1;
Hung-Te Lineab2c812013-01-29 01:56:17 +0800390 }
Patrick Georgi2f953d32015-09-11 18:34:39 +0200391 ERROR("Selected image region is not a valid CBFS.\n");
392 return 1;
Hung-Te Lineab2c812013-01-29 01:56:17 +0800393}
394
Patrick Georgi214e4af2015-11-20 19:22:50 +0100395int cbfs_copy_instance(struct cbfs_image *image, struct buffer *dst)
Vadim Bendebury5e273a42014-12-23 19:26:54 -0800396{
Sol Boucher67a0a862015-03-18 12:36:27 -0700397 assert(image);
Sol Boucher67a0a862015-03-18 12:36:27 -0700398
Vadim Bendebury5e273a42014-12-23 19:26:54 -0800399 struct cbfs_file *src_entry, *dst_entry;
Patrick Georgibd0bb232015-11-20 21:48:18 +0100400 size_t align;
Vadim Bendebury5e273a42014-12-23 19:26:54 -0800401 ssize_t last_entry_size;
402
Patrick Georgi214e4af2015-11-20 19:22:50 +0100403 size_t copy_end = buffer_size(dst);
Vadim Bendebury5e273a42014-12-23 19:26:54 -0800404
Patrick Georgibd0bb232015-11-20 21:48:18 +0100405 align = CBFS_ENTRY_ALIGNMENT;
Vadim Bendebury5e273a42014-12-23 19:26:54 -0800406
Patrick Georgibd0bb232015-11-20 21:48:18 +0100407 dst_entry = (struct cbfs_file *)buffer_get(dst);
Vadim Bendebury5e273a42014-12-23 19:26:54 -0800408
409 /* Copy non-empty files */
410 for (src_entry = cbfs_find_first_entry(image);
411 src_entry && cbfs_is_valid_entry(image, src_entry);
412 src_entry = cbfs_find_next_entry(image, src_entry)) {
413 size_t entry_size;
414
415 if ((src_entry->type == htonl(CBFS_COMPONENT_NULL)) ||
Patrick Georgibd0bb232015-11-20 21:48:18 +0100416 (src_entry->type == htonl(CBFS_COMPONENT_CBFSHEADER)) ||
Vadim Bendebury5e273a42014-12-23 19:26:54 -0800417 (src_entry->type == htonl(CBFS_COMPONENT_DELETED)))
418 continue;
419
420 entry_size = htonl(src_entry->len) + htonl(src_entry->offset);
421 memcpy(dst_entry, src_entry, entry_size);
422 dst_entry = (struct cbfs_file *)(
423 (uintptr_t)dst_entry + align_up(entry_size, align));
424
Richard Spiegelb59c1f42018-11-02 11:14:38 -0700425 if ((size_t)((uint8_t *)dst_entry - (uint8_t *)buffer_get(dst))
426 >= copy_end) {
Vadim Bendebury5e273a42014-12-23 19:26:54 -0800427 ERROR("Ran out of room in copy region.\n");
428 return 1;
429 }
430 }
431
Patrick Georgibd0bb232015-11-20 21:48:18 +0100432 /* Last entry size is all the room above it, except for top 4 bytes
433 * which may be used by the master header pointer. This messes with
434 * the ability to stash something "top-aligned" into the region, but
435 * keeps things simpler. */
Richard Spiegelb59c1f42018-11-02 11:14:38 -0700436 last_entry_size = copy_end -
437 ((uint8_t *)dst_entry - (uint8_t *)buffer_get(dst)) -
438 cbfs_calculate_file_header_size("") - sizeof(int32_t);
Vadim Bendebury5e273a42014-12-23 19:26:54 -0800439
440 if (last_entry_size < 0)
441 WARN("No room to create the last entry!\n")
442 else
Patrick Georgiedf25d92015-08-12 09:12:06 +0200443 cbfs_create_empty_entry(dst_entry, CBFS_COMPONENT_NULL,
444 last_entry_size, "");
Vadim Bendebury5e273a42014-12-23 19:26:54 -0800445
446 return 0;
447}
448
Patrick Georgi5d982d72017-09-19 14:39:58 +0200449int cbfs_expand_to_region(struct buffer *region)
450{
451 if (buffer_get(region) == NULL)
452 return 1;
453
454 struct cbfs_image image;
455 memset(&image, 0, sizeof(image));
456 if (cbfs_image_from_buffer(&image, region, 0)) {
457 ERROR("reading CBFS failed!\n");
458 return 1;
459 }
460
461 uint32_t region_sz = buffer_size(region);
462
463 struct cbfs_file *entry;
464 for (entry = buffer_get(region);
465 cbfs_is_valid_entry(&image, entry);
466 entry = cbfs_find_next_entry(&image, entry)) {
467 /* just iterate through */
468 }
469
470 /* entry now points to the first aligned address after the last valid
471 * file header. That's either outside the image or exactly the place
472 * where we need to create a new file.
473 */
Richard Spiegelb59c1f42018-11-02 11:14:38 -0700474 int last_entry_size = region_sz -
475 ((uint8_t *)entry - (uint8_t *)buffer_get(region)) -
476 cbfs_calculate_file_header_size("") - sizeof(int32_t);
Patrick Georgi5d982d72017-09-19 14:39:58 +0200477
478 if (last_entry_size > 0) {
479 cbfs_create_empty_entry(entry, CBFS_COMPONENT_NULL,
480 last_entry_size, "");
481 /* If the last entry was an empty file, merge them. */
482 cbfs_walk(&image, cbfs_merge_empty_entry, NULL);
483 }
484
485 return 0;
486}
487
Patrick Georgi12631a42017-09-20 11:59:18 +0200488int cbfs_truncate_space(struct buffer *region, uint32_t *size)
489{
490 if (buffer_get(region) == NULL)
491 return 1;
492
493 struct cbfs_image image;
494 memset(&image, 0, sizeof(image));
495 if (cbfs_image_from_buffer(&image, region, 0)) {
496 ERROR("reading CBFS failed!\n");
497 return 1;
498 }
499
500 struct cbfs_file *entry, *trailer;
501 for (trailer = entry = buffer_get(region);
502 cbfs_is_valid_entry(&image, entry);
503 trailer = entry,
504 entry = cbfs_find_next_entry(&image, entry)) {
505 /* just iterate through */
506 }
507
508 /* trailer now points to the last valid CBFS entry's header.
509 * If that file is empty, remove it and report its header's offset as
510 * maximum size.
511 */
512 if ((strlen(trailer->filename) != 0) &&
513 (trailer->type != htonl(CBFS_COMPONENT_NULL)) &&
514 (trailer->type != htonl(CBFS_COMPONENT_DELETED))) {
515 /* nothing to truncate. Return de-facto CBFS size in case it
516 * was already truncated. */
Richard Spiegelb59c1f42018-11-02 11:14:38 -0700517 *size = (uint8_t *)entry - (uint8_t *)buffer_get(region);
Patrick Georgi12631a42017-09-20 11:59:18 +0200518 return 0;
519 }
Richard Spiegelb59c1f42018-11-02 11:14:38 -0700520 *size = (uint8_t *)trailer - (uint8_t *)buffer_get(region);
Patrick Georgi12631a42017-09-20 11:59:18 +0200521 memset(trailer, 0xff, buffer_size(region) - *size);
522
523 return 0;
524}
525
Aaron Durbin71c60ca2016-01-26 17:08:56 -0600526static size_t cbfs_file_entry_metadata_size(const struct cbfs_file *f)
527{
528 return ntohl(f->offset);
529}
530
531static size_t cbfs_file_entry_data_size(const struct cbfs_file *f)
532{
533 return ntohl(f->len);
534}
535
536static size_t cbfs_file_entry_size(const struct cbfs_file *f)
537{
538 return cbfs_file_entry_metadata_size(f) + cbfs_file_entry_data_size(f);
539}
540
541int cbfs_compact_instance(struct cbfs_image *image)
542{
543 assert(image);
544
545 struct cbfs_file *prev;
546 struct cbfs_file *cur;
547
548 /* The prev entry will always be an empty entry. */
549 prev = NULL;
550
551 /*
552 * Note: this function does not honor alignment or fixed location files.
553 * It's behavior is akin to cbfs_copy_instance() in that it expects
554 * the caller to understand the ramifications of compacting a
555 * fragmented CBFS image.
556 */
557
558 for (cur = cbfs_find_first_entry(image);
559 cur && cbfs_is_valid_entry(image, cur);
560 cur = cbfs_find_next_entry(image, cur)) {
561 size_t prev_size;
562 size_t cur_size;
563 size_t empty_metadata_size;
564 size_t spill_size;
565 uint32_t type = htonl(cur->type);
566
567 /* Current entry is empty. Kepp track of it. */
568 if ((type == htonl(CBFS_COMPONENT_NULL)) ||
569 (type == htonl(CBFS_COMPONENT_DELETED))) {
570 prev = cur;
571 continue;
572 }
573
574 /* Need to ensure the previous entry is an empty one. */
575 if (prev == NULL)
576 continue;
577
578 /* At this point prev is an empty entry. Put the non-empty
Patrick Georgi01cfecc2020-01-29 13:31:16 +0100579 * file in prev's location. Then add a new empty entry. This
Aaron Durbin71c60ca2016-01-26 17:08:56 -0600580 * essentialy bubbles empty entries towards the end. */
581
582 prev_size = cbfs_file_entry_size(prev);
583 cur_size = cbfs_file_entry_size(cur);
584
585 /*
586 * Adjust the empty file size by the actual space occupied
587 * bewtween the beginning of the empty file and the non-empty
588 * file.
589 */
590 prev_size += (cbfs_get_entry_addr(image, cur) -
591 cbfs_get_entry_addr(image, prev)) - prev_size;
592
593 /* Move the non-empty file over the empty file. */
594 memmove(prev, cur, cur_size);
595
596 /*
597 * Get location of the empty file. Note that since prev was
598 * overwritten with the non-empty file the previously moved
599 * file needs to be used to calculate the empty file's location.
600 */
601 cur = cbfs_find_next_entry(image, prev);
602
603 /*
604 * The total space to work with for swapping the 2 entries
605 * consists of the 2 files' sizes combined. However, the
606 * cbfs_file entries start on CBFS_ALIGNMENT boundaries.
607 * Because of this the empty file size may end up smaller
608 * because of the non-empty file's metadata and data length.
609 *
610 * Calculate the spill size which is the amount of data lost
611 * due to the alignment constraints after moving the non-empty
612 * file.
613 */
614 spill_size = (cbfs_get_entry_addr(image, cur) -
615 cbfs_get_entry_addr(image, prev)) - cur_size;
616
617 empty_metadata_size = cbfs_calculate_file_header_size("");
618
619 /* Check if new empty size can contain the metadata. */
620 if (empty_metadata_size + spill_size > prev_size) {
621 ERROR("Unable to swap '%s' with prev empty entry.\n",
622 prev->filename);
623 return 1;
624 }
625
626 /* Update the empty file's size. */
627 prev_size -= spill_size + empty_metadata_size;
628
629 /* Create new empty file. */
630 cbfs_create_empty_entry(cur, CBFS_COMPONENT_NULL,
631 prev_size, "");
632
633 /* Merge any potential empty entries together. */
634 cbfs_walk(image, cbfs_merge_empty_entry, NULL);
635
636 /*
637 * Since current switched to an empty file keep track of it.
638 * Even if any empty files were merged the empty entry still
639 * starts at previously calculated location.
640 */
641 prev = cur;
642 }
643
644 return 0;
645}
646
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -0700647int cbfs_image_delete(struct cbfs_image *image)
648{
Edward O'Callaghana0f9ece2014-03-09 00:05:18 +1100649 if (image == NULL)
650 return 0;
651
Hung-Te Lineab2c812013-01-29 01:56:17 +0800652 buffer_delete(&image->buffer);
Hung-Te Lineab2c812013-01-29 01:56:17 +0800653 return 0;
654}
655
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800656/* Tries to add an entry with its data (CBFS_SUBHEADER) at given offset. */
657static int cbfs_add_entry_at(struct cbfs_image *image,
658 struct cbfs_file *entry,
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800659 const void *data,
Patrick Georgi7fd14182015-08-11 15:55:16 +0200660 uint32_t content_offset,
Philipp Deppenwiese7ba58712018-11-20 13:54:49 +0100661 const struct cbfs_file *header,
662 const size_t len_align)
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -0700663{
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800664 struct cbfs_file *next = cbfs_find_next_entry(image, entry);
665 uint32_t addr = cbfs_get_entry_addr(image, entry),
666 addr_next = cbfs_get_entry_addr(image, next);
Patrick Georgi7fd14182015-08-11 15:55:16 +0200667 uint32_t min_entry_size = cbfs_calculate_file_header_size("");
Patrick Georgi4eb8abe2015-08-25 12:24:49 +0200668 uint32_t len, header_offset;
Sol Boucher67a0a862015-03-18 12:36:27 -0700669 uint32_t align = image->has_header ? image->header.align :
670 CBFS_ENTRY_ALIGNMENT;
Patrick Georgid5a4afa2015-08-25 22:27:57 +0200671 uint32_t header_size = ntohl(header->offset);
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800672
Patrick Georgi4eb8abe2015-08-25 12:24:49 +0200673 header_offset = content_offset - header_size;
674 if (header_offset % align)
675 header_offset -= header_offset % align;
676 if (header_offset < addr) {
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800677 ERROR("No space to hold cbfs_file header.");
678 return -1;
679 }
680
681 // Process buffer BEFORE content_offset.
Patrick Georgi4eb8abe2015-08-25 12:24:49 +0200682 if (header_offset - addr > min_entry_size) {
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800683 DEBUG("|min|...|header|content|... <create new entry>\n");
Patrick Georgi4eb8abe2015-08-25 12:24:49 +0200684 len = header_offset - addr - min_entry_size;
Patrick Georgiedf25d92015-08-12 09:12:06 +0200685 cbfs_create_empty_entry(entry, CBFS_COMPONENT_NULL, len, "");
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800686 if (verbose > 1) cbfs_print_entry_info(image, entry, stderr);
687 entry = cbfs_find_next_entry(image, entry);
688 addr = cbfs_get_entry_addr(image, entry);
689 }
690
Patrick Georgi7a33b532015-08-25 13:00:04 +0200691 len = content_offset - addr - header_size;
Patrick Georgia60e7b62015-08-25 22:26:02 +0200692 memcpy(entry, header, header_size);
Patrick Georgi7a33b532015-08-25 13:00:04 +0200693 if (len != 0) {
Elyes HAOUAS3db01982018-08-23 18:08:20 +0200694 /* the header moved backwards a bit to accommodate cbfs_file
Patrick Georgi7a33b532015-08-25 13:00:04 +0200695 * alignment requirements, so patch up ->offset to still point
696 * to file data.
697 */
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800698 DEBUG("|..|header|content|... <use offset to create entry>\n");
Patrick Georgiae7efb92015-08-25 13:11:28 +0200699 DEBUG("before: offset=0x%x\n", ntohl(entry->offset));
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800700 // TODO reset expanded name buffer to 0xFF.
Patrick Georgi7a33b532015-08-25 13:00:04 +0200701 entry->offset = htonl(ntohl(entry->offset) + len);
Patrick Georgiae7efb92015-08-25 13:11:28 +0200702 DEBUG("after: offset=0x%x\n", ntohl(entry->len));
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800703 }
704
705 // Ready to fill data into entry.
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800706 DEBUG("content_offset: 0x%x, entry location: %x\n",
707 content_offset, (int)((char*)CBFS_SUBHEADER(entry) -
708 image->buffer.data));
709 assert((char*)CBFS_SUBHEADER(entry) - image->buffer.data ==
Patrick Georgicccc9d42015-04-28 13:09:36 +0200710 (ptrdiff_t)content_offset);
Patrick Georgi19c80b22015-08-25 13:16:04 +0200711 memcpy(CBFS_SUBHEADER(entry), data, ntohl(entry->len));
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800712 if (verbose > 1) cbfs_print_entry_info(image, entry, stderr);
713
Philipp Deppenwiese7ba58712018-11-20 13:54:49 +0100714 // Align the length to a multiple of len_align
715 if (len_align &&
716 ((ntohl(entry->offset) + ntohl(entry->len)) % len_align)) {
717 size_t off = (ntohl(entry->offset) + ntohl(entry->len)) % len_align;
718 entry->len = htonl(ntohl(entry->len) + len_align - off);
719 }
720
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800721 // Process buffer AFTER entry.
722 entry = cbfs_find_next_entry(image, entry);
723 addr = cbfs_get_entry_addr(image, entry);
Sol Boucher05725652015-04-02 20:58:26 -0700724 if (addr == addr_next)
725 return 0;
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800726
Sol Boucher05725652015-04-02 20:58:26 -0700727 assert(addr < addr_next);
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800728 if (addr_next - addr < min_entry_size) {
Sol Boucher636cc852015-04-03 09:13:04 -0700729 DEBUG("No need for new \"empty\" entry\n");
730 /* No need to increase the size of the just
731 * stored file to extend to next file. Alignment
732 * of next file takes care of this.
733 */
734 return 0;
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800735 }
736
737 len = addr_next - addr - min_entry_size;
Patrick Georgi29a04d92015-11-20 23:23:44 +0100738 /* keep space for master header pointer */
Richard Spiegelb59c1f42018-11-02 11:14:38 -0700739 if ((uint8_t *)entry + min_entry_size + len >
740 (uint8_t *)buffer_get(&image->buffer) +
741 buffer_size(&image->buffer) - sizeof(int32_t)) {
Patrick Georgi29a04d92015-11-20 23:23:44 +0100742 len -= sizeof(int32_t);
743 }
Patrick Georgiedf25d92015-08-12 09:12:06 +0200744 cbfs_create_empty_entry(entry, CBFS_COMPONENT_NULL, len, "");
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800745 if (verbose > 1) cbfs_print_entry_info(image, entry, stderr);
746 return 0;
747}
748
749int cbfs_add_entry(struct cbfs_image *image, struct buffer *buffer,
Patrick Georgie5903582015-08-25 13:53:42 +0200750 uint32_t content_offset,
Philipp Deppenwiese7ba58712018-11-20 13:54:49 +0100751 struct cbfs_file *header,
752 const size_t len_align)
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -0700753{
Sol Boucher67d59982015-05-07 02:39:22 -0700754 assert(image);
755 assert(buffer);
756 assert(buffer->data);
Sol Boucher67d59982015-05-07 02:39:22 -0700757 assert(!IS_TOP_ALIGNED_ADDRESS(content_offset));
758
Patrick Georgia60e7b62015-08-25 22:26:02 +0200759 const char *name = header->filename;
Patrick Georgie5903582015-08-25 13:53:42 +0200760
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800761 uint32_t entry_type;
762 uint32_t addr, addr_next;
763 struct cbfs_file *entry, *next;
Patrick Georgidd2d3f92015-08-12 12:29:20 +0200764 uint32_t need_size;
Patrick Georgif5252f32015-08-25 22:27:57 +0200765 uint32_t header_size = ntohl(header->offset);
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800766
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800767 need_size = header_size + buffer->size;
768 DEBUG("cbfs_add_entry('%s'@0x%x) => need_size = %u+%zu=%u\n",
769 name, content_offset, header_size, buffer->size, need_size);
770
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800771 // Merge empty entries.
772 DEBUG("(trying to merge empty entries...)\n");
773 cbfs_walk(image, cbfs_merge_empty_entry, NULL);
774
775 for (entry = cbfs_find_first_entry(image);
Hung-Te Lin408aefd2013-02-09 10:38:55 +0800776 entry && cbfs_is_valid_entry(image, entry);
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800777 entry = cbfs_find_next_entry(image, entry)) {
778
779 entry_type = ntohl(entry->type);
780 if (entry_type != CBFS_COMPONENT_NULL)
781 continue;
782
783 addr = cbfs_get_entry_addr(image, entry);
784 next = cbfs_find_next_entry(image, entry);
785 addr_next = cbfs_get_entry_addr(image, next);
786
787 DEBUG("cbfs_add_entry: space at 0x%x+0x%x(%d) bytes\n",
788 addr, addr_next - addr, addr_next - addr);
Aaron Durbin1ebc7e92014-01-21 15:28:38 -0600789
790 /* Will the file fit? Don't yet worry if we have space for a new
791 * "empty" entry. We take care of that later.
792 */
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800793 if (addr + need_size > addr_next)
794 continue;
795
Patrick Georgiaa44dbd2015-08-12 12:05:21 +0200796 // Test for complicated cases
797 if (content_offset > 0) {
798 if (addr_next < content_offset) {
799 DEBUG("Not for specified offset yet");
800 continue;
801 } else if (addr > content_offset) {
802 DEBUG("Exceed specified content_offset.");
803 break;
804 } else if (addr + header_size > content_offset) {
805 ERROR("Not enough space for header.\n");
806 break;
807 } else if (content_offset + buffer->size > addr_next) {
808 ERROR("Not enough space for content.\n");
809 break;
810 }
811 }
812
813 // TODO there are more few tricky cases that we may
814 // want to fit by altering offset.
815
Patrick Georgidd2d3f92015-08-12 12:29:20 +0200816 if (content_offset == 0) {
817 // we tested every condition earlier under which
818 // placing the file there might fail
819 content_offset = addr + header_size;
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800820 }
821
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800822 DEBUG("section 0x%x+0x%x for content_offset 0x%x.\n",
823 addr, addr_next - addr, content_offset);
824
Patrick Georgid5a4afa2015-08-25 22:27:57 +0200825 if (cbfs_add_entry_at(image, entry, buffer->data,
Philipp Deppenwiese7ba58712018-11-20 13:54:49 +0100826 content_offset, header, len_align) == 0) {
Hung-Te Lin5f3eb262013-01-29 10:24:00 +0800827 return 0;
828 }
829 break;
830 }
831
832 ERROR("Could not add [%s, %zd bytes (%zd KB)@0x%x]; too big?\n",
833 buffer->name, buffer->size, buffer->size / 1024, content_offset);
834 return -1;
835}
836
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -0700837struct cbfs_file *cbfs_get_entry(struct cbfs_image *image, const char *name)
838{
Hung-Te Lin0f8af712013-01-29 02:29:49 +0800839 struct cbfs_file *entry;
840 for (entry = cbfs_find_first_entry(image);
Hung-Te Lin408aefd2013-02-09 10:38:55 +0800841 entry && cbfs_is_valid_entry(image, entry);
Hung-Te Lin0f8af712013-01-29 02:29:49 +0800842 entry = cbfs_find_next_entry(image, entry)) {
Patrick Georgic569b8b2015-07-15 16:42:38 +0200843 if (strcasecmp(entry->filename, name) == 0) {
Hung-Te Lin0f8af712013-01-29 02:29:49 +0800844 DEBUG("cbfs_get_entry: found %s\n", name);
845 return entry;
846 }
847 }
848 return NULL;
849}
850
Aaron Durbin5a1e85c2015-10-27 21:02:30 -0500851static int cbfs_stage_decompress(struct cbfs_stage *stage, struct buffer *buff)
Aaron Durbin539aed02015-10-23 17:42:32 -0500852{
853 struct buffer reader;
Aaron Durbin539aed02015-10-23 17:42:32 -0500854 char *orig_buffer;
855 char *new_buffer;
856 size_t new_buff_sz;
857 decomp_func_ptr decompress;
858
859 buffer_clone(&reader, buff);
860
861 /* The stage metadata is in little endian. */
Aaron Durbin5a1e85c2015-10-27 21:02:30 -0500862 stage->compression = xdr_le.get32(&reader);
863 stage->entry = xdr_le.get64(&reader);
864 stage->load = xdr_le.get64(&reader);
865 stage->len = xdr_le.get32(&reader);
866 stage->memlen = xdr_le.get32(&reader);
Aaron Durbin539aed02015-10-23 17:42:32 -0500867
Aaron Durbin5a1e85c2015-10-27 21:02:30 -0500868 /* Create a buffer just with the uncompressed program now that the
869 * struct cbfs_stage has been peeled off. */
870 if (stage->compression == CBFS_COMPRESS_NONE) {
871 new_buff_sz = buffer_size(buff) - sizeof(struct cbfs_stage);
872
873 orig_buffer = buffer_get(buff);
874 new_buffer = calloc(1, new_buff_sz);
875 memcpy(new_buffer, orig_buffer + sizeof(struct cbfs_stage),
876 new_buff_sz);
877 buffer_init(buff, buff->name, new_buffer, new_buff_sz);
878 free(orig_buffer);
Aaron Durbin539aed02015-10-23 17:42:32 -0500879 return 0;
Aaron Durbin5a1e85c2015-10-27 21:02:30 -0500880 }
Aaron Durbin539aed02015-10-23 17:42:32 -0500881
Aaron Durbin5a1e85c2015-10-27 21:02:30 -0500882 decompress = decompression_function(stage->compression);
Aaron Durbin539aed02015-10-23 17:42:32 -0500883 if (decompress == NULL)
884 return -1;
885
886 orig_buffer = buffer_get(buff);
887
888 /* This can be too big of a buffer needed, but there's no current
889 * field indicating decompressed size of data. */
Aaron Durbin5a1e85c2015-10-27 21:02:30 -0500890 new_buff_sz = stage->memlen;
Aaron Durbin539aed02015-10-23 17:42:32 -0500891 new_buffer = calloc(1, new_buff_sz);
892
893 if (decompress(orig_buffer + sizeof(struct cbfs_stage),
894 (int)(buffer_size(buff) - sizeof(struct cbfs_stage)),
Aaron Durbin5a1e85c2015-10-27 21:02:30 -0500895 new_buffer, (int)new_buff_sz, &new_buff_sz)) {
Aaron Durbin539aed02015-10-23 17:42:32 -0500896 ERROR("Couldn't decompress stage.\n");
897 free(new_buffer);
898 return -1;
899 }
900
901 /* Include correct size for full stage info. */
Aaron Durbin539aed02015-10-23 17:42:32 -0500902 buffer_init(buff, buff->name, new_buffer, new_buff_sz);
Aaron Durbin539aed02015-10-23 17:42:32 -0500903
904 /* True decompressed size is just the data size -- no metadata. */
Aaron Durbin5a1e85c2015-10-27 21:02:30 -0500905 stage->len = new_buff_sz;
Aaron Durbin539aed02015-10-23 17:42:32 -0500906 /* Stage is not compressed. */
Aaron Durbin5a1e85c2015-10-27 21:02:30 -0500907 stage->compression = CBFS_COMPRESS_NONE;
Aaron Durbin539aed02015-10-23 17:42:32 -0500908
909 free(orig_buffer);
910
911 return 0;
912}
913
Antonello Dettorifda691e2016-06-09 12:35:36 +0200914static int cbfs_payload_decompress(struct cbfs_payload_segment *segments,
915 struct buffer *buff, int num_seg)
916{
917 struct buffer new_buffer;
918 struct buffer seg_buffer;
919 size_t new_buff_sz;
920 char *in_ptr;
921 char *out_ptr;
922 size_t new_offset;
923 decomp_func_ptr decompress;
924
925 new_offset = num_seg * sizeof(*segments);
926 new_buff_sz = num_seg * sizeof(*segments);
927
928 /* Find out and allocate the amount of memory occupied
929 * by the binary data */
930 for (int i = 0; i < num_seg; i++)
931 new_buff_sz += segments[i].mem_len;
932
Furquan Shaikh58644a02016-08-05 08:27:18 -0700933 if (buffer_create(&new_buffer, new_buff_sz, "decompressed_buff"))
934 return -1;
Antonello Dettorifda691e2016-06-09 12:35:36 +0200935
936 in_ptr = buffer_get(buff) + new_offset;
937 out_ptr = buffer_get(&new_buffer) + new_offset;
938
939 for (int i = 0; i < num_seg; i++) {
940 struct buffer tbuff;
941 size_t decomp_size;
942
Antonello Dettorifda691e2016-06-09 12:35:36 +0200943 /* Segments BSS and ENTRY do not have binary data. */
944 if (segments[i].type == PAYLOAD_SEGMENT_BSS ||
945 segments[i].type == PAYLOAD_SEGMENT_ENTRY) {
946 continue;
947 } else if (segments[i].type == PAYLOAD_SEGMENT_PARAMS) {
948 memcpy(out_ptr, in_ptr, segments[i].len);
949 segments[i].offset = new_offset;
950 new_offset += segments[i].len;
951 in_ptr += segments[i].len;
952 out_ptr += segments[i].len;
953 segments[i].compression = CBFS_COMPRESS_NONE;
954 continue;
955 }
956
Joel Kitching72d77a92018-07-18 13:23:52 +0800957 /* The payload uses an unknown compression algorithm. */
958 decompress = decompression_function(segments[i].compression);
959 if (decompress == NULL) {
960 ERROR("Unknown decompression algorithm: %u\n",
961 segments[i].compression);
962 return -1;
963 }
964
Furquan Shaikh58644a02016-08-05 08:27:18 -0700965 if (buffer_create(&tbuff, segments[i].mem_len, "segment")) {
966 buffer_delete(&new_buffer);
967 return -1;
968 }
Antonello Dettorifda691e2016-06-09 12:35:36 +0200969
970 if (decompress(in_ptr, segments[i].len, buffer_get(&tbuff),
971 (int) buffer_size(&tbuff),
972 &decomp_size)) {
973 ERROR("Couldn't decompress payload segment %u\n", i);
974 buffer_delete(&new_buffer);
Furquan Shaikh9844d562016-08-05 08:32:23 -0700975 buffer_delete(&tbuff);
Antonello Dettorifda691e2016-06-09 12:35:36 +0200976 return -1;
977 }
978
979 memcpy(out_ptr, buffer_get(&tbuff), decomp_size);
980
981 in_ptr += segments[i].len;
982
983 /* Update the offset of the segment. */
984 segments[i].offset = new_offset;
985 /* True decompressed size is just the data size. No metadata */
986 segments[i].len = decomp_size;
987 /* Segment is not compressed. */
988 segments[i].compression = CBFS_COMPRESS_NONE;
989
990 /* Update the offset and output buffer pointer. */
991 new_offset += decomp_size;
992 out_ptr += decomp_size;
993
994 buffer_delete(&tbuff);
995 }
996
997 buffer_splice(&seg_buffer, &new_buffer, 0, 0);
998 xdr_segs(&seg_buffer, segments, num_seg);
999
1000 buffer_delete(buff);
1001 *buff = new_buffer;
1002
1003 return 0;
1004}
1005
Aaron Durbin5a1e85c2015-10-27 21:02:30 -05001006static int init_elf_from_arch(Elf64_Ehdr *ehdr, uint32_t cbfs_arch)
1007{
1008 int endian;
1009 int nbits;
1010 int machine;
1011
1012 switch (cbfs_arch) {
1013 case CBFS_ARCHITECTURE_X86:
1014 endian = ELFDATA2LSB;
1015 nbits = ELFCLASS32;
1016 machine = EM_386;
1017 break;
1018 case CBFS_ARCHITECTURE_ARM:
1019 endian = ELFDATA2LSB;
1020 nbits = ELFCLASS32;
1021 machine = EM_ARM;
1022 break;
1023 case CBFS_ARCHITECTURE_AARCH64:
1024 endian = ELFDATA2LSB;
1025 nbits = ELFCLASS64;
1026 machine = EM_AARCH64;
1027 break;
1028 case CBFS_ARCHITECTURE_MIPS:
1029 endian = ELFDATA2LSB;
1030 nbits = ELFCLASS32;
1031 machine = EM_MIPS;
1032 break;
1033 case CBFS_ARCHITECTURE_RISCV:
1034 endian = ELFDATA2LSB;
1035 nbits = ELFCLASS32;
1036 machine = EM_RISCV;
1037 break;
1038 default:
1039 ERROR("Unsupported arch: %x\n", cbfs_arch);
1040 return -1;
1041 }
1042
1043 elf_init_eheader(ehdr, machine, nbits, endian);
1044 return 0;
1045}
1046
1047static int cbfs_stage_make_elf(struct buffer *buff, uint32_t arch)
1048{
1049 Elf64_Ehdr ehdr;
1050 Elf64_Shdr shdr;
1051 struct cbfs_stage stage;
1052 struct elf_writer *ew;
1053 struct buffer elf_out;
1054 size_t empty_sz;
Aaron Durbin694fd132015-10-28 11:39:34 -05001055 int rmod_ret;
Aaron Durbin5a1e85c2015-10-27 21:02:30 -05001056
Antonello Dettori0b806282016-06-26 00:24:25 +02001057 if (arch == CBFS_ARCHITECTURE_UNKNOWN) {
1058 ERROR("You need to specify -m ARCH.\n");
1059 return -1;
1060 }
1061
Aaron Durbin5a1e85c2015-10-27 21:02:30 -05001062 if (cbfs_stage_decompress(&stage, buff)) {
1063 ERROR("Failed to decompress stage.\n");
1064 return -1;
1065 }
1066
1067 if (init_elf_from_arch(&ehdr, arch))
1068 return -1;
1069
1070 ehdr.e_entry = stage.entry;
1071
Aaron Durbin694fd132015-10-28 11:39:34 -05001072 /* Attempt rmodule translation first. */
1073 rmod_ret = rmodule_stage_to_elf(&ehdr, buff);
1074
1075 if (rmod_ret < 0) {
1076 ERROR("rmodule parsing failed\n");
1077 return -1;
1078 } else if (rmod_ret == 0)
1079 return 0;
1080
1081 /* Rmodule couldn't do anything with the data. Continue on with SELF. */
1082
Aaron Durbin5a1e85c2015-10-27 21:02:30 -05001083 ew = elf_writer_init(&ehdr);
1084 if (ew == NULL) {
1085 ERROR("Unable to init ELF writer.\n");
1086 return -1;
1087 }
1088
1089 memset(&shdr, 0, sizeof(shdr));
1090 shdr.sh_type = SHT_PROGBITS;
1091 shdr.sh_flags = SHF_WRITE | SHF_ALLOC | SHF_EXECINSTR;
1092 shdr.sh_addr = stage.load;
1093 shdr.sh_size = stage.len;
1094 empty_sz = stage.memlen - stage.len;
1095
1096 if (elf_writer_add_section(ew, &shdr, buff, ".program")) {
1097 ERROR("Unable to add ELF section: .program\n");
1098 elf_writer_destroy(ew);
1099 return -1;
1100 }
1101
1102 if (empty_sz != 0) {
1103 struct buffer b;
1104
1105 buffer_init(&b, NULL, NULL, 0);
1106 memset(&shdr, 0, sizeof(shdr));
1107 shdr.sh_type = SHT_NOBITS;
1108 shdr.sh_flags = SHF_WRITE | SHF_ALLOC;
1109 shdr.sh_addr = stage.load + stage.len;
1110 shdr.sh_size = empty_sz;
1111 if (elf_writer_add_section(ew, &shdr, &b, ".empty")) {
1112 ERROR("Unable to add ELF section: .empty\n");
1113 elf_writer_destroy(ew);
1114 return -1;
1115 }
1116 }
1117
1118 if (elf_writer_serialize(ew, &elf_out)) {
1119 ERROR("Unable to create ELF file from stage.\n");
1120 elf_writer_destroy(ew);
1121 return -1;
1122 }
1123
1124 /* Flip buffer with the created ELF one. */
1125 buffer_delete(buff);
1126 *buff = elf_out;
1127
1128 elf_writer_destroy(ew);
1129
1130 return 0;
1131}
1132
Antonello Dettorifda691e2016-06-09 12:35:36 +02001133static int cbfs_payload_make_elf(struct buffer *buff, uint32_t arch)
1134{
1135 Elf64_Ehdr ehdr;
1136 Elf64_Shdr shdr;
Furquan Shaikh7b405172016-08-05 08:20:37 -07001137 struct cbfs_payload_segment *segs = NULL;
Jonathan Neuschäfer5de54582016-08-09 15:01:58 +02001138 struct elf_writer *ew = NULL;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001139 struct buffer elf_out;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001140 int segments = 0;
Furquan Shaikh7b405172016-08-05 08:20:37 -07001141 int retval = -1;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001142
Antonello Dettori0b806282016-06-26 00:24:25 +02001143 if (arch == CBFS_ARCHITECTURE_UNKNOWN) {
1144 ERROR("You need to specify -m ARCH.\n");
Furquan Shaikh7b405172016-08-05 08:20:37 -07001145 goto out;
Antonello Dettori0b806282016-06-26 00:24:25 +02001146 }
1147
Antonello Dettorifda691e2016-06-09 12:35:36 +02001148 /* Count the number of segments inside buffer */
1149 while (true) {
1150 uint32_t payload_type = 0;
1151
1152 struct cbfs_payload_segment *seg;
1153
1154 seg = buffer_get(buff);
1155 payload_type = read_be32(&seg[segments].type);
1156
1157 if (payload_type == PAYLOAD_SEGMENT_CODE) {
1158 segments++;
1159 } else if (payload_type == PAYLOAD_SEGMENT_DATA) {
1160 segments++;
1161 } else if (payload_type == PAYLOAD_SEGMENT_BSS) {
1162 segments++;
1163 } else if (payload_type == PAYLOAD_SEGMENT_PARAMS) {
1164 segments++;
1165 } else if (payload_type == PAYLOAD_SEGMENT_ENTRY) {
1166 /* The last segment in a payload is always ENTRY as
1167 * specified by the parse_elf_to_payload() function.
1168 * Therefore there is no need to continue looking for
1169 * segments.*/
1170 segments++;
1171 break;
1172 } else {
1173 ERROR("Unknown payload segment type: %x\n",
1174 payload_type);
Furquan Shaikh7b405172016-08-05 08:20:37 -07001175 goto out;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001176 }
1177 }
1178
1179 segs = malloc(segments * sizeof(*segs));
1180
1181 /* Decode xdr segments */
1182 for (int i = 0; i < segments; i++) {
1183 struct cbfs_payload_segment *serialized_seg = buffer_get(buff);
Antonello Dettorifda691e2016-06-09 12:35:36 +02001184 xdr_get_seg(&segs[i], &serialized_seg[i]);
1185 }
1186
1187 if (cbfs_payload_decompress(segs, buff, segments)) {
1188 ERROR("Failed to decompress payload.\n");
Furquan Shaikh7b405172016-08-05 08:20:37 -07001189 goto out;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001190 }
1191
1192 if (init_elf_from_arch(&ehdr, arch))
Furquan Shaikh7b405172016-08-05 08:20:37 -07001193 goto out;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001194
1195 ehdr.e_entry = segs[segments-1].load_addr;
1196
1197 ew = elf_writer_init(&ehdr);
1198 if (ew == NULL) {
1199 ERROR("Unable to init ELF writer.\n");
Furquan Shaikh7b405172016-08-05 08:20:37 -07001200 goto out;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001201 }
1202
1203 for (int i = 0; i < segments; i++) {
1204 struct buffer tbuff;
Furquan Shaikhf3bba442016-08-05 08:12:31 -07001205 size_t empty_sz = 0;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001206
1207 memset(&shdr, 0, sizeof(shdr));
1208 char *name = NULL;
1209
1210 if (segs[i].type == PAYLOAD_SEGMENT_CODE) {
1211 shdr.sh_type = SHT_PROGBITS;
1212 shdr.sh_flags = SHF_WRITE | SHF_ALLOC | SHF_EXECINSTR;
1213 shdr.sh_addr = segs[i].load_addr;
1214 shdr.sh_size = segs[i].len;
1215 empty_sz = segs[i].mem_len - segs[i].len;
1216 name = strdup(".text");
1217 buffer_splice(&tbuff, buff, segs[i].offset,
1218 segs[i].len);
1219 } else if (segs[i].type == PAYLOAD_SEGMENT_DATA) {
1220 shdr.sh_type = SHT_PROGBITS;
1221 shdr.sh_flags = SHF_ALLOC | SHF_WRITE;
1222 shdr.sh_addr = segs[i].load_addr;
1223 shdr.sh_size = segs[i].len;
1224 empty_sz = segs[i].mem_len - segs[i].len;
1225 name = strdup(".data");
1226 buffer_splice(&tbuff, buff, segs[i].offset,
1227 segs[i].len);
1228 } else if (segs[i].type == PAYLOAD_SEGMENT_BSS) {
1229 shdr.sh_type = SHT_NOBITS;
1230 shdr.sh_flags = SHF_ALLOC | SHF_WRITE;
1231 shdr.sh_addr = segs[i].load_addr;
1232 shdr.sh_size = segs[i].len;
1233 name = strdup(".bss");
1234 buffer_splice(&tbuff, buff, 0, 0);
1235 } else if (segs[i].type == PAYLOAD_SEGMENT_PARAMS) {
1236 shdr.sh_type = SHT_NOTE;
1237 shdr.sh_flags = 0;
1238 shdr.sh_size = segs[i].len;
1239 name = strdup(".note.pinfo");
1240 buffer_splice(&tbuff, buff, segs[i].offset,
1241 segs[i].len);
1242 } else if (segs[i].type == PAYLOAD_SEGMENT_ENTRY) {
1243 break;
Patrick Georgidce629b2017-01-13 13:30:54 +01001244 } else {
1245 ERROR("unknown ELF segment type\n");
1246 goto out;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001247 }
1248
Patrick Georgidce629b2017-01-13 13:30:54 +01001249 if (!name) {
1250 ERROR("out of memory\n");
1251 goto out;
1252 }
Antonello Dettorifda691e2016-06-09 12:35:36 +02001253
1254 if (elf_writer_add_section(ew, &shdr, &tbuff, name)) {
1255 ERROR("Unable to add ELF section: %s\n", name);
Patrick Georgidce629b2017-01-13 13:30:54 +01001256 free(name);
Furquan Shaikh7b405172016-08-05 08:20:37 -07001257 goto out;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001258 }
Patrick Georgidce629b2017-01-13 13:30:54 +01001259 free(name);
Antonello Dettorifda691e2016-06-09 12:35:36 +02001260
1261 if (empty_sz != 0) {
1262 struct buffer b;
1263
1264 buffer_init(&b, NULL, NULL, 0);
1265 memset(&shdr, 0, sizeof(shdr));
1266 shdr.sh_type = SHT_NOBITS;
1267 shdr.sh_flags = SHF_WRITE | SHF_ALLOC;
1268 shdr.sh_addr = segs[i].load_addr + segs[i].len;
1269 shdr.sh_size = empty_sz;
1270 name = strdup(".empty");
Patrick Georgidce629b2017-01-13 13:30:54 +01001271 if (!name) {
1272 ERROR("out of memory\n");
Furquan Shaikh7b405172016-08-05 08:20:37 -07001273 goto out;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001274 }
Patrick Georgidce629b2017-01-13 13:30:54 +01001275 if (elf_writer_add_section(ew, &shdr, &b, name)) {
1276 ERROR("Unable to add ELF section: %s\n", name);
1277 free(name);
1278 goto out;
1279 }
1280 free(name);
Antonello Dettorifda691e2016-06-09 12:35:36 +02001281 }
Antonello Dettorifda691e2016-06-09 12:35:36 +02001282 }
1283
1284 if (elf_writer_serialize(ew, &elf_out)) {
1285 ERROR("Unable to create ELF file from stage.\n");
Furquan Shaikh7b405172016-08-05 08:20:37 -07001286 goto out;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001287 }
1288
1289 /* Flip buffer with the created ELF one. */
1290 buffer_delete(buff);
1291 *buff = elf_out;
Furquan Shaikh7b405172016-08-05 08:20:37 -07001292 retval = 0;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001293
Furquan Shaikh7b405172016-08-05 08:20:37 -07001294out:
1295 free(segs);
Antonello Dettorifda691e2016-06-09 12:35:36 +02001296 elf_writer_destroy(ew);
Furquan Shaikh7b405172016-08-05 08:20:37 -07001297 return retval;
Antonello Dettorifda691e2016-06-09 12:35:36 +02001298}
1299
Hung-Te Lin0f8af712013-01-29 02:29:49 +08001300int cbfs_export_entry(struct cbfs_image *image, const char *entry_name,
Joel Kitching21fdd892018-08-09 17:49:52 +08001301 const char *filename, uint32_t arch, bool do_processing)
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001302{
Hung-Te Lin0f8af712013-01-29 02:29:49 +08001303 struct cbfs_file *entry = cbfs_get_entry(image, entry_name);
1304 struct buffer buffer;
1305 if (!entry) {
1306 ERROR("File not found: %s\n", entry_name);
1307 return -1;
1308 }
Patrick Georgi23aeaff2015-08-26 13:01:10 +02001309
Joel Kitching21fdd892018-08-09 17:49:52 +08001310 unsigned int compressed_size = ntohl(entry->len);
Patrick Georgi23aeaff2015-08-26 13:01:10 +02001311 unsigned int decompressed_size = 0;
1312 unsigned int compression = cbfs_file_get_compression_info(entry,
1313 &decompressed_size);
Werner Zehbbf1df72018-11-21 13:07:50 +01001314 unsigned int buffer_len;
Joel Kitching21fdd892018-08-09 17:49:52 +08001315 decomp_func_ptr decompress;
Patrick Georgi23aeaff2015-08-26 13:01:10 +02001316
Joel Kitching21fdd892018-08-09 17:49:52 +08001317 if (do_processing) {
1318 decompress = decompression_function(compression);
1319 if (!decompress) {
1320 ERROR("looking up decompression routine failed\n");
1321 return -1;
1322 }
Werner Zehbbf1df72018-11-21 13:07:50 +01001323 buffer_len = decompressed_size;
Joel Kitching21fdd892018-08-09 17:49:52 +08001324 } else {
1325 /* Force nop decompression */
1326 decompress = decompression_function(CBFS_COMPRESS_NONE);
Werner Zehbbf1df72018-11-21 13:07:50 +01001327 buffer_len = compressed_size;
Patrick Georgi23aeaff2015-08-26 13:01:10 +02001328 }
1329
Joel Kitching21fdd892018-08-09 17:49:52 +08001330 LOG("Found file %.30s at 0x%x, type %.12s, compressed %d, size %d\n",
Hung-Te Lin0f8af712013-01-29 02:29:49 +08001331 entry_name, cbfs_get_entry_addr(image, entry),
Joel Kitching21fdd892018-08-09 17:49:52 +08001332 get_cbfs_entry_type_name(ntohl(entry->type)), compressed_size,
1333 decompressed_size);
Hung-Te Lin0f8af712013-01-29 02:29:49 +08001334
Aaron Durbin539aed02015-10-23 17:42:32 -05001335 buffer_init(&buffer, strdup("(cbfs_export_entry)"), NULL, 0);
Werner Zehbbf1df72018-11-21 13:07:50 +01001336 buffer.data = malloc(buffer_len);
1337 buffer.size = buffer_len;
Aaron Durbin539aed02015-10-23 17:42:32 -05001338
Joel Kitching21fdd892018-08-09 17:49:52 +08001339 if (decompress(CBFS_SUBHEADER(entry), compressed_size,
1340 buffer.data, buffer.size, NULL)) {
Patrick Georgi23aeaff2015-08-26 13:01:10 +02001341 ERROR("decompression failed for %s\n", entry_name);
Aaron Durbin539aed02015-10-23 17:42:32 -05001342 buffer_delete(&buffer);
Patrick Georgi23aeaff2015-08-26 13:01:10 +02001343 return -1;
1344 }
Aaron Durbin539aed02015-10-23 17:42:32 -05001345
1346 /*
1347 * The stage metadata is never compressed proper for cbfs_stage
1348 * files. The contents of the stage data can be though. Therefore
1349 * one has to do a second pass for stages to potentially decompress
1350 * the stage data to make it more meaningful.
1351 */
Joel Kitching21fdd892018-08-09 17:49:52 +08001352 if (do_processing) {
1353 int (*make_elf)(struct buffer *, uint32_t) = NULL;
1354 switch (ntohl(entry->type)) {
1355 case CBFS_COMPONENT_STAGE:
1356 make_elf = cbfs_stage_make_elf;
1357 break;
1358 case CBFS_COMPONENT_SELF:
1359 make_elf = cbfs_payload_make_elf;
1360 break;
Aaron Durbin539aed02015-10-23 17:42:32 -05001361 }
Joel Kitching21fdd892018-08-09 17:49:52 +08001362 if (make_elf && make_elf(&buffer, arch)) {
1363 ERROR("Failed to write %s into %s.\n",
1364 entry_name, filename);
Antonello Dettorifda691e2016-06-09 12:35:36 +02001365 buffer_delete(&buffer);
1366 return -1;
1367 }
Aaron Durbin539aed02015-10-23 17:42:32 -05001368 }
1369
Hung-Te Lin0f8af712013-01-29 02:29:49 +08001370 if (buffer_write_file(&buffer, filename) != 0) {
1371 ERROR("Failed to write %s into %s.\n",
1372 entry_name, filename);
Aaron Durbin539aed02015-10-23 17:42:32 -05001373 buffer_delete(&buffer);
Hung-Te Lin0f8af712013-01-29 02:29:49 +08001374 return -1;
1375 }
Aaron Durbin539aed02015-10-23 17:42:32 -05001376
1377 buffer_delete(&buffer);
Hung-Te Lin0f8af712013-01-29 02:29:49 +08001378 INFO("Successfully dumped the file to: %s\n", filename);
1379 return 0;
1380}
1381
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001382int cbfs_remove_entry(struct cbfs_image *image, const char *name)
1383{
Patrick Georgi4d1c5aa2015-07-17 22:07:26 +02001384 struct cbfs_file *entry;
Hung-Te Linc03d9b02013-01-29 02:38:40 +08001385 entry = cbfs_get_entry(image, name);
1386 if (!entry) {
1387 ERROR("CBFS file %s not found.\n", name);
1388 return -1;
1389 }
Hung-Te Linc03d9b02013-01-29 02:38:40 +08001390 DEBUG("cbfs_remove_entry: Removed %s @ 0x%x\n",
Patrick Georgic569b8b2015-07-15 16:42:38 +02001391 entry->filename, cbfs_get_entry_addr(image, entry));
Hung-Te Linc03d9b02013-01-29 02:38:40 +08001392 entry->type = htonl(CBFS_COMPONENT_DELETED);
Patrick Georgi4d1c5aa2015-07-17 22:07:26 +02001393 cbfs_walk(image, cbfs_merge_empty_entry, NULL);
Hung-Te Linc03d9b02013-01-29 02:38:40 +08001394 return 0;
1395}
1396
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001397int cbfs_print_header_info(struct cbfs_image *image)
1398{
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001399 char *name = strdup(image->buffer.name);
Sol Boucher3e060ed2015-05-05 15:40:15 -07001400 assert(image);
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001401 printf("%s: %zd kB, bootblocksize %d, romsize %d, offset 0x%x\n"
Stefan Reinauer8f50e532013-11-13 14:34:57 -08001402 "alignment: %d bytes, architecture: %s\n\n",
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001403 basename(name),
1404 image->buffer.size / 1024,
Sol Boucher3e060ed2015-05-05 15:40:15 -07001405 image->header.bootblocksize,
1406 image->header.romsize,
1407 image->header.offset,
1408 image->header.align,
1409 arch_to_string(image->header.architecture));
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001410 free(name);
1411 return 0;
1412}
1413
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001414static int cbfs_print_stage_info(struct cbfs_stage *stage, FILE* fp)
1415{
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001416 fprintf(fp,
1417 " %s compression, entry: 0x%" PRIx64 ", load: 0x%" PRIx64 ", "
1418 "length: %d/%d\n",
1419 lookup_name_by_type(types_cbfs_compression,
1420 stage->compression, "(unknown)"),
1421 stage->entry,
1422 stage->load,
1423 stage->len,
1424 stage->memlen);
1425 return 0;
1426}
1427
Hung-Te Lin0780d672014-05-16 10:14:05 +08001428static int cbfs_print_decoded_payload_segment_info(
1429 struct cbfs_payload_segment *seg, FILE *fp)
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001430{
Hung-Te Lin0780d672014-05-16 10:14:05 +08001431 /* The input (seg) must be already decoded by
1432 * cbfs_decode_payload_segment.
1433 */
1434 switch (seg->type) {
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001435 case PAYLOAD_SEGMENT_CODE:
1436 case PAYLOAD_SEGMENT_DATA:
1437 fprintf(fp, " %s (%s compression, offset: 0x%x, "
1438 "load: 0x%" PRIx64 ", length: %d/%d)\n",
Hung-Te Lin0780d672014-05-16 10:14:05 +08001439 (seg->type == PAYLOAD_SEGMENT_CODE ?
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001440 "code " : "data"),
1441 lookup_name_by_type(types_cbfs_compression,
Hung-Te Lin0780d672014-05-16 10:14:05 +08001442 seg->compression,
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001443 "(unknown)"),
Hung-Te Lin0780d672014-05-16 10:14:05 +08001444 seg->offset, seg->load_addr, seg->len,
1445 seg->mem_len);
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001446 break;
1447
1448 case PAYLOAD_SEGMENT_ENTRY:
1449 fprintf(fp, " entry (0x%" PRIx64 ")\n",
Hung-Te Lin0780d672014-05-16 10:14:05 +08001450 seg->load_addr);
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001451 break;
1452
1453 case PAYLOAD_SEGMENT_BSS:
1454 fprintf(fp, " BSS (address 0x%016" PRIx64 ", "
1455 "length 0x%x)\n",
Hung-Te Lin0780d672014-05-16 10:14:05 +08001456 seg->load_addr, seg->len);
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001457 break;
1458
1459 case PAYLOAD_SEGMENT_PARAMS:
1460 fprintf(fp, " parameters\n");
1461 break;
1462
1463 default:
1464 fprintf(fp, " 0x%x (%s compression, offset: 0x%x, "
1465 "load: 0x%" PRIx64 ", length: %d/%d\n",
Hung-Te Lin0780d672014-05-16 10:14:05 +08001466 seg->type,
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001467 lookup_name_by_type(types_cbfs_compression,
Hung-Te Lin0780d672014-05-16 10:14:05 +08001468 seg->compression,
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001469 "(unknown)"),
Hung-Te Lin0780d672014-05-16 10:14:05 +08001470 seg->offset, seg->load_addr, seg->len,
1471 seg->mem_len);
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001472 break;
1473 }
1474 return 0;
1475}
1476
1477int cbfs_print_entry_info(struct cbfs_image *image, struct cbfs_file *entry,
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001478 void *arg)
1479{
Patrick Georgic569b8b2015-07-15 16:42:38 +02001480 const char *name = entry->filename;
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001481 struct cbfs_payload_segment *payload;
1482 FILE *fp = (FILE *)arg;
1483
Hung-Te Lin408aefd2013-02-09 10:38:55 +08001484 if (!cbfs_is_valid_entry(image, entry)) {
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001485 ERROR("cbfs_print_entry_info: Invalid entry at 0x%x\n",
1486 cbfs_get_entry_addr(image, entry));
1487 return -1;
1488 }
1489 if (!fp)
1490 fp = stdout;
1491
Patrick Georgic82725c2015-08-26 12:13:03 +02001492 unsigned int decompressed_size = 0;
Patrick Georgia71c83f2015-08-26 12:23:26 +02001493 unsigned int compression = cbfs_file_get_compression_info(entry,
1494 &decompressed_size);
Daisuke Nojiri0c2f0c12017-10-26 17:40:41 -07001495 const char *compression_name = lookup_name_by_type(
1496 types_cbfs_compression, compression, "????");
Patrick Georgic82725c2015-08-26 12:13:03 +02001497
Daisuke Nojiri0c2f0c12017-10-26 17:40:41 -07001498 if (compression == CBFS_COMPRESS_NONE)
1499 fprintf(fp, "%-30s 0x%-8x %-12s %8d %-4s\n",
Patrick Georgic82725c2015-08-26 12:13:03 +02001500 *name ? name : "(empty)",
1501 cbfs_get_entry_addr(image, entry),
1502 get_cbfs_entry_type_name(ntohl(entry->type)),
1503 ntohl(entry->len),
Daisuke Nojiri0c2f0c12017-10-26 17:40:41 -07001504 compression_name
Patrick Georgic82725c2015-08-26 12:13:03 +02001505 );
Daisuke Nojiri0c2f0c12017-10-26 17:40:41 -07001506 else
1507 fprintf(fp, "%-30s 0x%-8x %-12s %8d %-4s (%d decompressed)\n",
1508 *name ? name : "(empty)",
1509 cbfs_get_entry_addr(image, entry),
1510 get_cbfs_entry_type_name(ntohl(entry->type)),
1511 ntohl(entry->len),
1512 compression_name,
1513 decompressed_size
1514 );
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001515
Patrick Georgi89f20342015-10-01 15:54:04 +02001516 struct cbfs_file_attr_hash *hash = NULL;
1517 while ((hash = cbfs_file_get_next_hash(entry, hash)) != NULL) {
1518 unsigned int hash_type = ntohl(hash->hash_type);
Furquan Shaikh1d56eef2016-12-02 09:24:50 -08001519 if (hash_type >= CBFS_NUM_SUPPORTED_HASHES) {
Patrick Georgi89f20342015-10-01 15:54:04 +02001520 fprintf(fp, "invalid hash type %d\n", hash_type);
1521 break;
1522 }
1523 size_t hash_len = widths_cbfs_hash[hash_type];
1524 char *hash_str = bintohex(hash->hash_data, hash_len);
1525 uint8_t local_hash[hash_len];
1526 if (vb2_digest_buffer(CBFS_SUBHEADER(entry),
1527 ntohl(entry->len), hash_type, local_hash,
1528 hash_len) != VB2_SUCCESS) {
1529 fprintf(fp, "failed to hash '%s'\n", name);
Patrick Georgi862df922016-12-14 16:10:00 +01001530 free(hash_str);
Patrick Georgi89f20342015-10-01 15:54:04 +02001531 break;
1532 }
1533 int valid = memcmp(local_hash, hash->hash_data, hash_len) == 0;
1534 const char *valid_str = valid ? "valid" : "invalid";
1535
1536 fprintf(fp, " hash %s:%s %s\n",
1537 get_hash_attr_name(hash_type),
1538 hash_str, valid_str);
1539 free(hash_str);
1540 }
1541
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001542 if (!verbose)
1543 return 0;
1544
1545 DEBUG(" cbfs_file=0x%x, offset=0x%x, content_address=0x%x+0x%x\n",
1546 cbfs_get_entry_addr(image, entry), ntohl(entry->offset),
1547 cbfs_get_entry_addr(image, entry) + ntohl(entry->offset),
1548 ntohl(entry->len));
1549
1550 /* note the components of the subheader may be in host order ... */
1551 switch (ntohl(entry->type)) {
1552 case CBFS_COMPONENT_STAGE:
1553 cbfs_print_stage_info((struct cbfs_stage *)
1554 CBFS_SUBHEADER(entry), fp);
1555 break;
1556
Patrick Rudolph4f5bed52018-05-02 09:44:08 +02001557 case CBFS_COMPONENT_SELF:
Paul Menzel831bbe82015-08-08 20:20:57 +02001558 payload = (struct cbfs_payload_segment *)
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001559 CBFS_SUBHEADER(entry);
1560 while (payload) {
Hung-Te Lin0780d672014-05-16 10:14:05 +08001561 struct cbfs_payload_segment seg;
1562 cbfs_decode_payload_segment(&seg, payload);
1563 cbfs_print_decoded_payload_segment_info(
1564 &seg, fp);
1565 if (seg.type == PAYLOAD_SEGMENT_ENTRY)
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001566 break;
Hung-Te Lin0780d672014-05-16 10:14:05 +08001567 else
Aaron Durbinca630272014-08-05 10:48:20 -05001568 payload ++;
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001569 }
1570 break;
1571 default:
1572 break;
1573 }
1574 return 0;
1575}
1576
Aaron Durbin5dc628a2016-01-26 15:35:34 -06001577static int cbfs_print_parseable_entry_info(struct cbfs_image *image,
1578 struct cbfs_file *entry, void *arg)
1579{
1580 FILE *fp = (FILE *)arg;
1581 const char *name;
1582 const char *type;
1583 size_t offset;
1584 size_t metadata_size;
1585 size_t data_size;
1586 const char *sep = "\t";
1587
1588 if (!cbfs_is_valid_entry(image, entry)) {
1589 ERROR("cbfs_print_entry_info: Invalid entry at 0x%x\n",
1590 cbfs_get_entry_addr(image, entry));
1591 return -1;
1592 }
1593
1594 name = entry->filename;
1595 if (*name == '\0')
1596 name = "(empty)";
1597 type = get_cbfs_entry_type_name(ntohl(entry->type)),
1598 metadata_size = ntohl(entry->offset);
1599 data_size = ntohl(entry->len);
1600 offset = cbfs_get_entry_addr(image, entry);
1601
1602 fprintf(fp, "%s%s", name, sep);
1603 fprintf(fp, "0x%zx%s", offset, sep);
1604 fprintf(fp, "%s%s", type, sep);
1605 fprintf(fp, "0x%zx%s", metadata_size, sep);
1606 fprintf(fp, "0x%zx%s", data_size, sep);
1607 fprintf(fp, "0x%zx\n", metadata_size + data_size);
1608
1609 return 0;
1610}
1611
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001612int cbfs_print_directory(struct cbfs_image *image)
1613{
Sol Boucher67a0a862015-03-18 12:36:27 -07001614 if (cbfs_is_legacy_cbfs(image))
1615 cbfs_print_header_info(image);
Daisuke Nojiri0c2f0c12017-10-26 17:40:41 -07001616 printf("%-30s %-10s %-12s Size Comp\n", "Name", "Offset", "Type");
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001617 cbfs_walk(image, cbfs_print_entry_info, NULL);
1618 return 0;
1619}
1620
Aaron Durbin5dc628a2016-01-26 15:35:34 -06001621int cbfs_print_parseable_directory(struct cbfs_image *image)
1622{
Furquan Shaikh161d2332016-05-26 14:41:02 -07001623 size_t i;
Aaron Durbin5dc628a2016-01-26 15:35:34 -06001624 const char *header[] = {
1625 "Name",
1626 "Offset",
1627 "Type",
1628 "Metadata Size",
1629 "Data Size",
1630 "Total Size",
1631 };
1632 const char *sep = "\t";
1633
1634 for (i = 0; i < ARRAY_SIZE(header) - 1; i++)
1635 fprintf(stdout, "%s%s", header[i], sep);
1636 fprintf(stdout, "%s\n", header[i]);
1637 cbfs_walk(image, cbfs_print_parseable_entry_info, stdout);
1638 return 0;
1639}
1640
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001641int cbfs_merge_empty_entry(struct cbfs_image *image, struct cbfs_file *entry,
Sol Boucher0e539312015-03-05 15:38:03 -08001642 unused void *arg)
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001643{
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001644 struct cbfs_file *next;
Daisuke Nojiri2b59c612018-10-02 12:59:58 -07001645 uint32_t next_addr = 0;
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001646
Daisuke Nojiri2b59c612018-10-02 12:59:58 -07001647 /* We don't return here even if this entry is already empty because we
1648 want to merge the empty entries following after it. */
1649
1650 /* Loop until non-empty entry is found, starting from the current entry.
1651 After the loop, next_addr points to the next non-empty entry. */
1652 next = entry;
1653 while (ntohl(next->type) == CBFS_COMPONENT_DELETED ||
1654 ntohl(next->type) == CBFS_COMPONENT_NULL) {
1655 next = cbfs_find_next_entry(image, next);
1656 if (!next)
1657 break;
1658 next_addr = cbfs_get_entry_addr(image, next);
1659 if (!cbfs_is_valid_entry(image, next))
1660 /* 'next' could be the end of cbfs */
1661 break;
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001662 }
Daisuke Nojiri2b59c612018-10-02 12:59:58 -07001663
1664 if (!next_addr)
1665 /* Nothing to empty */
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001666 return 0;
1667
Daisuke Nojiri2b59c612018-10-02 12:59:58 -07001668 /* We can return here if we find only a single empty entry.
1669 For simplicity, we just proceed (and make it empty again). */
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001670
Daisuke Nojiri2b59c612018-10-02 12:59:58 -07001671 /* We're creating one empty entry for combined empty spaces */
1672 uint32_t addr = cbfs_get_entry_addr(image, entry);
1673 size_t len = next_addr - addr - cbfs_calculate_file_header_size("");
1674 DEBUG("join_empty_entry: [0x%x, 0x%x) len=%zu\n", addr, next_addr, len);
1675 cbfs_create_empty_entry(entry, CBFS_COMPONENT_NULL, len, "");
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001676
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001677 return 0;
1678}
1679
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001680int cbfs_walk(struct cbfs_image *image, cbfs_entry_callback callback,
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001681 void *arg)
1682{
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001683 int count = 0;
1684 struct cbfs_file *entry;
1685 for (entry = cbfs_find_first_entry(image);
Hung-Te Lin408aefd2013-02-09 10:38:55 +08001686 entry && cbfs_is_valid_entry(image, entry);
Hung-Te Lin3bb035b2013-01-29 02:15:49 +08001687 entry = cbfs_find_next_entry(image, entry)) {
1688 count ++;
1689 if (callback(image, entry, arg) != 0)
1690 break;
1691 }
1692 return count;
1693}
1694
Patrick Georgi7db2b6c2015-11-11 15:35:24 +01001695static int cbfs_header_valid(struct cbfs_header *header)
Vadim Bendebury458a12e2014-12-23 15:10:12 -08001696{
1697 if ((ntohl(header->magic) == CBFS_HEADER_MAGIC) &&
1698 ((ntohl(header->version) == CBFS_HEADER_VERSION1) ||
1699 (ntohl(header->version) == CBFS_HEADER_VERSION2)) &&
Vadim Bendebury458a12e2014-12-23 15:10:12 -08001700 (ntohl(header->offset) < ntohl(header->romsize)))
1701 return 1;
1702 return 0;
1703}
1704
1705struct cbfs_header *cbfs_find_header(char *data, size_t size,
1706 uint32_t forced_offset)
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001707{
Hung-Te Lineab2c812013-01-29 01:56:17 +08001708 size_t offset;
1709 int found = 0;
Julius Wernerefcee762014-11-10 13:14:24 -08001710 int32_t rel_offset;
Hung-Te Lineab2c812013-01-29 01:56:17 +08001711 struct cbfs_header *header, *result = NULL;
1712
Vadim Bendebury458a12e2014-12-23 15:10:12 -08001713 if (forced_offset < (size - sizeof(struct cbfs_header))) {
1714 /* Check if the forced header is valid. */
1715 header = (struct cbfs_header *)(data + forced_offset);
Patrick Georgi7db2b6c2015-11-11 15:35:24 +01001716 if (cbfs_header_valid(header))
Vadim Bendebury458a12e2014-12-23 15:10:12 -08001717 return header;
1718 return NULL;
1719 }
1720
Julius Wernerefcee762014-11-10 13:14:24 -08001721 // Try finding relative offset of master header at end of file first.
1722 rel_offset = *(int32_t *)(data + size - sizeof(int32_t));
1723 offset = size + rel_offset;
1724 DEBUG("relative offset: %#zx(-%#zx), offset: %#zx\n",
1725 (size_t)rel_offset, (size_t)-rel_offset, offset);
Vadim Bendebury458a12e2014-12-23 15:10:12 -08001726
Hung-Te Lineab2c812013-01-29 01:56:17 +08001727 if (offset >= size - sizeof(*header) ||
Patrick Georgi7db2b6c2015-11-11 15:35:24 +01001728 !cbfs_header_valid((struct cbfs_header *)(data + offset))) {
Julius Wernerefcee762014-11-10 13:14:24 -08001729 // Some use cases append non-CBFS data to the end of the ROM.
1730 DEBUG("relative offset seems wrong, scanning whole image...\n");
Hung-Te Lineab2c812013-01-29 01:56:17 +08001731 offset = 0;
Julius Wernerefcee762014-11-10 13:14:24 -08001732 }
Hung-Te Lineab2c812013-01-29 01:56:17 +08001733
1734 for (; offset + sizeof(*header) < size; offset++) {
1735 header = (struct cbfs_header *)(data + offset);
Patrick Georgi7db2b6c2015-11-11 15:35:24 +01001736 if (!cbfs_header_valid(header))
Hung-Te Lineab2c812013-01-29 01:56:17 +08001737 continue;
Julius Wernerefcee762014-11-10 13:14:24 -08001738 if (!found++)
1739 result = header;
Hung-Te Lineab2c812013-01-29 01:56:17 +08001740 }
Julius Wernerefcee762014-11-10 13:14:24 -08001741 if (found > 1)
1742 // Top-aligned images usually have a working relative offset
1743 // field, so this is more likely to happen on bottom-aligned
1744 // ones (where the first header is the "outermost" one)
1745 WARN("Multiple (%d) CBFS headers found, using the first one.\n",
Hung-Te Lineab2c812013-01-29 01:56:17 +08001746 found);
Hung-Te Lineab2c812013-01-29 01:56:17 +08001747 return result;
1748}
1749
1750
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001751struct cbfs_file *cbfs_find_first_entry(struct cbfs_image *image)
1752{
Sol Boucher3e060ed2015-05-05 15:40:15 -07001753 assert(image);
Patrick Georgi7db2b6c2015-11-11 15:35:24 +01001754 if (image->has_header)
1755 /* header.offset is relative to start of flash, not
1756 * start of region, so use it with the full image.
1757 */
1758 return (struct cbfs_file *)
1759 (buffer_get_original_backing(&image->buffer) +
1760 image->header.offset);
1761 else
1762 return (struct cbfs_file *)buffer_get(&image->buffer);
Hung-Te Lineab2c812013-01-29 01:56:17 +08001763}
1764
1765struct cbfs_file *cbfs_find_next_entry(struct cbfs_image *image,
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001766 struct cbfs_file *entry)
1767{
Hung-Te Lineab2c812013-01-29 01:56:17 +08001768 uint32_t addr = cbfs_get_entry_addr(image, entry);
Sol Boucher67a0a862015-03-18 12:36:27 -07001769 int align = image->has_header ? image->header.align :
1770 CBFS_ENTRY_ALIGNMENT;
Hung-Te Lin408aefd2013-02-09 10:38:55 +08001771 assert(entry && cbfs_is_valid_entry(image, entry));
Hung-Te Lineab2c812013-01-29 01:56:17 +08001772 addr += ntohl(entry->offset) + ntohl(entry->len);
1773 addr = align_up(addr, align);
1774 return (struct cbfs_file *)(image->buffer.data + addr);
1775}
1776
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001777uint32_t cbfs_get_entry_addr(struct cbfs_image *image, struct cbfs_file *entry)
1778{
Hung-Te Lineab2c812013-01-29 01:56:17 +08001779 assert(image && image->buffer.data && entry);
1780 return (int32_t)((char *)entry - image->buffer.data);
1781}
1782
Sol Boucher67a0a862015-03-18 12:36:27 -07001783int cbfs_is_valid_cbfs(struct cbfs_image *image)
1784{
1785 return buffer_check_magic(&image->buffer, CBFS_FILE_MAGIC,
1786 strlen(CBFS_FILE_MAGIC));
1787}
1788
1789int cbfs_is_legacy_cbfs(struct cbfs_image *image)
1790{
1791 return image->has_header;
1792}
1793
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001794int cbfs_is_valid_entry(struct cbfs_image *image, struct cbfs_file *entry)
1795{
Sol Bouchere3260a02015-03-25 13:40:08 -07001796 uint32_t offset = cbfs_get_entry_addr(image, entry);
1797
1798 if (offset >= image->buffer.size)
1799 return 0;
1800
1801 struct buffer entry_data;
1802 buffer_clone(&entry_data, &image->buffer);
1803 buffer_seek(&entry_data, offset);
1804 return buffer_check_magic(&entry_data, CBFS_FILE_MAGIC,
Sol Boucher67a0a862015-03-18 12:36:27 -07001805 strlen(CBFS_FILE_MAGIC));
Hung-Te Lineab2c812013-01-29 01:56:17 +08001806}
1807
Patrick Georgi57edf162015-08-12 09:20:11 +02001808struct cbfs_file *cbfs_create_file_header(int type,
Vadim Bendebury45e59972014-12-23 15:59:57 -08001809 size_t len, const char *name)
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001810{
Patrick Georgi2c615062015-07-15 20:49:00 +02001811 struct cbfs_file *entry = malloc(MAX_CBFS_FILE_HEADER_BUFFER);
1812 memset(entry, CBFS_CONTENT_DEFAULT_VALUE, MAX_CBFS_FILE_HEADER_BUFFER);
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001813 memcpy(entry->magic, CBFS_FILE_MAGIC, sizeof(entry->magic));
Patrick Georgiedf25d92015-08-12 09:12:06 +02001814 entry->type = htonl(type);
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001815 entry->len = htonl(len);
Patrick Georgi0d618af2015-07-15 18:28:23 +02001816 entry->attributes_offset = 0;
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001817 entry->offset = htonl(cbfs_calculate_file_header_size(name));
Patrick Georgic569b8b2015-07-15 16:42:38 +02001818 memset(entry->filename, 0, ntohl(entry->offset) - sizeof(*entry));
1819 strcpy(entry->filename, name);
Patrick Georgi57edf162015-08-12 09:20:11 +02001820 return entry;
1821}
1822
1823int cbfs_create_empty_entry(struct cbfs_file *entry, int type,
1824 size_t len, const char *name)
1825{
1826 struct cbfs_file *tmp = cbfs_create_file_header(type, len, name);
1827 memcpy(entry, tmp, ntohl(tmp->offset));
1828 free(tmp);
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001829 memset(CBFS_SUBHEADER(entry), CBFS_CONTENT_DEFAULT_VALUE, len);
1830 return 0;
1831}
1832
Patrick Georgi2c615062015-07-15 20:49:00 +02001833struct cbfs_file_attribute *cbfs_file_first_attr(struct cbfs_file *file)
1834{
1835 /* attributes_offset should be 0 when there is no attribute, but all
1836 * values that point into the cbfs_file header are invalid, too. */
1837 if (ntohl(file->attributes_offset) <= sizeof(*file))
1838 return NULL;
1839
1840 /* There needs to be enough space for the file header and one
1841 * attribute header for this to make sense. */
1842 if (ntohl(file->offset) <=
1843 sizeof(*file) + sizeof(struct cbfs_file_attribute))
1844 return NULL;
1845
1846 return (struct cbfs_file_attribute *)
1847 (((uint8_t *)file) + ntohl(file->attributes_offset));
1848}
1849
1850struct cbfs_file_attribute *cbfs_file_next_attr(struct cbfs_file *file,
1851 struct cbfs_file_attribute *attr)
1852{
1853 /* ex falso sequitur quodlibet */
1854 if (attr == NULL)
1855 return NULL;
1856
1857 /* Is there enough space for another attribute? */
1858 if ((uint8_t *)attr + ntohl(attr->len) +
Patrick Rudolphe28fa402019-02-14 11:19:07 +01001859 sizeof(struct cbfs_file_attribute) >
Patrick Georgi2c615062015-07-15 20:49:00 +02001860 (uint8_t *)file + ntohl(file->offset))
1861 return NULL;
1862
1863 struct cbfs_file_attribute *next = (struct cbfs_file_attribute *)
1864 (((uint8_t *)attr) + ntohl(attr->len));
1865 /* If any, "unused" attributes must come last. */
1866 if (ntohl(next->tag) == CBFS_FILE_ATTR_TAG_UNUSED)
1867 return NULL;
1868 if (ntohl(next->tag) == CBFS_FILE_ATTR_TAG_UNUSED2)
1869 return NULL;
1870
1871 return next;
1872}
1873
1874struct cbfs_file_attribute *cbfs_add_file_attr(struct cbfs_file *header,
1875 uint32_t tag,
1876 uint32_t size)
1877{
1878 struct cbfs_file_attribute *attr, *next;
1879 next = cbfs_file_first_attr(header);
1880 do {
1881 attr = next;
1882 next = cbfs_file_next_attr(header, attr);
1883 } while (next != NULL);
1884 uint32_t header_size = ntohl(header->offset) + size;
1885 if (header_size > MAX_CBFS_FILE_HEADER_BUFFER) {
1886 DEBUG("exceeding allocated space for cbfs_file headers");
1887 return NULL;
1888 }
1889 /* attr points to the last valid attribute now.
1890 * If NULL, we have to create the first one. */
1891 if (attr == NULL) {
1892 /* New attributes start where the header ends.
Elyes HAOUAS3db01982018-08-23 18:08:20 +02001893 * header->offset is later set to accommodate the
Patrick Georgi2c615062015-07-15 20:49:00 +02001894 * additional structure.
Elyes HAOUAS3db01982018-08-23 18:08:20 +02001895 * No endianness translation necessary here, because both
Patrick Georgi2c615062015-07-15 20:49:00 +02001896 * fields are encoded the same way. */
1897 header->attributes_offset = header->offset;
1898 attr = (struct cbfs_file_attribute *)
1899 (((uint8_t *)header) +
1900 ntohl(header->attributes_offset));
1901 } else {
1902 attr = (struct cbfs_file_attribute *)
1903 (((uint8_t *)attr) +
1904 ntohl(attr->len));
1905 }
1906 header->offset = htonl(header_size);
1907 memset(attr, CBFS_CONTENT_DEFAULT_VALUE, size);
1908 attr->tag = htonl(tag);
1909 attr->len = htonl(size);
1910 return attr;
1911}
1912
Patrick Georgi89f20342015-10-01 15:54:04 +02001913int cbfs_add_file_hash(struct cbfs_file *header, struct buffer *buffer,
1914 enum vb2_hash_algorithm hash_type)
1915{
zbao37450ff2015-11-05 14:35:57 +08001916 uint32_t hash_index = hash_type;
1917
1918 if (hash_index >= CBFS_NUM_SUPPORTED_HASHES)
Patrick Georgi89f20342015-10-01 15:54:04 +02001919 return -1;
1920
1921 unsigned hash_size = widths_cbfs_hash[hash_type];
1922 if (hash_size == 0)
1923 return -1;
1924
1925 struct cbfs_file_attr_hash *attrs =
1926 (struct cbfs_file_attr_hash *)cbfs_add_file_attr(header,
1927 CBFS_FILE_ATTR_TAG_HASH,
1928 sizeof(struct cbfs_file_attr_hash) + hash_size);
1929
1930 if (attrs == NULL)
1931 return -1;
1932
1933 attrs->hash_type = htonl(hash_type);
1934 if (vb2_digest_buffer(buffer_get(buffer), buffer_size(buffer),
1935 hash_type, attrs->hash_data, hash_size) != VB2_SUCCESS)
1936 return -1;
1937
1938 return 0;
1939}
1940
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001941/* Finds a place to hold whole data in same memory page. */
1942static int is_in_same_page(uint32_t start, uint32_t size, uint32_t page)
1943{
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001944 if (!page)
1945 return 1;
1946 return (start / page) == (start + size - 1) / page;
1947}
1948
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08001949/* Tests if data can fit in a range by given offset:
Aaron Durbind7339412015-09-15 12:50:14 -05001950 * start ->| metadata_size | offset (+ size) |<- end
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08001951 */
Aaron Durbind7339412015-09-15 12:50:14 -05001952static int is_in_range(size_t start, size_t end, size_t metadata_size,
1953 size_t offset, size_t size)
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001954{
Aaron Durbind7339412015-09-15 12:50:14 -05001955 return (offset >= start + metadata_size && offset + size <= end);
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08001956}
1957
Werner Zeh95bfcae2016-01-25 12:47:20 +01001958static size_t absolute_align(const struct cbfs_image *image, size_t val,
1959 size_t align)
1960{
1961 const size_t region_offset = buffer_offset(&image->buffer);
1962 /* To perform alignment on absolute address, take the region offset */
1963 /* of the image into account. */
1964 return align_up(val + region_offset, align) - region_offset;
1965
1966}
1967
Aaron Durbind7339412015-09-15 12:50:14 -05001968int32_t cbfs_locate_entry(struct cbfs_image *image, size_t size,
1969 size_t page_size, size_t align, size_t metadata_size)
Stefan Reinauerdc7bc8e2013-03-26 12:51:36 -07001970{
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001971 struct cbfs_file *entry;
1972 size_t need_len;
Aaron Durbind7339412015-09-15 12:50:14 -05001973 size_t addr, addr_next, addr2, addr3, offset;
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08001974
1975 /* Default values: allow fitting anywhere in ROM. */
1976 if (!page_size)
Sol Boucher67a0a862015-03-18 12:36:27 -07001977 page_size = image->has_header ? image->header.romsize :
1978 image->buffer.size;
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08001979 if (!align)
1980 align = 1;
1981
1982 if (size > page_size)
Aaron Durbind7339412015-09-15 12:50:14 -05001983 ERROR("Input file size (%zd) greater than page size (%zd).\n",
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08001984 size, page_size);
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001985
Aaron Durbind7339412015-09-15 12:50:14 -05001986 size_t image_align = image->has_header ? image->header.align :
Sol Boucher67a0a862015-03-18 12:36:27 -07001987 CBFS_ENTRY_ALIGNMENT;
1988 if (page_size % image_align)
Aaron Durbind7339412015-09-15 12:50:14 -05001989 WARN("%s: Page size (%#zx) not aligned with CBFS image (%#zx).\n",
Sol Boucher67a0a862015-03-18 12:36:27 -07001990 __func__, page_size, image_align);
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001991
Aaron Durbind7339412015-09-15 12:50:14 -05001992 need_len = metadata_size + size;
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001993
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08001994 // Merge empty entries to build get max available space.
Hung-Te Lin215d1d72013-01-29 03:46:02 +08001995 cbfs_walk(image, cbfs_merge_empty_entry, NULL);
1996
1997 /* Three cases of content location on memory page:
1998 * case 1.
1999 * | PAGE 1 | PAGE 2 |
2000 * | <header><content>| Fit. Return start of content.
2001 *
2002 * case 2.
2003 * | PAGE 1 | PAGE 2 |
2004 * | <header><content> | Fits when we shift content to align
2005 * shift-> | <header>|<content> | at starting of PAGE 2.
2006 *
2007 * case 3. (large content filling whole page)
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08002008 * | PAGE 1 | PAGE 2 | PAGE 3 |
2009 * | <header>< content > | Can't fit. If we shift content to
2010 * |trial-> <header>< content > | PAGE 2, header can't fit in free
2011 * | shift-> <header><content> space, so we must use PAGE 3.
Hung-Te Lin215d1d72013-01-29 03:46:02 +08002012 *
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08002013 * The returned address can be then used as "base-address" (-b) in add-*
2014 * commands (will be re-calculated and positioned by cbfs_add_entry_at).
2015 * For stage targets, the address is also used to re-link stage before
2016 * being added into CBFS.
Hung-Te Lin215d1d72013-01-29 03:46:02 +08002017 */
2018 for (entry = cbfs_find_first_entry(image);
Hung-Te Lin408aefd2013-02-09 10:38:55 +08002019 entry && cbfs_is_valid_entry(image, entry);
Hung-Te Lin215d1d72013-01-29 03:46:02 +08002020 entry = cbfs_find_next_entry(image, entry)) {
2021
2022 uint32_t type = ntohl(entry->type);
2023 if (type != CBFS_COMPONENT_NULL)
2024 continue;
2025
2026 addr = cbfs_get_entry_addr(image, entry);
2027 addr_next = cbfs_get_entry_addr(image, cbfs_find_next_entry(
2028 image, entry));
2029 if (addr_next - addr < need_len)
2030 continue;
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08002031
Werner Zeh95bfcae2016-01-25 12:47:20 +01002032 offset = absolute_align(image, addr + metadata_size, align);
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08002033 if (is_in_same_page(offset, size, page_size) &&
Aaron Durbind7339412015-09-15 12:50:14 -05002034 is_in_range(addr, addr_next, metadata_size, offset, size)) {
Hung-Te Lin215d1d72013-01-29 03:46:02 +08002035 DEBUG("cbfs_locate_entry: FIT (PAGE1).");
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08002036 return offset;
Hung-Te Lin215d1d72013-01-29 03:46:02 +08002037 }
2038
2039 addr2 = align_up(addr, page_size);
Werner Zeh95bfcae2016-01-25 12:47:20 +01002040 offset = absolute_align(image, addr2, align);
Aaron Durbind7339412015-09-15 12:50:14 -05002041 if (is_in_range(addr, addr_next, metadata_size, offset, size)) {
Hung-Te Lin215d1d72013-01-29 03:46:02 +08002042 DEBUG("cbfs_locate_entry: OVERLAP (PAGE2).");
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08002043 return offset;
Hung-Te Lin215d1d72013-01-29 03:46:02 +08002044 }
2045
Aaron Durbind7339412015-09-15 12:50:14 -05002046 /* Assume page_size >= metadata_size so adding one page will
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08002047 * definitely provide the space for header. */
Aaron Durbind7339412015-09-15 12:50:14 -05002048 assert(page_size >= metadata_size);
Hung-Te Lin215d1d72013-01-29 03:46:02 +08002049 addr3 = addr2 + page_size;
Werner Zeh95bfcae2016-01-25 12:47:20 +01002050 offset = absolute_align(image, addr3, align);
Aaron Durbind7339412015-09-15 12:50:14 -05002051 if (is_in_range(addr, addr_next, metadata_size, offset, size)) {
Hung-Te Lin215d1d72013-01-29 03:46:02 +08002052 DEBUG("cbfs_locate_entry: OVERLAP+ (PAGE3).");
Hung-Te Line4ea2ca2013-03-19 12:24:43 +08002053 return offset;
Hung-Te Lin215d1d72013-01-29 03:46:02 +08002054 }
2055 }
2056 return -1;
2057}