blob: f937991139c93913255f69eadcb7585ab6c75d7b [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
Simon Glass9dd10bf2013-11-10 10:27:03 -0700672int os_write_ram_buf(const char *fname)
673{
674 struct sandbox_state *state = state_get_current();
675 int fd, ret;
676
677 fd = open(fname, O_CREAT | O_WRONLY, 0777);
678 if (fd < 0)
679 return -ENOENT;
680 ret = write(fd, state->ram_buf, state->ram_size);
681 close(fd);
682 if (ret != state->ram_size)
683 return -EIO;
684
685 return 0;
686}
687
688int os_read_ram_buf(const char *fname)
689{
690 struct sandbox_state *state = state_get_current();
691 int fd, ret;
Heinrich Schuchardt011a1e02022-01-11 01:50:24 +0100692 long long size;
Simon Glass9dd10bf2013-11-10 10:27:03 -0700693
Suriyan Ramasami378da1032014-11-17 14:39:37 -0800694 ret = os_get_filesize(fname, &size);
695 if (ret < 0)
696 return ret;
Simon Glass9dd10bf2013-11-10 10:27:03 -0700697 if (size != state->ram_size)
698 return -ENOSPC;
699 fd = open(fname, O_RDONLY);
700 if (fd < 0)
701 return -ENOENT;
702
703 ret = read(fd, state->ram_buf, state->ram_size);
704 close(fd);
705 if (ret != state->ram_size)
706 return -EIO;
707
708 return 0;
709}
Simon Glass860b7d92014-02-27 13:26:15 -0700710
711static int make_exec(char *fname, const void *data, int size)
712{
713 int fd;
714
715 strcpy(fname, "/tmp/u-boot.jump.XXXXXX");
716 fd = mkstemp(fname);
717 if (fd < 0)
718 return -ENOENT;
719 if (write(fd, data, size) < 0)
720 return -EIO;
721 close(fd);
722 if (chmod(fname, 0777))
723 return -ENOEXEC;
724
725 return 0;
726}
727
Simon Glass7dafd022018-11-15 18:44:05 -0700728/**
729 * add_args() - Allocate a new argv with the given args
730 *
731 * This is used to create a new argv array with all the old arguments and some
732 * new ones that are passed in
733 *
734 * @argvp: Returns newly allocated args list
735 * @add_args: Arguments to add, each a string
736 * @count: Number of arguments in @add_args
Heinrich Schuchardt47b4c022022-01-19 18:05:50 +0100737 * Return: 0 if OK, -ENOMEM if out of memory
Simon Glass7dafd022018-11-15 18:44:05 -0700738 */
739static int add_args(char ***argvp, char *add_args[], int count)
Simon Glass860b7d92014-02-27 13:26:15 -0700740{
Simon Glass7465f002018-11-15 18:44:07 -0700741 char **argv, **ap;
Simon Glass860b7d92014-02-27 13:26:15 -0700742 int argc;
743
Simon Glass7465f002018-11-15 18:44:07 -0700744 for (argc = 0; (*argvp)[argc]; argc++)
Simon Glass860b7d92014-02-27 13:26:15 -0700745 ;
746
Simon Glassedd094e2021-02-06 09:57:33 -0700747 argv = os_malloc((argc + count + 1) * sizeof(char *));
Simon Glass860b7d92014-02-27 13:26:15 -0700748 if (!argv) {
749 printf("Out of memory for %d argv\n", count);
750 return -ENOMEM;
751 }
Simon Glass7465f002018-11-15 18:44:07 -0700752 for (ap = *argvp, argc = 0; *ap; ap++) {
753 char *arg = *ap;
754
755 /* Drop args that we don't want to propagate */
756 if (*arg == '-' && strlen(arg) == 2) {
757 switch (arg[1]) {
758 case 'j':
759 case 'm':
760 ap++;
761 continue;
762 }
763 } else if (!strcmp(arg, "--rm_memory")) {
Simon Glass7465f002018-11-15 18:44:07 -0700764 continue;
765 }
766 argv[argc++] = arg;
767 }
768
Simon Glass860b7d92014-02-27 13:26:15 -0700769 memcpy(argv + argc, add_args, count * sizeof(char *));
770 argv[argc + count] = NULL;
771
772 *argvp = argv;
773 return 0;
774}
775
Simon Glass7dafd022018-11-15 18:44:05 -0700776/**
777 * os_jump_to_file() - Jump to a new program
778 *
779 * This saves the memory buffer, sets up arguments to the new process, then
780 * execs it.
781 *
782 * @fname: Filename to exec
Heinrich Schuchardt47b4c022022-01-19 18:05:50 +0100783 * Return: does not return on success, any return value is an error
Simon Glass7dafd022018-11-15 18:44:05 -0700784 */
Simon Glassdafc5d72021-03-15 18:11:07 +1300785static int os_jump_to_file(const char *fname, bool delete_it)
Simon Glass860b7d92014-02-27 13:26:15 -0700786{
787 struct sandbox_state *state = state_get_current();
Simon Glass7dafd022018-11-15 18:44:05 -0700788 char mem_fname[30];
Simon Glass860b7d92014-02-27 13:26:15 -0700789 int fd, err;
Simon Glass7dafd022018-11-15 18:44:05 -0700790 char *extra_args[5];
Simon Glass860b7d92014-02-27 13:26:15 -0700791 char **argv = state->argv;
Simon Glass7465f002018-11-15 18:44:07 -0700792 int argc;
Simon Glass860b7d92014-02-27 13:26:15 -0700793#ifdef DEBUG
Simon Glass7dafd022018-11-15 18:44:05 -0700794 int i;
Simon Glass860b7d92014-02-27 13:26:15 -0700795#endif
796
Simon Glass860b7d92014-02-27 13:26:15 -0700797 strcpy(mem_fname, "/tmp/u-boot.mem.XXXXXX");
798 fd = mkstemp(mem_fname);
799 if (fd < 0)
800 return -ENOENT;
801 close(fd);
802 err = os_write_ram_buf(mem_fname);
803 if (err)
804 return err;
805
806 os_fd_restore();
807
Simon Glassdafc5d72021-03-15 18:11:07 +1300808 argc = 0;
809 if (delete_it) {
810 extra_args[argc++] = "-j";
811 extra_args[argc++] = (char *)fname;
812 }
813 extra_args[argc++] = "-m";
814 extra_args[argc++] = mem_fname;
Simon Glass7465f002018-11-15 18:44:07 -0700815 if (state->ram_buf_rm)
816 extra_args[argc++] = "--rm_memory";
817 err = add_args(&argv, extra_args, argc);
Simon Glass860b7d92014-02-27 13:26:15 -0700818 if (err)
819 return err;
Simon Glass7465f002018-11-15 18:44:07 -0700820 argv[0] = (char *)fname;
Simon Glass860b7d92014-02-27 13:26:15 -0700821
822#ifdef DEBUG
823 for (i = 0; argv[i]; i++)
824 printf("%d %s\n", i, argv[i]);
825#endif
826
827 if (state_uninit())
828 os_exit(2);
829
830 err = execv(fname, argv);
Simon Glassedd094e2021-02-06 09:57:33 -0700831 os_free(argv);
Simon Glasscca25522018-11-15 18:44:08 -0700832 if (err) {
833 perror("Unable to run image");
Simon Glass23eabbb2018-11-23 21:29:24 -0700834 printf("Image filename '%s'\n", fname);
Simon Glass860b7d92014-02-27 13:26:15 -0700835 return err;
Simon Glasscca25522018-11-15 18:44:08 -0700836 }
Simon Glass860b7d92014-02-27 13:26:15 -0700837
Simon Glassdafc5d72021-03-15 18:11:07 +1300838 if (delete_it)
839 return unlink(fname);
840
841 return -EFAULT;
Simon Glass860b7d92014-02-27 13:26:15 -0700842}
Simon Glass504548f2015-04-20 12:37:22 -0600843
Simon Glass7dafd022018-11-15 18:44:05 -0700844int os_jump_to_image(const void *dest, int size)
845{
846 char fname[30];
847 int err;
848
849 err = make_exec(fname, dest, size);
850 if (err)
851 return err;
852
Simon Glassdafc5d72021-03-15 18:11:07 +1300853 return os_jump_to_file(fname, true);
Simon Glass7dafd022018-11-15 18:44:05 -0700854}
855
Simon Glass1cd06002021-07-05 16:32:45 -0600856int os_find_u_boot(char *fname, int maxlen, bool use_img,
857 const char *cur_prefix, const char *next_prefix)
Simon Glass2c931ba2016-07-04 11:57:45 -0600858{
859 struct sandbox_state *state = state_get_current();
860 const char *progname = state->argv[0];
861 int len = strlen(progname);
Simon Glass1cd06002021-07-05 16:32:45 -0600862 char subdir[10];
863 char *suffix;
Simon Glass2c931ba2016-07-04 11:57:45 -0600864 char *p;
865 int fd;
866
867 if (len >= maxlen || len < 4)
868 return -ENOSPC;
869
Simon Glass2c931ba2016-07-04 11:57:45 -0600870 strcpy(fname, progname);
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600871 suffix = fname + len - 4;
872
Simon Glass1cd06002021-07-05 16:32:45 -0600873 /* Change the existing suffix to the new one */
874 if (*suffix != '-')
875 return -EINVAL;
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600876
Simon Glass1cd06002021-07-05 16:32:45 -0600877 if (*next_prefix)
878 strcpy(suffix + 1, next_prefix); /* e.g. "-tpl" to "-spl" */
879 else
880 *suffix = '\0'; /* e.g. "-spl" to "" */
881 fd = os_open(fname, O_RDONLY);
882 if (fd >= 0) {
883 close(fd);
884 return 0;
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600885 }
886
Simon Glass1cd06002021-07-05 16:32:45 -0600887 /*
888 * We didn't find it, so try looking for 'u-boot-xxx' in the xxx/
889 * directory. Replace the old dirname with the new one.
890 */
891 snprintf(subdir, sizeof(subdir), "/%s/", cur_prefix);
892 p = strstr(fname, subdir);
Simon Glass2c931ba2016-07-04 11:57:45 -0600893 if (p) {
Simon Glass1cd06002021-07-05 16:32:45 -0600894 if (*next_prefix)
895 /* e.g. ".../tpl/u-boot-spl" to "../spl/u-boot-spl" */
896 memcpy(p + 1, next_prefix, strlen(next_prefix));
897 else
898 /* e.g. ".../spl/u-boot" to ".../u-boot" */
899 strcpy(p, p + 1 + strlen(cur_prefix));
Simon Glassb90e4872021-03-07 17:35:13 -0700900 if (use_img)
901 strcat(p, ".img");
Simon Glass1cd06002021-07-05 16:32:45 -0600902
Simon Glass2c931ba2016-07-04 11:57:45 -0600903 fd = os_open(fname, O_RDONLY);
904 if (fd >= 0) {
905 close(fd);
906 return 0;
907 }
908 }
909
910 return -ENOENT;
911}
912
913int os_spl_to_uboot(const char *fname)
914{
Patrick Delaunay6daf9052020-11-20 09:48:33 +0100915 struct sandbox_state *state = state_get_current();
916
Patrick Delaunay6daf9052020-11-20 09:48:33 +0100917 /* U-Boot will delete ram buffer after read: "--rm_memory"*/
918 state->ram_buf_rm = true;
Simon Glassdafc5d72021-03-15 18:11:07 +1300919
920 return os_jump_to_file(fname, false);
Simon Glass2c931ba2016-07-04 11:57:45 -0600921}
922
Heinrich Schuchardtc0d1a002020-12-30 18:07:48 +0100923long os_get_time_offset(void)
924{
925 const char *offset;
926
927 offset = getenv(ENV_TIME_OFFSET);
928 if (offset)
929 return strtol(offset, NULL, 0);
930 return 0;
931}
932
933void os_set_time_offset(long offset)
934{
935 char buf[21];
936 int ret;
937
938 snprintf(buf, sizeof(buf), "%ld", offset);
939 ret = setenv(ENV_TIME_OFFSET, buf, true);
940 if (ret)
941 printf("Could not set environment variable %s\n",
942 ENV_TIME_OFFSET);
943}
944
Simon Glass504548f2015-04-20 12:37:22 -0600945void os_localtime(struct rtc_time *rt)
946{
947 time_t t = time(NULL);
948 struct tm *tm;
949
950 tm = localtime(&t);
951 rt->tm_sec = tm->tm_sec;
952 rt->tm_min = tm->tm_min;
953 rt->tm_hour = tm->tm_hour;
954 rt->tm_mday = tm->tm_mday;
955 rt->tm_mon = tm->tm_mon + 1;
956 rt->tm_year = tm->tm_year + 1900;
957 rt->tm_wday = tm->tm_wday;
958 rt->tm_yday = tm->tm_yday;
959 rt->tm_isdst = tm->tm_isdst;
960}
Simon Glass5dccd152018-05-16 09:42:22 -0600961
Simon Glassb7255ef2018-09-15 00:50:55 -0600962void os_abort(void)
963{
964 abort();
965}
Simon Glass4e766c22018-10-01 21:12:32 -0600966
967int os_mprotect_allow(void *start, size_t len)
968{
969 int page_size = getpagesize();
970
971 /* Move start to the start of a page, len to the end */
972 start = (void *)(((ulong)start) & ~(page_size - 1));
973 len = (len + page_size * 2) & ~(page_size - 1);
974
975 return mprotect(start, len, PROT_READ | PROT_WRITE);
976}
Simon Glass752707a2019-04-08 13:20:41 -0600977
978void *os_find_text_base(void)
979{
980 char line[500];
981 void *base = NULL;
982 int len;
983 int fd;
984
985 /*
986 * This code assumes that the first line of /proc/self/maps holds
987 * information about the text, for example:
988 *
989 * 5622d9907000-5622d9a55000 r-xp 00000000 08:01 15067168 u-boot
990 *
991 * The first hex value is assumed to be the address.
992 *
993 * This is tested in Linux 4.15.
994 */
995 fd = open("/proc/self/maps", O_RDONLY);
996 if (fd == -1)
997 return NULL;
998 len = read(fd, line, sizeof(line));
999 if (len > 0) {
1000 char *end = memchr(line, '-', len);
1001
1002 if (end) {
Heinrich Schuchardt05a16842019-10-26 23:17:44 +02001003 uintptr_t addr;
Simon Glass752707a2019-04-08 13:20:41 -06001004
1005 *end = '\0';
Heinrich Schuchardt05a16842019-10-26 23:17:44 +02001006 if (sscanf(line, "%zx", &addr) == 1)
Simon Glass752707a2019-04-08 13:20:41 -06001007 base = (void *)addr;
1008 }
1009 }
1010 close(fd);
1011
1012 return base;
1013}
Heinrich Schuchardt1c678442020-10-27 20:29:25 +01001014
1015void os_relaunch(char *argv[])
1016{
1017 execv(argv[0], argv);
1018 os_exit(1);
1019}
Andrew Scullca5d1372022-05-30 10:00:10 +00001020
Andrew Scull2b40f802022-05-30 10:00:11 +00001021
1022#ifdef CONFIG_FUZZ
1023static void *fuzzer_thread(void * ptr)
1024{
1025 char cmd[64];
1026 char *argv[5] = {"./u-boot", "-T", "-c", cmd, NULL};
1027 const char *fuzz_test;
1028
1029 /* Find which test to run from an environment variable. */
1030 fuzz_test = getenv("UBOOT_SB_FUZZ_TEST");
1031 if (!fuzz_test)
1032 os_abort();
1033
1034 snprintf(cmd, sizeof(cmd), "fuzz %s", fuzz_test);
1035
1036 sandbox_main(4, argv);
1037 os_abort();
1038 return NULL;
1039}
1040
1041static bool fuzzer_initialized = false;
1042static pthread_mutex_t fuzzer_mutex = PTHREAD_MUTEX_INITIALIZER;
1043static pthread_cond_t fuzzer_cond = PTHREAD_COND_INITIALIZER;
1044static const uint8_t *fuzzer_data;
1045static size_t fuzzer_size;
1046
1047int sandbox_fuzzing_engine_get_input(const uint8_t **data, size_t *size)
1048{
1049 if (!fuzzer_initialized)
1050 return -ENOSYS;
1051
1052 /* Tell the main thread we need new inputs then wait for them. */
1053 pthread_mutex_lock(&fuzzer_mutex);
1054 pthread_cond_signal(&fuzzer_cond);
1055 pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1056 *data = fuzzer_data;
1057 *size = fuzzer_size;
1058 pthread_mutex_unlock(&fuzzer_mutex);
1059 return 0;
1060}
1061
1062int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
1063{
1064 static pthread_t tid;
1065
1066 pthread_mutex_lock(&fuzzer_mutex);
1067
1068 /* Initialize the sandbox on another thread. */
1069 if (!fuzzer_initialized) {
1070 fuzzer_initialized = true;
1071 if (pthread_create(&tid, NULL, fuzzer_thread, NULL))
1072 os_abort();
1073 pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1074 }
1075
1076 /* Hand over the input. */
1077 fuzzer_data = data;
1078 fuzzer_size = size;
1079 pthread_cond_signal(&fuzzer_cond);
1080
1081 /* Wait for the inputs to be finished with. */
1082 pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1083 pthread_mutex_unlock(&fuzzer_mutex);
1084
1085 return 0;
1086}
1087#else
Andrew Scullca5d1372022-05-30 10:00:10 +00001088int main(int argc, char *argv[])
1089{
1090 return sandbox_main(argc, argv);
1091}
Andrew Scull2b40f802022-05-30 10:00:11 +00001092#endif