xref: /aosp_15_r20/external/flashrom/fmap.c (revision 0d6140be3aa665ecc836e8907834fcd3e3b018fc)
1 /*
2  * Copyright 2010, Google LLC.
3  * Copyright 2018-present, Facebook Inc.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are
8  * met:
9  *
10  *    * Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *    * Redistributions in binary form must reproduce the above
13  * copyright notice, this list of conditions and the following disclaimer
14  * in the documentation and/or other materials provided with the
15  * distribution.
16  *    * Neither the name of Google Inc. nor the names of its
17  * contributors may be used to endorse or promote products derived from
18  * this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * Alternatively, this software may be distributed under the terms of the
33  * GNU General Public License ("GPL") version 2 as published by the Free
34  * Software Foundation.
35  */
36 
37 #include <ctype.h>
38 #include <stdbool.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sys/types.h>
42 #include "flash.h"
43 #include "fmap.h"
44 
fmap_size(const struct fmap * fmap)45 static size_t fmap_size(const struct fmap *fmap)
46 {
47 	return sizeof(*fmap) + (fmap->nareas * sizeof(struct fmap_area));
48 }
49 
50 /* Make a best-effort assessment if the given fmap is real */
is_valid_fmap(const struct fmap * fmap)51 static int is_valid_fmap(const struct fmap *fmap)
52 {
53 	if (memcmp(fmap, FMAP_SIGNATURE, strlen(FMAP_SIGNATURE)) != 0)
54 		return 0;
55 	/* strings containing the magic tend to fail here */
56 	if (fmap->ver_major != FMAP_VER_MAJOR)
57 		return 0;
58 	/* a basic consistency check: flash address space size should be larger
59 	 * than the size of the fmap data structure */
60 	if (fmap->size < fmap_size(fmap))
61 		return 0;
62 
63 	/* fmap-alikes along binary data tend to fail on having a valid,
64 	 * null-terminated string in the name field.*/
65 	int i;
66 	for (i = 0; i < FMAP_STRLEN; i++) {
67 		if (fmap->name[i] == 0)
68 			break;
69 		if (!isgraph(fmap->name[i]))
70 			return 0;
71 		if (i == FMAP_STRLEN - 1) {
72 			/* name is specified to be null terminated single-word string
73 			 * without spaces. We did not break in the 0 test, we know it
74 			 * is a printable spaceless string but we're seeing FMAP_STRLEN
75 			 * symbols, which is one too many.
76 			 */
77 			 return 0;
78 		}
79 	}
80 	return 1;
81 
82 }
83 
84 /**
85  * @brief Do a brute-force linear search for fmap in provided buffer
86  *
87  * @param[in] buffer The buffer to search
88  * @param[in] len Length (in bytes) to search
89  *
90  * @return offset in buffer where fmap is found if successful
91  *         -1 to indicate that fmap was not found
92  *         -2 to indicate fmap is truncated or exceeds buffer + len
93  */
fmap_lsearch(const uint8_t * buf,size_t len)94 static ssize_t fmap_lsearch(const uint8_t *buf, size_t len)
95 {
96 	ssize_t offset;
97 	bool fmap_found = false;
98 
99 	if (len < sizeof(struct fmap))
100 		return -1;
101 
102 	for (offset = 0; offset <= (ssize_t)(len - sizeof(struct fmap)); offset++) {
103 		if (is_valid_fmap((struct fmap *)&buf[offset])) {
104 			fmap_found = true;
105 			break;
106 		}
107 	}
108 
109 	if (!fmap_found)
110 		return -1;
111 
112 	if (offset + fmap_size((struct fmap *)&buf[offset]) > len) {
113 		msg_gerr("fmap size exceeds buffer boundary.\n");
114 		return -2;
115 	}
116 
117 	return offset;
118 }
119 
120 /**
121  * @brief Read fmap from provided buffer and copy it to fmap_out
122  *
123  * @param[out] fmap_out Double-pointer to location to store fmap contents.
124  *                      Caller must free allocated fmap contents.
125  * @param[in] buf Buffer to search
126  * @param[in] len Length (in bytes) to search
127  *
128  * @return 0 if successful
129  *         1 to indicate error
130  *         2 to indicate fmap is not found
131  */
fmap_read_from_buffer(struct fmap ** fmap_out,const uint8_t * const buf,size_t len)132 int fmap_read_from_buffer(struct fmap **fmap_out, const uint8_t *const buf, size_t len)
133 {
134 	ssize_t offset = fmap_lsearch(buf, len);
135 	if (offset < 0) {
136 		msg_gdbg("Unable to find fmap in provided buffer.\n");
137 		return 2;
138 	}
139 	msg_gdbg("Found fmap at offset 0x%06zx\n", (size_t)offset);
140 
141 	const struct fmap *fmap = (const struct fmap *)(buf + offset);
142 	*fmap_out = malloc(fmap_size(fmap));
143 	if (*fmap_out == NULL) {
144 		msg_gerr("Out of memory.\n");
145 		return 1;
146 	}
147 
148 	memcpy(*fmap_out, fmap, fmap_size(fmap));
149 	return 0;
150 }
151 
fmap_lsearch_rom(struct fmap ** fmap_out,struct flashctx * const flashctx,size_t rom_offset,size_t len)152 static int fmap_lsearch_rom(struct fmap **fmap_out,
153 		struct flashctx *const flashctx, size_t rom_offset, size_t len)
154 {
155 	int ret = -1;
156 	uint8_t *buf;
157 
158 	if (prepare_flash_access(flashctx, true, false, false, false))
159 		goto _finalize_ret;
160 
161 	/* likely more memory than we need, but it simplifies handling and
162 	 * printing offsets to keep them uniform with what's on the ROM */
163 	buf = malloc(rom_offset + len);
164 	if (!buf) {
165 		msg_gerr("Out of memory.\n");
166 		goto _finalize_ret;
167 	}
168 
169 	ret = read_flash(flashctx, buf + rom_offset, rom_offset, len);
170 	if (ret) {
171 		msg_pdbg("Cannot read ROM contents.\n");
172 		goto _free_ret;
173 	}
174 
175 	ret = fmap_read_from_buffer(fmap_out, buf + rom_offset, len);
176 _free_ret:
177 	free(buf);
178 _finalize_ret:
179 	finalize_flash_access(flashctx);
180 	return ret;
181 }
182 
fmap_bsearch_rom(struct fmap ** fmap_out,struct flashctx * const flashctx,size_t rom_offset,size_t len,size_t min_stride)183 static int fmap_bsearch_rom(struct fmap **fmap_out, struct flashctx *const flashctx,
184 		size_t rom_offset, size_t len, size_t min_stride)
185 {
186 	size_t stride, fmap_len = 0;
187 	int ret = 1;
188 	bool fmap_found = false;
189 	bool check_offset_0 = true;
190 	struct fmap *fmap;
191 	const unsigned int chip_size = flashctx->chip->total_size * 1024;
192 	const int sig_len = strlen(FMAP_SIGNATURE);
193 
194 	if (rom_offset + len > flashctx->chip->total_size * 1024)
195 		return 1;
196 
197 	if (len < sizeof(*fmap))
198 		return 1;
199 
200 	if (prepare_flash_access(flashctx, true, false, false, false))
201 		return 1;
202 
203 	fmap = malloc(sizeof(*fmap));
204 	if (!fmap) {
205 		msg_gerr("Out of memory.\n");
206 		goto _free_ret;
207 	}
208 
209 	/*
210 	 * For efficient operation, we start with the largest stride possible
211 	 * and then decrease the stride on each iteration. Also, check for a
212 	 * remainder when modding the offset with the previous stride. This
213 	 * makes it so that each offset is only checked once.
214 	 *
215 	 * Zero (rom_offset == 0) is a special case and is handled using a
216 	 * variable to track whether or not we've checked it.
217 	 */
218 	size_t offset;
219 	for (stride = chip_size / 2; stride >= min_stride; stride /= 2) {
220 		if (stride > len)
221 			continue;
222 
223 		for (offset = rom_offset;
224 		     offset <= rom_offset + len - sizeof(struct fmap);
225 		     offset += stride) {
226 			if ((offset % (stride * 2) == 0) && (offset != 0))
227 				continue;
228 			if (offset == 0 && !check_offset_0)
229 				continue;
230 			check_offset_0 = false;
231 
232 			/* Read errors are considered non-fatal since we may
233 			 * encounter locked regions and want to continue. */
234 			if (read_flash(flashctx, (uint8_t *)fmap, offset, sig_len)) {
235 				/*
236 				 * Print in verbose mode only to avoid excessive
237 				 * messages for benign errors. Subsequent error
238 				 * prints should be done as usual.
239 				 */
240 				msg_cdbg("Cannot read %d bytes at offset %zu\n", sig_len, offset);
241 				continue;
242 			}
243 
244 			if (memcmp(fmap, FMAP_SIGNATURE, sig_len) != 0)
245 				continue;
246 
247 			if (read_flash(flashctx, (uint8_t *)fmap + sig_len,
248 						offset + sig_len, sizeof(*fmap) - sig_len)) {
249 				msg_cerr("Cannot read %zu bytes at offset %06zx\n",
250 						sizeof(*fmap) - sig_len, offset + sig_len);
251 				continue;
252 			}
253 
254 			if (is_valid_fmap(fmap)) {
255 				msg_gdbg("fmap found at offset 0x%06zx\n", offset);
256 				fmap_found = true;
257 				break;
258 			}
259 			msg_gerr("fmap signature found at %zu but header is invalid.\n", offset);
260 			ret = 2;
261 		}
262 
263 		if (fmap_found)
264 			break;
265 	}
266 
267 	if (!fmap_found)
268 		goto _free_ret;
269 
270 	fmap_len = fmap_size(fmap);
271 	struct fmap *tmp = fmap;
272 	fmap = realloc(fmap, fmap_len);
273 	if (!fmap) {
274 		msg_gerr("Failed to realloc.\n");
275 		free(tmp);
276 		goto _free_ret;
277 	}
278 
279 	if (read_flash(flashctx, (uint8_t *)fmap + sizeof(*fmap),
280 				offset + sizeof(*fmap), fmap_len - sizeof(*fmap))) {
281 		msg_cerr("Cannot read %zu bytes at offset %06zx\n",
282 				fmap_len - sizeof(*fmap), offset + sizeof(*fmap));
283 		/* Treat read failure to be fatal since this
284 		 * should be a valid, usable fmap. */
285 		ret = 2;
286 		goto _free_ret;
287 	}
288 
289 	*fmap_out = fmap;
290 	ret = 0;
291 _free_ret:
292 	if (ret)
293 		free(fmap);
294 	finalize_flash_access(flashctx);
295 	return ret;
296 }
297 
298 /**
299  * @brief Read fmap from ROM
300  *
301  * @param[out] fmap_out Double-pointer to location to store fmap contents.
302  *                      Caller must free allocated fmap contents.
303  * @param[in] flashctx Flash context
304  * @param[in] rom_offset Offset in ROM to begin search
305  * @param[in] len Length to search relative to rom_offset
306  *
307  * @return 0 on success,
308  *         2 if the fmap couldn't be read,
309  *         1 on any other error.
310  */
fmap_read_from_rom(struct fmap ** fmap_out,struct flashctx * const flashctx,size_t rom_offset,size_t len)311 int fmap_read_from_rom(struct fmap **fmap_out,
312 	struct flashctx *const flashctx, size_t rom_offset, size_t len)
313 {
314 	int ret;
315 
316 	if (!flashctx || !flashctx->chip)
317 		return 1;
318 
319 	/*
320 	 * Binary search is used at first to see if we can find an fmap quickly
321 	 * in a usual location (often at a power-of-2 offset). However, once we
322 	 * reach a small enough stride the transaction overhead will reverse the
323 	 * speed benefit of using bsearch at which point we need to use brute-
324 	 * force instead.
325 	 *
326 	 * TODO: Since flashrom is often used with high-latency external
327 	 * programmers we should not be overly aggressive with bsearch.
328 	 */
329 	ret = fmap_bsearch_rom(fmap_out, flashctx, rom_offset, len, 256);
330 	if (ret) {
331 		msg_gdbg("Binary search failed, trying linear search...\n");
332 		ret = fmap_lsearch_rom(fmap_out, flashctx, rom_offset, len);
333 	}
334 
335 	return ret;
336 }
337