sandbox: Support file truncation with os_open()
[platform/kernel/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 <stdio.h>
12 #include <stdint.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <termios.h>
16 #include <time.h>
17 #include <unistd.h>
18 #include <sys/mman.h>
19 #include <sys/stat.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <linux/types.h>
23
24 #include <asm/getopt.h>
25 #include <asm/sections.h>
26 #include <asm/state.h>
27 #include <os.h>
28 #include <rtc_def.h>
29
30 /* Operating System Interface */
31
32 struct os_mem_hdr {
33         size_t length;          /* number of bytes in the block */
34 };
35
36 ssize_t os_read(int fd, void *buf, size_t count)
37 {
38         return read(fd, buf, count);
39 }
40
41 ssize_t os_read_no_block(int fd, void *buf, size_t count)
42 {
43         const int flags = fcntl(fd, F_GETFL, 0);
44
45         fcntl(fd, F_SETFL, flags | O_NONBLOCK);
46         return os_read(fd, buf, count);
47 }
48
49 ssize_t os_write(int fd, const void *buf, size_t count)
50 {
51         return write(fd, buf, count);
52 }
53
54 off_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
67 int os_open(const char *pathname, int os_flags)
68 {
69         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;
88         if (os_flags & OS_O_TRUNC)
89                 flags |= O_TRUNC;
90
91         return open(pathname, flags, 0777);
92 }
93
94 int os_close(int fd)
95 {
96         return close(fd);
97 }
98
99 int os_unlink(const char *pathname)
100 {
101         return unlink(pathname);
102 }
103
104 void os_exit(int exit_code)
105 {
106         exit(exit_code);
107 }
108
109 /* Restore tty state when we exit */
110 static struct termios orig_term;
111 static bool term_setup;
112
113 void os_fd_restore(void)
114 {
115         if (term_setup) {
116                 tcsetattr(0, TCSANOW, &orig_term);
117                 term_setup = false;
118         }
119 }
120
121 /* Put tty into raw mode so <tab> and <ctrl+c> work */
122 void os_tty_raw(int fd, bool allow_sigs)
123 {
124         struct termios term;
125
126         if (term_setup)
127                 return;
128
129         /* If not a tty, don't complain */
130         if (tcgetattr(fd, &orig_term))
131                 return;
132
133         term = orig_term;
134         term.c_iflag = IGNBRK | IGNPAR;
135         term.c_oflag = OPOST | ONLCR;
136         term.c_cflag = CS8 | CREAD | CLOCAL;
137         term.c_lflag = allow_sigs ? ISIG : 0;
138         if (tcsetattr(fd, TCSANOW, &term))
139                 return;
140
141         term_setup = true;
142         atexit(os_fd_restore);
143 }
144
145 void *os_malloc(size_t length)
146 {
147         struct os_mem_hdr *hdr;
148         int page_size = getpagesize();
149
150         hdr = mmap(NULL, length + page_size,
151                    PROT_READ | PROT_WRITE | PROT_EXEC,
152                    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
153         if (hdr == MAP_FAILED)
154                 return NULL;
155         hdr->length = length;
156
157         return (void *)hdr + page_size;
158 }
159
160 void os_free(void *ptr)
161 {
162         struct os_mem_hdr *hdr = ptr;
163
164         hdr--;
165         if (ptr)
166                 munmap(hdr, hdr->length + sizeof(*hdr));
167 }
168
169 void *os_realloc(void *ptr, size_t length)
170 {
171         struct os_mem_hdr *hdr = ptr;
172         void *buf = NULL;
173
174         hdr--;
175         if (length != 0) {
176                 buf = os_malloc(length);
177                 if (!buf)
178                         return buf;
179                 if (ptr) {
180                         if (length > hdr->length)
181                                 length = hdr->length;
182                         memcpy(buf, ptr, length);
183                 }
184         }
185         os_free(ptr);
186
187         return buf;
188 }
189
190 void os_usleep(unsigned long usec)
191 {
192         usleep(usec);
193 }
194
195 uint64_t __attribute__((no_instrument_function)) os_get_nsec(void)
196 {
197 #if defined(CLOCK_MONOTONIC) && defined(_POSIX_MONOTONIC_CLOCK)
198         struct timespec tp;
199         if (EINVAL == clock_gettime(CLOCK_MONOTONIC, &tp)) {
200                 struct timeval tv;
201
202                 gettimeofday(&tv, NULL);
203                 tp.tv_sec = tv.tv_sec;
204                 tp.tv_nsec = tv.tv_usec * 1000;
205         }
206         return tp.tv_sec * 1000000000ULL + tp.tv_nsec;
207 #else
208         struct timeval tv;
209         gettimeofday(&tv, NULL);
210         return tv.tv_sec * 1000000000ULL + tv.tv_usec * 1000;
211 #endif
212 }
213
214 static char *short_opts;
215 static struct option *long_opts;
216
217 int os_parse_args(struct sandbox_state *state, int argc, char *argv[])
218 {
219         struct sandbox_cmdline_option **sb_opt = __u_boot_sandbox_option_start;
220         size_t num_options = __u_boot_sandbox_option_count();
221         size_t i;
222
223         int hidden_short_opt;
224         size_t si;
225
226         int c;
227
228         if (short_opts || long_opts)
229                 return 1;
230
231         state->argc = argc;
232         state->argv = argv;
233
234         /* dynamically construct the arguments to the system getopt_long */
235         short_opts = os_malloc(sizeof(*short_opts) * num_options * 2 + 1);
236         long_opts = os_malloc(sizeof(*long_opts) * num_options);
237         if (!short_opts || !long_opts)
238                 return 1;
239
240         /*
241          * getopt_long requires "val" to be unique (since that is what the
242          * func returns), so generate unique values automatically for flags
243          * that don't have a short option.  pick 0x100 as that is above the
244          * single byte range (where ASCII/ISO-XXXX-X charsets live).
245          */
246         hidden_short_opt = 0x100;
247         si = 0;
248         for (i = 0; i < num_options; ++i) {
249                 long_opts[i].name = sb_opt[i]->flag;
250                 long_opts[i].has_arg = sb_opt[i]->has_arg ?
251                         required_argument : no_argument;
252                 long_opts[i].flag = NULL;
253
254                 if (sb_opt[i]->flag_short) {
255                         short_opts[si++] = long_opts[i].val = sb_opt[i]->flag_short;
256                         if (long_opts[i].has_arg == required_argument)
257                                 short_opts[si++] = ':';
258                 } else
259                         long_opts[i].val = sb_opt[i]->flag_short = hidden_short_opt++;
260         }
261         short_opts[si] = '\0';
262
263         /* we need to handle output ourselves since u-boot provides printf */
264         opterr = 0;
265
266         /*
267          * walk all of the options the user gave us on the command line,
268          * figure out what u-boot option structure they belong to (via
269          * the unique short val key), and call the appropriate callback.
270          */
271         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
272                 for (i = 0; i < num_options; ++i) {
273                         if (sb_opt[i]->flag_short == c) {
274                                 if (sb_opt[i]->callback(state, optarg)) {
275                                         state->parse_err = sb_opt[i]->flag;
276                                         return 0;
277                                 }
278                                 break;
279                         }
280                 }
281                 if (i == num_options) {
282                         /*
283                          * store the faulting flag for later display.  we have to
284                          * store the flag itself as the getopt parsing itself is
285                          * tricky: need to handle the following flags (assume all
286                          * of the below are unknown):
287                          *   -a        optopt='a' optind=<next>
288                          *   -abbbb    optopt='a' optind=<this>
289                          *   -aaaaa    optopt='a' optind=<this>
290                          *   --a       optopt=0   optind=<this>
291                          * as you can see, it is impossible to determine the exact
292                          * faulting flag without doing the parsing ourselves, so
293                          * we just report the specific flag that failed.
294                          */
295                         if (optopt) {
296                                 static char parse_err[3] = { '-', 0, '\0', };
297                                 parse_err[1] = optopt;
298                                 state->parse_err = parse_err;
299                         } else
300                                 state->parse_err = argv[optind - 1];
301                         break;
302                 }
303         }
304
305         return 0;
306 }
307
308 void os_dirent_free(struct os_dirent_node *node)
309 {
310         struct os_dirent_node *next;
311
312         while (node) {
313                 next = node->next;
314                 free(node);
315                 node = next;
316         }
317 }
318
319 int os_dirent_ls(const char *dirname, struct os_dirent_node **headp)
320 {
321         struct dirent *entry;
322         struct os_dirent_node *head, *node, *next;
323         struct stat buf;
324         DIR *dir;
325         int ret;
326         char *fname;
327         char *old_fname;
328         int len;
329         int dirlen;
330
331         *headp = NULL;
332         dir = opendir(dirname);
333         if (!dir)
334                 return -1;
335
336         /* Create a buffer upfront, with typically sufficient size */
337         dirlen = strlen(dirname) + 2;
338         len = dirlen + 256;
339         fname = malloc(len);
340         if (!fname) {
341                 ret = -ENOMEM;
342                 goto done;
343         }
344
345         for (node = head = NULL;; node = next) {
346                 errno = 0;
347                 entry = readdir(dir);
348                 if (!entry) {
349                         ret = errno;
350                         break;
351                 }
352                 next = malloc(sizeof(*node) + strlen(entry->d_name) + 1);
353                 if (!next) {
354                         os_dirent_free(head);
355                         ret = -ENOMEM;
356                         goto done;
357                 }
358                 if (dirlen + strlen(entry->d_name) > len) {
359                         len = dirlen + strlen(entry->d_name);
360                         old_fname = fname;
361                         fname = realloc(fname, len);
362                         if (!fname) {
363                                 free(old_fname);
364                                 free(next);
365                                 os_dirent_free(head);
366                                 ret = -ENOMEM;
367                                 goto done;
368                         }
369                 }
370                 next->next = NULL;
371                 strcpy(next->name, entry->d_name);
372                 switch (entry->d_type) {
373                 case DT_REG:
374                         next->type = OS_FILET_REG;
375                         break;
376                 case DT_DIR:
377                         next->type = OS_FILET_DIR;
378                         break;
379                 case DT_LNK:
380                         next->type = OS_FILET_LNK;
381                         break;
382                 default:
383                         next->type = OS_FILET_UNKNOWN;
384                 }
385                 next->size = 0;
386                 snprintf(fname, len, "%s/%s", dirname, next->name);
387                 if (!stat(fname, &buf))
388                         next->size = buf.st_size;
389                 if (node)
390                         node->next = next;
391                 else
392                         head = next;
393         }
394         *headp = head;
395
396 done:
397         closedir(dir);
398         free(fname);
399         return ret;
400 }
401
402 const char *os_dirent_typename[OS_FILET_COUNT] = {
403         "   ",
404         "SYM",
405         "DIR",
406         "???",
407 };
408
409 const char *os_dirent_get_typename(enum os_dirent_t type)
410 {
411         if (type >= OS_FILET_REG && type < OS_FILET_COUNT)
412                 return os_dirent_typename[type];
413
414         return os_dirent_typename[OS_FILET_UNKNOWN];
415 }
416
417 int os_get_filesize(const char *fname, loff_t *size)
418 {
419         struct stat buf;
420         int ret;
421
422         ret = stat(fname, &buf);
423         if (ret)
424                 return ret;
425         *size = buf.st_size;
426         return 0;
427 }
428
429 void os_putc(int ch)
430 {
431         putchar(ch);
432 }
433
434 void os_puts(const char *str)
435 {
436         while (*str)
437                 os_putc(*str++);
438 }
439
440 int os_write_ram_buf(const char *fname)
441 {
442         struct sandbox_state *state = state_get_current();
443         int fd, ret;
444
445         fd = open(fname, O_CREAT | O_WRONLY, 0777);
446         if (fd < 0)
447                 return -ENOENT;
448         ret = write(fd, state->ram_buf, state->ram_size);
449         close(fd);
450         if (ret != state->ram_size)
451                 return -EIO;
452
453         return 0;
454 }
455
456 int os_read_ram_buf(const char *fname)
457 {
458         struct sandbox_state *state = state_get_current();
459         int fd, ret;
460         loff_t size;
461
462         ret = os_get_filesize(fname, &size);
463         if (ret < 0)
464                 return ret;
465         if (size != state->ram_size)
466                 return -ENOSPC;
467         fd = open(fname, O_RDONLY);
468         if (fd < 0)
469                 return -ENOENT;
470
471         ret = read(fd, state->ram_buf, state->ram_size);
472         close(fd);
473         if (ret != state->ram_size)
474                 return -EIO;
475
476         return 0;
477 }
478
479 static int make_exec(char *fname, const void *data, int size)
480 {
481         int fd;
482
483         strcpy(fname, "/tmp/u-boot.jump.XXXXXX");
484         fd = mkstemp(fname);
485         if (fd < 0)
486                 return -ENOENT;
487         if (write(fd, data, size) < 0)
488                 return -EIO;
489         close(fd);
490         if (chmod(fname, 0777))
491                 return -ENOEXEC;
492
493         return 0;
494 }
495
496 static int add_args(char ***argvp, const char *add_args[], int count)
497 {
498         char **argv;
499         int argc;
500
501         for (argv = *argvp, argc = 0; (*argvp)[argc]; argc++)
502                 ;
503
504         argv = malloc((argc + count + 1) * sizeof(char *));
505         if (!argv) {
506                 printf("Out of memory for %d argv\n", count);
507                 return -ENOMEM;
508         }
509         memcpy(argv, *argvp, argc * sizeof(char *));
510         memcpy(argv + argc, add_args, count * sizeof(char *));
511         argv[argc + count] = NULL;
512
513         *argvp = argv;
514         return 0;
515 }
516
517 int os_jump_to_image(const void *dest, int size)
518 {
519         struct sandbox_state *state = state_get_current();
520         char fname[30], mem_fname[30];
521         int fd, err;
522         const char *extra_args[5];
523         char **argv = state->argv;
524 #ifdef DEBUG
525         int argc, i;
526 #endif
527
528         err = make_exec(fname, dest, size);
529         if (err)
530                 return err;
531
532         strcpy(mem_fname, "/tmp/u-boot.mem.XXXXXX");
533         fd = mkstemp(mem_fname);
534         if (fd < 0)
535                 return -ENOENT;
536         close(fd);
537         err = os_write_ram_buf(mem_fname);
538         if (err)
539                 return err;
540
541         os_fd_restore();
542
543         extra_args[0] = "-j";
544         extra_args[1] = fname;
545         extra_args[2] = "-m";
546         extra_args[3] = mem_fname;
547         extra_args[4] = "--rm_memory";
548         err = add_args(&argv, extra_args,
549                        sizeof(extra_args) / sizeof(extra_args[0]));
550         if (err)
551                 return err;
552
553 #ifdef DEBUG
554         for (i = 0; argv[i]; i++)
555                 printf("%d %s\n", i, argv[i]);
556 #endif
557
558         if (state_uninit())
559                 os_exit(2);
560
561         err = execv(fname, argv);
562         free(argv);
563         if (err)
564                 return err;
565
566         return unlink(fname);
567 }
568
569 int os_find_u_boot(char *fname, int maxlen)
570 {
571         struct sandbox_state *state = state_get_current();
572         const char *progname = state->argv[0];
573         int len = strlen(progname);
574         char *p;
575         int fd;
576
577         if (len >= maxlen || len < 4)
578                 return -ENOSPC;
579
580         /* Look for 'u-boot' in the same directory as 'u-boot-spl' */
581         strcpy(fname, progname);
582         if (!strcmp(fname + len - 4, "-spl")) {
583                 fname[len - 4] = '\0';
584                 fd = os_open(fname, O_RDONLY);
585                 if (fd >= 0) {
586                         close(fd);
587                         return 0;
588                 }
589         }
590
591         /* Look for 'u-boot' in the parent directory of spl/ */
592         p = strstr(fname, "/spl/");
593         if (p) {
594                 strcpy(p, p + 4);
595                 fd = os_open(fname, O_RDONLY);
596                 if (fd >= 0) {
597                         close(fd);
598                         return 0;
599                 }
600         }
601
602         return -ENOENT;
603 }
604
605 int os_spl_to_uboot(const char *fname)
606 {
607         struct sandbox_state *state = state_get_current();
608         char *argv[state->argc + 1];
609         int ret;
610
611         memcpy(argv, state->argv, sizeof(char *) * (state->argc + 1));
612         argv[0] = (char *)fname;
613         ret = execv(fname, argv);
614         if (ret)
615                 return ret;
616
617         return unlink(fname);
618 }
619
620 void os_localtime(struct rtc_time *rt)
621 {
622         time_t t = time(NULL);
623         struct tm *tm;
624
625         tm = localtime(&t);
626         rt->tm_sec = tm->tm_sec;
627         rt->tm_min = tm->tm_min;
628         rt->tm_hour = tm->tm_hour;
629         rt->tm_mday = tm->tm_mday;
630         rt->tm_mon = tm->tm_mon + 1;
631         rt->tm_year = tm->tm_year + 1900;
632         rt->tm_wday = tm->tm_wday;
633         rt->tm_yday = tm->tm_yday;
634         rt->tm_isdst = tm->tm_isdst;
635 }
636
637 void os_abort(void)
638 {
639         abort();
640 }
641
642 int os_mprotect_allow(void *start, size_t len)
643 {
644         int page_size = getpagesize();
645
646         /* Move start to the start of a page, len to the end */
647         start = (void *)(((ulong)start) & ~(page_size - 1));
648         len = (len + page_size * 2) & ~(page_size - 1);
649
650         return mprotect(start, len, PROT_READ | PROT_WRITE);
651 }