Merge tag 'efi-2020-07-rc6' of https://gitlab.denx.de/u-boot/custodians/u-boot-efi
[oweals/u-boot.git] / arch / sandbox / cpu / os.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (c) 2011 The Chromium OS Authors.
4  */
5
6 #include <dirent.h>
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <getopt.h>
10 #include <setjmp.h>
11 #include <signal.h>
12 #include <stdio.h>
13 #include <stdint.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <termios.h>
17 #include <time.h>
18 #include <unistd.h>
19 #include <sys/mman.h>
20 #include <sys/stat.h>
21 #include <sys/time.h>
22 #include <sys/types.h>
23 #include <linux/types.h>
24
25 #include <asm/getopt.h>
26 #include <asm/sections.h>
27 #include <asm/state.h>
28 #include <os.h>
29 #include <rtc_def.h>
30
31 /* Operating System Interface */
32
33 struct os_mem_hdr {
34         size_t length;          /* number of bytes in the block */
35 };
36
37 ssize_t os_read(int fd, void *buf, size_t count)
38 {
39         return read(fd, buf, count);
40 }
41
42 ssize_t os_write(int fd, const void *buf, size_t count)
43 {
44         return write(fd, buf, count);
45 }
46
47 off_t os_lseek(int fd, off_t offset, int whence)
48 {
49         if (whence == OS_SEEK_SET)
50                 whence = SEEK_SET;
51         else if (whence == OS_SEEK_CUR)
52                 whence = SEEK_CUR;
53         else if (whence == OS_SEEK_END)
54                 whence = SEEK_END;
55         else
56                 os_exit(1);
57         return lseek(fd, offset, whence);
58 }
59
60 int os_open(const char *pathname, int os_flags)
61 {
62         int flags;
63
64         switch (os_flags & OS_O_MASK) {
65         case OS_O_RDONLY:
66         default:
67                 flags = O_RDONLY;
68                 break;
69
70         case OS_O_WRONLY:
71                 flags = O_WRONLY;
72                 break;
73
74         case OS_O_RDWR:
75                 flags = O_RDWR;
76                 break;
77         }
78
79         if (os_flags & OS_O_CREAT)
80                 flags |= O_CREAT;
81         if (os_flags & OS_O_TRUNC)
82                 flags |= O_TRUNC;
83
84         return open(pathname, flags, 0777);
85 }
86
87 int os_close(int fd)
88 {
89         return close(fd);
90 }
91
92 int os_unlink(const char *pathname)
93 {
94         return unlink(pathname);
95 }
96
97 void os_exit(int exit_code)
98 {
99         exit(exit_code);
100 }
101
102 int os_write_file(const char *fname, const void *buf, int size)
103 {
104         int fd;
105
106         fd = os_open(fname, OS_O_WRONLY | OS_O_CREAT | OS_O_TRUNC);
107         if (fd < 0) {
108                 printf("Cannot open file '%s'\n", fname);
109                 return -EIO;
110         }
111         if (os_write(fd, buf, size) != size) {
112                 printf("Cannot write to file '%s'\n", fname);
113                 os_close(fd);
114                 return -EIO;
115         }
116         os_close(fd);
117
118         return 0;
119 }
120
121 int os_read_file(const char *fname, void **bufp, int *sizep)
122 {
123         off_t size;
124         int ret = -EIO;
125         int fd;
126
127         fd = os_open(fname, OS_O_RDONLY);
128         if (fd < 0) {
129                 printf("Cannot open file '%s'\n", fname);
130                 goto err;
131         }
132         size = os_lseek(fd, 0, OS_SEEK_END);
133         if (size < 0) {
134                 printf("Cannot seek to end of file '%s'\n", fname);
135                 goto err;
136         }
137         if (os_lseek(fd, 0, OS_SEEK_SET) < 0) {
138                 printf("Cannot seek to start of file '%s'\n", fname);
139                 goto err;
140         }
141         *bufp = malloc(size);
142         if (!*bufp) {
143                 printf("Not enough memory to read file '%s'\n", fname);
144                 ret = -ENOMEM;
145                 goto err;
146         }
147         if (os_read(fd, *bufp, size) != size) {
148                 printf("Cannot read from file '%s'\n", fname);
149                 goto err;
150         }
151         os_close(fd);
152         *sizep = size;
153
154         return 0;
155 err:
156         os_close(fd);
157         return ret;
158 }
159
160 /* Restore tty state when we exit */
161 static struct termios orig_term;
162 static bool term_setup;
163 static bool term_nonblock;
164
165 void os_fd_restore(void)
166 {
167         if (term_setup) {
168                 int flags;
169
170                 tcsetattr(0, TCSANOW, &orig_term);
171                 if (term_nonblock) {
172                         flags = fcntl(0, F_GETFL, 0);
173                         fcntl(0, F_SETFL, flags & ~O_NONBLOCK);
174                 }
175                 term_setup = false;
176         }
177 }
178
179 static void os_sigint_handler(int sig)
180 {
181         os_fd_restore();
182         signal(SIGINT, SIG_DFL);
183         raise(SIGINT);
184 }
185
186 /* Put tty into raw mode so <tab> and <ctrl+c> work */
187 void os_tty_raw(int fd, bool allow_sigs)
188 {
189         struct termios term;
190         int flags;
191
192         if (term_setup)
193                 return;
194
195         /* If not a tty, don't complain */
196         if (tcgetattr(fd, &orig_term))
197                 return;
198
199         term = orig_term;
200         term.c_iflag = IGNBRK | IGNPAR;
201         term.c_oflag = OPOST | ONLCR;
202         term.c_cflag = CS8 | CREAD | CLOCAL;
203         term.c_lflag = allow_sigs ? ISIG : 0;
204         if (tcsetattr(fd, TCSANOW, &term))
205                 return;
206
207         flags = fcntl(fd, F_GETFL, 0);
208         if (!(flags & O_NONBLOCK)) {
209                 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK))
210                         return;
211                 term_nonblock = true;
212         }
213
214         term_setup = true;
215         atexit(os_fd_restore);
216         signal(SIGINT, os_sigint_handler);
217 }
218
219 void *os_malloc(size_t length)
220 {
221         int page_size = getpagesize();
222         struct os_mem_hdr *hdr;
223
224         /*
225          * Use an address that is hopefully available to us so that pointers
226          * to this memory are fairly obvious. If we end up with a different
227          * address, that's fine too.
228          */
229         hdr = mmap((void *)0x10000000, length + page_size,
230                    PROT_READ | PROT_WRITE | PROT_EXEC,
231                    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
232         if (hdr == MAP_FAILED)
233                 return NULL;
234         hdr->length = length;
235
236         return (void *)hdr + page_size;
237 }
238
239 void os_free(void *ptr)
240 {
241         int page_size = getpagesize();
242         struct os_mem_hdr *hdr;
243
244         if (ptr) {
245                 hdr = ptr - page_size;
246                 munmap(hdr, hdr->length + page_size);
247         }
248 }
249
250 void os_usleep(unsigned long usec)
251 {
252         usleep(usec);
253 }
254
255 uint64_t __attribute__((no_instrument_function)) os_get_nsec(void)
256 {
257 #if defined(CLOCK_MONOTONIC) && defined(_POSIX_MONOTONIC_CLOCK)
258         struct timespec tp;
259         if (EINVAL == clock_gettime(CLOCK_MONOTONIC, &tp)) {
260                 struct timeval tv;
261
262                 gettimeofday(&tv, NULL);
263                 tp.tv_sec = tv.tv_sec;
264                 tp.tv_nsec = tv.tv_usec * 1000;
265         }
266         return tp.tv_sec * 1000000000ULL + tp.tv_nsec;
267 #else
268         struct timeval tv;
269         gettimeofday(&tv, NULL);
270         return tv.tv_sec * 1000000000ULL + tv.tv_usec * 1000;
271 #endif
272 }
273
274 static char *short_opts;
275 static struct option *long_opts;
276
277 int os_parse_args(struct sandbox_state *state, int argc, char *argv[])
278 {
279         struct sandbox_cmdline_option **sb_opt = __u_boot_sandbox_option_start;
280         size_t num_options = __u_boot_sandbox_option_count();
281         size_t i;
282
283         int hidden_short_opt;
284         size_t si;
285
286         int c;
287
288         if (short_opts || long_opts)
289                 return 1;
290
291         state->argc = argc;
292         state->argv = argv;
293
294         /* dynamically construct the arguments to the system getopt_long */
295         short_opts = malloc(sizeof(*short_opts) * num_options * 2 + 1);
296         long_opts = malloc(sizeof(*long_opts) * (num_options + 1));
297         if (!short_opts || !long_opts)
298                 return 1;
299
300         /*
301          * getopt_long requires "val" to be unique (since that is what the
302          * func returns), so generate unique values automatically for flags
303          * that don't have a short option.  pick 0x100 as that is above the
304          * single byte range (where ASCII/ISO-XXXX-X charsets live).
305          */
306         hidden_short_opt = 0x100;
307         si = 0;
308         for (i = 0; i < num_options; ++i) {
309                 long_opts[i].name = sb_opt[i]->flag;
310                 long_opts[i].has_arg = sb_opt[i]->has_arg ?
311                         required_argument : no_argument;
312                 long_opts[i].flag = NULL;
313
314                 if (sb_opt[i]->flag_short) {
315                         short_opts[si++] = long_opts[i].val = sb_opt[i]->flag_short;
316                         if (long_opts[i].has_arg == required_argument)
317                                 short_opts[si++] = ':';
318                 } else
319                         long_opts[i].val = sb_opt[i]->flag_short = hidden_short_opt++;
320         }
321         short_opts[si] = '\0';
322
323         /* we need to handle output ourselves since u-boot provides printf */
324         opterr = 0;
325
326         memset(&long_opts[num_options], '\0', sizeof(*long_opts));
327         /*
328          * walk all of the options the user gave us on the command line,
329          * figure out what u-boot option structure they belong to (via
330          * the unique short val key), and call the appropriate callback.
331          */
332         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
333                 for (i = 0; i < num_options; ++i) {
334                         if (sb_opt[i]->flag_short == c) {
335                                 if (sb_opt[i]->callback(state, optarg)) {
336                                         state->parse_err = sb_opt[i]->flag;
337                                         return 0;
338                                 }
339                                 break;
340                         }
341                 }
342                 if (i == num_options) {
343                         /*
344                          * store the faulting flag for later display.  we have to
345                          * store the flag itself as the getopt parsing itself is
346                          * tricky: need to handle the following flags (assume all
347                          * of the below are unknown):
348                          *   -a        optopt='a' optind=<next>
349                          *   -abbbb    optopt='a' optind=<this>
350                          *   -aaaaa    optopt='a' optind=<this>
351                          *   --a       optopt=0   optind=<this>
352                          * as you can see, it is impossible to determine the exact
353                          * faulting flag without doing the parsing ourselves, so
354                          * we just report the specific flag that failed.
355                          */
356                         if (optopt) {
357                                 static char parse_err[3] = { '-', 0, '\0', };
358                                 parse_err[1] = optopt;
359                                 state->parse_err = parse_err;
360                         } else
361                                 state->parse_err = argv[optind - 1];
362                         break;
363                 }
364         }
365
366         return 0;
367 }
368
369 void os_dirent_free(struct os_dirent_node *node)
370 {
371         struct os_dirent_node *next;
372
373         while (node) {
374                 next = node->next;
375                 free(node);
376                 node = next;
377         }
378 }
379
380 int os_dirent_ls(const char *dirname, struct os_dirent_node **headp)
381 {
382         struct dirent *entry;
383         struct os_dirent_node *head, *node, *next;
384         struct stat buf;
385         DIR *dir;
386         int ret;
387         char *fname;
388         char *old_fname;
389         int len;
390         int dirlen;
391
392         *headp = NULL;
393         dir = opendir(dirname);
394         if (!dir)
395                 return -1;
396
397         /* Create a buffer upfront, with typically sufficient size */
398         dirlen = strlen(dirname) + 2;
399         len = dirlen + 256;
400         fname = malloc(len);
401         if (!fname) {
402                 ret = -ENOMEM;
403                 goto done;
404         }
405
406         for (node = head = NULL;; node = next) {
407                 errno = 0;
408                 entry = readdir(dir);
409                 if (!entry) {
410                         ret = errno;
411                         break;
412                 }
413                 next = malloc(sizeof(*node) + strlen(entry->d_name) + 1);
414                 if (!next) {
415                         os_dirent_free(head);
416                         ret = -ENOMEM;
417                         goto done;
418                 }
419                 if (dirlen + strlen(entry->d_name) > len) {
420                         len = dirlen + strlen(entry->d_name);
421                         old_fname = fname;
422                         fname = realloc(fname, len);
423                         if (!fname) {
424                                 free(old_fname);
425                                 free(next);
426                                 os_dirent_free(head);
427                                 ret = -ENOMEM;
428                                 goto done;
429                         }
430                 }
431                 next->next = NULL;
432                 strcpy(next->name, entry->d_name);
433                 switch (entry->d_type) {
434                 case DT_REG:
435                         next->type = OS_FILET_REG;
436                         break;
437                 case DT_DIR:
438                         next->type = OS_FILET_DIR;
439                         break;
440                 case DT_LNK:
441                         next->type = OS_FILET_LNK;
442                         break;
443                 default:
444                         next->type = OS_FILET_UNKNOWN;
445                 }
446                 next->size = 0;
447                 snprintf(fname, len, "%s/%s", dirname, next->name);
448                 if (!stat(fname, &buf))
449                         next->size = buf.st_size;
450                 if (node)
451                         node->next = next;
452                 else
453                         head = next;
454         }
455         *headp = head;
456
457 done:
458         closedir(dir);
459         free(fname);
460         return ret;
461 }
462
463 const char *os_dirent_typename[OS_FILET_COUNT] = {
464         "   ",
465         "SYM",
466         "DIR",
467         "???",
468 };
469
470 const char *os_dirent_get_typename(enum os_dirent_t type)
471 {
472         if (type >= OS_FILET_REG && type < OS_FILET_COUNT)
473                 return os_dirent_typename[type];
474
475         return os_dirent_typename[OS_FILET_UNKNOWN];
476 }
477
478 int os_get_filesize(const char *fname, loff_t *size)
479 {
480         struct stat buf;
481         int ret;
482
483         ret = stat(fname, &buf);
484         if (ret)
485                 return ret;
486         *size = buf.st_size;
487         return 0;
488 }
489
490 void os_putc(int ch)
491 {
492         putchar(ch);
493 }
494
495 void os_puts(const char *str)
496 {
497         while (*str)
498                 os_putc(*str++);
499 }
500
501 int os_write_ram_buf(const char *fname)
502 {
503         struct sandbox_state *state = state_get_current();
504         int fd, ret;
505
506         fd = open(fname, O_CREAT | O_WRONLY, 0777);
507         if (fd < 0)
508                 return -ENOENT;
509         ret = write(fd, state->ram_buf, state->ram_size);
510         close(fd);
511         if (ret != state->ram_size)
512                 return -EIO;
513
514         return 0;
515 }
516
517 int os_read_ram_buf(const char *fname)
518 {
519         struct sandbox_state *state = state_get_current();
520         int fd, ret;
521         loff_t size;
522
523         ret = os_get_filesize(fname, &size);
524         if (ret < 0)
525                 return ret;
526         if (size != state->ram_size)
527                 return -ENOSPC;
528         fd = open(fname, O_RDONLY);
529         if (fd < 0)
530                 return -ENOENT;
531
532         ret = read(fd, state->ram_buf, state->ram_size);
533         close(fd);
534         if (ret != state->ram_size)
535                 return -EIO;
536
537         return 0;
538 }
539
540 static int make_exec(char *fname, const void *data, int size)
541 {
542         int fd;
543
544         strcpy(fname, "/tmp/u-boot.jump.XXXXXX");
545         fd = mkstemp(fname);
546         if (fd < 0)
547                 return -ENOENT;
548         if (write(fd, data, size) < 0)
549                 return -EIO;
550         close(fd);
551         if (chmod(fname, 0777))
552                 return -ENOEXEC;
553
554         return 0;
555 }
556
557 /**
558  * add_args() - Allocate a new argv with the given args
559  *
560  * This is used to create a new argv array with all the old arguments and some
561  * new ones that are passed in
562  *
563  * @argvp:  Returns newly allocated args list
564  * @add_args: Arguments to add, each a string
565  * @count: Number of arguments in @add_args
566  * @return 0 if OK, -ENOMEM if out of memory
567  */
568 static int add_args(char ***argvp, char *add_args[], int count)
569 {
570         char **argv, **ap;
571         int argc;
572
573         for (argc = 0; (*argvp)[argc]; argc++)
574                 ;
575
576         argv = malloc((argc + count + 1) * sizeof(char *));
577         if (!argv) {
578                 printf("Out of memory for %d argv\n", count);
579                 return -ENOMEM;
580         }
581         for (ap = *argvp, argc = 0; *ap; ap++) {
582                 char *arg = *ap;
583
584                 /* Drop args that we don't want to propagate */
585                 if (*arg == '-' && strlen(arg) == 2) {
586                         switch (arg[1]) {
587                         case 'j':
588                         case 'm':
589                                 ap++;
590                                 continue;
591                         }
592                 } else if (!strcmp(arg, "--rm_memory")) {
593                         ap++;
594                         continue;
595                 }
596                 argv[argc++] = arg;
597         }
598
599         memcpy(argv + argc, add_args, count * sizeof(char *));
600         argv[argc + count] = NULL;
601
602         *argvp = argv;
603         return 0;
604 }
605
606 /**
607  * os_jump_to_file() - Jump to a new program
608  *
609  * This saves the memory buffer, sets up arguments to the new process, then
610  * execs it.
611  *
612  * @fname: Filename to exec
613  * @return does not return on success, any return value is an error
614  */
615 static int os_jump_to_file(const char *fname)
616 {
617         struct sandbox_state *state = state_get_current();
618         char mem_fname[30];
619         int fd, err;
620         char *extra_args[5];
621         char **argv = state->argv;
622         int argc;
623 #ifdef DEBUG
624         int i;
625 #endif
626
627         strcpy(mem_fname, "/tmp/u-boot.mem.XXXXXX");
628         fd = mkstemp(mem_fname);
629         if (fd < 0)
630                 return -ENOENT;
631         close(fd);
632         err = os_write_ram_buf(mem_fname);
633         if (err)
634                 return err;
635
636         os_fd_restore();
637
638         extra_args[0] = "-j";
639         extra_args[1] = (char *)fname;
640         extra_args[2] = "-m";
641         extra_args[3] = mem_fname;
642         argc = 4;
643         if (state->ram_buf_rm)
644                 extra_args[argc++] = "--rm_memory";
645         err = add_args(&argv, extra_args, argc);
646         if (err)
647                 return err;
648         argv[0] = (char *)fname;
649
650 #ifdef DEBUG
651         for (i = 0; argv[i]; i++)
652                 printf("%d %s\n", i, argv[i]);
653 #endif
654
655         if (state_uninit())
656                 os_exit(2);
657
658         err = execv(fname, argv);
659         free(argv);
660         if (err) {
661                 perror("Unable to run image");
662                 printf("Image filename '%s'\n", fname);
663                 return err;
664         }
665
666         return unlink(fname);
667 }
668
669 int os_jump_to_image(const void *dest, int size)
670 {
671         char fname[30];
672         int err;
673
674         err = make_exec(fname, dest, size);
675         if (err)
676                 return err;
677
678         return os_jump_to_file(fname);
679 }
680
681 int os_find_u_boot(char *fname, int maxlen)
682 {
683         struct sandbox_state *state = state_get_current();
684         const char *progname = state->argv[0];
685         int len = strlen(progname);
686         const char *suffix;
687         char *p;
688         int fd;
689
690         if (len >= maxlen || len < 4)
691                 return -ENOSPC;
692
693         strcpy(fname, progname);
694         suffix = fname + len - 4;
695
696         /* If we are TPL, boot to SPL */
697         if (!strcmp(suffix, "-tpl")) {
698                 fname[len - 3] = 's';
699                 fd = os_open(fname, O_RDONLY);
700                 if (fd >= 0) {
701                         close(fd);
702                         return 0;
703                 }
704
705                 /* Look for 'u-boot-tpl' in the tpl/ directory */
706                 p = strstr(fname, "/tpl/");
707                 if (p) {
708                         p[1] = 's';
709                         fd = os_open(fname, O_RDONLY);
710                         if (fd >= 0) {
711                                 close(fd);
712                                 return 0;
713                         }
714                 }
715                 return -ENOENT;
716         }
717
718         /* Look for 'u-boot' in the same directory as 'u-boot-spl' */
719         if (!strcmp(suffix, "-spl")) {
720                 fname[len - 4] = '\0';
721                 fd = os_open(fname, O_RDONLY);
722                 if (fd >= 0) {
723                         close(fd);
724                         return 0;
725                 }
726         }
727
728         /* Look for 'u-boot' in the parent directory of spl/ */
729         p = strstr(fname, "spl/");
730         if (p) {
731                 /* Remove the "spl" characters */
732                 memmove(p, p + 4, strlen(p + 4) + 1);
733                 fd = os_open(fname, O_RDONLY);
734                 if (fd >= 0) {
735                         close(fd);
736                         return 0;
737                 }
738         }
739
740         return -ENOENT;
741 }
742
743 int os_spl_to_uboot(const char *fname)
744 {
745         return os_jump_to_file(fname);
746 }
747
748 void os_localtime(struct rtc_time *rt)
749 {
750         time_t t = time(NULL);
751         struct tm *tm;
752
753         tm = localtime(&t);
754         rt->tm_sec = tm->tm_sec;
755         rt->tm_min = tm->tm_min;
756         rt->tm_hour = tm->tm_hour;
757         rt->tm_mday = tm->tm_mday;
758         rt->tm_mon = tm->tm_mon + 1;
759         rt->tm_year = tm->tm_year + 1900;
760         rt->tm_wday = tm->tm_wday;
761         rt->tm_yday = tm->tm_yday;
762         rt->tm_isdst = tm->tm_isdst;
763 }
764
765 void os_abort(void)
766 {
767         abort();
768 }
769
770 int os_mprotect_allow(void *start, size_t len)
771 {
772         int page_size = getpagesize();
773
774         /* Move start to the start of a page, len to the end */
775         start = (void *)(((ulong)start) & ~(page_size - 1));
776         len = (len + page_size * 2) & ~(page_size - 1);
777
778         return mprotect(start, len, PROT_READ | PROT_WRITE);
779 }
780
781 void *os_find_text_base(void)
782 {
783         char line[500];
784         void *base = NULL;
785         int len;
786         int fd;
787
788         /*
789          * This code assumes that the first line of /proc/self/maps holds
790          * information about the text, for example:
791          *
792          * 5622d9907000-5622d9a55000 r-xp 00000000 08:01 15067168   u-boot
793          *
794          * The first hex value is assumed to be the address.
795          *
796          * This is tested in Linux 4.15.
797          */
798         fd = open("/proc/self/maps", O_RDONLY);
799         if (fd == -1)
800                 return NULL;
801         len = read(fd, line, sizeof(line));
802         if (len > 0) {
803                 char *end = memchr(line, '-', len);
804
805                 if (end) {
806                         uintptr_t addr;
807
808                         *end = '\0';
809                         if (sscanf(line, "%zx", &addr) == 1)
810                                 base = (void *)addr;
811                 }
812         }
813         close(fd);
814
815         return base;
816 }