blob: f5c9a8aecf2e3e9368560aa984b4794b3e61921e [file] [log] [blame]
Tom Rini10e47792018-05-06 17:58:06 -04001// SPDX-License-Identifier: GPL-2.0+
Simon Glasscd0684f2011-10-03 19:26:44 +00002/*
3 * Copyright (c) 2011 The Chromium OS Authors.
Simon Glasscd0684f2011-10-03 19:26:44 +00004 */
5
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +01006#define _GNU_SOURCE
7
Simon Glassf1c45c82012-12-26 09:53:34 +00008#include <dirent.h>
Simon Glasse8015a62012-01-10 15:54:05 -08009#include <errno.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000010#include <fcntl.h>
Andrew Scull2b40f802022-05-30 10:00:11 +000011#include <pthread.h>
Simon Glass8a3e0352012-02-15 15:51:16 -080012#include <getopt.h>
Simon Glass5dccd152018-05-16 09:42:22 -060013#include <setjmp.h>
Rasmus Villemoes2b72ad22020-02-14 10:58:37 +000014#include <signal.h>
Heinrich Schuchardtbb63ea82022-04-04 22:45:03 +020015#include <stdarg.h>
Simon Glassf1c45c82012-12-26 09:53:34 +000016#include <stdio.h>
Simon Glassfb4b4e82013-05-19 16:45:35 -070017#include <stdint.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000018#include <stdlib.h>
Simon Glassf1c45c82012-12-26 09:53:34 +000019#include <string.h>
Mike Frysingera5baaee2011-10-26 00:21:29 +000020#include <termios.h>
Matthias Weisser0d3dd142011-11-29 12:16:40 +010021#include <time.h>
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +010022#include <ucontext.h>
Simon Glasse8015a62012-01-10 15:54:05 -080023#include <unistd.h>
Matthias Weisserb5f7b472011-11-05 11:40:34 +010024#include <sys/mman.h>
Simon Glasse8015a62012-01-10 15:54:05 -080025#include <sys/stat.h>
Simon Glass17064c02012-01-10 15:54:06 -080026#include <sys/time.h>
Simon Glasse8015a62012-01-10 15:54:05 -080027#include <sys/types.h>
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +010028#include <linux/compiler_attributes.h>
Matthias Weisser0d3dd142011-11-29 12:16:40 +010029#include <linux/types.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000030
Andrew Scull2b40f802022-05-30 10:00:11 +000031#include <asm/fuzzing_engine.h>
Simon Glass8a3e0352012-02-15 15:51:16 -080032#include <asm/getopt.h>
Andrew Scullca5d1372022-05-30 10:00:10 +000033#include <asm/main.h>
Simon Glass8a3e0352012-02-15 15:51:16 -080034#include <asm/sections.h>
35#include <asm/state.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000036#include <os.h>
Simon Glass504548f2015-04-20 12:37:22 -060037#include <rtc_def.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000038
Heinrich Schuchardtc0d1a002020-12-30 18:07:48 +010039/* Environment variable for time offset */
40#define ENV_TIME_OFFSET "UBOOT_SB_TIME_OFFSET"
41
Simon Glasscd0684f2011-10-03 19:26:44 +000042/* Operating System Interface */
43
Simon Glass1e6594c2013-11-10 10:26:57 -070044struct os_mem_hdr {
45 size_t length; /* number of bytes in the block */
46};
47
Simon Glasscd0684f2011-10-03 19:26:44 +000048ssize_t os_read(int fd, void *buf, size_t count)
49{
Simon Glass3dbd4ae2024-08-07 16:47:24 -060050 ssize_t ret;
51
52 ret = read(fd, buf, count);
53 if (ret == -1)
54 return -errno;
55
56 return ret;
Simon Glasscd0684f2011-10-03 19:26:44 +000057}
58
59ssize_t os_write(int fd, const void *buf, size_t count)
60{
Simon Glass3dbd4ae2024-08-07 16:47:24 -060061 ssize_t ret;
62
63 ret = write(fd, buf, count);
64 if (ret == -1)
65 return -errno;
66
67 return ret;
Simon Glasscd0684f2011-10-03 19:26:44 +000068}
69
Heinrich Schuchardtbb63ea82022-04-04 22:45:03 +020070int os_printf(const char *fmt, ...)
71{
72 va_list args;
73 int i;
74
75 va_start(args, fmt);
76 i = vfprintf(stdout, fmt, args);
77 va_end(args);
78
79 return i;
80}
81
Mike Frysinger60addac2011-10-25 13:02:58 +020082off_t os_lseek(int fd, off_t offset, int whence)
83{
Simon Glass3dbd4ae2024-08-07 16:47:24 -060084 off_t ret;
85
Mike Frysinger60addac2011-10-25 13:02:58 +020086 if (whence == OS_SEEK_SET)
87 whence = SEEK_SET;
88 else if (whence == OS_SEEK_CUR)
89 whence = SEEK_CUR;
90 else if (whence == OS_SEEK_END)
91 whence = SEEK_END;
92 else
93 os_exit(1);
Simon Glass3dbd4ae2024-08-07 16:47:24 -060094 ret = lseek(fd, offset, whence);
95 if (ret == -1)
96 return -errno;
97
98 return ret;
Mike Frysinger60addac2011-10-25 13:02:58 +020099}
100
Simon Glass3196d752012-02-20 23:56:58 -0500101int os_open(const char *pathname, int os_flags)
Simon Glasscd0684f2011-10-03 19:26:44 +0000102{
Simon Glass3196d752012-02-20 23:56:58 -0500103 int flags;
104
105 switch (os_flags & OS_O_MASK) {
106 case OS_O_RDONLY:
107 default:
108 flags = O_RDONLY;
109 break;
110
111 case OS_O_WRONLY:
112 flags = O_WRONLY;
113 break;
114
115 case OS_O_RDWR:
116 flags = O_RDWR;
117 break;
118 }
119
120 if (os_flags & OS_O_CREAT)
121 flags |= O_CREAT;
Simon Glassce55a112018-10-01 11:55:07 -0600122 if (os_flags & OS_O_TRUNC)
123 flags |= O_TRUNC;
Heinrich Schuchardtfc96df62020-10-27 20:29:24 +0100124 /*
125 * During a cold reset execv() is used to relaunch the U-Boot binary.
126 * We must ensure that all files are closed in this case.
127 */
128 flags |= O_CLOEXEC;
Simon Glass3196d752012-02-20 23:56:58 -0500129
Heinrich Schuchardt118b9882024-04-10 10:38:28 +0200130 return open(pathname, flags, 0644);
Simon Glasscd0684f2011-10-03 19:26:44 +0000131}
132
133int os_close(int fd)
134{
Heinrich Schuchardt69db2ee2020-10-27 20:29:21 +0100135 /* Do not close the console input */
136 if (fd)
137 return close(fd);
138 return -1;
Simon Glasscd0684f2011-10-03 19:26:44 +0000139}
140
Stephen Warrencd5edba2014-03-01 22:18:00 -0700141int os_unlink(const char *pathname)
142{
143 return unlink(pathname);
144}
145
Simon Glasscd0684f2011-10-03 19:26:44 +0000146void os_exit(int exit_code)
147{
148 exit(exit_code);
149}
Mike Frysingera5baaee2011-10-26 00:21:29 +0000150
Rasmus Villemoesae400f32022-09-27 11:54:04 +0200151unsigned int os_alarm(unsigned int seconds)
152{
153 return alarm(seconds);
154}
155
156void os_set_alarm_handler(void (*handler)(int))
157{
158 if (!handler)
159 handler = SIG_DFL;
160 signal(SIGALRM, handler);
161}
162
163void os_raise_sigalrm(void)
164{
165 raise(SIGALRM);
166}
167
Simon Glass8d176d82018-11-06 15:21:25 -0700168int os_write_file(const char *fname, const void *buf, int size)
Simon Glasscbfa8452018-10-01 11:55:08 -0600169{
Simon Glasscbfa8452018-10-01 11:55:08 -0600170 int fd;
171
172 fd = os_open(fname, OS_O_WRONLY | OS_O_CREAT | OS_O_TRUNC);
173 if (fd < 0) {
174 printf("Cannot open file '%s'\n", fname);
175 return -EIO;
176 }
177 if (os_write(fd, buf, size) != size) {
178 printf("Cannot write to file '%s'\n", fname);
Simon Glass8d176d82018-11-06 15:21:25 -0700179 os_close(fd);
Simon Glasscbfa8452018-10-01 11:55:08 -0600180 return -EIO;
181 }
182 os_close(fd);
Simon Glasscbfa8452018-10-01 11:55:08 -0600183
184 return 0;
185}
186
Heinrich Schuchardt6db1b652023-04-05 11:34:15 +0200187off_t os_filesize(int fd)
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600188{
189 off_t size;
190
191 size = os_lseek(fd, 0, OS_SEEK_END);
192 if (size < 0)
193 return -errno;
194 if (os_lseek(fd, 0, OS_SEEK_SET) < 0)
195 return -errno;
196
197 return size;
198}
199
Simon Glass8d176d82018-11-06 15:21:25 -0700200int os_read_file(const char *fname, void **bufp, int *sizep)
201{
202 off_t size;
203 int ret = -EIO;
204 int fd;
205
206 fd = os_open(fname, OS_O_RDONLY);
207 if (fd < 0) {
208 printf("Cannot open file '%s'\n", fname);
Heinrich Schuchardt8ac326d2024-04-10 23:50:34 +0200209 return -EIO;
Simon Glass8d176d82018-11-06 15:21:25 -0700210 }
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600211 size = os_filesize(fd);
Simon Glass8d176d82018-11-06 15:21:25 -0700212 if (size < 0) {
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600213 printf("Cannot get file size of '%s'\n", fname);
Simon Glass8d176d82018-11-06 15:21:25 -0700214 goto err;
215 }
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600216
Simon Glassedd094e2021-02-06 09:57:33 -0700217 *bufp = os_malloc(size);
Simon Glass8d176d82018-11-06 15:21:25 -0700218 if (!*bufp) {
219 printf("Not enough memory to read file '%s'\n", fname);
220 ret = -ENOMEM;
221 goto err;
222 }
223 if (os_read(fd, *bufp, size) != size) {
224 printf("Cannot read from file '%s'\n", fname);
225 goto err;
226 }
227 os_close(fd);
228 *sizep = size;
229
230 return 0;
231err:
232 os_close(fd);
233 return ret;
234}
235
Simon Glasse4c25c82021-08-18 21:40:31 -0600236int os_map_file(const char *pathname, int os_flags, void **bufp, int *sizep)
237{
238 void *ptr;
Heinrich Schuchardt6db1b652023-04-05 11:34:15 +0200239 off_t size;
Sean Andersonc7bc6cd2023-11-04 15:57:33 -0400240 int ifd, ret = 0;
Simon Glasse4c25c82021-08-18 21:40:31 -0600241
242 ifd = os_open(pathname, os_flags);
243 if (ifd < 0) {
244 printf("Cannot open file '%s'\n", pathname);
245 return -EIO;
246 }
247 size = os_filesize(ifd);
248 if (size < 0) {
249 printf("Cannot get file size of '%s'\n", pathname);
Sean Andersonc7bc6cd2023-11-04 15:57:33 -0400250 ret = -EIO;
251 goto out;
Simon Glasse4c25c82021-08-18 21:40:31 -0600252 }
Heinrich Schuchardt6db1b652023-04-05 11:34:15 +0200253 if ((unsigned long long)size > (unsigned long long)SIZE_MAX) {
254 printf("File '%s' too large to map\n", pathname);
Sean Andersonc7bc6cd2023-11-04 15:57:33 -0400255 ret = -EIO;
256 goto out;
Heinrich Schuchardt6db1b652023-04-05 11:34:15 +0200257 }
Simon Glasse4c25c82021-08-18 21:40:31 -0600258
259 ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, ifd, 0);
260 if (ptr == MAP_FAILED) {
261 printf("Can't map file '%s': %s\n", pathname, strerror(errno));
Sean Andersonc7bc6cd2023-11-04 15:57:33 -0400262 ret = -EPERM;
263 goto out;
Simon Glasse4c25c82021-08-18 21:40:31 -0600264 }
265
266 *bufp = ptr;
267 *sizep = size;
268
Sean Andersonc7bc6cd2023-11-04 15:57:33 -0400269out:
270 os_close(ifd);
271 return ret;
Simon Glasse4c25c82021-08-18 21:40:31 -0600272}
273
Simon Glass5c1fd582021-10-23 17:25:58 -0600274int os_unmap(void *buf, int size)
275{
276 if (munmap(buf, size)) {
277 printf("Can't unmap %p %x\n", buf, size);
278 return -EIO;
279 }
280
281 return 0;
282}
283
Simon Glass528a0f62023-08-24 13:55:37 -0600284int os_persistent_file(char *buf, int maxsize, const char *fname)
285{
286 const char *dirname = getenv("U_BOOT_PERSISTENT_DATA_DIR");
287 char *ptr;
288 int len;
289
290 len = strlen(fname) + (dirname ? strlen(dirname) + 1 : 0) + 1;
291 if (len > maxsize)
292 return -ENOSPC;
293
294 ptr = buf;
295 if (dirname) {
296 strcpy(ptr, dirname);
297 ptr += strlen(dirname);
298 *ptr++ = '/';
299 }
300 strcpy(ptr, fname);
301
302 if (access(buf, F_OK) == -1)
303 return -ENOENT;
304
305 return 0;
306}
307
Sean Anderson988996f2023-11-04 16:37:51 -0400308int os_mktemp(char *fname, off_t size)
309{
310 int fd;
311
312 fd = mkostemp(fname, O_CLOEXEC);
313 if (fd < 0)
314 return -errno;
315
316 if (unlink(fname) < 0)
317 return -errno;
318
319 if (ftruncate(fd, size))
320 return -errno;
321
322 return fd;
323}
324
Mike Frysingera5baaee2011-10-26 00:21:29 +0000325/* Restore tty state when we exit */
326static struct termios orig_term;
Simon Glass678ef472014-02-27 13:26:22 -0700327static bool term_setup;
Simon Glassae50ec72018-10-01 11:55:20 -0600328static bool term_nonblock;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000329
Simon Glass9c3b7d62015-05-10 21:07:27 -0600330void os_fd_restore(void)
Mike Frysingera5baaee2011-10-26 00:21:29 +0000331{
Simon Glass9c3b7d62015-05-10 21:07:27 -0600332 if (term_setup) {
Simon Glassae50ec72018-10-01 11:55:20 -0600333 int flags;
334
Simon Glass678ef472014-02-27 13:26:22 -0700335 tcsetattr(0, TCSANOW, &orig_term);
Simon Glassae50ec72018-10-01 11:55:20 -0600336 if (term_nonblock) {
337 flags = fcntl(0, F_GETFL, 0);
338 fcntl(0, F_SETFL, flags & ~O_NONBLOCK);
339 }
Simon Glass9c3b7d62015-05-10 21:07:27 -0600340 term_setup = false;
341 }
Mike Frysingera5baaee2011-10-26 00:21:29 +0000342}
343
Rasmus Villemoes2b72ad22020-02-14 10:58:37 +0000344static void os_sigint_handler(int sig)
345{
346 os_fd_restore();
347 signal(SIGINT, SIG_DFL);
348 raise(SIGINT);
349}
350
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +0100351static void os_signal_handler(int sig, siginfo_t *info, void *con)
352{
353 ucontext_t __maybe_unused *context = con;
354 unsigned long pc;
355
356#if defined(__x86_64__)
357 pc = context->uc_mcontext.gregs[REG_RIP];
358#elif defined(__aarch64__)
359 pc = context->uc_mcontext.pc;
360#elif defined(__riscv)
361 pc = context->uc_mcontext.__gregs[REG_PC];
362#else
363 const char msg[] =
364 "\nUnsupported architecture, cannot read program counter\n";
365
366 os_write(1, msg, sizeof(msg));
367 pc = 0;
368#endif
369
370 os_signal_action(sig, pc);
371}
372
373int os_setup_signal_handlers(void)
374{
375 struct sigaction act;
376
377 act.sa_sigaction = os_signal_handler;
378 sigemptyset(&act.sa_mask);
Heinrich Schuchardtd3741bc2021-07-05 19:43:00 +0200379 act.sa_flags = SA_SIGINFO;
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +0100380 if (sigaction(SIGILL, &act, NULL) ||
381 sigaction(SIGBUS, &act, NULL) ||
382 sigaction(SIGSEGV, &act, NULL))
383 return -1;
384 return 0;
385}
386
Mike Frysingera5baaee2011-10-26 00:21:29 +0000387/* Put tty into raw mode so <tab> and <ctrl+c> work */
Simon Glass678ef472014-02-27 13:26:22 -0700388void os_tty_raw(int fd, bool allow_sigs)
Mike Frysingera5baaee2011-10-26 00:21:29 +0000389{
Mike Frysingera5baaee2011-10-26 00:21:29 +0000390 struct termios term;
Simon Glassae50ec72018-10-01 11:55:20 -0600391 int flags;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000392
Simon Glass678ef472014-02-27 13:26:22 -0700393 if (term_setup)
Mike Frysingera5baaee2011-10-26 00:21:29 +0000394 return;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000395
396 /* If not a tty, don't complain */
397 if (tcgetattr(fd, &orig_term))
398 return;
399
400 term = orig_term;
401 term.c_iflag = IGNBRK | IGNPAR;
402 term.c_oflag = OPOST | ONLCR;
403 term.c_cflag = CS8 | CREAD | CLOCAL;
Simon Glass678ef472014-02-27 13:26:22 -0700404 term.c_lflag = allow_sigs ? ISIG : 0;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000405 if (tcsetattr(fd, TCSANOW, &term))
406 return;
407
Simon Glassae50ec72018-10-01 11:55:20 -0600408 flags = fcntl(fd, F_GETFL, 0);
409 if (!(flags & O_NONBLOCK)) {
410 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK))
411 return;
412 term_nonblock = true;
413 }
414
Simon Glass9c3b7d62015-05-10 21:07:27 -0600415 term_setup = true;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000416 atexit(os_fd_restore);
Rasmus Villemoes2b72ad22020-02-14 10:58:37 +0000417 signal(SIGINT, os_sigint_handler);
Mike Frysingera5baaee2011-10-26 00:21:29 +0000418}
Matthias Weisserb5f7b472011-11-05 11:40:34 +0100419
Simon Glass4c902fa2021-02-06 09:57:32 -0700420/*
421 * Provide our own malloc so we don't use space in the sandbox ram_buf for
422 * allocations that are internal to sandbox, or need to be done before U-Boot's
423 * malloc() is ready.
424 */
Matthias Weisserb5f7b472011-11-05 11:40:34 +0100425void *os_malloc(size_t length)
426{
Simon Glassbe005d82018-09-15 00:50:54 -0600427 int page_size = getpagesize();
Simon Glassfc2dde82019-04-08 13:20:42 -0600428 struct os_mem_hdr *hdr;
Simon Glass1e6594c2013-11-10 10:26:57 -0700429
Simon Glass4c902fa2021-02-06 09:57:32 -0700430 if (!length)
431 return NULL;
Simon Glass57ba9422018-06-17 08:57:43 -0600432 /*
433 * Use an address that is hopefully available to us so that pointers
434 * to this memory are fairly obvious. If we end up with a different
435 * address, that's fine too.
436 */
437 hdr = mmap((void *)0x10000000, length + page_size,
Alexander Graf934a5452018-06-22 14:44:13 +0200438 PROT_READ | PROT_WRITE | PROT_EXEC,
439 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
Simon Glass1e6594c2013-11-10 10:26:57 -0700440 if (hdr == MAP_FAILED)
441 return NULL;
442 hdr->length = length;
443
Simon Glassbe005d82018-09-15 00:50:54 -0600444 return (void *)hdr + page_size;
Simon Glass1e6594c2013-11-10 10:26:57 -0700445}
446
Masahiro Yamadaee957282014-01-15 13:06:41 +0900447void os_free(void *ptr)
Simon Glass1e6594c2013-11-10 10:26:57 -0700448{
Simon Glassfc2dde82019-04-08 13:20:42 -0600449 int page_size = getpagesize();
450 struct os_mem_hdr *hdr;
Simon Glass1e6594c2013-11-10 10:26:57 -0700451
Simon Glassfc2dde82019-04-08 13:20:42 -0600452 if (ptr) {
453 hdr = ptr - page_size;
454 munmap(hdr, hdr->length + page_size);
455 }
Simon Glass4c902fa2021-02-06 09:57:32 -0700456}
457
458/* These macros are from kernel.h but not accessible in this file */
459#define ALIGN(x, a) __ALIGN_MASK((x), (typeof(x))(a) - 1)
460#define __ALIGN_MASK(x, mask) (((x) + (mask)) & ~(mask))
461
462/*
463 * Provide our own malloc so we don't use space in the sandbox ram_buf for
464 * allocations that are internal to sandbox, or need to be done before U-Boot's
465 * malloc() is ready.
466 */
467void *os_realloc(void *ptr, size_t length)
468{
469 int page_size = getpagesize();
470 struct os_mem_hdr *hdr;
471 void *new_ptr;
472
473 /* Reallocating a NULL pointer is just an alloc */
474 if (!ptr)
475 return os_malloc(length);
476
477 /* Changing a length to 0 is just a free */
478 if (length) {
479 os_free(ptr);
480 return NULL;
481 }
482
483 /*
484 * If the new size is the same number of pages as the old, nothing to
485 * do. There isn't much point in shrinking things
486 */
487 hdr = ptr - page_size;
488 if (ALIGN(length, page_size) <= ALIGN(hdr->length, page_size))
489 return ptr;
490
491 /* We have to grow it, so allocate something new */
492 new_ptr = os_malloc(length);
493 memcpy(new_ptr, ptr, hdr->length);
494 os_free(ptr);
495
496 return new_ptr;
Simon Glass1e6594c2013-11-10 10:26:57 -0700497}
498
Matthias Weisser0d3dd142011-11-29 12:16:40 +0100499void os_usleep(unsigned long usec)
500{
501 usleep(usec);
502}
503
Simon Glassfb4b4e82013-05-19 16:45:35 -0700504uint64_t __attribute__((no_instrument_function)) os_get_nsec(void)
Matthias Weisser0d3dd142011-11-29 12:16:40 +0100505{
506#if defined(CLOCK_MONOTONIC) && defined(_POSIX_MONOTONIC_CLOCK)
507 struct timespec tp;
508 if (EINVAL == clock_gettime(CLOCK_MONOTONIC, &tp)) {
509 struct timeval tv;
510
511 gettimeofday(&tv, NULL);
512 tp.tv_sec = tv.tv_sec;
513 tp.tv_nsec = tv.tv_usec * 1000;
514 }
515 return tp.tv_sec * 1000000000ULL + tp.tv_nsec;
516#else
517 struct timeval tv;
518 gettimeofday(&tv, NULL);
519 return tv.tv_sec * 1000000000ULL + tv.tv_usec * 1000;
520#endif
521}
Simon Glass8a3e0352012-02-15 15:51:16 -0800522
523static char *short_opts;
524static struct option *long_opts;
525
526int os_parse_args(struct sandbox_state *state, int argc, char *argv[])
527{
Marek Behún184c4af2021-05-20 13:24:06 +0200528 struct sandbox_cmdline_option **sb_opt =
529 __u_boot_sandbox_option_start();
Simon Glass8a3e0352012-02-15 15:51:16 -0800530 size_t num_options = __u_boot_sandbox_option_count();
531 size_t i;
532
533 int hidden_short_opt;
534 size_t si;
535
536 int c;
537
538 if (short_opts || long_opts)
539 return 1;
540
541 state->argc = argc;
542 state->argv = argv;
543
544 /* dynamically construct the arguments to the system getopt_long */
Simon Glassedd094e2021-02-06 09:57:33 -0700545 short_opts = os_malloc(sizeof(*short_opts) * num_options * 2 + 1);
546 long_opts = os_malloc(sizeof(*long_opts) * (num_options + 1));
Simon Glass8a3e0352012-02-15 15:51:16 -0800547 if (!short_opts || !long_opts)
548 return 1;
549
550 /*
551 * getopt_long requires "val" to be unique (since that is what the
552 * func returns), so generate unique values automatically for flags
553 * that don't have a short option. pick 0x100 as that is above the
554 * single byte range (where ASCII/ISO-XXXX-X charsets live).
555 */
556 hidden_short_opt = 0x100;
557 si = 0;
558 for (i = 0; i < num_options; ++i) {
559 long_opts[i].name = sb_opt[i]->flag;
560 long_opts[i].has_arg = sb_opt[i]->has_arg ?
561 required_argument : no_argument;
562 long_opts[i].flag = NULL;
563
564 if (sb_opt[i]->flag_short) {
565 short_opts[si++] = long_opts[i].val = sb_opt[i]->flag_short;
566 if (long_opts[i].has_arg == required_argument)
567 short_opts[si++] = ':';
568 } else
569 long_opts[i].val = sb_opt[i]->flag_short = hidden_short_opt++;
570 }
571 short_opts[si] = '\0';
572
573 /* we need to handle output ourselves since u-boot provides printf */
574 opterr = 0;
575
Simon Glass0a4eabb2020-02-03 07:36:04 -0700576 memset(&long_opts[num_options], '\0', sizeof(*long_opts));
Simon Glass8a3e0352012-02-15 15:51:16 -0800577 /*
578 * walk all of the options the user gave us on the command line,
579 * figure out what u-boot option structure they belong to (via
580 * the unique short val key), and call the appropriate callback.
581 */
582 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
583 for (i = 0; i < num_options; ++i) {
584 if (sb_opt[i]->flag_short == c) {
585 if (sb_opt[i]->callback(state, optarg)) {
586 state->parse_err = sb_opt[i]->flag;
587 return 0;
588 }
589 break;
590 }
591 }
592 if (i == num_options) {
593 /*
594 * store the faulting flag for later display. we have to
595 * store the flag itself as the getopt parsing itself is
596 * tricky: need to handle the following flags (assume all
597 * of the below are unknown):
598 * -a optopt='a' optind=<next>
599 * -abbbb optopt='a' optind=<this>
600 * -aaaaa optopt='a' optind=<this>
601 * --a optopt=0 optind=<this>
602 * as you can see, it is impossible to determine the exact
603 * faulting flag without doing the parsing ourselves, so
604 * we just report the specific flag that failed.
605 */
606 if (optopt) {
607 static char parse_err[3] = { '-', 0, '\0', };
608 parse_err[1] = optopt;
609 state->parse_err = parse_err;
610 } else
611 state->parse_err = argv[optind - 1];
612 break;
613 }
614 }
615
616 return 0;
617}
Simon Glassf1c45c82012-12-26 09:53:34 +0000618
619void os_dirent_free(struct os_dirent_node *node)
620{
621 struct os_dirent_node *next;
622
623 while (node) {
624 next = node->next;
Simon Glassedd094e2021-02-06 09:57:33 -0700625 os_free(node);
Simon Glassf1c45c82012-12-26 09:53:34 +0000626 node = next;
627 }
628}
629
630int os_dirent_ls(const char *dirname, struct os_dirent_node **headp)
631{
Stefan Brünsae71ede2016-10-01 20:41:42 +0200632 struct dirent *entry;
Simon Glassf1c45c82012-12-26 09:53:34 +0000633 struct os_dirent_node *head, *node, *next;
634 struct stat buf;
635 DIR *dir;
636 int ret;
637 char *fname;
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200638 char *old_fname;
Simon Glassf1c45c82012-12-26 09:53:34 +0000639 int len;
Stefan Brünsb2129902016-10-01 20:41:40 +0200640 int dirlen;
Simon Glassf1c45c82012-12-26 09:53:34 +0000641
642 *headp = NULL;
643 dir = opendir(dirname);
644 if (!dir)
645 return -1;
646
Stefan Brünsb2129902016-10-01 20:41:40 +0200647 /* Create a buffer upfront, with typically sufficient size */
648 dirlen = strlen(dirname) + 2;
649 len = dirlen + 256;
Simon Glassedd094e2021-02-06 09:57:33 -0700650 fname = os_malloc(len);
Simon Glassf1c45c82012-12-26 09:53:34 +0000651 if (!fname) {
652 ret = -ENOMEM;
653 goto done;
654 }
655
656 for (node = head = NULL;; node = next) {
Stefan Brünsae71ede2016-10-01 20:41:42 +0200657 errno = 0;
658 entry = readdir(dir);
659 if (!entry) {
660 ret = errno;
Simon Glassf1c45c82012-12-26 09:53:34 +0000661 break;
Stefan Brünsae71ede2016-10-01 20:41:42 +0200662 }
Simon Glassedd094e2021-02-06 09:57:33 -0700663 next = os_malloc(sizeof(*node) + strlen(entry->d_name) + 1);
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200664 if (!next) {
Simon Glassf1c45c82012-12-26 09:53:34 +0000665 os_dirent_free(head);
666 ret = -ENOMEM;
667 goto done;
668 }
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200669 if (dirlen + strlen(entry->d_name) > len) {
670 len = dirlen + strlen(entry->d_name);
671 old_fname = fname;
Simon Glassedd094e2021-02-06 09:57:33 -0700672 fname = os_realloc(fname, len);
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200673 if (!fname) {
Simon Glassedd094e2021-02-06 09:57:33 -0700674 os_free(old_fname);
675 os_free(next);
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200676 os_dirent_free(head);
677 ret = -ENOMEM;
678 goto done;
679 }
680 }
Stephen Warren9671c672014-06-11 10:26:23 -0600681 next->next = NULL;
Stefan Brünsae71ede2016-10-01 20:41:42 +0200682 strcpy(next->name, entry->d_name);
683 switch (entry->d_type) {
Simon Glassf1c45c82012-12-26 09:53:34 +0000684 case DT_REG:
685 next->type = OS_FILET_REG;
686 break;
687 case DT_DIR:
688 next->type = OS_FILET_DIR;
689 break;
690 case DT_LNK:
691 next->type = OS_FILET_LNK;
692 break;
Stefan Brünsb7ffa822016-10-04 21:46:35 +0200693 default:
694 next->type = OS_FILET_UNKNOWN;
Simon Glassf1c45c82012-12-26 09:53:34 +0000695 }
696 next->size = 0;
697 snprintf(fname, len, "%s/%s", dirname, next->name);
698 if (!stat(fname, &buf))
699 next->size = buf.st_size;
700 if (node)
701 node->next = next;
Stefan Brünsd4cb8882016-10-01 20:41:39 +0200702 else
703 head = next;
Simon Glassf1c45c82012-12-26 09:53:34 +0000704 }
705 *headp = head;
706
707done:
708 closedir(dir);
Simon Glassedd094e2021-02-06 09:57:33 -0700709 os_free(fname);
Simon Glassf1c45c82012-12-26 09:53:34 +0000710 return ret;
711}
712
713const char *os_dirent_typename[OS_FILET_COUNT] = {
714 " ",
715 "SYM",
716 "DIR",
717 "???",
718};
719
720const char *os_dirent_get_typename(enum os_dirent_t type)
721{
Tom Rinib6f605e2017-05-13 20:11:30 -0400722 if (type >= OS_FILET_REG && type < OS_FILET_COUNT)
Simon Glassf1c45c82012-12-26 09:53:34 +0000723 return os_dirent_typename[type];
724
725 return os_dirent_typename[OS_FILET_UNKNOWN];
726}
727
Heinrich Schuchardt011a1e02022-01-11 01:50:24 +0100728/*
729 * For compatibility reasons avoid loff_t here.
730 * U-Boot defines loff_t as long long.
731 * But /usr/include/linux/types.h may not define it at all.
732 * Alpine Linux being one example.
733 */
734int os_get_filesize(const char *fname, long long *size)
Simon Glassf1c45c82012-12-26 09:53:34 +0000735{
736 struct stat buf;
737 int ret;
738
739 ret = stat(fname, &buf);
740 if (ret)
741 return ret;
Suriyan Ramasami378da1032014-11-17 14:39:37 -0800742 *size = buf.st_size;
743 return 0;
Simon Glassf1c45c82012-12-26 09:53:34 +0000744}
Simon Glass3e9fd242013-11-10 10:27:01 -0700745
Simon Glass29d11432017-12-04 13:48:17 -0700746void os_putc(int ch)
747{
Simon Glassd56c6f42022-03-27 14:26:14 -0600748 os_write(1, &ch, 1);
Simon Glass29d11432017-12-04 13:48:17 -0700749}
750
751void os_puts(const char *str)
752{
753 while (*str)
754 os_putc(*str++);
755}
756
Pali Rohár4acd1a02022-09-05 11:31:16 +0200757void os_flush(void)
758{
759 fflush(stdout);
760}
761
Simon Glass9dd10bf2013-11-10 10:27:03 -0700762int os_write_ram_buf(const char *fname)
763{
764 struct sandbox_state *state = state_get_current();
765 int fd, ret;
766
Heinrich Schuchardt118b9882024-04-10 10:38:28 +0200767 fd = open(fname, O_CREAT | O_WRONLY, 0644);
Simon Glass9dd10bf2013-11-10 10:27:03 -0700768 if (fd < 0)
769 return -ENOENT;
770 ret = write(fd, state->ram_buf, state->ram_size);
771 close(fd);
772 if (ret != state->ram_size)
773 return -EIO;
774
775 return 0;
776}
777
778int os_read_ram_buf(const char *fname)
779{
780 struct sandbox_state *state = state_get_current();
781 int fd, ret;
Heinrich Schuchardt011a1e02022-01-11 01:50:24 +0100782 long long size;
Simon Glass9dd10bf2013-11-10 10:27:03 -0700783
Suriyan Ramasami378da1032014-11-17 14:39:37 -0800784 ret = os_get_filesize(fname, &size);
785 if (ret < 0)
786 return ret;
Simon Glass9dd10bf2013-11-10 10:27:03 -0700787 if (size != state->ram_size)
788 return -ENOSPC;
789 fd = open(fname, O_RDONLY);
790 if (fd < 0)
791 return -ENOENT;
792
793 ret = read(fd, state->ram_buf, state->ram_size);
794 close(fd);
795 if (ret != state->ram_size)
796 return -EIO;
797
798 return 0;
799}
Simon Glass860b7d92014-02-27 13:26:15 -0700800
801static int make_exec(char *fname, const void *data, int size)
802{
803 int fd;
804
805 strcpy(fname, "/tmp/u-boot.jump.XXXXXX");
806 fd = mkstemp(fname);
807 if (fd < 0)
808 return -ENOENT;
809 if (write(fd, data, size) < 0)
810 return -EIO;
811 close(fd);
Heinrich Schuchardt118b9882024-04-10 10:38:28 +0200812 if (chmod(fname, 0755))
Simon Glass860b7d92014-02-27 13:26:15 -0700813 return -ENOEXEC;
814
815 return 0;
816}
817
Simon Glass7dafd022018-11-15 18:44:05 -0700818/**
819 * add_args() - Allocate a new argv with the given args
820 *
821 * This is used to create a new argv array with all the old arguments and some
822 * new ones that are passed in
823 *
824 * @argvp: Returns newly allocated args list
825 * @add_args: Arguments to add, each a string
826 * @count: Number of arguments in @add_args
Heinrich Schuchardt47b4c022022-01-19 18:05:50 +0100827 * Return: 0 if OK, -ENOMEM if out of memory
Simon Glass7dafd022018-11-15 18:44:05 -0700828 */
Simon Glassf1c9e612024-08-07 16:47:19 -0600829static int add_args(char ***argvp, const char *add_args[], int count)
Simon Glass860b7d92014-02-27 13:26:15 -0700830{
Simon Glass7465f002018-11-15 18:44:07 -0700831 char **argv, **ap;
Simon Glass860b7d92014-02-27 13:26:15 -0700832 int argc;
833
Simon Glass7465f002018-11-15 18:44:07 -0700834 for (argc = 0; (*argvp)[argc]; argc++)
Simon Glass860b7d92014-02-27 13:26:15 -0700835 ;
836
Simon Glassedd094e2021-02-06 09:57:33 -0700837 argv = os_malloc((argc + count + 1) * sizeof(char *));
Simon Glass860b7d92014-02-27 13:26:15 -0700838 if (!argv) {
839 printf("Out of memory for %d argv\n", count);
840 return -ENOMEM;
841 }
Simon Glass7465f002018-11-15 18:44:07 -0700842 for (ap = *argvp, argc = 0; *ap; ap++) {
843 char *arg = *ap;
844
845 /* Drop args that we don't want to propagate */
846 if (*arg == '-' && strlen(arg) == 2) {
847 switch (arg[1]) {
848 case 'j':
849 case 'm':
850 ap++;
851 continue;
852 }
853 } else if (!strcmp(arg, "--rm_memory")) {
Simon Glass7465f002018-11-15 18:44:07 -0700854 continue;
855 }
856 argv[argc++] = arg;
857 }
858
Simon Glass860b7d92014-02-27 13:26:15 -0700859 memcpy(argv + argc, add_args, count * sizeof(char *));
860 argv[argc + count] = NULL;
861
862 *argvp = argv;
863 return 0;
864}
865
Simon Glass7dafd022018-11-15 18:44:05 -0700866/**
867 * os_jump_to_file() - Jump to a new program
868 *
869 * This saves the memory buffer, sets up arguments to the new process, then
870 * execs it.
871 *
872 * @fname: Filename to exec
Heinrich Schuchardt47b4c022022-01-19 18:05:50 +0100873 * Return: does not return on success, any return value is an error
Simon Glass7dafd022018-11-15 18:44:05 -0700874 */
Simon Glassdafc5d72021-03-15 18:11:07 +1300875static int os_jump_to_file(const char *fname, bool delete_it)
Simon Glass860b7d92014-02-27 13:26:15 -0700876{
877 struct sandbox_state *state = state_get_current();
Simon Glass7dafd022018-11-15 18:44:05 -0700878 char mem_fname[30];
Simon Glass860b7d92014-02-27 13:26:15 -0700879 int fd, err;
Simon Glassf1c9e612024-08-07 16:47:19 -0600880 const char *extra_args[5];
Simon Glass860b7d92014-02-27 13:26:15 -0700881 char **argv = state->argv;
Simon Glass7465f002018-11-15 18:44:07 -0700882 int argc;
Simon Glass860b7d92014-02-27 13:26:15 -0700883#ifdef DEBUG
Simon Glass7dafd022018-11-15 18:44:05 -0700884 int i;
Simon Glass860b7d92014-02-27 13:26:15 -0700885#endif
886
Simon Glass860b7d92014-02-27 13:26:15 -0700887 strcpy(mem_fname, "/tmp/u-boot.mem.XXXXXX");
888 fd = mkstemp(mem_fname);
889 if (fd < 0)
890 return -ENOENT;
891 close(fd);
892 err = os_write_ram_buf(mem_fname);
893 if (err)
894 return err;
895
896 os_fd_restore();
897
Simon Glassdafc5d72021-03-15 18:11:07 +1300898 argc = 0;
899 if (delete_it) {
900 extra_args[argc++] = "-j";
901 extra_args[argc++] = (char *)fname;
902 }
903 extra_args[argc++] = "-m";
904 extra_args[argc++] = mem_fname;
Simon Glass7465f002018-11-15 18:44:07 -0700905 if (state->ram_buf_rm)
906 extra_args[argc++] = "--rm_memory";
907 err = add_args(&argv, extra_args, argc);
Simon Glass860b7d92014-02-27 13:26:15 -0700908 if (err)
909 return err;
Simon Glass7465f002018-11-15 18:44:07 -0700910 argv[0] = (char *)fname;
Simon Glass860b7d92014-02-27 13:26:15 -0700911
912#ifdef DEBUG
913 for (i = 0; argv[i]; i++)
914 printf("%d %s\n", i, argv[i]);
915#endif
916
917 if (state_uninit())
918 os_exit(2);
919
920 err = execv(fname, argv);
Simon Glassedd094e2021-02-06 09:57:33 -0700921 os_free(argv);
Simon Glasscca25522018-11-15 18:44:08 -0700922 if (err) {
923 perror("Unable to run image");
Simon Glass23eabbb2018-11-23 21:29:24 -0700924 printf("Image filename '%s'\n", fname);
Simon Glass860b7d92014-02-27 13:26:15 -0700925 return err;
Simon Glasscca25522018-11-15 18:44:08 -0700926 }
Simon Glass860b7d92014-02-27 13:26:15 -0700927
Simon Glassdafc5d72021-03-15 18:11:07 +1300928 if (delete_it)
929 return unlink(fname);
930
931 return -EFAULT;
Simon Glass860b7d92014-02-27 13:26:15 -0700932}
Simon Glass504548f2015-04-20 12:37:22 -0600933
Simon Glass7dafd022018-11-15 18:44:05 -0700934int os_jump_to_image(const void *dest, int size)
935{
936 char fname[30];
937 int err;
938
939 err = make_exec(fname, dest, size);
940 if (err)
941 return err;
942
Simon Glassdafc5d72021-03-15 18:11:07 +1300943 return os_jump_to_file(fname, true);
Simon Glass7dafd022018-11-15 18:44:05 -0700944}
945
Simon Glass1cd06002021-07-05 16:32:45 -0600946int os_find_u_boot(char *fname, int maxlen, bool use_img,
947 const char *cur_prefix, const char *next_prefix)
Simon Glass2c931ba2016-07-04 11:57:45 -0600948{
949 struct sandbox_state *state = state_get_current();
950 const char *progname = state->argv[0];
951 int len = strlen(progname);
Simon Glass1cd06002021-07-05 16:32:45 -0600952 char subdir[10];
953 char *suffix;
Simon Glass2c931ba2016-07-04 11:57:45 -0600954 char *p;
955 int fd;
956
957 if (len >= maxlen || len < 4)
958 return -ENOSPC;
959
Simon Glass2c931ba2016-07-04 11:57:45 -0600960 strcpy(fname, progname);
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600961 suffix = fname + len - 4;
962
Simon Glass1cd06002021-07-05 16:32:45 -0600963 /* Change the existing suffix to the new one */
964 if (*suffix != '-')
965 return -EINVAL;
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600966
Simon Glass1cd06002021-07-05 16:32:45 -0600967 if (*next_prefix)
968 strcpy(suffix + 1, next_prefix); /* e.g. "-tpl" to "-spl" */
969 else
970 *suffix = '\0'; /* e.g. "-spl" to "" */
971 fd = os_open(fname, O_RDONLY);
972 if (fd >= 0) {
973 close(fd);
974 return 0;
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600975 }
976
Simon Glass1cd06002021-07-05 16:32:45 -0600977 /*
978 * We didn't find it, so try looking for 'u-boot-xxx' in the xxx/
979 * directory. Replace the old dirname with the new one.
980 */
981 snprintf(subdir, sizeof(subdir), "/%s/", cur_prefix);
982 p = strstr(fname, subdir);
Simon Glass2c931ba2016-07-04 11:57:45 -0600983 if (p) {
Simon Glass1cd06002021-07-05 16:32:45 -0600984 if (*next_prefix)
Simon Glass61eda3a2024-08-07 16:47:20 -0600985 /* e.g. ".../tpl/u-boot-spl" to ".../spl/u-boot-spl" */
Simon Glass1cd06002021-07-05 16:32:45 -0600986 memcpy(p + 1, next_prefix, strlen(next_prefix));
987 else
988 /* e.g. ".../spl/u-boot" to ".../u-boot" */
989 strcpy(p, p + 1 + strlen(cur_prefix));
Simon Glassb90e4872021-03-07 17:35:13 -0700990 if (use_img)
991 strcat(p, ".img");
Simon Glass1cd06002021-07-05 16:32:45 -0600992
Simon Glass2c931ba2016-07-04 11:57:45 -0600993 fd = os_open(fname, O_RDONLY);
994 if (fd >= 0) {
995 close(fd);
996 return 0;
997 }
998 }
999
1000 return -ENOENT;
1001}
1002
1003int os_spl_to_uboot(const char *fname)
1004{
Patrick Delaunay6daf9052020-11-20 09:48:33 +01001005 struct sandbox_state *state = state_get_current();
1006
Patrick Delaunay6daf9052020-11-20 09:48:33 +01001007 /* U-Boot will delete ram buffer after read: "--rm_memory"*/
1008 state->ram_buf_rm = true;
Simon Glassdafc5d72021-03-15 18:11:07 +13001009
1010 return os_jump_to_file(fname, false);
Simon Glass2c931ba2016-07-04 11:57:45 -06001011}
1012
Heinrich Schuchardtc0d1a002020-12-30 18:07:48 +01001013long os_get_time_offset(void)
1014{
1015 const char *offset;
1016
1017 offset = getenv(ENV_TIME_OFFSET);
1018 if (offset)
1019 return strtol(offset, NULL, 0);
1020 return 0;
1021}
1022
1023void os_set_time_offset(long offset)
1024{
1025 char buf[21];
1026 int ret;
1027
1028 snprintf(buf, sizeof(buf), "%ld", offset);
1029 ret = setenv(ENV_TIME_OFFSET, buf, true);
1030 if (ret)
1031 printf("Could not set environment variable %s\n",
1032 ENV_TIME_OFFSET);
1033}
1034
Simon Glass504548f2015-04-20 12:37:22 -06001035void os_localtime(struct rtc_time *rt)
1036{
1037 time_t t = time(NULL);
1038 struct tm *tm;
1039
1040 tm = localtime(&t);
1041 rt->tm_sec = tm->tm_sec;
1042 rt->tm_min = tm->tm_min;
1043 rt->tm_hour = tm->tm_hour;
1044 rt->tm_mday = tm->tm_mday;
1045 rt->tm_mon = tm->tm_mon + 1;
1046 rt->tm_year = tm->tm_year + 1900;
1047 rt->tm_wday = tm->tm_wday;
1048 rt->tm_yday = tm->tm_yday;
1049 rt->tm_isdst = tm->tm_isdst;
1050}
Simon Glass5dccd152018-05-16 09:42:22 -06001051
Simon Glassb7255ef2018-09-15 00:50:55 -06001052void os_abort(void)
1053{
1054 abort();
1055}
Simon Glass4e766c22018-10-01 21:12:32 -06001056
1057int os_mprotect_allow(void *start, size_t len)
1058{
1059 int page_size = getpagesize();
1060
1061 /* Move start to the start of a page, len to the end */
1062 start = (void *)(((ulong)start) & ~(page_size - 1));
1063 len = (len + page_size * 2) & ~(page_size - 1);
1064
1065 return mprotect(start, len, PROT_READ | PROT_WRITE);
1066}
Simon Glass752707a2019-04-08 13:20:41 -06001067
1068void *os_find_text_base(void)
1069{
1070 char line[500];
1071 void *base = NULL;
1072 int len;
1073 int fd;
1074
1075 /*
1076 * This code assumes that the first line of /proc/self/maps holds
1077 * information about the text, for example:
1078 *
1079 * 5622d9907000-5622d9a55000 r-xp 00000000 08:01 15067168 u-boot
1080 *
1081 * The first hex value is assumed to be the address.
1082 *
1083 * This is tested in Linux 4.15.
1084 */
1085 fd = open("/proc/self/maps", O_RDONLY);
1086 if (fd == -1)
1087 return NULL;
1088 len = read(fd, line, sizeof(line));
1089 if (len > 0) {
1090 char *end = memchr(line, '-', len);
1091
1092 if (end) {
Heinrich Schuchardt05a16842019-10-26 23:17:44 +02001093 uintptr_t addr;
Simon Glass752707a2019-04-08 13:20:41 -06001094
1095 *end = '\0';
Heinrich Schuchardt05a16842019-10-26 23:17:44 +02001096 if (sscanf(line, "%zx", &addr) == 1)
Simon Glass752707a2019-04-08 13:20:41 -06001097 base = (void *)addr;
1098 }
1099 }
1100 close(fd);
1101
1102 return base;
1103}
Heinrich Schuchardt1c678442020-10-27 20:29:25 +01001104
Heinrich Schuchardt79cb2412022-09-02 02:32:25 +02001105/**
1106 * os_unblock_signals() - unblock all signals
1107 *
1108 * If we are relaunching the sandbox in a signal handler, we have to unblock
1109 * the respective signal before calling execv(). See signal(7) man-page.
1110 */
1111static void os_unblock_signals(void)
1112{
1113 sigset_t sigs;
1114
1115 sigfillset(&sigs);
1116 sigprocmask(SIG_UNBLOCK, &sigs, NULL);
1117}
1118
Heinrich Schuchardt1c678442020-10-27 20:29:25 +01001119void os_relaunch(char *argv[])
1120{
Heinrich Schuchardt79cb2412022-09-02 02:32:25 +02001121 os_unblock_signals();
1122
Heinrich Schuchardt1c678442020-10-27 20:29:25 +01001123 execv(argv[0], argv);
1124 os_exit(1);
1125}
Andrew Scullca5d1372022-05-30 10:00:10 +00001126
Andrew Scull2b40f802022-05-30 10:00:11 +00001127#ifdef CONFIG_FUZZ
1128static void *fuzzer_thread(void * ptr)
1129{
1130 char cmd[64];
1131 char *argv[5] = {"./u-boot", "-T", "-c", cmd, NULL};
1132 const char *fuzz_test;
1133
1134 /* Find which test to run from an environment variable. */
1135 fuzz_test = getenv("UBOOT_SB_FUZZ_TEST");
1136 if (!fuzz_test)
1137 os_abort();
1138
1139 snprintf(cmd, sizeof(cmd), "fuzz %s", fuzz_test);
1140
1141 sandbox_main(4, argv);
1142 os_abort();
1143 return NULL;
1144}
1145
1146static bool fuzzer_initialized = false;
1147static pthread_mutex_t fuzzer_mutex = PTHREAD_MUTEX_INITIALIZER;
1148static pthread_cond_t fuzzer_cond = PTHREAD_COND_INITIALIZER;
1149static const uint8_t *fuzzer_data;
1150static size_t fuzzer_size;
1151
1152int sandbox_fuzzing_engine_get_input(const uint8_t **data, size_t *size)
1153{
1154 if (!fuzzer_initialized)
1155 return -ENOSYS;
1156
1157 /* Tell the main thread we need new inputs then wait for them. */
1158 pthread_mutex_lock(&fuzzer_mutex);
1159 pthread_cond_signal(&fuzzer_cond);
1160 pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1161 *data = fuzzer_data;
1162 *size = fuzzer_size;
1163 pthread_mutex_unlock(&fuzzer_mutex);
1164 return 0;
1165}
1166
1167int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
1168{
1169 static pthread_t tid;
1170
1171 pthread_mutex_lock(&fuzzer_mutex);
1172
1173 /* Initialize the sandbox on another thread. */
1174 if (!fuzzer_initialized) {
1175 fuzzer_initialized = true;
1176 if (pthread_create(&tid, NULL, fuzzer_thread, NULL))
1177 os_abort();
1178 pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1179 }
1180
1181 /* Hand over the input. */
1182 fuzzer_data = data;
1183 fuzzer_size = size;
1184 pthread_cond_signal(&fuzzer_cond);
1185
1186 /* Wait for the inputs to be finished with. */
1187 pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1188 pthread_mutex_unlock(&fuzzer_mutex);
1189
1190 return 0;
1191}
1192#else
Andrew Scullca5d1372022-05-30 10:00:10 +00001193int main(int argc, char *argv[])
1194{
1195 return sandbox_main(argc, argv);
1196}
Andrew Scull2b40f802022-05-30 10:00:11 +00001197#endif