1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (c) 2011 The Chromium OS Authors.
22 #include <sys/types.h>
23 #include <linux/types.h>
25 #include <asm/getopt.h>
26 #include <asm/sections.h>
27 #include <asm/state.h>
31 /* Operating System Interface */
34 size_t length; /* number of bytes in the block */
37 ssize_t os_read(int fd, void *buf, size_t count)
39 return read(fd, buf, count);
42 ssize_t os_write(int fd, const void *buf, size_t count)
44 return write(fd, buf, count);
47 off_t os_lseek(int fd, off_t offset, int whence)
49 if (whence == OS_SEEK_SET)
51 else if (whence == OS_SEEK_CUR)
53 else if (whence == OS_SEEK_END)
57 return lseek(fd, offset, whence);
60 int os_open(const char *pathname, int os_flags)
64 switch (os_flags & OS_O_MASK) {
79 if (os_flags & OS_O_CREAT)
81 if (os_flags & OS_O_TRUNC)
84 * During a cold reset execv() is used to relaunch the U-Boot binary.
85 * We must ensure that all files are closed in this case.
89 return open(pathname, flags, 0777);
94 /* Do not close the console input */
100 int os_unlink(const char *pathname)
102 return unlink(pathname);
105 void os_exit(int exit_code)
110 int os_write_file(const char *fname, const void *buf, int size)
114 fd = os_open(fname, OS_O_WRONLY | OS_O_CREAT | OS_O_TRUNC);
116 printf("Cannot open file '%s'\n", fname);
119 if (os_write(fd, buf, size) != size) {
120 printf("Cannot write to file '%s'\n", fname);
129 int os_read_file(const char *fname, void **bufp, int *sizep)
135 fd = os_open(fname, OS_O_RDONLY);
137 printf("Cannot open file '%s'\n", fname);
140 size = os_lseek(fd, 0, OS_SEEK_END);
142 printf("Cannot seek to end of file '%s'\n", fname);
145 if (os_lseek(fd, 0, OS_SEEK_SET) < 0) {
146 printf("Cannot seek to start of file '%s'\n", fname);
149 *bufp = malloc(size);
151 printf("Not enough memory to read file '%s'\n", fname);
155 if (os_read(fd, *bufp, size) != size) {
156 printf("Cannot read from file '%s'\n", fname);
168 /* Restore tty state when we exit */
169 static struct termios orig_term;
170 static bool term_setup;
171 static bool term_nonblock;
173 void os_fd_restore(void)
178 tcsetattr(0, TCSANOW, &orig_term);
180 flags = fcntl(0, F_GETFL, 0);
181 fcntl(0, F_SETFL, flags & ~O_NONBLOCK);
187 static void os_sigint_handler(int sig)
190 signal(SIGINT, SIG_DFL);
194 /* Put tty into raw mode so <tab> and <ctrl+c> work */
195 void os_tty_raw(int fd, bool allow_sigs)
203 /* If not a tty, don't complain */
204 if (tcgetattr(fd, &orig_term))
208 term.c_iflag = IGNBRK | IGNPAR;
209 term.c_oflag = OPOST | ONLCR;
210 term.c_cflag = CS8 | CREAD | CLOCAL;
211 term.c_lflag = allow_sigs ? ISIG : 0;
212 if (tcsetattr(fd, TCSANOW, &term))
215 flags = fcntl(fd, F_GETFL, 0);
216 if (!(flags & O_NONBLOCK)) {
217 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK))
219 term_nonblock = true;
223 atexit(os_fd_restore);
224 signal(SIGINT, os_sigint_handler);
227 void *os_malloc(size_t length)
229 int page_size = getpagesize();
230 struct os_mem_hdr *hdr;
233 * Use an address that is hopefully available to us so that pointers
234 * to this memory are fairly obvious. If we end up with a different
235 * address, that's fine too.
237 hdr = mmap((void *)0x10000000, length + page_size,
238 PROT_READ | PROT_WRITE | PROT_EXEC,
239 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
240 if (hdr == MAP_FAILED)
242 hdr->length = length;
244 return (void *)hdr + page_size;
247 void os_free(void *ptr)
249 int page_size = getpagesize();
250 struct os_mem_hdr *hdr;
253 hdr = ptr - page_size;
254 munmap(hdr, hdr->length + page_size);
258 void os_usleep(unsigned long usec)
263 uint64_t __attribute__((no_instrument_function)) os_get_nsec(void)
265 #if defined(CLOCK_MONOTONIC) && defined(_POSIX_MONOTONIC_CLOCK)
267 if (EINVAL == clock_gettime(CLOCK_MONOTONIC, &tp)) {
270 gettimeofday(&tv, NULL);
271 tp.tv_sec = tv.tv_sec;
272 tp.tv_nsec = tv.tv_usec * 1000;
274 return tp.tv_sec * 1000000000ULL + tp.tv_nsec;
277 gettimeofday(&tv, NULL);
278 return tv.tv_sec * 1000000000ULL + tv.tv_usec * 1000;
282 static char *short_opts;
283 static struct option *long_opts;
285 int os_parse_args(struct sandbox_state *state, int argc, char *argv[])
287 struct sandbox_cmdline_option **sb_opt = __u_boot_sandbox_option_start;
288 size_t num_options = __u_boot_sandbox_option_count();
291 int hidden_short_opt;
296 if (short_opts || long_opts)
302 /* dynamically construct the arguments to the system getopt_long */
303 short_opts = malloc(sizeof(*short_opts) * num_options * 2 + 1);
304 long_opts = malloc(sizeof(*long_opts) * (num_options + 1));
305 if (!short_opts || !long_opts)
309 * getopt_long requires "val" to be unique (since that is what the
310 * func returns), so generate unique values automatically for flags
311 * that don't have a short option. pick 0x100 as that is above the
312 * single byte range (where ASCII/ISO-XXXX-X charsets live).
314 hidden_short_opt = 0x100;
316 for (i = 0; i < num_options; ++i) {
317 long_opts[i].name = sb_opt[i]->flag;
318 long_opts[i].has_arg = sb_opt[i]->has_arg ?
319 required_argument : no_argument;
320 long_opts[i].flag = NULL;
322 if (sb_opt[i]->flag_short) {
323 short_opts[si++] = long_opts[i].val = sb_opt[i]->flag_short;
324 if (long_opts[i].has_arg == required_argument)
325 short_opts[si++] = ':';
327 long_opts[i].val = sb_opt[i]->flag_short = hidden_short_opt++;
329 short_opts[si] = '\0';
331 /* we need to handle output ourselves since u-boot provides printf */
334 memset(&long_opts[num_options], '\0', sizeof(*long_opts));
336 * walk all of the options the user gave us on the command line,
337 * figure out what u-boot option structure they belong to (via
338 * the unique short val key), and call the appropriate callback.
340 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
341 for (i = 0; i < num_options; ++i) {
342 if (sb_opt[i]->flag_short == c) {
343 if (sb_opt[i]->callback(state, optarg)) {
344 state->parse_err = sb_opt[i]->flag;
350 if (i == num_options) {
352 * store the faulting flag for later display. we have to
353 * store the flag itself as the getopt parsing itself is
354 * tricky: need to handle the following flags (assume all
355 * of the below are unknown):
356 * -a optopt='a' optind=<next>
357 * -abbbb optopt='a' optind=<this>
358 * -aaaaa optopt='a' optind=<this>
359 * --a optopt=0 optind=<this>
360 * as you can see, it is impossible to determine the exact
361 * faulting flag without doing the parsing ourselves, so
362 * we just report the specific flag that failed.
365 static char parse_err[3] = { '-', 0, '\0', };
366 parse_err[1] = optopt;
367 state->parse_err = parse_err;
369 state->parse_err = argv[optind - 1];
377 void os_dirent_free(struct os_dirent_node *node)
379 struct os_dirent_node *next;
388 int os_dirent_ls(const char *dirname, struct os_dirent_node **headp)
390 struct dirent *entry;
391 struct os_dirent_node *head, *node, *next;
401 dir = opendir(dirname);
405 /* Create a buffer upfront, with typically sufficient size */
406 dirlen = strlen(dirname) + 2;
414 for (node = head = NULL;; node = next) {
416 entry = readdir(dir);
421 next = malloc(sizeof(*node) + strlen(entry->d_name) + 1);
423 os_dirent_free(head);
427 if (dirlen + strlen(entry->d_name) > len) {
428 len = dirlen + strlen(entry->d_name);
430 fname = realloc(fname, len);
434 os_dirent_free(head);
440 strcpy(next->name, entry->d_name);
441 switch (entry->d_type) {
443 next->type = OS_FILET_REG;
446 next->type = OS_FILET_DIR;
449 next->type = OS_FILET_LNK;
452 next->type = OS_FILET_UNKNOWN;
455 snprintf(fname, len, "%s/%s", dirname, next->name);
456 if (!stat(fname, &buf))
457 next->size = buf.st_size;
471 const char *os_dirent_typename[OS_FILET_COUNT] = {
478 const char *os_dirent_get_typename(enum os_dirent_t type)
480 if (type >= OS_FILET_REG && type < OS_FILET_COUNT)
481 return os_dirent_typename[type];
483 return os_dirent_typename[OS_FILET_UNKNOWN];
486 int os_get_filesize(const char *fname, loff_t *size)
491 ret = stat(fname, &buf);
503 void os_puts(const char *str)
509 int os_write_ram_buf(const char *fname)
511 struct sandbox_state *state = state_get_current();
514 fd = open(fname, O_CREAT | O_WRONLY, 0777);
517 ret = write(fd, state->ram_buf, state->ram_size);
519 if (ret != state->ram_size)
525 int os_read_ram_buf(const char *fname)
527 struct sandbox_state *state = state_get_current();
531 ret = os_get_filesize(fname, &size);
534 if (size != state->ram_size)
536 fd = open(fname, O_RDONLY);
540 ret = read(fd, state->ram_buf, state->ram_size);
542 if (ret != state->ram_size)
548 static int make_exec(char *fname, const void *data, int size)
552 strcpy(fname, "/tmp/u-boot.jump.XXXXXX");
556 if (write(fd, data, size) < 0)
559 if (chmod(fname, 0777))
566 * add_args() - Allocate a new argv with the given args
568 * This is used to create a new argv array with all the old arguments and some
569 * new ones that are passed in
571 * @argvp: Returns newly allocated args list
572 * @add_args: Arguments to add, each a string
573 * @count: Number of arguments in @add_args
574 * @return 0 if OK, -ENOMEM if out of memory
576 static int add_args(char ***argvp, char *add_args[], int count)
581 for (argc = 0; (*argvp)[argc]; argc++)
584 argv = malloc((argc + count + 1) * sizeof(char *));
586 printf("Out of memory for %d argv\n", count);
589 for (ap = *argvp, argc = 0; *ap; ap++) {
592 /* Drop args that we don't want to propagate */
593 if (*arg == '-' && strlen(arg) == 2) {
600 } else if (!strcmp(arg, "--rm_memory")) {
607 memcpy(argv + argc, add_args, count * sizeof(char *));
608 argv[argc + count] = NULL;
615 * os_jump_to_file() - Jump to a new program
617 * This saves the memory buffer, sets up arguments to the new process, then
620 * @fname: Filename to exec
621 * @return does not return on success, any return value is an error
623 static int os_jump_to_file(const char *fname)
625 struct sandbox_state *state = state_get_current();
629 char **argv = state->argv;
635 strcpy(mem_fname, "/tmp/u-boot.mem.XXXXXX");
636 fd = mkstemp(mem_fname);
640 err = os_write_ram_buf(mem_fname);
646 extra_args[0] = "-j";
647 extra_args[1] = (char *)fname;
648 extra_args[2] = "-m";
649 extra_args[3] = mem_fname;
651 if (state->ram_buf_rm)
652 extra_args[argc++] = "--rm_memory";
653 err = add_args(&argv, extra_args, argc);
656 argv[0] = (char *)fname;
659 for (i = 0; argv[i]; i++)
660 printf("%d %s\n", i, argv[i]);
666 err = execv(fname, argv);
669 perror("Unable to run image");
670 printf("Image filename '%s'\n", fname);
674 return unlink(fname);
677 int os_jump_to_image(const void *dest, int size)
682 err = make_exec(fname, dest, size);
686 return os_jump_to_file(fname);
689 int os_find_u_boot(char *fname, int maxlen)
691 struct sandbox_state *state = state_get_current();
692 const char *progname = state->argv[0];
693 int len = strlen(progname);
698 if (len >= maxlen || len < 4)
701 strcpy(fname, progname);
702 suffix = fname + len - 4;
704 /* If we are TPL, boot to SPL */
705 if (!strcmp(suffix, "-tpl")) {
706 fname[len - 3] = 's';
707 fd = os_open(fname, O_RDONLY);
713 /* Look for 'u-boot-tpl' in the tpl/ directory */
714 p = strstr(fname, "/tpl/");
717 fd = os_open(fname, O_RDONLY);
726 /* Look for 'u-boot' in the same directory as 'u-boot-spl' */
727 if (!strcmp(suffix, "-spl")) {
728 fname[len - 4] = '\0';
729 fd = os_open(fname, O_RDONLY);
736 /* Look for 'u-boot' in the parent directory of spl/ */
737 p = strstr(fname, "spl/");
739 /* Remove the "spl" characters */
740 memmove(p, p + 4, strlen(p + 4) + 1);
741 fd = os_open(fname, O_RDONLY);
751 int os_spl_to_uboot(const char *fname)
753 return os_jump_to_file(fname);
756 void os_localtime(struct rtc_time *rt)
758 time_t t = time(NULL);
762 rt->tm_sec = tm->tm_sec;
763 rt->tm_min = tm->tm_min;
764 rt->tm_hour = tm->tm_hour;
765 rt->tm_mday = tm->tm_mday;
766 rt->tm_mon = tm->tm_mon + 1;
767 rt->tm_year = tm->tm_year + 1900;
768 rt->tm_wday = tm->tm_wday;
769 rt->tm_yday = tm->tm_yday;
770 rt->tm_isdst = tm->tm_isdst;
778 int os_mprotect_allow(void *start, size_t len)
780 int page_size = getpagesize();
782 /* Move start to the start of a page, len to the end */
783 start = (void *)(((ulong)start) & ~(page_size - 1));
784 len = (len + page_size * 2) & ~(page_size - 1);
786 return mprotect(start, len, PROT_READ | PROT_WRITE);
789 void *os_find_text_base(void)
797 * This code assumes that the first line of /proc/self/maps holds
798 * information about the text, for example:
800 * 5622d9907000-5622d9a55000 r-xp 00000000 08:01 15067168 u-boot
802 * The first hex value is assumed to be the address.
804 * This is tested in Linux 4.15.
806 fd = open("/proc/self/maps", O_RDONLY);
809 len = read(fd, line, sizeof(line));
811 char *end = memchr(line, '-', len);
817 if (sscanf(line, "%zx", &addr) == 1)
826 void os_relaunch(char *argv[])
828 execv(argv[0], argv);