1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (c) 2011 The Chromium OS Authors.
21 #include <sys/types.h>
22 #include <linux/types.h>
24 #include <asm/getopt.h>
25 #include <asm/sections.h>
26 #include <asm/state.h>
30 /* Operating System Interface */
33 size_t length; /* number of bytes in the block */
36 ssize_t os_read(int fd, void *buf, size_t count)
38 return read(fd, buf, count);
41 ssize_t os_write(int fd, const void *buf, size_t count)
43 return write(fd, buf, count);
46 off_t os_lseek(int fd, off_t offset, int whence)
48 if (whence == OS_SEEK_SET)
50 else if (whence == OS_SEEK_CUR)
52 else if (whence == OS_SEEK_END)
56 return lseek(fd, offset, whence);
59 int os_open(const char *pathname, int os_flags)
63 switch (os_flags & OS_O_MASK) {
78 if (os_flags & OS_O_CREAT)
80 if (os_flags & OS_O_TRUNC)
83 return open(pathname, flags, 0777);
91 int os_unlink(const char *pathname)
93 return unlink(pathname);
96 void os_exit(int exit_code)
101 int os_write_file(const char *fname, const void *buf, int size)
105 fd = os_open(fname, OS_O_WRONLY | OS_O_CREAT | OS_O_TRUNC);
107 printf("Cannot open file '%s'\n", fname);
110 if (os_write(fd, buf, size) != size) {
111 printf("Cannot write to file '%s'\n", fname);
120 int os_read_file(const char *fname, void **bufp, int *sizep)
126 fd = os_open(fname, OS_O_RDONLY);
128 printf("Cannot open file '%s'\n", fname);
131 size = os_lseek(fd, 0, OS_SEEK_END);
133 printf("Cannot seek to end of file '%s'\n", fname);
136 if (os_lseek(fd, 0, OS_SEEK_SET) < 0) {
137 printf("Cannot seek to start of file '%s'\n", fname);
140 *bufp = os_malloc(size);
142 printf("Not enough memory to read file '%s'\n", fname);
146 if (os_read(fd, *bufp, size) != size) {
147 printf("Cannot read from file '%s'\n", fname);
159 /* Restore tty state when we exit */
160 static struct termios orig_term;
161 static bool term_setup;
162 static bool term_nonblock;
164 void os_fd_restore(void)
169 tcsetattr(0, TCSANOW, &orig_term);
171 flags = fcntl(0, F_GETFL, 0);
172 fcntl(0, F_SETFL, flags & ~O_NONBLOCK);
178 /* Put tty into raw mode so <tab> and <ctrl+c> work */
179 void os_tty_raw(int fd, bool allow_sigs)
187 /* If not a tty, don't complain */
188 if (tcgetattr(fd, &orig_term))
192 term.c_iflag = IGNBRK | IGNPAR;
193 term.c_oflag = OPOST | ONLCR;
194 term.c_cflag = CS8 | CREAD | CLOCAL;
195 term.c_lflag = allow_sigs ? ISIG : 0;
196 if (tcsetattr(fd, TCSANOW, &term))
199 flags = fcntl(fd, F_GETFL, 0);
200 if (!(flags & O_NONBLOCK)) {
201 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK))
203 term_nonblock = true;
207 atexit(os_fd_restore);
210 void *os_malloc(size_t length)
212 int page_size = getpagesize();
213 struct os_mem_hdr *hdr;
216 * Use an address that is hopefully available to us so that pointers
217 * to this memory are fairly obvious. If we end up with a different
218 * address, that's fine too.
220 hdr = mmap((void *)0x10000000, length + page_size,
221 PROT_READ | PROT_WRITE | PROT_EXEC,
222 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
223 if (hdr == MAP_FAILED)
225 hdr->length = length;
227 return (void *)hdr + page_size;
230 void os_free(void *ptr)
232 int page_size = getpagesize();
233 struct os_mem_hdr *hdr;
236 hdr = ptr - page_size;
237 munmap(hdr, hdr->length + page_size);
241 void *os_realloc(void *ptr, size_t length)
243 int page_size = getpagesize();
244 struct os_mem_hdr *hdr;
248 buf = os_malloc(length);
252 hdr = ptr - page_size;
253 if (length > hdr->length)
254 length = hdr->length;
255 memcpy(buf, ptr, length);
264 void os_usleep(unsigned long usec)
269 uint64_t __attribute__((no_instrument_function)) os_get_nsec(void)
271 #if defined(CLOCK_MONOTONIC) && defined(_POSIX_MONOTONIC_CLOCK)
273 if (EINVAL == clock_gettime(CLOCK_MONOTONIC, &tp)) {
276 gettimeofday(&tv, NULL);
277 tp.tv_sec = tv.tv_sec;
278 tp.tv_nsec = tv.tv_usec * 1000;
280 return tp.tv_sec * 1000000000ULL + tp.tv_nsec;
283 gettimeofday(&tv, NULL);
284 return tv.tv_sec * 1000000000ULL + tv.tv_usec * 1000;
288 static char *short_opts;
289 static struct option *long_opts;
291 int os_parse_args(struct sandbox_state *state, int argc, char *argv[])
293 struct sandbox_cmdline_option **sb_opt = __u_boot_sandbox_option_start;
294 size_t num_options = __u_boot_sandbox_option_count();
297 int hidden_short_opt;
302 if (short_opts || long_opts)
308 /* dynamically construct the arguments to the system getopt_long */
309 short_opts = os_malloc(sizeof(*short_opts) * num_options * 2 + 1);
310 long_opts = os_malloc(sizeof(*long_opts) * num_options);
311 if (!short_opts || !long_opts)
315 * getopt_long requires "val" to be unique (since that is what the
316 * func returns), so generate unique values automatically for flags
317 * that don't have a short option. pick 0x100 as that is above the
318 * single byte range (where ASCII/ISO-XXXX-X charsets live).
320 hidden_short_opt = 0x100;
322 for (i = 0; i < num_options; ++i) {
323 long_opts[i].name = sb_opt[i]->flag;
324 long_opts[i].has_arg = sb_opt[i]->has_arg ?
325 required_argument : no_argument;
326 long_opts[i].flag = NULL;
328 if (sb_opt[i]->flag_short) {
329 short_opts[si++] = long_opts[i].val = sb_opt[i]->flag_short;
330 if (long_opts[i].has_arg == required_argument)
331 short_opts[si++] = ':';
333 long_opts[i].val = sb_opt[i]->flag_short = hidden_short_opt++;
335 short_opts[si] = '\0';
337 /* we need to handle output ourselves since u-boot provides printf */
341 * walk all of the options the user gave us on the command line,
342 * figure out what u-boot option structure they belong to (via
343 * the unique short val key), and call the appropriate callback.
345 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
346 for (i = 0; i < num_options; ++i) {
347 if (sb_opt[i]->flag_short == c) {
348 if (sb_opt[i]->callback(state, optarg)) {
349 state->parse_err = sb_opt[i]->flag;
355 if (i == num_options) {
357 * store the faulting flag for later display. we have to
358 * store the flag itself as the getopt parsing itself is
359 * tricky: need to handle the following flags (assume all
360 * of the below are unknown):
361 * -a optopt='a' optind=<next>
362 * -abbbb optopt='a' optind=<this>
363 * -aaaaa optopt='a' optind=<this>
364 * --a optopt=0 optind=<this>
365 * as you can see, it is impossible to determine the exact
366 * faulting flag without doing the parsing ourselves, so
367 * we just report the specific flag that failed.
370 static char parse_err[3] = { '-', 0, '\0', };
371 parse_err[1] = optopt;
372 state->parse_err = parse_err;
374 state->parse_err = argv[optind - 1];
382 void os_dirent_free(struct os_dirent_node *node)
384 struct os_dirent_node *next;
393 int os_dirent_ls(const char *dirname, struct os_dirent_node **headp)
395 struct dirent *entry;
396 struct os_dirent_node *head, *node, *next;
406 dir = opendir(dirname);
410 /* Create a buffer upfront, with typically sufficient size */
411 dirlen = strlen(dirname) + 2;
413 fname = os_malloc(len);
419 for (node = head = NULL;; node = next) {
421 entry = readdir(dir);
426 next = os_malloc(sizeof(*node) + strlen(entry->d_name) + 1);
428 os_dirent_free(head);
432 if (dirlen + strlen(entry->d_name) > len) {
433 len = dirlen + strlen(entry->d_name);
435 fname = os_realloc(fname, len);
439 os_dirent_free(head);
445 strcpy(next->name, entry->d_name);
446 switch (entry->d_type) {
448 next->type = OS_FILET_REG;
451 next->type = OS_FILET_DIR;
454 next->type = OS_FILET_LNK;
457 next->type = OS_FILET_UNKNOWN;
460 snprintf(fname, len, "%s/%s", dirname, next->name);
461 if (!stat(fname, &buf))
462 next->size = buf.st_size;
476 const char *os_dirent_typename[OS_FILET_COUNT] = {
483 const char *os_dirent_get_typename(enum os_dirent_t type)
485 if (type >= OS_FILET_REG && type < OS_FILET_COUNT)
486 return os_dirent_typename[type];
488 return os_dirent_typename[OS_FILET_UNKNOWN];
491 int os_get_filesize(const char *fname, loff_t *size)
496 ret = stat(fname, &buf);
508 void os_puts(const char *str)
514 int os_write_ram_buf(const char *fname)
516 struct sandbox_state *state = state_get_current();
519 fd = open(fname, O_CREAT | O_WRONLY, 0777);
522 ret = write(fd, state->ram_buf, state->ram_size);
524 if (ret != state->ram_size)
530 int os_read_ram_buf(const char *fname)
532 struct sandbox_state *state = state_get_current();
536 ret = os_get_filesize(fname, &size);
539 if (size != state->ram_size)
541 fd = open(fname, O_RDONLY);
545 ret = read(fd, state->ram_buf, state->ram_size);
547 if (ret != state->ram_size)
553 static int make_exec(char *fname, const void *data, int size)
557 strcpy(fname, "/tmp/u-boot.jump.XXXXXX");
561 if (write(fd, data, size) < 0)
564 if (chmod(fname, 0777))
571 * add_args() - Allocate a new argv with the given args
573 * This is used to create a new argv array with all the old arguments and some
574 * new ones that are passed in
576 * @argvp: Returns newly allocated args list
577 * @add_args: Arguments to add, each a string
578 * @count: Number of arguments in @add_args
579 * @return 0 if OK, -ENOMEM if out of memory
581 static int add_args(char ***argvp, char *add_args[], int count)
586 for (argc = 0; (*argvp)[argc]; argc++)
589 argv = os_malloc((argc + count + 1) * sizeof(char *));
591 printf("Out of memory for %d argv\n", count);
594 for (ap = *argvp, argc = 0; *ap; ap++) {
597 /* Drop args that we don't want to propagate */
598 if (*arg == '-' && strlen(arg) == 2) {
605 } else if (!strcmp(arg, "--rm_memory")) {
612 memcpy(argv + argc, add_args, count * sizeof(char *));
613 argv[argc + count] = NULL;
620 * os_jump_to_file() - Jump to a new program
622 * This saves the memory buffer, sets up arguments to the new process, then
625 * @fname: Filename to exec
626 * @return does not return on success, any return value is an error
628 static int os_jump_to_file(const char *fname)
630 struct sandbox_state *state = state_get_current();
634 char **argv = state->argv;
640 strcpy(mem_fname, "/tmp/u-boot.mem.XXXXXX");
641 fd = mkstemp(mem_fname);
645 err = os_write_ram_buf(mem_fname);
651 extra_args[0] = "-j";
652 extra_args[1] = (char *)fname;
653 extra_args[2] = "-m";
654 extra_args[3] = mem_fname;
656 if (state->ram_buf_rm)
657 extra_args[argc++] = "--rm_memory";
658 err = add_args(&argv, extra_args, argc);
661 argv[0] = (char *)fname;
664 for (i = 0; argv[i]; i++)
665 printf("%d %s\n", i, argv[i]);
671 err = execv(fname, argv);
674 perror("Unable to run image");
675 printf("Image filename '%s'\n", fname);
679 return unlink(fname);
682 int os_jump_to_image(const void *dest, int size)
687 err = make_exec(fname, dest, size);
691 return os_jump_to_file(fname);
694 int os_find_u_boot(char *fname, int maxlen)
696 struct sandbox_state *state = state_get_current();
697 const char *progname = state->argv[0];
698 int len = strlen(progname);
703 if (len >= maxlen || len < 4)
706 strcpy(fname, progname);
707 suffix = fname + len - 4;
709 /* If we are TPL, boot to SPL */
710 if (!strcmp(suffix, "-tpl")) {
711 fname[len - 3] = 's';
712 fd = os_open(fname, O_RDONLY);
718 /* Look for 'u-boot-tpl' in the tpl/ directory */
719 p = strstr(fname, "/tpl/");
722 fd = os_open(fname, O_RDONLY);
731 /* Look for 'u-boot' in the same directory as 'u-boot-spl' */
732 if (!strcmp(suffix, "-spl")) {
733 fname[len - 4] = '\0';
734 fd = os_open(fname, O_RDONLY);
741 /* Look for 'u-boot' in the parent directory of spl/ */
742 p = strstr(fname, "spl/");
744 /* Remove the "spl" characters */
745 memmove(p, p + 4, strlen(p + 4) + 1);
746 fd = os_open(fname, O_RDONLY);
756 int os_spl_to_uboot(const char *fname)
758 return os_jump_to_file(fname);
761 void os_localtime(struct rtc_time *rt)
763 time_t t = time(NULL);
767 rt->tm_sec = tm->tm_sec;
768 rt->tm_min = tm->tm_min;
769 rt->tm_hour = tm->tm_hour;
770 rt->tm_mday = tm->tm_mday;
771 rt->tm_mon = tm->tm_mon + 1;
772 rt->tm_year = tm->tm_year + 1900;
773 rt->tm_wday = tm->tm_wday;
774 rt->tm_yday = tm->tm_yday;
775 rt->tm_isdst = tm->tm_isdst;
783 int os_mprotect_allow(void *start, size_t len)
785 int page_size = getpagesize();
787 /* Move start to the start of a page, len to the end */
788 start = (void *)(((ulong)start) & ~(page_size - 1));
789 len = (len + page_size * 2) & ~(page_size - 1);
791 return mprotect(start, len, PROT_READ | PROT_WRITE);
794 void *os_find_text_base(void)
802 * This code assumes that the first line of /proc/self/maps holds
803 * information about the text, for example:
805 * 5622d9907000-5622d9a55000 r-xp 00000000 08:01 15067168 u-boot
807 * The first hex value is assumed to be the address.
809 * This is tested in Linux 4.15.
811 fd = open("/proc/self/maps", O_RDONLY);
814 len = read(fd, line, sizeof(line));
816 char *end = memchr(line, '-', len);
819 unsigned long long addr;
822 if (sscanf(line, "%llx", &addr) == 1)