blob: d6170adaf5e8e92a0975ca364a9cad1300cec144 [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{
50 return read(fd, buf, count);
51}
52
53ssize_t os_write(int fd, const void *buf, size_t count)
54{
55 return write(fd, buf, count);
56}
57
Heinrich Schuchardtbb63ea82022-04-04 22:45:03 +020058int os_printf(const char *fmt, ...)
59{
60 va_list args;
61 int i;
62
63 va_start(args, fmt);
64 i = vfprintf(stdout, fmt, args);
65 va_end(args);
66
67 return i;
68}
69
Mike Frysinger60addac2011-10-25 13:02:58 +020070off_t os_lseek(int fd, off_t offset, int whence)
71{
72 if (whence == OS_SEEK_SET)
73 whence = SEEK_SET;
74 else if (whence == OS_SEEK_CUR)
75 whence = SEEK_CUR;
76 else if (whence == OS_SEEK_END)
77 whence = SEEK_END;
78 else
79 os_exit(1);
80 return lseek(fd, offset, whence);
81}
82
Simon Glass3196d752012-02-20 23:56:58 -050083int os_open(const char *pathname, int os_flags)
Simon Glasscd0684f2011-10-03 19:26:44 +000084{
Simon Glass3196d752012-02-20 23:56:58 -050085 int flags;
86
87 switch (os_flags & OS_O_MASK) {
88 case OS_O_RDONLY:
89 default:
90 flags = O_RDONLY;
91 break;
92
93 case OS_O_WRONLY:
94 flags = O_WRONLY;
95 break;
96
97 case OS_O_RDWR:
98 flags = O_RDWR;
99 break;
100 }
101
102 if (os_flags & OS_O_CREAT)
103 flags |= O_CREAT;
Simon Glassce55a112018-10-01 11:55:07 -0600104 if (os_flags & OS_O_TRUNC)
105 flags |= O_TRUNC;
Heinrich Schuchardtfc96df62020-10-27 20:29:24 +0100106 /*
107 * During a cold reset execv() is used to relaunch the U-Boot binary.
108 * We must ensure that all files are closed in this case.
109 */
110 flags |= O_CLOEXEC;
Simon Glass3196d752012-02-20 23:56:58 -0500111
112 return open(pathname, flags, 0777);
Simon Glasscd0684f2011-10-03 19:26:44 +0000113}
114
115int os_close(int fd)
116{
Heinrich Schuchardt69db2ee2020-10-27 20:29:21 +0100117 /* Do not close the console input */
118 if (fd)
119 return close(fd);
120 return -1;
Simon Glasscd0684f2011-10-03 19:26:44 +0000121}
122
Stephen Warrencd5edba2014-03-01 22:18:00 -0700123int os_unlink(const char *pathname)
124{
125 return unlink(pathname);
126}
127
Simon Glasscd0684f2011-10-03 19:26:44 +0000128void os_exit(int exit_code)
129{
130 exit(exit_code);
131}
Mike Frysingera5baaee2011-10-26 00:21:29 +0000132
Simon Glass8d176d82018-11-06 15:21:25 -0700133int os_write_file(const char *fname, const void *buf, int size)
Simon Glasscbfa8452018-10-01 11:55:08 -0600134{
Simon Glasscbfa8452018-10-01 11:55:08 -0600135 int fd;
136
137 fd = os_open(fname, OS_O_WRONLY | OS_O_CREAT | OS_O_TRUNC);
138 if (fd < 0) {
139 printf("Cannot open file '%s'\n", fname);
140 return -EIO;
141 }
142 if (os_write(fd, buf, size) != size) {
143 printf("Cannot write to file '%s'\n", fname);
Simon Glass8d176d82018-11-06 15:21:25 -0700144 os_close(fd);
Simon Glasscbfa8452018-10-01 11:55:08 -0600145 return -EIO;
146 }
147 os_close(fd);
Simon Glasscbfa8452018-10-01 11:55:08 -0600148
149 return 0;
150}
151
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600152int os_filesize(int fd)
153{
154 off_t size;
155
156 size = os_lseek(fd, 0, OS_SEEK_END);
157 if (size < 0)
158 return -errno;
159 if (os_lseek(fd, 0, OS_SEEK_SET) < 0)
160 return -errno;
161
162 return size;
163}
164
Simon Glass8d176d82018-11-06 15:21:25 -0700165int os_read_file(const char *fname, void **bufp, int *sizep)
166{
167 off_t size;
168 int ret = -EIO;
169 int fd;
170
171 fd = os_open(fname, OS_O_RDONLY);
172 if (fd < 0) {
173 printf("Cannot open file '%s'\n", fname);
174 goto err;
175 }
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600176 size = os_filesize(fd);
Simon Glass8d176d82018-11-06 15:21:25 -0700177 if (size < 0) {
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600178 printf("Cannot get file size of '%s'\n", fname);
Simon Glass8d176d82018-11-06 15:21:25 -0700179 goto err;
180 }
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600181
Simon Glassedd094e2021-02-06 09:57:33 -0700182 *bufp = os_malloc(size);
Simon Glass8d176d82018-11-06 15:21:25 -0700183 if (!*bufp) {
184 printf("Not enough memory to read file '%s'\n", fname);
185 ret = -ENOMEM;
186 goto err;
187 }
188 if (os_read(fd, *bufp, size) != size) {
189 printf("Cannot read from file '%s'\n", fname);
190 goto err;
191 }
192 os_close(fd);
193 *sizep = size;
194
195 return 0;
196err:
197 os_close(fd);
198 return ret;
199}
200
Simon Glasse4c25c82021-08-18 21:40:31 -0600201int os_map_file(const char *pathname, int os_flags, void **bufp, int *sizep)
202{
203 void *ptr;
204 int size;
205 int ifd;
206
207 ifd = os_open(pathname, os_flags);
208 if (ifd < 0) {
209 printf("Cannot open file '%s'\n", pathname);
210 return -EIO;
211 }
212 size = os_filesize(ifd);
213 if (size < 0) {
214 printf("Cannot get file size of '%s'\n", pathname);
215 return -EIO;
216 }
217
218 ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, ifd, 0);
219 if (ptr == MAP_FAILED) {
220 printf("Can't map file '%s': %s\n", pathname, strerror(errno));
221 return -EPERM;
222 }
223
224 *bufp = ptr;
225 *sizep = size;
226
227 return 0;
228}
229
Simon Glass5c1fd582021-10-23 17:25:58 -0600230int os_unmap(void *buf, int size)
231{
232 if (munmap(buf, size)) {
233 printf("Can't unmap %p %x\n", buf, size);
234 return -EIO;
235 }
236
237 return 0;
238}
239
Mike Frysingera5baaee2011-10-26 00:21:29 +0000240/* Restore tty state when we exit */
241static struct termios orig_term;
Simon Glass678ef472014-02-27 13:26:22 -0700242static bool term_setup;
Simon Glassae50ec72018-10-01 11:55:20 -0600243static bool term_nonblock;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000244
Simon Glass9c3b7d62015-05-10 21:07:27 -0600245void os_fd_restore(void)
Mike Frysingera5baaee2011-10-26 00:21:29 +0000246{
Simon Glass9c3b7d62015-05-10 21:07:27 -0600247 if (term_setup) {
Simon Glassae50ec72018-10-01 11:55:20 -0600248 int flags;
249
Simon Glass678ef472014-02-27 13:26:22 -0700250 tcsetattr(0, TCSANOW, &orig_term);
Simon Glassae50ec72018-10-01 11:55:20 -0600251 if (term_nonblock) {
252 flags = fcntl(0, F_GETFL, 0);
253 fcntl(0, F_SETFL, flags & ~O_NONBLOCK);
254 }
Simon Glass9c3b7d62015-05-10 21:07:27 -0600255 term_setup = false;
256 }
Mike Frysingera5baaee2011-10-26 00:21:29 +0000257}
258
Rasmus Villemoes2b72ad22020-02-14 10:58:37 +0000259static void os_sigint_handler(int sig)
260{
261 os_fd_restore();
262 signal(SIGINT, SIG_DFL);
263 raise(SIGINT);
264}
265
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +0100266static void os_signal_handler(int sig, siginfo_t *info, void *con)
267{
268 ucontext_t __maybe_unused *context = con;
269 unsigned long pc;
270
271#if defined(__x86_64__)
272 pc = context->uc_mcontext.gregs[REG_RIP];
273#elif defined(__aarch64__)
274 pc = context->uc_mcontext.pc;
275#elif defined(__riscv)
276 pc = context->uc_mcontext.__gregs[REG_PC];
277#else
278 const char msg[] =
279 "\nUnsupported architecture, cannot read program counter\n";
280
281 os_write(1, msg, sizeof(msg));
282 pc = 0;
283#endif
284
285 os_signal_action(sig, pc);
286}
287
288int os_setup_signal_handlers(void)
289{
290 struct sigaction act;
291
292 act.sa_sigaction = os_signal_handler;
293 sigemptyset(&act.sa_mask);
Heinrich Schuchardtd3741bc2021-07-05 19:43:00 +0200294 act.sa_flags = SA_SIGINFO;
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +0100295 if (sigaction(SIGILL, &act, NULL) ||
296 sigaction(SIGBUS, &act, NULL) ||
297 sigaction(SIGSEGV, &act, NULL))
298 return -1;
299 return 0;
300}
301
Mike Frysingera5baaee2011-10-26 00:21:29 +0000302/* Put tty into raw mode so <tab> and <ctrl+c> work */
Simon Glass678ef472014-02-27 13:26:22 -0700303void os_tty_raw(int fd, bool allow_sigs)
Mike Frysingera5baaee2011-10-26 00:21:29 +0000304{
Mike Frysingera5baaee2011-10-26 00:21:29 +0000305 struct termios term;
Simon Glassae50ec72018-10-01 11:55:20 -0600306 int flags;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000307
Simon Glass678ef472014-02-27 13:26:22 -0700308 if (term_setup)
Mike Frysingera5baaee2011-10-26 00:21:29 +0000309 return;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000310
311 /* If not a tty, don't complain */
312 if (tcgetattr(fd, &orig_term))
313 return;
314
315 term = orig_term;
316 term.c_iflag = IGNBRK | IGNPAR;
317 term.c_oflag = OPOST | ONLCR;
318 term.c_cflag = CS8 | CREAD | CLOCAL;
Simon Glass678ef472014-02-27 13:26:22 -0700319 term.c_lflag = allow_sigs ? ISIG : 0;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000320 if (tcsetattr(fd, TCSANOW, &term))
321 return;
322
Simon Glassae50ec72018-10-01 11:55:20 -0600323 flags = fcntl(fd, F_GETFL, 0);
324 if (!(flags & O_NONBLOCK)) {
325 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK))
326 return;
327 term_nonblock = true;
328 }
329
Simon Glass9c3b7d62015-05-10 21:07:27 -0600330 term_setup = true;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000331 atexit(os_fd_restore);
Rasmus Villemoes2b72ad22020-02-14 10:58:37 +0000332 signal(SIGINT, os_sigint_handler);
Mike Frysingera5baaee2011-10-26 00:21:29 +0000333}
Matthias Weisserb5f7b472011-11-05 11:40:34 +0100334
Simon Glass4c902fa2021-02-06 09:57:32 -0700335/*
336 * Provide our own malloc so we don't use space in the sandbox ram_buf for
337 * allocations that are internal to sandbox, or need to be done before U-Boot's
338 * malloc() is ready.
339 */
Matthias Weisserb5f7b472011-11-05 11:40:34 +0100340void *os_malloc(size_t length)
341{
Simon Glassbe005d82018-09-15 00:50:54 -0600342 int page_size = getpagesize();
Simon Glassfc2dde82019-04-08 13:20:42 -0600343 struct os_mem_hdr *hdr;
Simon Glass1e6594c2013-11-10 10:26:57 -0700344
Simon Glass4c902fa2021-02-06 09:57:32 -0700345 if (!length)
346 return NULL;
Simon Glass57ba9422018-06-17 08:57:43 -0600347 /*
348 * Use an address that is hopefully available to us so that pointers
349 * to this memory are fairly obvious. If we end up with a different
350 * address, that's fine too.
351 */
352 hdr = mmap((void *)0x10000000, length + page_size,
Alexander Graf934a5452018-06-22 14:44:13 +0200353 PROT_READ | PROT_WRITE | PROT_EXEC,
354 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
Simon Glass1e6594c2013-11-10 10:26:57 -0700355 if (hdr == MAP_FAILED)
356 return NULL;
357 hdr->length = length;
358
Simon Glassbe005d82018-09-15 00:50:54 -0600359 return (void *)hdr + page_size;
Simon Glass1e6594c2013-11-10 10:26:57 -0700360}
361
Masahiro Yamadaee957282014-01-15 13:06:41 +0900362void os_free(void *ptr)
Simon Glass1e6594c2013-11-10 10:26:57 -0700363{
Simon Glassfc2dde82019-04-08 13:20:42 -0600364 int page_size = getpagesize();
365 struct os_mem_hdr *hdr;
Simon Glass1e6594c2013-11-10 10:26:57 -0700366
Simon Glassfc2dde82019-04-08 13:20:42 -0600367 if (ptr) {
368 hdr = ptr - page_size;
369 munmap(hdr, hdr->length + page_size);
370 }
Simon Glass4c902fa2021-02-06 09:57:32 -0700371}
372
373/* These macros are from kernel.h but not accessible in this file */
374#define ALIGN(x, a) __ALIGN_MASK((x), (typeof(x))(a) - 1)
375#define __ALIGN_MASK(x, mask) (((x) + (mask)) & ~(mask))
376
377/*
378 * Provide our own malloc so we don't use space in the sandbox ram_buf for
379 * allocations that are internal to sandbox, or need to be done before U-Boot's
380 * malloc() is ready.
381 */
382void *os_realloc(void *ptr, size_t length)
383{
384 int page_size = getpagesize();
385 struct os_mem_hdr *hdr;
386 void *new_ptr;
387
388 /* Reallocating a NULL pointer is just an alloc */
389 if (!ptr)
390 return os_malloc(length);
391
392 /* Changing a length to 0 is just a free */
393 if (length) {
394 os_free(ptr);
395 return NULL;
396 }
397
398 /*
399 * If the new size is the same number of pages as the old, nothing to
400 * do. There isn't much point in shrinking things
401 */
402 hdr = ptr - page_size;
403 if (ALIGN(length, page_size) <= ALIGN(hdr->length, page_size))
404 return ptr;
405
406 /* We have to grow it, so allocate something new */
407 new_ptr = os_malloc(length);
408 memcpy(new_ptr, ptr, hdr->length);
409 os_free(ptr);
410
411 return new_ptr;
Simon Glass1e6594c2013-11-10 10:26:57 -0700412}
413
Matthias Weisser0d3dd142011-11-29 12:16:40 +0100414void os_usleep(unsigned long usec)
415{
416 usleep(usec);
417}
418
Simon Glassfb4b4e82013-05-19 16:45:35 -0700419uint64_t __attribute__((no_instrument_function)) os_get_nsec(void)
Matthias Weisser0d3dd142011-11-29 12:16:40 +0100420{
421#if defined(CLOCK_MONOTONIC) && defined(_POSIX_MONOTONIC_CLOCK)
422 struct timespec tp;
423 if (EINVAL == clock_gettime(CLOCK_MONOTONIC, &tp)) {
424 struct timeval tv;
425
426 gettimeofday(&tv, NULL);
427 tp.tv_sec = tv.tv_sec;
428 tp.tv_nsec = tv.tv_usec * 1000;
429 }
430 return tp.tv_sec * 1000000000ULL + tp.tv_nsec;
431#else
432 struct timeval tv;
433 gettimeofday(&tv, NULL);
434 return tv.tv_sec * 1000000000ULL + tv.tv_usec * 1000;
435#endif
436}
Simon Glass8a3e0352012-02-15 15:51:16 -0800437
438static char *short_opts;
439static struct option *long_opts;
440
441int os_parse_args(struct sandbox_state *state, int argc, char *argv[])
442{
Marek Behún184c4af2021-05-20 13:24:06 +0200443 struct sandbox_cmdline_option **sb_opt =
444 __u_boot_sandbox_option_start();
Simon Glass8a3e0352012-02-15 15:51:16 -0800445 size_t num_options = __u_boot_sandbox_option_count();
446 size_t i;
447
448 int hidden_short_opt;
449 size_t si;
450
451 int c;
452
453 if (short_opts || long_opts)
454 return 1;
455
456 state->argc = argc;
457 state->argv = argv;
458
459 /* dynamically construct the arguments to the system getopt_long */
Simon Glassedd094e2021-02-06 09:57:33 -0700460 short_opts = os_malloc(sizeof(*short_opts) * num_options * 2 + 1);
461 long_opts = os_malloc(sizeof(*long_opts) * (num_options + 1));
Simon Glass8a3e0352012-02-15 15:51:16 -0800462 if (!short_opts || !long_opts)
463 return 1;
464
465 /*
466 * getopt_long requires "val" to be unique (since that is what the
467 * func returns), so generate unique values automatically for flags
468 * that don't have a short option. pick 0x100 as that is above the
469 * single byte range (where ASCII/ISO-XXXX-X charsets live).
470 */
471 hidden_short_opt = 0x100;
472 si = 0;
473 for (i = 0; i < num_options; ++i) {
474 long_opts[i].name = sb_opt[i]->flag;
475 long_opts[i].has_arg = sb_opt[i]->has_arg ?
476 required_argument : no_argument;
477 long_opts[i].flag = NULL;
478
479 if (sb_opt[i]->flag_short) {
480 short_opts[si++] = long_opts[i].val = sb_opt[i]->flag_short;
481 if (long_opts[i].has_arg == required_argument)
482 short_opts[si++] = ':';
483 } else
484 long_opts[i].val = sb_opt[i]->flag_short = hidden_short_opt++;
485 }
486 short_opts[si] = '\0';
487
488 /* we need to handle output ourselves since u-boot provides printf */
489 opterr = 0;
490
Simon Glass0a4eabb2020-02-03 07:36:04 -0700491 memset(&long_opts[num_options], '\0', sizeof(*long_opts));
Simon Glass8a3e0352012-02-15 15:51:16 -0800492 /*
493 * walk all of the options the user gave us on the command line,
494 * figure out what u-boot option structure they belong to (via
495 * the unique short val key), and call the appropriate callback.
496 */
497 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
498 for (i = 0; i < num_options; ++i) {
499 if (sb_opt[i]->flag_short == c) {
500 if (sb_opt[i]->callback(state, optarg)) {
501 state->parse_err = sb_opt[i]->flag;
502 return 0;
503 }
504 break;
505 }
506 }
507 if (i == num_options) {
508 /*
509 * store the faulting flag for later display. we have to
510 * store the flag itself as the getopt parsing itself is
511 * tricky: need to handle the following flags (assume all
512 * of the below are unknown):
513 * -a optopt='a' optind=<next>
514 * -abbbb optopt='a' optind=<this>
515 * -aaaaa optopt='a' optind=<this>
516 * --a optopt=0 optind=<this>
517 * as you can see, it is impossible to determine the exact
518 * faulting flag without doing the parsing ourselves, so
519 * we just report the specific flag that failed.
520 */
521 if (optopt) {
522 static char parse_err[3] = { '-', 0, '\0', };
523 parse_err[1] = optopt;
524 state->parse_err = parse_err;
525 } else
526 state->parse_err = argv[optind - 1];
527 break;
528 }
529 }
530
531 return 0;
532}
Simon Glassf1c45c82012-12-26 09:53:34 +0000533
534void os_dirent_free(struct os_dirent_node *node)
535{
536 struct os_dirent_node *next;
537
538 while (node) {
539 next = node->next;
Simon Glassedd094e2021-02-06 09:57:33 -0700540 os_free(node);
Simon Glassf1c45c82012-12-26 09:53:34 +0000541 node = next;
542 }
543}
544
545int os_dirent_ls(const char *dirname, struct os_dirent_node **headp)
546{
Stefan Brünsae71ede2016-10-01 20:41:42 +0200547 struct dirent *entry;
Simon Glassf1c45c82012-12-26 09:53:34 +0000548 struct os_dirent_node *head, *node, *next;
549 struct stat buf;
550 DIR *dir;
551 int ret;
552 char *fname;
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200553 char *old_fname;
Simon Glassf1c45c82012-12-26 09:53:34 +0000554 int len;
Stefan Brünsb2129902016-10-01 20:41:40 +0200555 int dirlen;
Simon Glassf1c45c82012-12-26 09:53:34 +0000556
557 *headp = NULL;
558 dir = opendir(dirname);
559 if (!dir)
560 return -1;
561
Stefan Brünsb2129902016-10-01 20:41:40 +0200562 /* Create a buffer upfront, with typically sufficient size */
563 dirlen = strlen(dirname) + 2;
564 len = dirlen + 256;
Simon Glassedd094e2021-02-06 09:57:33 -0700565 fname = os_malloc(len);
Simon Glassf1c45c82012-12-26 09:53:34 +0000566 if (!fname) {
567 ret = -ENOMEM;
568 goto done;
569 }
570
571 for (node = head = NULL;; node = next) {
Stefan Brünsae71ede2016-10-01 20:41:42 +0200572 errno = 0;
573 entry = readdir(dir);
574 if (!entry) {
575 ret = errno;
Simon Glassf1c45c82012-12-26 09:53:34 +0000576 break;
Stefan Brünsae71ede2016-10-01 20:41:42 +0200577 }
Simon Glassedd094e2021-02-06 09:57:33 -0700578 next = os_malloc(sizeof(*node) + strlen(entry->d_name) + 1);
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200579 if (!next) {
Simon Glassf1c45c82012-12-26 09:53:34 +0000580 os_dirent_free(head);
581 ret = -ENOMEM;
582 goto done;
583 }
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200584 if (dirlen + strlen(entry->d_name) > len) {
585 len = dirlen + strlen(entry->d_name);
586 old_fname = fname;
Simon Glassedd094e2021-02-06 09:57:33 -0700587 fname = os_realloc(fname, len);
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200588 if (!fname) {
Simon Glassedd094e2021-02-06 09:57:33 -0700589 os_free(old_fname);
590 os_free(next);
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200591 os_dirent_free(head);
592 ret = -ENOMEM;
593 goto done;
594 }
595 }
Stephen Warren9671c672014-06-11 10:26:23 -0600596 next->next = NULL;
Stefan Brünsae71ede2016-10-01 20:41:42 +0200597 strcpy(next->name, entry->d_name);
598 switch (entry->d_type) {
Simon Glassf1c45c82012-12-26 09:53:34 +0000599 case DT_REG:
600 next->type = OS_FILET_REG;
601 break;
602 case DT_DIR:
603 next->type = OS_FILET_DIR;
604 break;
605 case DT_LNK:
606 next->type = OS_FILET_LNK;
607 break;
Stefan Brünsb7ffa822016-10-04 21:46:35 +0200608 default:
609 next->type = OS_FILET_UNKNOWN;
Simon Glassf1c45c82012-12-26 09:53:34 +0000610 }
611 next->size = 0;
612 snprintf(fname, len, "%s/%s", dirname, next->name);
613 if (!stat(fname, &buf))
614 next->size = buf.st_size;
615 if (node)
616 node->next = next;
Stefan Brünsd4cb8882016-10-01 20:41:39 +0200617 else
618 head = next;
Simon Glassf1c45c82012-12-26 09:53:34 +0000619 }
620 *headp = head;
621
622done:
623 closedir(dir);
Simon Glassedd094e2021-02-06 09:57:33 -0700624 os_free(fname);
Simon Glassf1c45c82012-12-26 09:53:34 +0000625 return ret;
626}
627
628const char *os_dirent_typename[OS_FILET_COUNT] = {
629 " ",
630 "SYM",
631 "DIR",
632 "???",
633};
634
635const char *os_dirent_get_typename(enum os_dirent_t type)
636{
Tom Rinib6f605e2017-05-13 20:11:30 -0400637 if (type >= OS_FILET_REG && type < OS_FILET_COUNT)
Simon Glassf1c45c82012-12-26 09:53:34 +0000638 return os_dirent_typename[type];
639
640 return os_dirent_typename[OS_FILET_UNKNOWN];
641}
642
Heinrich Schuchardt011a1e02022-01-11 01:50:24 +0100643/*
644 * For compatibility reasons avoid loff_t here.
645 * U-Boot defines loff_t as long long.
646 * But /usr/include/linux/types.h may not define it at all.
647 * Alpine Linux being one example.
648 */
649int os_get_filesize(const char *fname, long long *size)
Simon Glassf1c45c82012-12-26 09:53:34 +0000650{
651 struct stat buf;
652 int ret;
653
654 ret = stat(fname, &buf);
655 if (ret)
656 return ret;
Suriyan Ramasami378da1032014-11-17 14:39:37 -0800657 *size = buf.st_size;
658 return 0;
Simon Glassf1c45c82012-12-26 09:53:34 +0000659}
Simon Glass3e9fd242013-11-10 10:27:01 -0700660
Simon Glass29d11432017-12-04 13:48:17 -0700661void os_putc(int ch)
662{
Simon Glassd56c6f42022-03-27 14:26:14 -0600663 os_write(1, &ch, 1);
Simon Glass29d11432017-12-04 13:48:17 -0700664}
665
666void os_puts(const char *str)
667{
668 while (*str)
669 os_putc(*str++);
670}
671
Pali Rohár4acd1a02022-09-05 11:31:16 +0200672void os_flush(void)
673{
674 fflush(stdout);
675}
676
Simon Glass9dd10bf2013-11-10 10:27:03 -0700677int os_write_ram_buf(const char *fname)
678{
679 struct sandbox_state *state = state_get_current();
680 int fd, ret;
681
682 fd = open(fname, O_CREAT | O_WRONLY, 0777);
683 if (fd < 0)
684 return -ENOENT;
685 ret = write(fd, state->ram_buf, state->ram_size);
686 close(fd);
687 if (ret != state->ram_size)
688 return -EIO;
689
690 return 0;
691}
692
693int os_read_ram_buf(const char *fname)
694{
695 struct sandbox_state *state = state_get_current();
696 int fd, ret;
Heinrich Schuchardt011a1e02022-01-11 01:50:24 +0100697 long long size;
Simon Glass9dd10bf2013-11-10 10:27:03 -0700698
Suriyan Ramasami378da1032014-11-17 14:39:37 -0800699 ret = os_get_filesize(fname, &size);
700 if (ret < 0)
701 return ret;
Simon Glass9dd10bf2013-11-10 10:27:03 -0700702 if (size != state->ram_size)
703 return -ENOSPC;
704 fd = open(fname, O_RDONLY);
705 if (fd < 0)
706 return -ENOENT;
707
708 ret = read(fd, state->ram_buf, state->ram_size);
709 close(fd);
710 if (ret != state->ram_size)
711 return -EIO;
712
713 return 0;
714}
Simon Glass860b7d92014-02-27 13:26:15 -0700715
716static int make_exec(char *fname, const void *data, int size)
717{
718 int fd;
719
720 strcpy(fname, "/tmp/u-boot.jump.XXXXXX");
721 fd = mkstemp(fname);
722 if (fd < 0)
723 return -ENOENT;
724 if (write(fd, data, size) < 0)
725 return -EIO;
726 close(fd);
727 if (chmod(fname, 0777))
728 return -ENOEXEC;
729
730 return 0;
731}
732
Simon Glass7dafd022018-11-15 18:44:05 -0700733/**
734 * add_args() - Allocate a new argv with the given args
735 *
736 * This is used to create a new argv array with all the old arguments and some
737 * new ones that are passed in
738 *
739 * @argvp: Returns newly allocated args list
740 * @add_args: Arguments to add, each a string
741 * @count: Number of arguments in @add_args
Heinrich Schuchardt47b4c022022-01-19 18:05:50 +0100742 * Return: 0 if OK, -ENOMEM if out of memory
Simon Glass7dafd022018-11-15 18:44:05 -0700743 */
744static int add_args(char ***argvp, char *add_args[], int count)
Simon Glass860b7d92014-02-27 13:26:15 -0700745{
Simon Glass7465f002018-11-15 18:44:07 -0700746 char **argv, **ap;
Simon Glass860b7d92014-02-27 13:26:15 -0700747 int argc;
748
Simon Glass7465f002018-11-15 18:44:07 -0700749 for (argc = 0; (*argvp)[argc]; argc++)
Simon Glass860b7d92014-02-27 13:26:15 -0700750 ;
751
Simon Glassedd094e2021-02-06 09:57:33 -0700752 argv = os_malloc((argc + count + 1) * sizeof(char *));
Simon Glass860b7d92014-02-27 13:26:15 -0700753 if (!argv) {
754 printf("Out of memory for %d argv\n", count);
755 return -ENOMEM;
756 }
Simon Glass7465f002018-11-15 18:44:07 -0700757 for (ap = *argvp, argc = 0; *ap; ap++) {
758 char *arg = *ap;
759
760 /* Drop args that we don't want to propagate */
761 if (*arg == '-' && strlen(arg) == 2) {
762 switch (arg[1]) {
763 case 'j':
764 case 'm':
765 ap++;
766 continue;
767 }
768 } else if (!strcmp(arg, "--rm_memory")) {
Simon Glass7465f002018-11-15 18:44:07 -0700769 continue;
770 }
771 argv[argc++] = arg;
772 }
773
Simon Glass860b7d92014-02-27 13:26:15 -0700774 memcpy(argv + argc, add_args, count * sizeof(char *));
775 argv[argc + count] = NULL;
776
777 *argvp = argv;
778 return 0;
779}
780
Simon Glass7dafd022018-11-15 18:44:05 -0700781/**
782 * os_jump_to_file() - Jump to a new program
783 *
784 * This saves the memory buffer, sets up arguments to the new process, then
785 * execs it.
786 *
787 * @fname: Filename to exec
Heinrich Schuchardt47b4c022022-01-19 18:05:50 +0100788 * Return: does not return on success, any return value is an error
Simon Glass7dafd022018-11-15 18:44:05 -0700789 */
Simon Glassdafc5d72021-03-15 18:11:07 +1300790static int os_jump_to_file(const char *fname, bool delete_it)
Simon Glass860b7d92014-02-27 13:26:15 -0700791{
792 struct sandbox_state *state = state_get_current();
Simon Glass7dafd022018-11-15 18:44:05 -0700793 char mem_fname[30];
Simon Glass860b7d92014-02-27 13:26:15 -0700794 int fd, err;
Simon Glass7dafd022018-11-15 18:44:05 -0700795 char *extra_args[5];
Simon Glass860b7d92014-02-27 13:26:15 -0700796 char **argv = state->argv;
Simon Glass7465f002018-11-15 18:44:07 -0700797 int argc;
Simon Glass860b7d92014-02-27 13:26:15 -0700798#ifdef DEBUG
Simon Glass7dafd022018-11-15 18:44:05 -0700799 int i;
Simon Glass860b7d92014-02-27 13:26:15 -0700800#endif
801
Simon Glass860b7d92014-02-27 13:26:15 -0700802 strcpy(mem_fname, "/tmp/u-boot.mem.XXXXXX");
803 fd = mkstemp(mem_fname);
804 if (fd < 0)
805 return -ENOENT;
806 close(fd);
807 err = os_write_ram_buf(mem_fname);
808 if (err)
809 return err;
810
811 os_fd_restore();
812
Simon Glassdafc5d72021-03-15 18:11:07 +1300813 argc = 0;
814 if (delete_it) {
815 extra_args[argc++] = "-j";
816 extra_args[argc++] = (char *)fname;
817 }
818 extra_args[argc++] = "-m";
819 extra_args[argc++] = mem_fname;
Simon Glass7465f002018-11-15 18:44:07 -0700820 if (state->ram_buf_rm)
821 extra_args[argc++] = "--rm_memory";
822 err = add_args(&argv, extra_args, argc);
Simon Glass860b7d92014-02-27 13:26:15 -0700823 if (err)
824 return err;
Simon Glass7465f002018-11-15 18:44:07 -0700825 argv[0] = (char *)fname;
Simon Glass860b7d92014-02-27 13:26:15 -0700826
827#ifdef DEBUG
828 for (i = 0; argv[i]; i++)
829 printf("%d %s\n", i, argv[i]);
830#endif
831
832 if (state_uninit())
833 os_exit(2);
834
835 err = execv(fname, argv);
Simon Glassedd094e2021-02-06 09:57:33 -0700836 os_free(argv);
Simon Glasscca25522018-11-15 18:44:08 -0700837 if (err) {
838 perror("Unable to run image");
Simon Glass23eabbb2018-11-23 21:29:24 -0700839 printf("Image filename '%s'\n", fname);
Simon Glass860b7d92014-02-27 13:26:15 -0700840 return err;
Simon Glasscca25522018-11-15 18:44:08 -0700841 }
Simon Glass860b7d92014-02-27 13:26:15 -0700842
Simon Glassdafc5d72021-03-15 18:11:07 +1300843 if (delete_it)
844 return unlink(fname);
845
846 return -EFAULT;
Simon Glass860b7d92014-02-27 13:26:15 -0700847}
Simon Glass504548f2015-04-20 12:37:22 -0600848
Simon Glass7dafd022018-11-15 18:44:05 -0700849int os_jump_to_image(const void *dest, int size)
850{
851 char fname[30];
852 int err;
853
854 err = make_exec(fname, dest, size);
855 if (err)
856 return err;
857
Simon Glassdafc5d72021-03-15 18:11:07 +1300858 return os_jump_to_file(fname, true);
Simon Glass7dafd022018-11-15 18:44:05 -0700859}
860
Simon Glass1cd06002021-07-05 16:32:45 -0600861int os_find_u_boot(char *fname, int maxlen, bool use_img,
862 const char *cur_prefix, const char *next_prefix)
Simon Glass2c931ba2016-07-04 11:57:45 -0600863{
864 struct sandbox_state *state = state_get_current();
865 const char *progname = state->argv[0];
866 int len = strlen(progname);
Simon Glass1cd06002021-07-05 16:32:45 -0600867 char subdir[10];
868 char *suffix;
Simon Glass2c931ba2016-07-04 11:57:45 -0600869 char *p;
870 int fd;
871
872 if (len >= maxlen || len < 4)
873 return -ENOSPC;
874
Simon Glass2c931ba2016-07-04 11:57:45 -0600875 strcpy(fname, progname);
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600876 suffix = fname + len - 4;
877
Simon Glass1cd06002021-07-05 16:32:45 -0600878 /* Change the existing suffix to the new one */
879 if (*suffix != '-')
880 return -EINVAL;
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600881
Simon Glass1cd06002021-07-05 16:32:45 -0600882 if (*next_prefix)
883 strcpy(suffix + 1, next_prefix); /* e.g. "-tpl" to "-spl" */
884 else
885 *suffix = '\0'; /* e.g. "-spl" to "" */
886 fd = os_open(fname, O_RDONLY);
887 if (fd >= 0) {
888 close(fd);
889 return 0;
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600890 }
891
Simon Glass1cd06002021-07-05 16:32:45 -0600892 /*
893 * We didn't find it, so try looking for 'u-boot-xxx' in the xxx/
894 * directory. Replace the old dirname with the new one.
895 */
896 snprintf(subdir, sizeof(subdir), "/%s/", cur_prefix);
897 p = strstr(fname, subdir);
Simon Glass2c931ba2016-07-04 11:57:45 -0600898 if (p) {
Simon Glass1cd06002021-07-05 16:32:45 -0600899 if (*next_prefix)
900 /* e.g. ".../tpl/u-boot-spl" to "../spl/u-boot-spl" */
901 memcpy(p + 1, next_prefix, strlen(next_prefix));
902 else
903 /* e.g. ".../spl/u-boot" to ".../u-boot" */
904 strcpy(p, p + 1 + strlen(cur_prefix));
Simon Glassb90e4872021-03-07 17:35:13 -0700905 if (use_img)
906 strcat(p, ".img");
Simon Glass1cd06002021-07-05 16:32:45 -0600907
Simon Glass2c931ba2016-07-04 11:57:45 -0600908 fd = os_open(fname, O_RDONLY);
909 if (fd >= 0) {
910 close(fd);
911 return 0;
912 }
913 }
914
915 return -ENOENT;
916}
917
918int os_spl_to_uboot(const char *fname)
919{
Patrick Delaunay6daf9052020-11-20 09:48:33 +0100920 struct sandbox_state *state = state_get_current();
921
Patrick Delaunay6daf9052020-11-20 09:48:33 +0100922 /* U-Boot will delete ram buffer after read: "--rm_memory"*/
923 state->ram_buf_rm = true;
Simon Glassdafc5d72021-03-15 18:11:07 +1300924
925 return os_jump_to_file(fname, false);
Simon Glass2c931ba2016-07-04 11:57:45 -0600926}
927
Heinrich Schuchardtc0d1a002020-12-30 18:07:48 +0100928long os_get_time_offset(void)
929{
930 const char *offset;
931
932 offset = getenv(ENV_TIME_OFFSET);
933 if (offset)
934 return strtol(offset, NULL, 0);
935 return 0;
936}
937
938void os_set_time_offset(long offset)
939{
940 char buf[21];
941 int ret;
942
943 snprintf(buf, sizeof(buf), "%ld", offset);
944 ret = setenv(ENV_TIME_OFFSET, buf, true);
945 if (ret)
946 printf("Could not set environment variable %s\n",
947 ENV_TIME_OFFSET);
948}
949
Simon Glass504548f2015-04-20 12:37:22 -0600950void os_localtime(struct rtc_time *rt)
951{
952 time_t t = time(NULL);
953 struct tm *tm;
954
955 tm = localtime(&t);
956 rt->tm_sec = tm->tm_sec;
957 rt->tm_min = tm->tm_min;
958 rt->tm_hour = tm->tm_hour;
959 rt->tm_mday = tm->tm_mday;
960 rt->tm_mon = tm->tm_mon + 1;
961 rt->tm_year = tm->tm_year + 1900;
962 rt->tm_wday = tm->tm_wday;
963 rt->tm_yday = tm->tm_yday;
964 rt->tm_isdst = tm->tm_isdst;
965}
Simon Glass5dccd152018-05-16 09:42:22 -0600966
Simon Glassb7255ef2018-09-15 00:50:55 -0600967void os_abort(void)
968{
969 abort();
970}
Simon Glass4e766c22018-10-01 21:12:32 -0600971
972int os_mprotect_allow(void *start, size_t len)
973{
974 int page_size = getpagesize();
975
976 /* Move start to the start of a page, len to the end */
977 start = (void *)(((ulong)start) & ~(page_size - 1));
978 len = (len + page_size * 2) & ~(page_size - 1);
979
980 return mprotect(start, len, PROT_READ | PROT_WRITE);
981}
Simon Glass752707a2019-04-08 13:20:41 -0600982
983void *os_find_text_base(void)
984{
985 char line[500];
986 void *base = NULL;
987 int len;
988 int fd;
989
990 /*
991 * This code assumes that the first line of /proc/self/maps holds
992 * information about the text, for example:
993 *
994 * 5622d9907000-5622d9a55000 r-xp 00000000 08:01 15067168 u-boot
995 *
996 * The first hex value is assumed to be the address.
997 *
998 * This is tested in Linux 4.15.
999 */
1000 fd = open("/proc/self/maps", O_RDONLY);
1001 if (fd == -1)
1002 return NULL;
1003 len = read(fd, line, sizeof(line));
1004 if (len > 0) {
1005 char *end = memchr(line, '-', len);
1006
1007 if (end) {
Heinrich Schuchardt05a16842019-10-26 23:17:44 +02001008 uintptr_t addr;
Simon Glass752707a2019-04-08 13:20:41 -06001009
1010 *end = '\0';
Heinrich Schuchardt05a16842019-10-26 23:17:44 +02001011 if (sscanf(line, "%zx", &addr) == 1)
Simon Glass752707a2019-04-08 13:20:41 -06001012 base = (void *)addr;
1013 }
1014 }
1015 close(fd);
1016
1017 return base;
1018}
Heinrich Schuchardt1c678442020-10-27 20:29:25 +01001019
Heinrich Schuchardt79cb2412022-09-02 02:32:25 +02001020/**
1021 * os_unblock_signals() - unblock all signals
1022 *
1023 * If we are relaunching the sandbox in a signal handler, we have to unblock
1024 * the respective signal before calling execv(). See signal(7) man-page.
1025 */
1026static void os_unblock_signals(void)
1027{
1028 sigset_t sigs;
1029
1030 sigfillset(&sigs);
1031 sigprocmask(SIG_UNBLOCK, &sigs, NULL);
1032}
1033
Heinrich Schuchardt1c678442020-10-27 20:29:25 +01001034void os_relaunch(char *argv[])
1035{
Heinrich Schuchardt79cb2412022-09-02 02:32:25 +02001036 os_unblock_signals();
1037
Heinrich Schuchardt1c678442020-10-27 20:29:25 +01001038 execv(argv[0], argv);
1039 os_exit(1);
1040}
Andrew Scullca5d1372022-05-30 10:00:10 +00001041
Andrew Scull2b40f802022-05-30 10:00:11 +00001042
1043#ifdef CONFIG_FUZZ
1044static void *fuzzer_thread(void * ptr)
1045{
1046 char cmd[64];
1047 char *argv[5] = {"./u-boot", "-T", "-c", cmd, NULL};
1048 const char *fuzz_test;
1049
1050 /* Find which test to run from an environment variable. */
1051 fuzz_test = getenv("UBOOT_SB_FUZZ_TEST");
1052 if (!fuzz_test)
1053 os_abort();
1054
1055 snprintf(cmd, sizeof(cmd), "fuzz %s", fuzz_test);
1056
1057 sandbox_main(4, argv);
1058 os_abort();
1059 return NULL;
1060}
1061
1062static bool fuzzer_initialized = false;
1063static pthread_mutex_t fuzzer_mutex = PTHREAD_MUTEX_INITIALIZER;
1064static pthread_cond_t fuzzer_cond = PTHREAD_COND_INITIALIZER;
1065static const uint8_t *fuzzer_data;
1066static size_t fuzzer_size;
1067
1068int sandbox_fuzzing_engine_get_input(const uint8_t **data, size_t *size)
1069{
1070 if (!fuzzer_initialized)
1071 return -ENOSYS;
1072
1073 /* Tell the main thread we need new inputs then wait for them. */
1074 pthread_mutex_lock(&fuzzer_mutex);
1075 pthread_cond_signal(&fuzzer_cond);
1076 pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1077 *data = fuzzer_data;
1078 *size = fuzzer_size;
1079 pthread_mutex_unlock(&fuzzer_mutex);
1080 return 0;
1081}
1082
1083int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
1084{
1085 static pthread_t tid;
1086
1087 pthread_mutex_lock(&fuzzer_mutex);
1088
1089 /* Initialize the sandbox on another thread. */
1090 if (!fuzzer_initialized) {
1091 fuzzer_initialized = true;
1092 if (pthread_create(&tid, NULL, fuzzer_thread, NULL))
1093 os_abort();
1094 pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1095 }
1096
1097 /* Hand over the input. */
1098 fuzzer_data = data;
1099 fuzzer_size = size;
1100 pthread_cond_signal(&fuzzer_cond);
1101
1102 /* Wait for the inputs to be finished with. */
1103 pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1104 pthread_mutex_unlock(&fuzzer_mutex);
1105
1106 return 0;
1107}
1108#else
Andrew Scullca5d1372022-05-30 10:00:10 +00001109int main(int argc, char *argv[])
1110{
1111 return sandbox_main(argc, argv);
1112}
Andrew Scull2b40f802022-05-30 10:00:11 +00001113#endif