blob: 40ebe322ae0f5a2361e5ef775a2069d9a926c8e3 [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>
Simon Glass8a3e0352012-02-15 15:51:16 -080011#include <getopt.h>
Simon Glass5dccd152018-05-16 09:42:22 -060012#include <setjmp.h>
Rasmus Villemoes2b72ad22020-02-14 10:58:37 +000013#include <signal.h>
Simon Glassf1c45c82012-12-26 09:53:34 +000014#include <stdio.h>
Simon Glassfb4b4e82013-05-19 16:45:35 -070015#include <stdint.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000016#include <stdlib.h>
Simon Glassf1c45c82012-12-26 09:53:34 +000017#include <string.h>
Mike Frysingera5baaee2011-10-26 00:21:29 +000018#include <termios.h>
Matthias Weisser0d3dd142011-11-29 12:16:40 +010019#include <time.h>
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +010020#include <ucontext.h>
Simon Glasse8015a62012-01-10 15:54:05 -080021#include <unistd.h>
Matthias Weisserb5f7b472011-11-05 11:40:34 +010022#include <sys/mman.h>
Simon Glasse8015a62012-01-10 15:54:05 -080023#include <sys/stat.h>
Simon Glass17064c02012-01-10 15:54:06 -080024#include <sys/time.h>
Simon Glasse8015a62012-01-10 15:54:05 -080025#include <sys/types.h>
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +010026#include <linux/compiler_attributes.h>
Matthias Weisser0d3dd142011-11-29 12:16:40 +010027#include <linux/types.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000028
Simon Glass8a3e0352012-02-15 15:51:16 -080029#include <asm/getopt.h>
30#include <asm/sections.h>
31#include <asm/state.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000032#include <os.h>
Simon Glass504548f2015-04-20 12:37:22 -060033#include <rtc_def.h>
Simon Glasscd0684f2011-10-03 19:26:44 +000034
Heinrich Schuchardtc0d1a002020-12-30 18:07:48 +010035/* Environment variable for time offset */
36#define ENV_TIME_OFFSET "UBOOT_SB_TIME_OFFSET"
37
Simon Glasscd0684f2011-10-03 19:26:44 +000038/* Operating System Interface */
39
Simon Glass1e6594c2013-11-10 10:26:57 -070040struct os_mem_hdr {
41 size_t length; /* number of bytes in the block */
42};
43
Simon Glasscd0684f2011-10-03 19:26:44 +000044ssize_t os_read(int fd, void *buf, size_t count)
45{
46 return read(fd, buf, count);
47}
48
49ssize_t os_write(int fd, const void *buf, size_t count)
50{
51 return write(fd, buf, count);
52}
53
Mike Frysinger60addac2011-10-25 13:02:58 +020054off_t os_lseek(int fd, off_t offset, int whence)
55{
56 if (whence == OS_SEEK_SET)
57 whence = SEEK_SET;
58 else if (whence == OS_SEEK_CUR)
59 whence = SEEK_CUR;
60 else if (whence == OS_SEEK_END)
61 whence = SEEK_END;
62 else
63 os_exit(1);
64 return lseek(fd, offset, whence);
65}
66
Simon Glass3196d752012-02-20 23:56:58 -050067int os_open(const char *pathname, int os_flags)
Simon Glasscd0684f2011-10-03 19:26:44 +000068{
Simon Glass3196d752012-02-20 23:56:58 -050069 int flags;
70
71 switch (os_flags & OS_O_MASK) {
72 case OS_O_RDONLY:
73 default:
74 flags = O_RDONLY;
75 break;
76
77 case OS_O_WRONLY:
78 flags = O_WRONLY;
79 break;
80
81 case OS_O_RDWR:
82 flags = O_RDWR;
83 break;
84 }
85
86 if (os_flags & OS_O_CREAT)
87 flags |= O_CREAT;
Simon Glassce55a112018-10-01 11:55:07 -060088 if (os_flags & OS_O_TRUNC)
89 flags |= O_TRUNC;
Heinrich Schuchardtfc96df62020-10-27 20:29:24 +010090 /*
91 * During a cold reset execv() is used to relaunch the U-Boot binary.
92 * We must ensure that all files are closed in this case.
93 */
94 flags |= O_CLOEXEC;
Simon Glass3196d752012-02-20 23:56:58 -050095
96 return open(pathname, flags, 0777);
Simon Glasscd0684f2011-10-03 19:26:44 +000097}
98
99int os_close(int fd)
100{
Heinrich Schuchardt69db2ee2020-10-27 20:29:21 +0100101 /* Do not close the console input */
102 if (fd)
103 return close(fd);
104 return -1;
Simon Glasscd0684f2011-10-03 19:26:44 +0000105}
106
Stephen Warrencd5edba2014-03-01 22:18:00 -0700107int os_unlink(const char *pathname)
108{
109 return unlink(pathname);
110}
111
Simon Glasscd0684f2011-10-03 19:26:44 +0000112void os_exit(int exit_code)
113{
114 exit(exit_code);
115}
Mike Frysingera5baaee2011-10-26 00:21:29 +0000116
Simon Glass8d176d82018-11-06 15:21:25 -0700117int os_write_file(const char *fname, const void *buf, int size)
Simon Glasscbfa8452018-10-01 11:55:08 -0600118{
Simon Glasscbfa8452018-10-01 11:55:08 -0600119 int fd;
120
121 fd = os_open(fname, OS_O_WRONLY | OS_O_CREAT | OS_O_TRUNC);
122 if (fd < 0) {
123 printf("Cannot open file '%s'\n", fname);
124 return -EIO;
125 }
126 if (os_write(fd, buf, size) != size) {
127 printf("Cannot write to file '%s'\n", fname);
Simon Glass8d176d82018-11-06 15:21:25 -0700128 os_close(fd);
Simon Glasscbfa8452018-10-01 11:55:08 -0600129 return -EIO;
130 }
131 os_close(fd);
Simon Glasscbfa8452018-10-01 11:55:08 -0600132
133 return 0;
134}
135
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600136int os_filesize(int fd)
137{
138 off_t size;
139
140 size = os_lseek(fd, 0, OS_SEEK_END);
141 if (size < 0)
142 return -errno;
143 if (os_lseek(fd, 0, OS_SEEK_SET) < 0)
144 return -errno;
145
146 return size;
147}
148
Simon Glass8d176d82018-11-06 15:21:25 -0700149int os_read_file(const char *fname, void **bufp, int *sizep)
150{
151 off_t size;
152 int ret = -EIO;
153 int fd;
154
155 fd = os_open(fname, OS_O_RDONLY);
156 if (fd < 0) {
157 printf("Cannot open file '%s'\n", fname);
158 goto err;
159 }
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600160 size = os_filesize(fd);
Simon Glass8d176d82018-11-06 15:21:25 -0700161 if (size < 0) {
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600162 printf("Cannot get file size of '%s'\n", fname);
Simon Glass8d176d82018-11-06 15:21:25 -0700163 goto err;
164 }
Simon Glass7b9cf84f2021-08-18 21:40:30 -0600165
Simon Glassedd094e2021-02-06 09:57:33 -0700166 *bufp = os_malloc(size);
Simon Glass8d176d82018-11-06 15:21:25 -0700167 if (!*bufp) {
168 printf("Not enough memory to read file '%s'\n", fname);
169 ret = -ENOMEM;
170 goto err;
171 }
172 if (os_read(fd, *bufp, size) != size) {
173 printf("Cannot read from file '%s'\n", fname);
174 goto err;
175 }
176 os_close(fd);
177 *sizep = size;
178
179 return 0;
180err:
181 os_close(fd);
182 return ret;
183}
184
Simon Glasse4c25c82021-08-18 21:40:31 -0600185int os_map_file(const char *pathname, int os_flags, void **bufp, int *sizep)
186{
187 void *ptr;
188 int size;
189 int ifd;
190
191 ifd = os_open(pathname, os_flags);
192 if (ifd < 0) {
193 printf("Cannot open file '%s'\n", pathname);
194 return -EIO;
195 }
196 size = os_filesize(ifd);
197 if (size < 0) {
198 printf("Cannot get file size of '%s'\n", pathname);
199 return -EIO;
200 }
201
202 ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, ifd, 0);
203 if (ptr == MAP_FAILED) {
204 printf("Can't map file '%s': %s\n", pathname, strerror(errno));
205 return -EPERM;
206 }
207
208 *bufp = ptr;
209 *sizep = size;
210
211 return 0;
212}
213
Simon Glass5c1fd582021-10-23 17:25:58 -0600214int os_unmap(void *buf, int size)
215{
216 if (munmap(buf, size)) {
217 printf("Can't unmap %p %x\n", buf, size);
218 return -EIO;
219 }
220
221 return 0;
222}
223
Mike Frysingera5baaee2011-10-26 00:21:29 +0000224/* Restore tty state when we exit */
225static struct termios orig_term;
Simon Glass678ef472014-02-27 13:26:22 -0700226static bool term_setup;
Simon Glassae50ec72018-10-01 11:55:20 -0600227static bool term_nonblock;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000228
Simon Glass9c3b7d62015-05-10 21:07:27 -0600229void os_fd_restore(void)
Mike Frysingera5baaee2011-10-26 00:21:29 +0000230{
Simon Glass9c3b7d62015-05-10 21:07:27 -0600231 if (term_setup) {
Simon Glassae50ec72018-10-01 11:55:20 -0600232 int flags;
233
Simon Glass678ef472014-02-27 13:26:22 -0700234 tcsetattr(0, TCSANOW, &orig_term);
Simon Glassae50ec72018-10-01 11:55:20 -0600235 if (term_nonblock) {
236 flags = fcntl(0, F_GETFL, 0);
237 fcntl(0, F_SETFL, flags & ~O_NONBLOCK);
238 }
Simon Glass9c3b7d62015-05-10 21:07:27 -0600239 term_setup = false;
240 }
Mike Frysingera5baaee2011-10-26 00:21:29 +0000241}
242
Rasmus Villemoes2b72ad22020-02-14 10:58:37 +0000243static void os_sigint_handler(int sig)
244{
245 os_fd_restore();
246 signal(SIGINT, SIG_DFL);
247 raise(SIGINT);
248}
249
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +0100250static void os_signal_handler(int sig, siginfo_t *info, void *con)
251{
252 ucontext_t __maybe_unused *context = con;
253 unsigned long pc;
254
255#if defined(__x86_64__)
256 pc = context->uc_mcontext.gregs[REG_RIP];
257#elif defined(__aarch64__)
258 pc = context->uc_mcontext.pc;
259#elif defined(__riscv)
260 pc = context->uc_mcontext.__gregs[REG_PC];
261#else
262 const char msg[] =
263 "\nUnsupported architecture, cannot read program counter\n";
264
265 os_write(1, msg, sizeof(msg));
266 pc = 0;
267#endif
268
269 os_signal_action(sig, pc);
270}
271
272int os_setup_signal_handlers(void)
273{
274 struct sigaction act;
275
276 act.sa_sigaction = os_signal_handler;
277 sigemptyset(&act.sa_mask);
Heinrich Schuchardtd3741bc2021-07-05 19:43:00 +0200278 act.sa_flags = SA_SIGINFO;
Heinrich Schuchardt28eb5092020-11-12 00:29:56 +0100279 if (sigaction(SIGILL, &act, NULL) ||
280 sigaction(SIGBUS, &act, NULL) ||
281 sigaction(SIGSEGV, &act, NULL))
282 return -1;
283 return 0;
284}
285
Mike Frysingera5baaee2011-10-26 00:21:29 +0000286/* Put tty into raw mode so <tab> and <ctrl+c> work */
Simon Glass678ef472014-02-27 13:26:22 -0700287void os_tty_raw(int fd, bool allow_sigs)
Mike Frysingera5baaee2011-10-26 00:21:29 +0000288{
Mike Frysingera5baaee2011-10-26 00:21:29 +0000289 struct termios term;
Simon Glassae50ec72018-10-01 11:55:20 -0600290 int flags;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000291
Simon Glass678ef472014-02-27 13:26:22 -0700292 if (term_setup)
Mike Frysingera5baaee2011-10-26 00:21:29 +0000293 return;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000294
295 /* If not a tty, don't complain */
296 if (tcgetattr(fd, &orig_term))
297 return;
298
299 term = orig_term;
300 term.c_iflag = IGNBRK | IGNPAR;
301 term.c_oflag = OPOST | ONLCR;
302 term.c_cflag = CS8 | CREAD | CLOCAL;
Simon Glass678ef472014-02-27 13:26:22 -0700303 term.c_lflag = allow_sigs ? ISIG : 0;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000304 if (tcsetattr(fd, TCSANOW, &term))
305 return;
306
Simon Glassae50ec72018-10-01 11:55:20 -0600307 flags = fcntl(fd, F_GETFL, 0);
308 if (!(flags & O_NONBLOCK)) {
309 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK))
310 return;
311 term_nonblock = true;
312 }
313
Simon Glass9c3b7d62015-05-10 21:07:27 -0600314 term_setup = true;
Mike Frysingera5baaee2011-10-26 00:21:29 +0000315 atexit(os_fd_restore);
Rasmus Villemoes2b72ad22020-02-14 10:58:37 +0000316 signal(SIGINT, os_sigint_handler);
Mike Frysingera5baaee2011-10-26 00:21:29 +0000317}
Matthias Weisserb5f7b472011-11-05 11:40:34 +0100318
Simon Glass4c902fa2021-02-06 09:57:32 -0700319/*
320 * Provide our own malloc so we don't use space in the sandbox ram_buf for
321 * allocations that are internal to sandbox, or need to be done before U-Boot's
322 * malloc() is ready.
323 */
Matthias Weisserb5f7b472011-11-05 11:40:34 +0100324void *os_malloc(size_t length)
325{
Simon Glassbe005d82018-09-15 00:50:54 -0600326 int page_size = getpagesize();
Simon Glassfc2dde82019-04-08 13:20:42 -0600327 struct os_mem_hdr *hdr;
Simon Glass1e6594c2013-11-10 10:26:57 -0700328
Simon Glass4c902fa2021-02-06 09:57:32 -0700329 if (!length)
330 return NULL;
Simon Glass57ba9422018-06-17 08:57:43 -0600331 /*
332 * Use an address that is hopefully available to us so that pointers
333 * to this memory are fairly obvious. If we end up with a different
334 * address, that's fine too.
335 */
336 hdr = mmap((void *)0x10000000, length + page_size,
Alexander Graf934a5452018-06-22 14:44:13 +0200337 PROT_READ | PROT_WRITE | PROT_EXEC,
338 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
Simon Glass1e6594c2013-11-10 10:26:57 -0700339 if (hdr == MAP_FAILED)
340 return NULL;
341 hdr->length = length;
342
Simon Glassbe005d82018-09-15 00:50:54 -0600343 return (void *)hdr + page_size;
Simon Glass1e6594c2013-11-10 10:26:57 -0700344}
345
Masahiro Yamadaee957282014-01-15 13:06:41 +0900346void os_free(void *ptr)
Simon Glass1e6594c2013-11-10 10:26:57 -0700347{
Simon Glassfc2dde82019-04-08 13:20:42 -0600348 int page_size = getpagesize();
349 struct os_mem_hdr *hdr;
Simon Glass1e6594c2013-11-10 10:26:57 -0700350
Simon Glassfc2dde82019-04-08 13:20:42 -0600351 if (ptr) {
352 hdr = ptr - page_size;
353 munmap(hdr, hdr->length + page_size);
354 }
Simon Glass4c902fa2021-02-06 09:57:32 -0700355}
356
357/* These macros are from kernel.h but not accessible in this file */
358#define ALIGN(x, a) __ALIGN_MASK((x), (typeof(x))(a) - 1)
359#define __ALIGN_MASK(x, mask) (((x) + (mask)) & ~(mask))
360
361/*
362 * Provide our own malloc so we don't use space in the sandbox ram_buf for
363 * allocations that are internal to sandbox, or need to be done before U-Boot's
364 * malloc() is ready.
365 */
366void *os_realloc(void *ptr, size_t length)
367{
368 int page_size = getpagesize();
369 struct os_mem_hdr *hdr;
370 void *new_ptr;
371
372 /* Reallocating a NULL pointer is just an alloc */
373 if (!ptr)
374 return os_malloc(length);
375
376 /* Changing a length to 0 is just a free */
377 if (length) {
378 os_free(ptr);
379 return NULL;
380 }
381
382 /*
383 * If the new size is the same number of pages as the old, nothing to
384 * do. There isn't much point in shrinking things
385 */
386 hdr = ptr - page_size;
387 if (ALIGN(length, page_size) <= ALIGN(hdr->length, page_size))
388 return ptr;
389
390 /* We have to grow it, so allocate something new */
391 new_ptr = os_malloc(length);
392 memcpy(new_ptr, ptr, hdr->length);
393 os_free(ptr);
394
395 return new_ptr;
Simon Glass1e6594c2013-11-10 10:26:57 -0700396}
397
Matthias Weisser0d3dd142011-11-29 12:16:40 +0100398void os_usleep(unsigned long usec)
399{
400 usleep(usec);
401}
402
Simon Glassfb4b4e82013-05-19 16:45:35 -0700403uint64_t __attribute__((no_instrument_function)) os_get_nsec(void)
Matthias Weisser0d3dd142011-11-29 12:16:40 +0100404{
405#if defined(CLOCK_MONOTONIC) && defined(_POSIX_MONOTONIC_CLOCK)
406 struct timespec tp;
407 if (EINVAL == clock_gettime(CLOCK_MONOTONIC, &tp)) {
408 struct timeval tv;
409
410 gettimeofday(&tv, NULL);
411 tp.tv_sec = tv.tv_sec;
412 tp.tv_nsec = tv.tv_usec * 1000;
413 }
414 return tp.tv_sec * 1000000000ULL + tp.tv_nsec;
415#else
416 struct timeval tv;
417 gettimeofday(&tv, NULL);
418 return tv.tv_sec * 1000000000ULL + tv.tv_usec * 1000;
419#endif
420}
Simon Glass8a3e0352012-02-15 15:51:16 -0800421
422static char *short_opts;
423static struct option *long_opts;
424
425int os_parse_args(struct sandbox_state *state, int argc, char *argv[])
426{
Marek Behún184c4af2021-05-20 13:24:06 +0200427 struct sandbox_cmdline_option **sb_opt =
428 __u_boot_sandbox_option_start();
Simon Glass8a3e0352012-02-15 15:51:16 -0800429 size_t num_options = __u_boot_sandbox_option_count();
430 size_t i;
431
432 int hidden_short_opt;
433 size_t si;
434
435 int c;
436
437 if (short_opts || long_opts)
438 return 1;
439
440 state->argc = argc;
441 state->argv = argv;
442
443 /* dynamically construct the arguments to the system getopt_long */
Simon Glassedd094e2021-02-06 09:57:33 -0700444 short_opts = os_malloc(sizeof(*short_opts) * num_options * 2 + 1);
445 long_opts = os_malloc(sizeof(*long_opts) * (num_options + 1));
Simon Glass8a3e0352012-02-15 15:51:16 -0800446 if (!short_opts || !long_opts)
447 return 1;
448
449 /*
450 * getopt_long requires "val" to be unique (since that is what the
451 * func returns), so generate unique values automatically for flags
452 * that don't have a short option. pick 0x100 as that is above the
453 * single byte range (where ASCII/ISO-XXXX-X charsets live).
454 */
455 hidden_short_opt = 0x100;
456 si = 0;
457 for (i = 0; i < num_options; ++i) {
458 long_opts[i].name = sb_opt[i]->flag;
459 long_opts[i].has_arg = sb_opt[i]->has_arg ?
460 required_argument : no_argument;
461 long_opts[i].flag = NULL;
462
463 if (sb_opt[i]->flag_short) {
464 short_opts[si++] = long_opts[i].val = sb_opt[i]->flag_short;
465 if (long_opts[i].has_arg == required_argument)
466 short_opts[si++] = ':';
467 } else
468 long_opts[i].val = sb_opt[i]->flag_short = hidden_short_opt++;
469 }
470 short_opts[si] = '\0';
471
472 /* we need to handle output ourselves since u-boot provides printf */
473 opterr = 0;
474
Simon Glass0a4eabb2020-02-03 07:36:04 -0700475 memset(&long_opts[num_options], '\0', sizeof(*long_opts));
Simon Glass8a3e0352012-02-15 15:51:16 -0800476 /*
477 * walk all of the options the user gave us on the command line,
478 * figure out what u-boot option structure they belong to (via
479 * the unique short val key), and call the appropriate callback.
480 */
481 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
482 for (i = 0; i < num_options; ++i) {
483 if (sb_opt[i]->flag_short == c) {
484 if (sb_opt[i]->callback(state, optarg)) {
485 state->parse_err = sb_opt[i]->flag;
486 return 0;
487 }
488 break;
489 }
490 }
491 if (i == num_options) {
492 /*
493 * store the faulting flag for later display. we have to
494 * store the flag itself as the getopt parsing itself is
495 * tricky: need to handle the following flags (assume all
496 * of the below are unknown):
497 * -a optopt='a' optind=<next>
498 * -abbbb optopt='a' optind=<this>
499 * -aaaaa optopt='a' optind=<this>
500 * --a optopt=0 optind=<this>
501 * as you can see, it is impossible to determine the exact
502 * faulting flag without doing the parsing ourselves, so
503 * we just report the specific flag that failed.
504 */
505 if (optopt) {
506 static char parse_err[3] = { '-', 0, '\0', };
507 parse_err[1] = optopt;
508 state->parse_err = parse_err;
509 } else
510 state->parse_err = argv[optind - 1];
511 break;
512 }
513 }
514
515 return 0;
516}
Simon Glassf1c45c82012-12-26 09:53:34 +0000517
518void os_dirent_free(struct os_dirent_node *node)
519{
520 struct os_dirent_node *next;
521
522 while (node) {
523 next = node->next;
Simon Glassedd094e2021-02-06 09:57:33 -0700524 os_free(node);
Simon Glassf1c45c82012-12-26 09:53:34 +0000525 node = next;
526 }
527}
528
529int os_dirent_ls(const char *dirname, struct os_dirent_node **headp)
530{
Stefan Brünsae71ede2016-10-01 20:41:42 +0200531 struct dirent *entry;
Simon Glassf1c45c82012-12-26 09:53:34 +0000532 struct os_dirent_node *head, *node, *next;
533 struct stat buf;
534 DIR *dir;
535 int ret;
536 char *fname;
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200537 char *old_fname;
Simon Glassf1c45c82012-12-26 09:53:34 +0000538 int len;
Stefan Brünsb2129902016-10-01 20:41:40 +0200539 int dirlen;
Simon Glassf1c45c82012-12-26 09:53:34 +0000540
541 *headp = NULL;
542 dir = opendir(dirname);
543 if (!dir)
544 return -1;
545
Stefan Brünsb2129902016-10-01 20:41:40 +0200546 /* Create a buffer upfront, with typically sufficient size */
547 dirlen = strlen(dirname) + 2;
548 len = dirlen + 256;
Simon Glassedd094e2021-02-06 09:57:33 -0700549 fname = os_malloc(len);
Simon Glassf1c45c82012-12-26 09:53:34 +0000550 if (!fname) {
551 ret = -ENOMEM;
552 goto done;
553 }
554
555 for (node = head = NULL;; node = next) {
Stefan Brünsae71ede2016-10-01 20:41:42 +0200556 errno = 0;
557 entry = readdir(dir);
558 if (!entry) {
559 ret = errno;
Simon Glassf1c45c82012-12-26 09:53:34 +0000560 break;
Stefan Brünsae71ede2016-10-01 20:41:42 +0200561 }
Simon Glassedd094e2021-02-06 09:57:33 -0700562 next = os_malloc(sizeof(*node) + strlen(entry->d_name) + 1);
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200563 if (!next) {
Simon Glassf1c45c82012-12-26 09:53:34 +0000564 os_dirent_free(head);
565 ret = -ENOMEM;
566 goto done;
567 }
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200568 if (dirlen + strlen(entry->d_name) > len) {
569 len = dirlen + strlen(entry->d_name);
570 old_fname = fname;
Simon Glassedd094e2021-02-06 09:57:33 -0700571 fname = os_realloc(fname, len);
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200572 if (!fname) {
Simon Glassedd094e2021-02-06 09:57:33 -0700573 os_free(old_fname);
574 os_free(next);
Heinrich Schuchardtf53b5ea2017-09-21 12:56:07 +0200575 os_dirent_free(head);
576 ret = -ENOMEM;
577 goto done;
578 }
579 }
Stephen Warren9671c672014-06-11 10:26:23 -0600580 next->next = NULL;
Stefan Brünsae71ede2016-10-01 20:41:42 +0200581 strcpy(next->name, entry->d_name);
582 switch (entry->d_type) {
Simon Glassf1c45c82012-12-26 09:53:34 +0000583 case DT_REG:
584 next->type = OS_FILET_REG;
585 break;
586 case DT_DIR:
587 next->type = OS_FILET_DIR;
588 break;
589 case DT_LNK:
590 next->type = OS_FILET_LNK;
591 break;
Stefan Brünsb7ffa822016-10-04 21:46:35 +0200592 default:
593 next->type = OS_FILET_UNKNOWN;
Simon Glassf1c45c82012-12-26 09:53:34 +0000594 }
595 next->size = 0;
596 snprintf(fname, len, "%s/%s", dirname, next->name);
597 if (!stat(fname, &buf))
598 next->size = buf.st_size;
599 if (node)
600 node->next = next;
Stefan Brünsd4cb8882016-10-01 20:41:39 +0200601 else
602 head = next;
Simon Glassf1c45c82012-12-26 09:53:34 +0000603 }
604 *headp = head;
605
606done:
607 closedir(dir);
Simon Glassedd094e2021-02-06 09:57:33 -0700608 os_free(fname);
Simon Glassf1c45c82012-12-26 09:53:34 +0000609 return ret;
610}
611
612const char *os_dirent_typename[OS_FILET_COUNT] = {
613 " ",
614 "SYM",
615 "DIR",
616 "???",
617};
618
619const char *os_dirent_get_typename(enum os_dirent_t type)
620{
Tom Rinib6f605e2017-05-13 20:11:30 -0400621 if (type >= OS_FILET_REG && type < OS_FILET_COUNT)
Simon Glassf1c45c82012-12-26 09:53:34 +0000622 return os_dirent_typename[type];
623
624 return os_dirent_typename[OS_FILET_UNKNOWN];
625}
626
Heinrich Schuchardt011a1e02022-01-11 01:50:24 +0100627/*
628 * For compatibility reasons avoid loff_t here.
629 * U-Boot defines loff_t as long long.
630 * But /usr/include/linux/types.h may not define it at all.
631 * Alpine Linux being one example.
632 */
633int os_get_filesize(const char *fname, long long *size)
Simon Glassf1c45c82012-12-26 09:53:34 +0000634{
635 struct stat buf;
636 int ret;
637
638 ret = stat(fname, &buf);
639 if (ret)
640 return ret;
Suriyan Ramasami378da1032014-11-17 14:39:37 -0800641 *size = buf.st_size;
642 return 0;
Simon Glassf1c45c82012-12-26 09:53:34 +0000643}
Simon Glass3e9fd242013-11-10 10:27:01 -0700644
Simon Glass29d11432017-12-04 13:48:17 -0700645void os_putc(int ch)
646{
Heinrich Schuchardt92ebac72021-11-20 13:28:33 +0100647 fputc(ch, stdout);
Simon Glass29d11432017-12-04 13:48:17 -0700648}
649
650void os_puts(const char *str)
651{
652 while (*str)
653 os_putc(*str++);
654}
655
Simon Glass9dd10bf2013-11-10 10:27:03 -0700656int os_write_ram_buf(const char *fname)
657{
658 struct sandbox_state *state = state_get_current();
659 int fd, ret;
660
661 fd = open(fname, O_CREAT | O_WRONLY, 0777);
662 if (fd < 0)
663 return -ENOENT;
664 ret = write(fd, state->ram_buf, state->ram_size);
665 close(fd);
666 if (ret != state->ram_size)
667 return -EIO;
668
669 return 0;
670}
671
672int os_read_ram_buf(const char *fname)
673{
674 struct sandbox_state *state = state_get_current();
675 int fd, ret;
Heinrich Schuchardt011a1e02022-01-11 01:50:24 +0100676 long long size;
Simon Glass9dd10bf2013-11-10 10:27:03 -0700677
Suriyan Ramasami378da1032014-11-17 14:39:37 -0800678 ret = os_get_filesize(fname, &size);
679 if (ret < 0)
680 return ret;
Simon Glass9dd10bf2013-11-10 10:27:03 -0700681 if (size != state->ram_size)
682 return -ENOSPC;
683 fd = open(fname, O_RDONLY);
684 if (fd < 0)
685 return -ENOENT;
686
687 ret = read(fd, state->ram_buf, state->ram_size);
688 close(fd);
689 if (ret != state->ram_size)
690 return -EIO;
691
692 return 0;
693}
Simon Glass860b7d92014-02-27 13:26:15 -0700694
695static int make_exec(char *fname, const void *data, int size)
696{
697 int fd;
698
699 strcpy(fname, "/tmp/u-boot.jump.XXXXXX");
700 fd = mkstemp(fname);
701 if (fd < 0)
702 return -ENOENT;
703 if (write(fd, data, size) < 0)
704 return -EIO;
705 close(fd);
706 if (chmod(fname, 0777))
707 return -ENOEXEC;
708
709 return 0;
710}
711
Simon Glass7dafd022018-11-15 18:44:05 -0700712/**
713 * add_args() - Allocate a new argv with the given args
714 *
715 * This is used to create a new argv array with all the old arguments and some
716 * new ones that are passed in
717 *
718 * @argvp: Returns newly allocated args list
719 * @add_args: Arguments to add, each a string
720 * @count: Number of arguments in @add_args
721 * @return 0 if OK, -ENOMEM if out of memory
722 */
723static int add_args(char ***argvp, char *add_args[], int count)
Simon Glass860b7d92014-02-27 13:26:15 -0700724{
Simon Glass7465f002018-11-15 18:44:07 -0700725 char **argv, **ap;
Simon Glass860b7d92014-02-27 13:26:15 -0700726 int argc;
727
Simon Glass7465f002018-11-15 18:44:07 -0700728 for (argc = 0; (*argvp)[argc]; argc++)
Simon Glass860b7d92014-02-27 13:26:15 -0700729 ;
730
Simon Glassedd094e2021-02-06 09:57:33 -0700731 argv = os_malloc((argc + count + 1) * sizeof(char *));
Simon Glass860b7d92014-02-27 13:26:15 -0700732 if (!argv) {
733 printf("Out of memory for %d argv\n", count);
734 return -ENOMEM;
735 }
Simon Glass7465f002018-11-15 18:44:07 -0700736 for (ap = *argvp, argc = 0; *ap; ap++) {
737 char *arg = *ap;
738
739 /* Drop args that we don't want to propagate */
740 if (*arg == '-' && strlen(arg) == 2) {
741 switch (arg[1]) {
742 case 'j':
743 case 'm':
744 ap++;
745 continue;
746 }
747 } else if (!strcmp(arg, "--rm_memory")) {
Simon Glass7465f002018-11-15 18:44:07 -0700748 continue;
749 }
750 argv[argc++] = arg;
751 }
752
Simon Glass860b7d92014-02-27 13:26:15 -0700753 memcpy(argv + argc, add_args, count * sizeof(char *));
754 argv[argc + count] = NULL;
755
756 *argvp = argv;
757 return 0;
758}
759
Simon Glass7dafd022018-11-15 18:44:05 -0700760/**
761 * os_jump_to_file() - Jump to a new program
762 *
763 * This saves the memory buffer, sets up arguments to the new process, then
764 * execs it.
765 *
766 * @fname: Filename to exec
767 * @return does not return on success, any return value is an error
768 */
Simon Glassdafc5d72021-03-15 18:11:07 +1300769static int os_jump_to_file(const char *fname, bool delete_it)
Simon Glass860b7d92014-02-27 13:26:15 -0700770{
771 struct sandbox_state *state = state_get_current();
Simon Glass7dafd022018-11-15 18:44:05 -0700772 char mem_fname[30];
Simon Glass860b7d92014-02-27 13:26:15 -0700773 int fd, err;
Simon Glass7dafd022018-11-15 18:44:05 -0700774 char *extra_args[5];
Simon Glass860b7d92014-02-27 13:26:15 -0700775 char **argv = state->argv;
Simon Glass7465f002018-11-15 18:44:07 -0700776 int argc;
Simon Glass860b7d92014-02-27 13:26:15 -0700777#ifdef DEBUG
Simon Glass7dafd022018-11-15 18:44:05 -0700778 int i;
Simon Glass860b7d92014-02-27 13:26:15 -0700779#endif
780
Simon Glass860b7d92014-02-27 13:26:15 -0700781 strcpy(mem_fname, "/tmp/u-boot.mem.XXXXXX");
782 fd = mkstemp(mem_fname);
783 if (fd < 0)
784 return -ENOENT;
785 close(fd);
786 err = os_write_ram_buf(mem_fname);
787 if (err)
788 return err;
789
790 os_fd_restore();
791
Simon Glassdafc5d72021-03-15 18:11:07 +1300792 argc = 0;
793 if (delete_it) {
794 extra_args[argc++] = "-j";
795 extra_args[argc++] = (char *)fname;
796 }
797 extra_args[argc++] = "-m";
798 extra_args[argc++] = mem_fname;
Simon Glass7465f002018-11-15 18:44:07 -0700799 if (state->ram_buf_rm)
800 extra_args[argc++] = "--rm_memory";
801 err = add_args(&argv, extra_args, argc);
Simon Glass860b7d92014-02-27 13:26:15 -0700802 if (err)
803 return err;
Simon Glass7465f002018-11-15 18:44:07 -0700804 argv[0] = (char *)fname;
Simon Glass860b7d92014-02-27 13:26:15 -0700805
806#ifdef DEBUG
807 for (i = 0; argv[i]; i++)
808 printf("%d %s\n", i, argv[i]);
809#endif
810
811 if (state_uninit())
812 os_exit(2);
813
814 err = execv(fname, argv);
Simon Glassedd094e2021-02-06 09:57:33 -0700815 os_free(argv);
Simon Glasscca25522018-11-15 18:44:08 -0700816 if (err) {
817 perror("Unable to run image");
Simon Glass23eabbb2018-11-23 21:29:24 -0700818 printf("Image filename '%s'\n", fname);
Simon Glass860b7d92014-02-27 13:26:15 -0700819 return err;
Simon Glasscca25522018-11-15 18:44:08 -0700820 }
Simon Glass860b7d92014-02-27 13:26:15 -0700821
Simon Glassdafc5d72021-03-15 18:11:07 +1300822 if (delete_it)
823 return unlink(fname);
824
825 return -EFAULT;
Simon Glass860b7d92014-02-27 13:26:15 -0700826}
Simon Glass504548f2015-04-20 12:37:22 -0600827
Simon Glass7dafd022018-11-15 18:44:05 -0700828int os_jump_to_image(const void *dest, int size)
829{
830 char fname[30];
831 int err;
832
833 err = make_exec(fname, dest, size);
834 if (err)
835 return err;
836
Simon Glassdafc5d72021-03-15 18:11:07 +1300837 return os_jump_to_file(fname, true);
Simon Glass7dafd022018-11-15 18:44:05 -0700838}
839
Simon Glass1cd06002021-07-05 16:32:45 -0600840int os_find_u_boot(char *fname, int maxlen, bool use_img,
841 const char *cur_prefix, const char *next_prefix)
Simon Glass2c931ba2016-07-04 11:57:45 -0600842{
843 struct sandbox_state *state = state_get_current();
844 const char *progname = state->argv[0];
845 int len = strlen(progname);
Simon Glass1cd06002021-07-05 16:32:45 -0600846 char subdir[10];
847 char *suffix;
Simon Glass2c931ba2016-07-04 11:57:45 -0600848 char *p;
849 int fd;
850
851 if (len >= maxlen || len < 4)
852 return -ENOSPC;
853
Simon Glass2c931ba2016-07-04 11:57:45 -0600854 strcpy(fname, progname);
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600855 suffix = fname + len - 4;
856
Simon Glass1cd06002021-07-05 16:32:45 -0600857 /* Change the existing suffix to the new one */
858 if (*suffix != '-')
859 return -EINVAL;
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600860
Simon Glass1cd06002021-07-05 16:32:45 -0600861 if (*next_prefix)
862 strcpy(suffix + 1, next_prefix); /* e.g. "-tpl" to "-spl" */
863 else
864 *suffix = '\0'; /* e.g. "-spl" to "" */
865 fd = os_open(fname, O_RDONLY);
866 if (fd >= 0) {
867 close(fd);
868 return 0;
Simon Glassdc4d8eb2018-10-01 11:55:10 -0600869 }
870
Simon Glass1cd06002021-07-05 16:32:45 -0600871 /*
872 * We didn't find it, so try looking for 'u-boot-xxx' in the xxx/
873 * directory. Replace the old dirname with the new one.
874 */
875 snprintf(subdir, sizeof(subdir), "/%s/", cur_prefix);
876 p = strstr(fname, subdir);
Simon Glass2c931ba2016-07-04 11:57:45 -0600877 if (p) {
Simon Glass1cd06002021-07-05 16:32:45 -0600878 if (*next_prefix)
879 /* e.g. ".../tpl/u-boot-spl" to "../spl/u-boot-spl" */
880 memcpy(p + 1, next_prefix, strlen(next_prefix));
881 else
882 /* e.g. ".../spl/u-boot" to ".../u-boot" */
883 strcpy(p, p + 1 + strlen(cur_prefix));
Simon Glassb90e4872021-03-07 17:35:13 -0700884 if (use_img)
885 strcat(p, ".img");
Simon Glass1cd06002021-07-05 16:32:45 -0600886
Simon Glass2c931ba2016-07-04 11:57:45 -0600887 fd = os_open(fname, O_RDONLY);
888 if (fd >= 0) {
889 close(fd);
890 return 0;
891 }
892 }
893
894 return -ENOENT;
895}
896
897int os_spl_to_uboot(const char *fname)
898{
Patrick Delaunay6daf9052020-11-20 09:48:33 +0100899 struct sandbox_state *state = state_get_current();
900
Patrick Delaunay6daf9052020-11-20 09:48:33 +0100901 /* U-Boot will delete ram buffer after read: "--rm_memory"*/
902 state->ram_buf_rm = true;
Simon Glassdafc5d72021-03-15 18:11:07 +1300903
904 return os_jump_to_file(fname, false);
Simon Glass2c931ba2016-07-04 11:57:45 -0600905}
906
Heinrich Schuchardtc0d1a002020-12-30 18:07:48 +0100907long os_get_time_offset(void)
908{
909 const char *offset;
910
911 offset = getenv(ENV_TIME_OFFSET);
912 if (offset)
913 return strtol(offset, NULL, 0);
914 return 0;
915}
916
917void os_set_time_offset(long offset)
918{
919 char buf[21];
920 int ret;
921
922 snprintf(buf, sizeof(buf), "%ld", offset);
923 ret = setenv(ENV_TIME_OFFSET, buf, true);
924 if (ret)
925 printf("Could not set environment variable %s\n",
926 ENV_TIME_OFFSET);
927}
928
Simon Glass504548f2015-04-20 12:37:22 -0600929void os_localtime(struct rtc_time *rt)
930{
931 time_t t = time(NULL);
932 struct tm *tm;
933
934 tm = localtime(&t);
935 rt->tm_sec = tm->tm_sec;
936 rt->tm_min = tm->tm_min;
937 rt->tm_hour = tm->tm_hour;
938 rt->tm_mday = tm->tm_mday;
939 rt->tm_mon = tm->tm_mon + 1;
940 rt->tm_year = tm->tm_year + 1900;
941 rt->tm_wday = tm->tm_wday;
942 rt->tm_yday = tm->tm_yday;
943 rt->tm_isdst = tm->tm_isdst;
944}
Simon Glass5dccd152018-05-16 09:42:22 -0600945
Simon Glassb7255ef2018-09-15 00:50:55 -0600946void os_abort(void)
947{
948 abort();
949}
Simon Glass4e766c22018-10-01 21:12:32 -0600950
951int os_mprotect_allow(void *start, size_t len)
952{
953 int page_size = getpagesize();
954
955 /* Move start to the start of a page, len to the end */
956 start = (void *)(((ulong)start) & ~(page_size - 1));
957 len = (len + page_size * 2) & ~(page_size - 1);
958
959 return mprotect(start, len, PROT_READ | PROT_WRITE);
960}
Simon Glass752707a2019-04-08 13:20:41 -0600961
962void *os_find_text_base(void)
963{
964 char line[500];
965 void *base = NULL;
966 int len;
967 int fd;
968
969 /*
970 * This code assumes that the first line of /proc/self/maps holds
971 * information about the text, for example:
972 *
973 * 5622d9907000-5622d9a55000 r-xp 00000000 08:01 15067168 u-boot
974 *
975 * The first hex value is assumed to be the address.
976 *
977 * This is tested in Linux 4.15.
978 */
979 fd = open("/proc/self/maps", O_RDONLY);
980 if (fd == -1)
981 return NULL;
982 len = read(fd, line, sizeof(line));
983 if (len > 0) {
984 char *end = memchr(line, '-', len);
985
986 if (end) {
Heinrich Schuchardt05a16842019-10-26 23:17:44 +0200987 uintptr_t addr;
Simon Glass752707a2019-04-08 13:20:41 -0600988
989 *end = '\0';
Heinrich Schuchardt05a16842019-10-26 23:17:44 +0200990 if (sscanf(line, "%zx", &addr) == 1)
Simon Glass752707a2019-04-08 13:20:41 -0600991 base = (void *)addr;
992 }
993 }
994 close(fd);
995
996 return base;
997}
Heinrich Schuchardt1c678442020-10-27 20:29:25 +0100998
999void os_relaunch(char *argv[])
1000{
1001 execv(argv[0], argv);
1002 os_exit(1);
1003}