blob: 3b230606a97e6cddc76eb7a1e1fdf47b5fce8da4 [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>
Simon Glassf1c45c82012-12-26 09:53:34 +000015#include <stdio.h>
Simon Glassfb4b4e82013-05-19 16:45:35 -070016#include <stdint.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000017#include <stdlib.h>
Simon Glassf1c45c82012-12-26 09:53:34 +000018#include <string.h>
Mike Frysingera5baaee2011-10-26 00:21:29 +000019#include <termios.h>
Matthias Weisser0d3dd142011-11-29 12:16:40 +010020#include <time.h>
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +010021#include <ucontext.h>
Simon Glasse8015a62012-01-10 15:54:05 -080022#include <unistd.h>
Matthias Weisserb5f7b472011-11-05 11:40:34 +010023#include <sys/mman.h>
Simon Glasse8015a62012-01-10 15:54:05 -080024#include <sys/stat.h>
Simon Glass17064c02012-01-10 15:54:06 -080025#include <sys/time.h>
Simon Glasse8015a62012-01-10 15:54:05 -080026#include <sys/types.h>
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +010027#include <linux/compiler_attributes.h>
Matthias Weisser0d3dd142011-11-29 12:16:40 +010028#include <linux/types.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000029
Andrew Scull2b40f802022-05-30 10:00:11 +000030#include <asm/fuzzing_engine.h>
Simon Glass8a3e0352012-02-15 15:51:16 -080031#include <asm/getopt.h>
Andrew Scullca5d1372022-05-30 10:00:10 +000032#include <asm/main.h>
Simon Glass8a3e0352012-02-15 15:51:16 -080033#include <asm/sections.h>
34#include <asm/state.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000035#include <os.h>
Simon Glass504548f2015-04-20 12:37:22 -060036#include <rtc_def.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000037
Heinrich Schuchardtc0d1a002020-12-30 18:07:48 +010038/* Environment variable for time offset */
39#define ENV_TIME_OFFSET "UBOOT_SB_TIME_OFFSET"
40
Simon Glasscd0684f2011-10-03 19:26:44 +000041/* Operating System Interface */
42
Simon Glass1e6594c2013-11-10 10:26:57 -070043struct os_mem_hdr {
44 size_t length; /* number of bytes in the block */
45};
46
Simon Glasscd0684f2011-10-03 19:26:44 +000047ssize_t os_read(int fd, void *buf, size_t count)
48{
49 return read(fd, buf, count);
50}
51
52ssize_t os_write(int fd, const void *buf, size_t count)
53{
54 return write(fd, buf, count);
55}
56
Mike Frysinger60addac2011-10-25 13:02:58 +020057off_t os_lseek(int fd, off_t offset, int whence)
58{
59 if (whence == OS_SEEK_SET)
60 whence = SEEK_SET;
61 else if (whence == OS_SEEK_CUR)
62 whence = SEEK_CUR;
63 else if (whence == OS_SEEK_END)
64 whence = SEEK_END;
65 else
66 os_exit(1);
67 return lseek(fd, offset, whence);
68}
69
Simon Glass3196d752012-02-20 23:56:58 -050070int os_open(const char *pathname, int os_flags)
Simon Glasscd0684f2011-10-03 19:26:44 +000071{
Simon Glass3196d752012-02-20 23:56:58 -050072 int flags;
73
74 switch (os_flags & OS_O_MASK) {
75 case OS_O_RDONLY:
76 default:
77 flags = O_RDONLY;
78 break;
79
80 case OS_O_WRONLY:
81 flags = O_WRONLY;
82 break;
83
84 case OS_O_RDWR:
85 flags = O_RDWR;
86 break;
87 }
88
89 if (os_flags & OS_O_CREAT)
90 flags |= O_CREAT;
Simon Glassce55a112018-10-01 11:55:07 -060091 if (os_flags & OS_O_TRUNC)
92 flags |= O_TRUNC;
Heinrich Schuchardtfc96df62020-10-27 20:29:24 +010093 /*
94 * During a cold reset execv() is used to relaunch the U-Boot binary.
95 * We must ensure that all files are closed in this case.
96 */
97 flags |= O_CLOEXEC;
Simon Glass3196d752012-02-20 23:56:58 -050098
99 return open(pathname, flags, 0777);
Simon Glasscd0684f2011-10-03 19:26:44 +0000100}
101
102int os_close(int fd)
103{
Heinrich Schuchardt69db2ee2020-10-27 20:29:21 +0100104 /* Do not close the console input */
105 if (fd)
106 return close(fd);
107 return -1;
Simon Glasscd0684f2011-10-03 19:26:44 +0000108}
109
Stephen Warrencd5edba2014-03-01 22:18:00 -0700110int os_unlink(const char *pathname)
111{
112 return unlink(pathname);
113}
114
Simon Glasscd0684f2011-10-03 19:26:44 +0000115void os_exit(int exit_code)
116{
117 exit(exit_code);
118}
Mike Frysingera5baaee2011-10-26 00:21:29 +0000119
Simon Glass8d176d82018-11-06 15:21:25 -0700120int os_write_file(const char *fname, const void *buf, int size)
Simon Glasscbfa8452018-10-01 11:55:08 -0600121{
Simon Glasscbfa8452018-10-01 11:55:08 -0600122 int fd;
123
124 fd = os_open(fname, OS_O_WRONLY | OS_O_CREAT | OS_O_TRUNC);
125 if (fd < 0) {
126 printf("Cannot open file '%s'\n", fname);
127 return -EIO;
128 }
129 if (os_write(fd, buf, size) != size) {
130 printf("Cannot write to file '%s'\n", fname);
Simon Glass8d176d82018-11-06 15:21:25 -0700131 os_close(fd);
Simon Glasscbfa8452018-10-01 11:55:08 -0600132 return -EIO;
133 }
134 os_close(fd);
Simon Glasscbfa8452018-10-01 11:55:08 -0600135
136 return 0;
137}
138
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600139int os_filesize(int fd)
140{
141 off_t size;
142
143 size = os_lseek(fd, 0, OS_SEEK_END);
144 if (size < 0)
145 return -errno;
146 if (os_lseek(fd, 0, OS_SEEK_SET) < 0)
147 return -errno;
148
149 return size;
150}
151
Simon Glass8d176d82018-11-06 15:21:25 -0700152int os_read_file(const char *fname, void **bufp, int *sizep)
153{
154 off_t size;
155 int ret = -EIO;
156 int fd;
157
158 fd = os_open(fname, OS_O_RDONLY);
159 if (fd < 0) {
160 printf("Cannot open file '%s'\n", fname);
161 goto err;
162 }
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600163 size = os_filesize(fd);
Simon Glass8d176d82018-11-06 15:21:25 -0700164 if (size < 0) {
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600165 printf("Cannot get file size of '%s'\n", fname);
Simon Glass8d176d82018-11-06 15:21:25 -0700166 goto err;
167 }
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600168
Simon Glassedd094e2021-02-06 09:57:33 -0700169 *bufp = os_malloc(size);
Simon Glass8d176d82018-11-06 15:21:25 -0700170 if (!*bufp) {
171 printf("Not enough memory to read file '%s'\n", fname);
172 ret = -ENOMEM;
173 goto err;
174 }
175 if (os_read(fd, *bufp, size) != size) {
176 printf("Cannot read from file '%s'\n", fname);
177 goto err;
178 }
179 os_close(fd);
180 *sizep = size;
181
182 return 0;
183err:
184 os_close(fd);
185 return ret;
186}
187
Simon Glasse4c25c82021-08-18 21:40:31 -0600188int os_map_file(const char *pathname, int os_flags, void **bufp, int *sizep)
189{
190 void *ptr;
191 int size;
192 int ifd;
193
194 ifd = os_open(pathname, os_flags);
195 if (ifd < 0) {
196 printf("Cannot open file '%s'\n", pathname);
197 return -EIO;
198 }
199 size = os_filesize(ifd);
200 if (size < 0) {
201 printf("Cannot get file size of '%s'\n", pathname);
202 return -EIO;
203 }
204
205 ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, ifd, 0);
206 if (ptr == MAP_FAILED) {
207 printf("Can't map file '%s': %s\n", pathname, strerror(errno));
208 return -EPERM;
209 }
210
211 *bufp = ptr;
212 *sizep = size;
213
214 return 0;
215}
216
Simon Glass5c1fd582021-10-23 17:25:58 -0600217int os_unmap(void *buf, int size)
218{
219 if (munmap(buf, size)) {
220 printf("Can't unmap %p %x\n", buf, size);
221 return -EIO;
222 }
223
224 return 0;
225}
226
Mike Frysingera5baaee2011-10-26 00:21:29 +0000227/* Restore tty state when we exit */
228static struct termios orig_term;
Simon Glass678ef472014-02-27 13:26:22 -0700229static bool term_setup;
Simon Glassae50ec72018-10-01 11:55:20 -0600230static bool term_nonblock;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000231
Simon Glass9c3b7d62015-05-10 21:07:27 -0600232void os_fd_restore(void)
Mike Frysingera5baaee2011-10-26 00:21:29 +0000233{
Simon Glass9c3b7d62015-05-10 21:07:27 -0600234 if (term_setup) {
Simon Glassae50ec72018-10-01 11:55:20 -0600235 int flags;
236
Simon Glass678ef472014-02-27 13:26:22 -0700237 tcsetattr(0, TCSANOW, &orig_term);
Simon Glassae50ec72018-10-01 11:55:20 -0600238 if (term_nonblock) {
239 flags = fcntl(0, F_GETFL, 0);
240 fcntl(0, F_SETFL, flags & ~O_NONBLOCK);
241 }
Simon Glass9c3b7d62015-05-10 21:07:27 -0600242 term_setup = false;
243 }
Mike Frysingera5baaee2011-10-26 00:21:29 +0000244}
245
Rasmus Villemoes2b72ad22020-02-14 10:58:37 +0000246static void os_sigint_handler(int sig)
247{
248 os_fd_restore();
249 signal(SIGINT, SIG_DFL);
250 raise(SIGINT);
251}
252
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +0100253static void os_signal_handler(int sig, siginfo_t *info, void *con)
254{
255 ucontext_t __maybe_unused *context = con;
256 unsigned long pc;
257
258#if defined(__x86_64__)
259 pc = context->uc_mcontext.gregs[REG_RIP];
260#elif defined(__aarch64__)
261 pc = context->uc_mcontext.pc;
262#elif defined(__riscv)
263 pc = context->uc_mcontext.__gregs[REG_PC];
264#else
265 const char msg[] =
266 "\nUnsupported architecture, cannot read program counter\n";
267
268 os_write(1, msg, sizeof(msg));
269 pc = 0;
270#endif
271
272 os_signal_action(sig, pc);
273}
274
275int os_setup_signal_handlers(void)
276{
277 struct sigaction act;
278
279 act.sa_sigaction = os_signal_handler;
280 sigemptyset(&act.sa_mask);
Heinrich Schuchardtd3741bc2021-07-05 19:43:00 +0200281 act.sa_flags = SA_SIGINFO;
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +0100282 if (sigaction(SIGILL, &act, NULL) ||
283 sigaction(SIGBUS, &act, NULL) ||
284 sigaction(SIGSEGV, &act, NULL))
285 return -1;
286 return 0;
287}
288
Mike Frysingera5baaee2011-10-26 00:21:29 +0000289/* Put tty into raw mode so <tab> and <ctrl+c> work */
Simon Glass678ef472014-02-27 13:26:22 -0700290void os_tty_raw(int fd, bool allow_sigs)
Mike Frysingera5baaee2011-10-26 00:21:29 +0000291{
Mike Frysingera5baaee2011-10-26 00:21:29 +0000292 struct termios term;
Simon Glassae50ec72018-10-01 11:55:20 -0600293 int flags;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000294
Simon Glass678ef472014-02-27 13:26:22 -0700295 if (term_setup)
Mike Frysingera5baaee2011-10-26 00:21:29 +0000296 return;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000297
298 /* If not a tty, don't complain */
299 if (tcgetattr(fd, &orig_term))
300 return;
301
302 term = orig_term;
303 term.c_iflag = IGNBRK | IGNPAR;
304 term.c_oflag = OPOST | ONLCR;
305 term.c_cflag = CS8 | CREAD | CLOCAL;
Simon Glass678ef472014-02-27 13:26:22 -0700306 term.c_lflag = allow_sigs ? ISIG : 0;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000307 if (tcsetattr(fd, TCSANOW, &term))
308 return;
309
Simon Glassae50ec72018-10-01 11:55:20 -0600310 flags = fcntl(fd, F_GETFL, 0);
311 if (!(flags & O_NONBLOCK)) {
312 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK))
313 return;
314 term_nonblock = true;
315 }
316
Simon Glass9c3b7d62015-05-10 21:07:27 -0600317 term_setup = true;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000318 atexit(os_fd_restore);
Rasmus Villemoes2b72ad22020-02-14 10:58:37 +0000319 signal(SIGINT, os_sigint_handler);
Mike Frysingera5baaee2011-10-26 00:21:29 +0000320}
Matthias Weisserb5f7b472011-11-05 11:40:34 +0100321
Simon Glass4c902fa2021-02-06 09:57:32 -0700322/*
323 * Provide our own malloc so we don't use space in the sandbox ram_buf for
324 * allocations that are internal to sandbox, or need to be done before U-Boot's
325 * malloc() is ready.
326 */
Matthias Weisserb5f7b472011-11-05 11:40:34 +0100327void *os_malloc(size_t length)
328{
Simon Glassbe005d82018-09-15 00:50:54 -0600329 int page_size = getpagesize();
Simon Glassfc2dde82019-04-08 13:20:42 -0600330 struct os_mem_hdr *hdr;
Simon Glass1e6594c2013-11-10 10:26:57 -0700331
Simon Glass4c902fa2021-02-06 09:57:32 -0700332 if (!length)
333 return NULL;
Simon Glass57ba9422018-06-17 08:57:43 -0600334 /*
335 * Use an address that is hopefully available to us so that pointers
336 * to this memory are fairly obvious. If we end up with a different
337 * address, that's fine too.
338 */
339 hdr = mmap((void *)0x10000000, length + page_size,
Alexander Graf934a5452018-06-22 14:44:13 +0200340 PROT_READ | PROT_WRITE | PROT_EXEC,
341 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
Simon Glass1e6594c2013-11-10 10:26:57 -0700342 if (hdr == MAP_FAILED)
343 return NULL;
344 hdr->length = length;
345
Simon Glassbe005d82018-09-15 00:50:54 -0600346 return (void *)hdr + page_size;
Simon Glass1e6594c2013-11-10 10:26:57 -0700347}
348
Masahiro Yamadaee957282014-01-15 13:06:41 +0900349void os_free(void *ptr)
Simon Glass1e6594c2013-11-10 10:26:57 -0700350{
Simon Glassfc2dde82019-04-08 13:20:42 -0600351 int page_size = getpagesize();
352 struct os_mem_hdr *hdr;
Simon Glass1e6594c2013-11-10 10:26:57 -0700353
Simon Glassfc2dde82019-04-08 13:20:42 -0600354 if (ptr) {
355 hdr = ptr - page_size;
356 munmap(hdr, hdr->length + page_size);
357 }
Simon Glass4c902fa2021-02-06 09:57:32 -0700358}
359
360/* These macros are from kernel.h but not accessible in this file */
361#define ALIGN(x, a) __ALIGN_MASK((x), (typeof(x))(a) - 1)
362#define __ALIGN_MASK(x, mask) (((x) + (mask)) & ~(mask))
363
364/*
365 * Provide our own malloc so we don't use space in the sandbox ram_buf for
366 * allocations that are internal to sandbox, or need to be done before U-Boot's
367 * malloc() is ready.
368 */
369void *os_realloc(void *ptr, size_t length)
370{
371 int page_size = getpagesize();
372 struct os_mem_hdr *hdr;
373 void *new_ptr;
374
375 /* Reallocating a NULL pointer is just an alloc */
376 if (!ptr)
377 return os_malloc(length);
378
379 /* Changing a length to 0 is just a free */
380 if (length) {
381 os_free(ptr);
382 return NULL;
383 }
384
385 /*
386 * If the new size is the same number of pages as the old, nothing to
387 * do. There isn't much point in shrinking things
388 */
389 hdr = ptr - page_size;
390 if (ALIGN(length, page_size) <= ALIGN(hdr->length, page_size))
391 return ptr;
392
393 /* We have to grow it, so allocate something new */
394 new_ptr = os_malloc(length);
395 memcpy(new_ptr, ptr, hdr->length);
396 os_free(ptr);
397
398 return new_ptr;
Simon Glass1e6594c2013-11-10 10:26:57 -0700399}
400
Matthias Weisser0d3dd142011-11-29 12:16:40 +0100401void os_usleep(unsigned long usec)
402{
403 usleep(usec);
404}
405
Simon Glassfb4b4e82013-05-19 16:45:35 -0700406uint64_t __attribute__((no_instrument_function)) os_get_nsec(void)
Matthias Weisser0d3dd142011-11-29 12:16:40 +0100407{
408#if defined(CLOCK_MONOTONIC) && defined(_POSIX_MONOTONIC_CLOCK)
409 struct timespec tp;
410 if (EINVAL == clock_gettime(CLOCK_MONOTONIC, &tp)) {
411 struct timeval tv;
412
413 gettimeofday(&tv, NULL);
414 tp.tv_sec = tv.tv_sec;
415 tp.tv_nsec = tv.tv_usec * 1000;
416 }
417 return tp.tv_sec * 1000000000ULL + tp.tv_nsec;
418#else
419 struct timeval tv;
420 gettimeofday(&tv, NULL);
421 return tv.tv_sec * 1000000000ULL + tv.tv_usec * 1000;
422#endif
423}
Simon Glass8a3e0352012-02-15 15:51:16 -0800424
425static char *short_opts;
426static struct option *long_opts;
427
428int os_parse_args(struct sandbox_state *state, int argc, char *argv[])
429{
Marek Behún184c4af2021-05-20 13:24:06 +0200430 struct sandbox_cmdline_option **sb_opt =
431 __u_boot_sandbox_option_start();
Simon Glass8a3e0352012-02-15 15:51:16 -0800432 size_t num_options = __u_boot_sandbox_option_count();
433 size_t i;
434
435 int hidden_short_opt;
436 size_t si;
437
438 int c;
439
440 if (short_opts || long_opts)
441 return 1;
442
443 state->argc = argc;
444 state->argv = argv;
445
446 /* dynamically construct the arguments to the system getopt_long */
Simon Glassedd094e2021-02-06 09:57:33 -0700447 short_opts = os_malloc(sizeof(*short_opts) * num_options * 2 + 1);
448 long_opts = os_malloc(sizeof(*long_opts) * (num_options + 1));
Simon Glass8a3e0352012-02-15 15:51:16 -0800449 if (!short_opts || !long_opts)
450 return 1;
451
452 /*
453 * getopt_long requires "val" to be unique (since that is what the
454 * func returns), so generate unique values automatically for flags
455 * that don't have a short option. pick 0x100 as that is above the
456 * single byte range (where ASCII/ISO-XXXX-X charsets live).
457 */
458 hidden_short_opt = 0x100;
459 si = 0;
460 for (i = 0; i < num_options; ++i) {
461 long_opts[i].name = sb_opt[i]->flag;
462 long_opts[i].has_arg = sb_opt[i]->has_arg ?
463 required_argument : no_argument;
464 long_opts[i].flag = NULL;
465
466 if (sb_opt[i]->flag_short) {
467 short_opts[si++] = long_opts[i].val = sb_opt[i]->flag_short;
468 if (long_opts[i].has_arg == required_argument)
469 short_opts[si++] = ':';
470 } else
471 long_opts[i].val = sb_opt[i]->flag_short = hidden_short_opt++;
472 }
473 short_opts[si] = '\0';
474
475 /* we need to handle output ourselves since u-boot provides printf */
476 opterr = 0;
477
Simon Glass0a4eabb2020-02-03 07:36:04 -0700478 memset(&long_opts[num_options], '\0', sizeof(*long_opts));
Simon Glass8a3e0352012-02-15 15:51:16 -0800479 /*
480 * walk all of the options the user gave us on the command line,
481 * figure out what u-boot option structure they belong to (via
482 * the unique short val key), and call the appropriate callback.
483 */
484 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
485 for (i = 0; i < num_options; ++i) {
486 if (sb_opt[i]->flag_short == c) {
487 if (sb_opt[i]->callback(state, optarg)) {
488 state->parse_err = sb_opt[i]->flag;
489 return 0;
490 }
491 break;
492 }
493 }
494 if (i == num_options) {
495 /*
496 * store the faulting flag for later display. we have to
497 * store the flag itself as the getopt parsing itself is
498 * tricky: need to handle the following flags (assume all
499 * of the below are unknown):
500 * -a optopt='a' optind=<next>
501 * -abbbb optopt='a' optind=<this>
502 * -aaaaa optopt='a' optind=<this>
503 * --a optopt=0 optind=<this>
504 * as you can see, it is impossible to determine the exact
505 * faulting flag without doing the parsing ourselves, so
506 * we just report the specific flag that failed.
507 */
508 if (optopt) {
509 static char parse_err[3] = { '-', 0, '\0', };
510 parse_err[1] = optopt;
511 state->parse_err = parse_err;
512 } else
513 state->parse_err = argv[optind - 1];
514 break;
515 }
516 }
517
518 return 0;
519}
Simon Glassf1c45c82012-12-26 09:53:34 +0000520
521void os_dirent_free(struct os_dirent_node *node)
522{
523 struct os_dirent_node *next;
524
525 while (node) {
526 next = node->next;
Simon Glassedd094e2021-02-06 09:57:33 -0700527 os_free(node);
Simon Glassf1c45c82012-12-26 09:53:34 +0000528 node = next;
529 }
530}
531
532int os_dirent_ls(const char *dirname, struct os_dirent_node **headp)
533{
Stefan Brünsae71ede2016-10-01 20:41:42 +0200534 struct dirent *entry;
Simon Glassf1c45c82012-12-26 09:53:34 +0000535 struct os_dirent_node *head, *node, *next;
536 struct stat buf;
537 DIR *dir;
538 int ret;
539 char *fname;
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200540 char *old_fname;
Simon Glassf1c45c82012-12-26 09:53:34 +0000541 int len;
Stefan Brünsb2129902016-10-01 20:41:40 +0200542 int dirlen;
Simon Glassf1c45c82012-12-26 09:53:34 +0000543
544 *headp = NULL;
545 dir = opendir(dirname);
546 if (!dir)
547 return -1;
548
Stefan Brünsb2129902016-10-01 20:41:40 +0200549 /* Create a buffer upfront, with typically sufficient size */
550 dirlen = strlen(dirname) + 2;
551 len = dirlen + 256;
Simon Glassedd094e2021-02-06 09:57:33 -0700552 fname = os_malloc(len);
Simon Glassf1c45c82012-12-26 09:53:34 +0000553 if (!fname) {
554 ret = -ENOMEM;
555 goto done;
556 }
557
558 for (node = head = NULL;; node = next) {
Stefan Brünsae71ede2016-10-01 20:41:42 +0200559 errno = 0;
560 entry = readdir(dir);
561 if (!entry) {
562 ret = errno;
Simon Glassf1c45c82012-12-26 09:53:34 +0000563 break;
Stefan Brünsae71ede2016-10-01 20:41:42 +0200564 }
Simon Glassedd094e2021-02-06 09:57:33 -0700565 next = os_malloc(sizeof(*node) + strlen(entry->d_name) + 1);
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200566 if (!next) {
Simon Glassf1c45c82012-12-26 09:53:34 +0000567 os_dirent_free(head);
568 ret = -ENOMEM;
569 goto done;
570 }
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200571 if (dirlen + strlen(entry->d_name) > len) {
572 len = dirlen + strlen(entry->d_name);
573 old_fname = fname;
Simon Glassedd094e2021-02-06 09:57:33 -0700574 fname = os_realloc(fname, len);
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200575 if (!fname) {
Simon Glassedd094e2021-02-06 09:57:33 -0700576 os_free(old_fname);
577 os_free(next);
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200578 os_dirent_free(head);
579 ret = -ENOMEM;
580 goto done;
581 }
582 }
Stephen Warren9671c672014-06-11 10:26:23 -0600583 next->next = NULL;
Stefan Brünsae71ede2016-10-01 20:41:42 +0200584 strcpy(next->name, entry->d_name);
585 switch (entry->d_type) {
Simon Glassf1c45c82012-12-26 09:53:34 +0000586 case DT_REG:
587 next->type = OS_FILET_REG;
588 break;
589 case DT_DIR:
590 next->type = OS_FILET_DIR;
591 break;
592 case DT_LNK:
593 next->type = OS_FILET_LNK;
594 break;
Stefan Brünsb7ffa822016-10-04 21:46:35 +0200595 default:
596 next->type = OS_FILET_UNKNOWN;
Simon Glassf1c45c82012-12-26 09:53:34 +0000597 }
598 next->size = 0;
599 snprintf(fname, len, "%s/%s", dirname, next->name);
600 if (!stat(fname, &buf))
601 next->size = buf.st_size;
602 if (node)
603 node->next = next;
Stefan Brünsd4cb8882016-10-01 20:41:39 +0200604 else
605 head = next;
Simon Glassf1c45c82012-12-26 09:53:34 +0000606 }
607 *headp = head;
608
609done:
610 closedir(dir);
Simon Glassedd094e2021-02-06 09:57:33 -0700611 os_free(fname);
Simon Glassf1c45c82012-12-26 09:53:34 +0000612 return ret;
613}
614
615const char *os_dirent_typename[OS_FILET_COUNT] = {
616 " ",
617 "SYM",
618 "DIR",
619 "???",
620};
621
622const char *os_dirent_get_typename(enum os_dirent_t type)
623{
Tom Rinib6f605e2017-05-13 20:11:30 -0400624 if (type >= OS_FILET_REG && type < OS_FILET_COUNT)
Simon Glassf1c45c82012-12-26 09:53:34 +0000625 return os_dirent_typename[type];
626
627 return os_dirent_typename[OS_FILET_UNKNOWN];
628}
629
Heinrich Schuchardt011a1e02022-01-11 01:50:24 +0100630/*
631 * For compatibility reasons avoid loff_t here.
632 * U-Boot defines loff_t as long long.
633 * But /usr/include/linux/types.h may not define it at all.
634 * Alpine Linux being one example.
635 */
636int os_get_filesize(const char *fname, long long *size)
Simon Glassf1c45c82012-12-26 09:53:34 +0000637{
638 struct stat buf;
639 int ret;
640
641 ret = stat(fname, &buf);
642 if (ret)
643 return ret;
Suriyan Ramasami378da1032014-11-17 14:39:37 -0800644 *size = buf.st_size;
645 return 0;
Simon Glassf1c45c82012-12-26 09:53:34 +0000646}
Simon Glass3e9fd242013-11-10 10:27:01 -0700647
Simon Glass29d11432017-12-04 13:48:17 -0700648void os_putc(int ch)
649{
Simon Glassd56c6f42022-03-27 14:26:14 -0600650 os_write(1, &ch, 1);
Simon Glass29d11432017-12-04 13:48:17 -0700651}
652
653void os_puts(const char *str)
654{
655 while (*str)
656 os_putc(*str++);
657}
658
Simon Glass9dd10bf2013-11-10 10:27:03 -0700659int os_write_ram_buf(const char *fname)
660{
661 struct sandbox_state *state = state_get_current();
662 int fd, ret;
663
664 fd = open(fname, O_CREAT | O_WRONLY, 0777);
665 if (fd < 0)
666 return -ENOENT;
667 ret = write(fd, state->ram_buf, state->ram_size);
668 close(fd);
669 if (ret != state->ram_size)
670 return -EIO;
671
672 return 0;
673}
674
675int os_read_ram_buf(const char *fname)
676{
677 struct sandbox_state *state = state_get_current();
678 int fd, ret;
Heinrich Schuchardt011a1e02022-01-11 01:50:24 +0100679 long long size;
Simon Glass9dd10bf2013-11-10 10:27:03 -0700680
Suriyan Ramasami378da1032014-11-17 14:39:37 -0800681 ret = os_get_filesize(fname, &size);
682 if (ret < 0)
683 return ret;
Simon Glass9dd10bf2013-11-10 10:27:03 -0700684 if (size != state->ram_size)
685 return -ENOSPC;
686 fd = open(fname, O_RDONLY);
687 if (fd < 0)
688 return -ENOENT;
689
690 ret = read(fd, state->ram_buf, state->ram_size);
691 close(fd);
692 if (ret != state->ram_size)
693 return -EIO;
694
695 return 0;
696}
Simon Glass860b7d92014-02-27 13:26:15 -0700697
698static int make_exec(char *fname, const void *data, int size)
699{
700 int fd;
701
702 strcpy(fname, "/tmp/u-boot.jump.XXXXXX");
703 fd = mkstemp(fname);
704 if (fd < 0)
705 return -ENOENT;
706 if (write(fd, data, size) < 0)
707 return -EIO;
708 close(fd);
709 if (chmod(fname, 0777))
710 return -ENOEXEC;
711
712 return 0;
713}
714
Simon Glass7dafd022018-11-15 18:44:05 -0700715/**
716 * add_args() - Allocate a new argv with the given args
717 *
718 * This is used to create a new argv array with all the old arguments and some
719 * new ones that are passed in
720 *
721 * @argvp: Returns newly allocated args list
722 * @add_args: Arguments to add, each a string
723 * @count: Number of arguments in @add_args
Heinrich Schuchardt47b4c022022-01-19 18:05:50 +0100724 * Return: 0 if OK, -ENOMEM if out of memory
Simon Glass7dafd022018-11-15 18:44:05 -0700725 */
726static int add_args(char ***argvp, char *add_args[], int count)
Simon Glass860b7d92014-02-27 13:26:15 -0700727{
Simon Glass7465f002018-11-15 18:44:07 -0700728 char **argv, **ap;
Simon Glass860b7d92014-02-27 13:26:15 -0700729 int argc;
730
Simon Glass7465f002018-11-15 18:44:07 -0700731 for (argc = 0; (*argvp)[argc]; argc++)
Simon Glass860b7d92014-02-27 13:26:15 -0700732 ;
733
Simon Glassedd094e2021-02-06 09:57:33 -0700734 argv = os_malloc((argc + count + 1) * sizeof(char *));
Simon Glass860b7d92014-02-27 13:26:15 -0700735 if (!argv) {
736 printf("Out of memory for %d argv\n", count);
737 return -ENOMEM;
738 }
Simon Glass7465f002018-11-15 18:44:07 -0700739 for (ap = *argvp, argc = 0; *ap; ap++) {
740 char *arg = *ap;
741
742 /* Drop args that we don't want to propagate */
743 if (*arg == '-' && strlen(arg) == 2) {
744 switch (arg[1]) {
745 case 'j':
746 case 'm':
747 ap++;
748 continue;
749 }
750 } else if (!strcmp(arg, "--rm_memory")) {
Simon Glass7465f002018-11-15 18:44:07 -0700751 continue;
752 }
753 argv[argc++] = arg;
754 }
755
Simon Glass860b7d92014-02-27 13:26:15 -0700756 memcpy(argv + argc, add_args, count * sizeof(char *));
757 argv[argc + count] = NULL;
758
759 *argvp = argv;
760 return 0;
761}
762
Simon Glass7dafd022018-11-15 18:44:05 -0700763/**
764 * os_jump_to_file() - Jump to a new program
765 *
766 * This saves the memory buffer, sets up arguments to the new process, then
767 * execs it.
768 *
769 * @fname: Filename to exec
Heinrich Schuchardt47b4c022022-01-19 18:05:50 +0100770 * Return: does not return on success, any return value is an error
Simon Glass7dafd022018-11-15 18:44:05 -0700771 */
Simon Glassdafc5d72021-03-15 18:11:07 +1300772static int os_jump_to_file(const char *fname, bool delete_it)
Simon Glass860b7d92014-02-27 13:26:15 -0700773{
774 struct sandbox_state *state = state_get_current();
Simon Glass7dafd022018-11-15 18:44:05 -0700775 char mem_fname[30];
Simon Glass860b7d92014-02-27 13:26:15 -0700776 int fd, err;
Simon Glass7dafd022018-11-15 18:44:05 -0700777 char *extra_args[5];
Simon Glass860b7d92014-02-27 13:26:15 -0700778 char **argv = state->argv;
Simon Glass7465f002018-11-15 18:44:07 -0700779 int argc;
Simon Glass860b7d92014-02-27 13:26:15 -0700780#ifdef DEBUG
Simon Glass7dafd022018-11-15 18:44:05 -0700781 int i;
Simon Glass860b7d92014-02-27 13:26:15 -0700782#endif
783
Simon Glass860b7d92014-02-27 13:26:15 -0700784 strcpy(mem_fname, "/tmp/u-boot.mem.XXXXXX");
785 fd = mkstemp(mem_fname);
786 if (fd < 0)
787 return -ENOENT;
788 close(fd);
789 err = os_write_ram_buf(mem_fname);
790 if (err)
791 return err;
792
793 os_fd_restore();
794
Simon Glassdafc5d72021-03-15 18:11:07 +1300795 argc = 0;
796 if (delete_it) {
797 extra_args[argc++] = "-j";
798 extra_args[argc++] = (char *)fname;
799 }
800 extra_args[argc++] = "-m";
801 extra_args[argc++] = mem_fname;
Simon Glass7465f002018-11-15 18:44:07 -0700802 if (state->ram_buf_rm)
803 extra_args[argc++] = "--rm_memory";
804 err = add_args(&argv, extra_args, argc);
Simon Glass860b7d92014-02-27 13:26:15 -0700805 if (err)
806 return err;
Simon Glass7465f002018-11-15 18:44:07 -0700807 argv[0] = (char *)fname;
Simon Glass860b7d92014-02-27 13:26:15 -0700808
809#ifdef DEBUG
810 for (i = 0; argv[i]; i++)
811 printf("%d %s\n", i, argv[i]);
812#endif
813
814 if (state_uninit())
815 os_exit(2);
816
817 err = execv(fname, argv);
Simon Glassedd094e2021-02-06 09:57:33 -0700818 os_free(argv);
Simon Glasscca25522018-11-15 18:44:08 -0700819 if (err) {
820 perror("Unable to run image");
Simon Glass23eabbb2018-11-23 21:29:24 -0700821 printf("Image filename '%s'\n", fname);
Simon Glass860b7d92014-02-27 13:26:15 -0700822 return err;
Simon Glasscca25522018-11-15 18:44:08 -0700823 }
Simon Glass860b7d92014-02-27 13:26:15 -0700824
Simon Glassdafc5d72021-03-15 18:11:07 +1300825 if (delete_it)
826 return unlink(fname);
827
828 return -EFAULT;
Simon Glass860b7d92014-02-27 13:26:15 -0700829}
Simon Glass504548f2015-04-20 12:37:22 -0600830
Simon Glass7dafd022018-11-15 18:44:05 -0700831int os_jump_to_image(const void *dest, int size)
832{
833 char fname[30];
834 int err;
835
836 err = make_exec(fname, dest, size);
837 if (err)
838 return err;
839
Simon Glassdafc5d72021-03-15 18:11:07 +1300840 return os_jump_to_file(fname, true);
Simon Glass7dafd022018-11-15 18:44:05 -0700841}
842
Simon Glass1cd06002021-07-05 16:32:45 -0600843int os_find_u_boot(char *fname, int maxlen, bool use_img,
844 const char *cur_prefix, const char *next_prefix)
Simon Glass2c931ba2016-07-04 11:57:45 -0600845{
846 struct sandbox_state *state = state_get_current();
847 const char *progname = state->argv[0];
848 int len = strlen(progname);
Simon Glass1cd06002021-07-05 16:32:45 -0600849 char subdir[10];
850 char *suffix;
Simon Glass2c931ba2016-07-04 11:57:45 -0600851 char *p;
852 int fd;
853
854 if (len >= maxlen || len < 4)
855 return -ENOSPC;
856
Simon Glass2c931ba2016-07-04 11:57:45 -0600857 strcpy(fname, progname);
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600858 suffix = fname + len - 4;
859
Simon Glass1cd06002021-07-05 16:32:45 -0600860 /* Change the existing suffix to the new one */
861 if (*suffix != '-')
862 return -EINVAL;
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600863
Simon Glass1cd06002021-07-05 16:32:45 -0600864 if (*next_prefix)
865 strcpy(suffix + 1, next_prefix); /* e.g. "-tpl" to "-spl" */
866 else
867 *suffix = '\0'; /* e.g. "-spl" to "" */
868 fd = os_open(fname, O_RDONLY);
869 if (fd >= 0) {
870 close(fd);
871 return 0;
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600872 }
873
Simon Glass1cd06002021-07-05 16:32:45 -0600874 /*
875 * We didn't find it, so try looking for 'u-boot-xxx' in the xxx/
876 * directory. Replace the old dirname with the new one.
877 */
878 snprintf(subdir, sizeof(subdir), "/%s/", cur_prefix);
879 p = strstr(fname, subdir);
Simon Glass2c931ba2016-07-04 11:57:45 -0600880 if (p) {
Simon Glass1cd06002021-07-05 16:32:45 -0600881 if (*next_prefix)
882 /* e.g. ".../tpl/u-boot-spl" to "../spl/u-boot-spl" */
883 memcpy(p + 1, next_prefix, strlen(next_prefix));
884 else
885 /* e.g. ".../spl/u-boot" to ".../u-boot" */
886 strcpy(p, p + 1 + strlen(cur_prefix));
Simon Glassb90e4872021-03-07 17:35:13 -0700887 if (use_img)
888 strcat(p, ".img");
Simon Glass1cd06002021-07-05 16:32:45 -0600889
Simon Glass2c931ba2016-07-04 11:57:45 -0600890 fd = os_open(fname, O_RDONLY);
891 if (fd >= 0) {
892 close(fd);
893 return 0;
894 }
895 }
896
897 return -ENOENT;
898}
899
900int os_spl_to_uboot(const char *fname)
901{
Patrick Delaunay6daf9052020-11-20 09:48:33 +0100902 struct sandbox_state *state = state_get_current();
903
Patrick Delaunay6daf9052020-11-20 09:48:33 +0100904 /* U-Boot will delete ram buffer after read: "--rm_memory"*/
905 state->ram_buf_rm = true;
Simon Glassdafc5d72021-03-15 18:11:07 +1300906
907 return os_jump_to_file(fname, false);
Simon Glass2c931ba2016-07-04 11:57:45 -0600908}
909
Heinrich Schuchardtc0d1a002020-12-30 18:07:48 +0100910long os_get_time_offset(void)
911{
912 const char *offset;
913
914 offset = getenv(ENV_TIME_OFFSET);
915 if (offset)
916 return strtol(offset, NULL, 0);
917 return 0;
918}
919
920void os_set_time_offset(long offset)
921{
922 char buf[21];
923 int ret;
924
925 snprintf(buf, sizeof(buf), "%ld", offset);
926 ret = setenv(ENV_TIME_OFFSET, buf, true);
927 if (ret)
928 printf("Could not set environment variable %s\n",
929 ENV_TIME_OFFSET);
930}
931
Simon Glass504548f2015-04-20 12:37:22 -0600932void os_localtime(struct rtc_time *rt)
933{
934 time_t t = time(NULL);
935 struct tm *tm;
936
937 tm = localtime(&t);
938 rt->tm_sec = tm->tm_sec;
939 rt->tm_min = tm->tm_min;
940 rt->tm_hour = tm->tm_hour;
941 rt->tm_mday = tm->tm_mday;
942 rt->tm_mon = tm->tm_mon + 1;
943 rt->tm_year = tm->tm_year + 1900;
944 rt->tm_wday = tm->tm_wday;
945 rt->tm_yday = tm->tm_yday;
946 rt->tm_isdst = tm->tm_isdst;
947}
Simon Glass5dccd152018-05-16 09:42:22 -0600948
Simon Glassb7255ef2018-09-15 00:50:55 -0600949void os_abort(void)
950{
951 abort();
952}
Simon Glass4e766c22018-10-01 21:12:32 -0600953
954int os_mprotect_allow(void *start, size_t len)
955{
956 int page_size = getpagesize();
957
958 /* Move start to the start of a page, len to the end */
959 start = (void *)(((ulong)start) & ~(page_size - 1));
960 len = (len + page_size * 2) & ~(page_size - 1);
961
962 return mprotect(start, len, PROT_READ | PROT_WRITE);
963}
Simon Glass752707a2019-04-08 13:20:41 -0600964
965void *os_find_text_base(void)
966{
967 char line[500];
968 void *base = NULL;
969 int len;
970 int fd;
971
972 /*
973 * This code assumes that the first line of /proc/self/maps holds
974 * information about the text, for example:
975 *
976 * 5622d9907000-5622d9a55000 r-xp 00000000 08:01 15067168 u-boot
977 *
978 * The first hex value is assumed to be the address.
979 *
980 * This is tested in Linux 4.15.
981 */
982 fd = open("/proc/self/maps", O_RDONLY);
983 if (fd == -1)
984 return NULL;
985 len = read(fd, line, sizeof(line));
986 if (len > 0) {
987 char *end = memchr(line, '-', len);
988
989 if (end) {
Heinrich Schuchardt05a16842019-10-26 23:17:44 +0200990 uintptr_t addr;
Simon Glass752707a2019-04-08 13:20:41 -0600991
992 *end = '\0';
Heinrich Schuchardt05a16842019-10-26 23:17:44 +0200993 if (sscanf(line, "%zx", &addr) == 1)
Simon Glass752707a2019-04-08 13:20:41 -0600994 base = (void *)addr;
995 }
996 }
997 close(fd);
998
999 return base;
1000}
Heinrich Schuchardt1c678442020-10-27 20:29:25 +01001001
1002void os_relaunch(char *argv[])
1003{
1004 execv(argv[0], argv);
1005 os_exit(1);
1006}
Andrew Scullca5d1372022-05-30 10:00:10 +00001007
Andrew Scull2b40f802022-05-30 10:00:11 +00001008
1009#ifdef CONFIG_FUZZ
1010static void *fuzzer_thread(void * ptr)
1011{
1012 char cmd[64];
1013 char *argv[5] = {"./u-boot", "-T", "-c", cmd, NULL};
1014 const char *fuzz_test;
1015
1016 /* Find which test to run from an environment variable. */
1017 fuzz_test = getenv("UBOOT_SB_FUZZ_TEST");
1018 if (!fuzz_test)
1019 os_abort();
1020
1021 snprintf(cmd, sizeof(cmd), "fuzz %s", fuzz_test);
1022
1023 sandbox_main(4, argv);
1024 os_abort();
1025 return NULL;
1026}
1027
1028static bool fuzzer_initialized = false;
1029static pthread_mutex_t fuzzer_mutex = PTHREAD_MUTEX_INITIALIZER;
1030static pthread_cond_t fuzzer_cond = PTHREAD_COND_INITIALIZER;
1031static const uint8_t *fuzzer_data;
1032static size_t fuzzer_size;
1033
1034int sandbox_fuzzing_engine_get_input(const uint8_t **data, size_t *size)
1035{
1036 if (!fuzzer_initialized)
1037 return -ENOSYS;
1038
1039 /* Tell the main thread we need new inputs then wait for them. */
1040 pthread_mutex_lock(&fuzzer_mutex);
1041 pthread_cond_signal(&fuzzer_cond);
1042 pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1043 *data = fuzzer_data;
1044 *size = fuzzer_size;
1045 pthread_mutex_unlock(&fuzzer_mutex);
1046 return 0;
1047}
1048
1049int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
1050{
1051 static pthread_t tid;
1052
1053 pthread_mutex_lock(&fuzzer_mutex);
1054
1055 /* Initialize the sandbox on another thread. */
1056 if (!fuzzer_initialized) {
1057 fuzzer_initialized = true;
1058 if (pthread_create(&tid, NULL, fuzzer_thread, NULL))
1059 os_abort();
1060 pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1061 }
1062
1063 /* Hand over the input. */
1064 fuzzer_data = data;
1065 fuzzer_size = size;
1066 pthread_cond_signal(&fuzzer_cond);
1067
1068 /* Wait for the inputs to be finished with. */
1069 pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1070 pthread_mutex_unlock(&fuzzer_mutex);
1071
1072 return 0;
1073}
1074#else
Andrew Scullca5d1372022-05-30 10:00:10 +00001075int main(int argc, char *argv[])
1076{
1077 return sandbox_main(argc, argv);
1078}
Andrew Scull2b40f802022-05-30 10:00:11 +00001079#endif