1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (c) 2011 The Chromium OS Authors.
4  */
5 
6 #define _GNU_SOURCE
7 
8 #include <dirent.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <pthread.h>
12 #include <getopt.h>
13 #include <setjmp.h>
14 #include <signal.h>
15 #include <stdarg.h>
16 #include <stdio.h>
17 #include <stdint.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <termios.h>
21 #include <time.h>
22 #include <ucontext.h>
23 #include <unistd.h>
24 #include <sys/mman.h>
25 #include <sys/stat.h>
26 #include <sys/time.h>
27 #include <sys/types.h>
28 #include <linux/compiler_attributes.h>
29 #include <linux/types.h>
30 
31 #include <asm/fuzzing_engine.h>
32 #include <asm/getopt.h>
33 #include <asm/main.h>
34 #include <asm/sections.h>
35 #include <asm/state.h>
36 #include <os.h>
37 #include <rtc_def.h>
38 
39 /* Environment variable for time offset */
40 #define ENV_TIME_OFFSET "UBOOT_SB_TIME_OFFSET"
41 
42 /* Operating System Interface */
43 
44 struct os_mem_hdr {
45 	size_t length;		/* number of bytes in the block */
46 };
47 
os_read(int fd,void * buf,size_t count)48 ssize_t os_read(int fd, void *buf, size_t count)
49 {
50 	ssize_t ret;
51 
52 	ret = read(fd, buf, count);
53 	if (ret == -1)
54 		return -errno;
55 
56 	return ret;
57 }
58 
os_write(int fd,const void * buf,size_t count)59 ssize_t os_write(int fd, const void *buf, size_t count)
60 {
61 	ssize_t ret;
62 
63 	ret = write(fd, buf, count);
64 	if (ret == -1)
65 		return -errno;
66 
67 	return ret;
68 }
69 
os_printf(const char * fmt,...)70 int os_printf(const char *fmt, ...)
71 {
72 	va_list args;
73 	int i;
74 
75 	va_start(args, fmt);
76 	i = vfprintf(stdout, fmt, args);
77 	va_end(args);
78 
79 	return i;
80 }
81 
os_lseek(int fd,off_t offset,int whence)82 off_t os_lseek(int fd, off_t offset, int whence)
83 {
84 	off_t ret;
85 
86 	if (whence == OS_SEEK_SET)
87 		whence = SEEK_SET;
88 	else if (whence == OS_SEEK_CUR)
89 		whence = SEEK_CUR;
90 	else if (whence == OS_SEEK_END)
91 		whence = SEEK_END;
92 	else
93 		os_exit(1);
94 	ret = lseek(fd, offset, whence);
95 	if (ret == -1)
96 		return -errno;
97 
98 	return ret;
99 }
100 
os_open(const char * pathname,int os_flags)101 int os_open(const char *pathname, int os_flags)
102 {
103 	int flags;
104 
105 	switch (os_flags & OS_O_MASK) {
106 	case OS_O_RDONLY:
107 	default:
108 		flags = O_RDONLY;
109 		break;
110 
111 	case OS_O_WRONLY:
112 		flags = O_WRONLY;
113 		break;
114 
115 	case OS_O_RDWR:
116 		flags = O_RDWR;
117 		break;
118 	}
119 
120 	if (os_flags & OS_O_CREAT)
121 		flags |= O_CREAT;
122 	if (os_flags & OS_O_TRUNC)
123 		flags |= O_TRUNC;
124 	/*
125 	 * During a cold reset execv() is used to relaunch the U-Boot binary.
126 	 * We must ensure that all files are closed in this case.
127 	 */
128 	flags |= O_CLOEXEC;
129 
130 	return open(pathname, flags, 0644);
131 }
132 
os_close(int fd)133 int os_close(int fd)
134 {
135 	/* Do not close the console input */
136 	if (fd)
137 		return close(fd);
138 	return -1;
139 }
140 
os_unlink(const char * pathname)141 int os_unlink(const char *pathname)
142 {
143 	return unlink(pathname);
144 }
145 
os_exit(int exit_code)146 void os_exit(int exit_code)
147 {
148 	exit(exit_code);
149 }
150 
os_alarm(unsigned int seconds)151 unsigned int os_alarm(unsigned int seconds)
152 {
153 	return alarm(seconds);
154 }
155 
os_set_alarm_handler(void (* handler)(int))156 void os_set_alarm_handler(void (*handler)(int))
157 {
158 	if (!handler)
159 		handler = SIG_DFL;
160 	signal(SIGALRM, handler);
161 }
162 
os_raise_sigalrm(void)163 void os_raise_sigalrm(void)
164 {
165 	raise(SIGALRM);
166 }
167 
os_write_file(const char * fname,const void * buf,int size)168 int os_write_file(const char *fname, const void *buf, int size)
169 {
170 	int fd;
171 
172 	fd = os_open(fname, OS_O_WRONLY | OS_O_CREAT | OS_O_TRUNC);
173 	if (fd < 0) {
174 		printf("Cannot open file '%s'\n", fname);
175 		return -EIO;
176 	}
177 	if (os_write(fd, buf, size) != size) {
178 		printf("Cannot write to file '%s'\n", fname);
179 		os_close(fd);
180 		return -EIO;
181 	}
182 	os_close(fd);
183 
184 	return 0;
185 }
186 
os_filesize(int fd)187 off_t os_filesize(int fd)
188 {
189 	off_t size;
190 
191 	size = os_lseek(fd, 0, OS_SEEK_END);
192 	if (size < 0)
193 		return -errno;
194 	if (os_lseek(fd, 0, OS_SEEK_SET) < 0)
195 		return -errno;
196 
197 	return size;
198 }
199 
os_read_file(const char * fname,void ** bufp,int * sizep)200 int os_read_file(const char *fname, void **bufp, int *sizep)
201 {
202 	off_t size;
203 	int ret = -EIO;
204 	int fd;
205 
206 	fd = os_open(fname, OS_O_RDONLY);
207 	if (fd < 0) {
208 		printf("Cannot open file '%s'\n", fname);
209 		return -EIO;
210 	}
211 	size = os_filesize(fd);
212 	if (size < 0) {
213 		printf("Cannot get file size of '%s'\n", fname);
214 		goto err;
215 	}
216 
217 	*bufp = os_malloc(size);
218 	if (!*bufp) {
219 		printf("Not enough memory to read file '%s'\n", fname);
220 		ret = -ENOMEM;
221 		goto err;
222 	}
223 	if (os_read(fd, *bufp, size) != size) {
224 		printf("Cannot read from file '%s'\n", fname);
225 		goto err;
226 	}
227 	os_close(fd);
228 	*sizep = size;
229 
230 	return 0;
231 err:
232 	os_close(fd);
233 	return ret;
234 }
235 
os_map_file(const char * pathname,int os_flags,void ** bufp,int * sizep)236 int os_map_file(const char *pathname, int os_flags, void **bufp, int *sizep)
237 {
238 	void *ptr;
239 	off_t size;
240 	int ifd, ret = 0;
241 
242 	ifd = os_open(pathname, os_flags);
243 	if (ifd < 0) {
244 		printf("Cannot open file '%s'\n", pathname);
245 		return -EIO;
246 	}
247 	size = os_filesize(ifd);
248 	if (size < 0) {
249 		printf("Cannot get file size of '%s'\n", pathname);
250 		ret = -EIO;
251 		goto out;
252 	}
253 	if ((unsigned long long)size > (unsigned long long)SIZE_MAX) {
254 		printf("File '%s' too large to map\n", pathname);
255 		ret = -EIO;
256 		goto out;
257 	}
258 
259 	ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, ifd, 0);
260 	if (ptr == MAP_FAILED) {
261 		printf("Can't map file '%s': %s\n", pathname, strerror(errno));
262 		ret = -EPERM;
263 		goto out;
264 	}
265 
266 	*bufp = ptr;
267 	*sizep = size;
268 
269 out:
270 	os_close(ifd);
271 	return ret;
272 }
273 
os_unmap(void * buf,int size)274 int os_unmap(void *buf, int size)
275 {
276 	if (munmap(buf, size)) {
277 		printf("Can't unmap %p %x\n", buf, size);
278 		return -EIO;
279 	}
280 
281 	return 0;
282 }
283 
os_persistent_file(char * buf,int maxsize,const char * fname)284 int os_persistent_file(char *buf, int maxsize, const char *fname)
285 {
286 	const char *dirname = getenv("U_BOOT_PERSISTENT_DATA_DIR");
287 	char *ptr;
288 	int len;
289 
290 	len = strlen(fname) + (dirname ? strlen(dirname) + 1 : 0) + 1;
291 	if (len > maxsize)
292 		return -ENOSPC;
293 
294 	ptr = buf;
295 	if (dirname) {
296 		strcpy(ptr, dirname);
297 		ptr += strlen(dirname);
298 		*ptr++ = '/';
299 	}
300 	strcpy(ptr, fname);
301 
302 	if (access(buf, F_OK) == -1)
303 		return -ENOENT;
304 
305 	return 0;
306 }
307 
os_mktemp(char * fname,off_t size)308 int os_mktemp(char *fname, off_t size)
309 {
310 	int fd;
311 
312 	fd = mkostemp(fname, O_CLOEXEC);
313 	if (fd < 0)
314 		return -errno;
315 
316 	if (unlink(fname) < 0)
317 		return -errno;
318 
319 	if (ftruncate(fd, size))
320 		return -errno;
321 
322 	return fd;
323 }
324 
325 /* Restore tty state when we exit */
326 static struct termios orig_term;
327 static bool term_setup;
328 static bool term_nonblock;
329 
os_fd_restore(void)330 void os_fd_restore(void)
331 {
332 	if (term_setup) {
333 		int flags;
334 
335 		tcsetattr(0, TCSANOW, &orig_term);
336 		if (term_nonblock) {
337 			flags = fcntl(0, F_GETFL, 0);
338 			fcntl(0, F_SETFL, flags & ~O_NONBLOCK);
339 		}
340 		term_setup = false;
341 	}
342 }
343 
os_sigint_handler(int sig)344 static void os_sigint_handler(int sig)
345 {
346 	os_fd_restore();
347 	signal(SIGINT, SIG_DFL);
348 	raise(SIGINT);
349 }
350 
os_signal_handler(int sig,siginfo_t * info,void * con)351 static void os_signal_handler(int sig, siginfo_t *info, void *con)
352 {
353 	ucontext_t __maybe_unused *context = con;
354 	unsigned long pc;
355 
356 #if defined(__x86_64__)
357 	pc = context->uc_mcontext.gregs[REG_RIP];
358 #elif defined(__aarch64__)
359 	pc = context->uc_mcontext.pc;
360 #elif defined(__riscv)
361 	pc = context->uc_mcontext.__gregs[REG_PC];
362 #else
363 	const char msg[] =
364 		"\nUnsupported architecture, cannot read program counter\n";
365 
366 	os_write(1, msg, sizeof(msg));
367 	pc = 0;
368 #endif
369 
370 	os_signal_action(sig, pc);
371 }
372 
os_setup_signal_handlers(void)373 int os_setup_signal_handlers(void)
374 {
375 	struct sigaction act;
376 
377 	act.sa_sigaction = os_signal_handler;
378 	sigemptyset(&act.sa_mask);
379 	act.sa_flags = SA_SIGINFO;
380 	if (sigaction(SIGILL, &act, NULL) ||
381 	    sigaction(SIGBUS, &act, NULL) ||
382 	    sigaction(SIGSEGV, &act, NULL))
383 		return -1;
384 	return 0;
385 }
386 
387 /* Put tty into raw mode so <tab> and <ctrl+c> work */
os_tty_raw(int fd,bool allow_sigs)388 void os_tty_raw(int fd, bool allow_sigs)
389 {
390 	struct termios term;
391 	int flags;
392 
393 	if (term_setup)
394 		return;
395 
396 	/* If not a tty, don't complain */
397 	if (tcgetattr(fd, &orig_term))
398 		return;
399 
400 	term = orig_term;
401 	term.c_iflag = IGNBRK | IGNPAR;
402 	term.c_oflag = OPOST | ONLCR;
403 	term.c_cflag = CS8 | CREAD | CLOCAL;
404 	term.c_lflag = allow_sigs ? ISIG : 0;
405 	if (tcsetattr(fd, TCSANOW, &term))
406 		return;
407 
408 	flags = fcntl(fd, F_GETFL, 0);
409 	if (!(flags & O_NONBLOCK)) {
410 		if (fcntl(fd, F_SETFL, flags | O_NONBLOCK))
411 			return;
412 		term_nonblock = true;
413 	}
414 
415 	term_setup = true;
416 	atexit(os_fd_restore);
417 	signal(SIGINT, os_sigint_handler);
418 }
419 
420 /*
421  * Provide our own malloc so we don't use space in the sandbox ram_buf for
422  * allocations that are internal to sandbox, or need to be done before U-Boot's
423  * malloc() is ready.
424  */
os_malloc(size_t length)425 void *os_malloc(size_t length)
426 {
427 	int page_size = getpagesize();
428 	struct os_mem_hdr *hdr;
429 
430 	if (!length)
431 		return NULL;
432 	/*
433 	 * Use an address that is hopefully available to us so that pointers
434 	 * to this memory are fairly obvious. If we end up with a different
435 	 * address, that's fine too.
436 	 */
437 	hdr = mmap((void *)0x10000000, length + page_size,
438 		   PROT_READ | PROT_WRITE | PROT_EXEC,
439 		   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
440 	if (hdr == MAP_FAILED)
441 		return NULL;
442 	hdr->length = length;
443 
444 	return (void *)hdr + page_size;
445 }
446 
os_free(void * ptr)447 void os_free(void *ptr)
448 {
449 	int page_size = getpagesize();
450 	struct os_mem_hdr *hdr;
451 
452 	if (ptr) {
453 		hdr = ptr - page_size;
454 		munmap(hdr, hdr->length + page_size);
455 	}
456 }
457 
458 /* These macros are from kernel.h but not accessible in this file */
459 #define ALIGN(x, a)		__ALIGN_MASK((x), (typeof(x))(a) - 1)
460 #define __ALIGN_MASK(x, mask)	(((x) + (mask)) & ~(mask))
461 
462 /*
463  * Provide our own malloc so we don't use space in the sandbox ram_buf for
464  * allocations that are internal to sandbox, or need to be done before U-Boot's
465  * malloc() is ready.
466  */
os_realloc(void * ptr,size_t length)467 void *os_realloc(void *ptr, size_t length)
468 {
469 	int page_size = getpagesize();
470 	struct os_mem_hdr *hdr;
471 	void *new_ptr;
472 
473 	/* Reallocating a NULL pointer is just an alloc */
474 	if (!ptr)
475 		return os_malloc(length);
476 
477 	/* Changing a length to 0 is just a free */
478 	if (length) {
479 		os_free(ptr);
480 		return NULL;
481 	}
482 
483 	/*
484 	 * If the new size is the same number of pages as the old, nothing to
485 	 * do. There isn't much point in shrinking things
486 	 */
487 	hdr = ptr - page_size;
488 	if (ALIGN(length, page_size) <= ALIGN(hdr->length, page_size))
489 		return ptr;
490 
491 	/* We have to grow it, so allocate something new */
492 	new_ptr = os_malloc(length);
493 	memcpy(new_ptr, ptr, hdr->length);
494 	os_free(ptr);
495 
496 	return new_ptr;
497 }
498 
os_usleep(unsigned long usec)499 void os_usleep(unsigned long usec)
500 {
501 	usleep(usec);
502 }
503 
os_get_nsec(void)504 uint64_t __attribute__((no_instrument_function)) os_get_nsec(void)
505 {
506 #if defined(CLOCK_MONOTONIC) && defined(_POSIX_MONOTONIC_CLOCK)
507 	struct timespec tp;
508 	if (EINVAL == clock_gettime(CLOCK_MONOTONIC, &tp)) {
509 		struct timeval tv;
510 
511 		gettimeofday(&tv, NULL);
512 		tp.tv_sec = tv.tv_sec;
513 		tp.tv_nsec = tv.tv_usec * 1000;
514 	}
515 	return tp.tv_sec * 1000000000ULL + tp.tv_nsec;
516 #else
517 	struct timeval tv;
518 	gettimeofday(&tv, NULL);
519 	return tv.tv_sec * 1000000000ULL + tv.tv_usec * 1000;
520 #endif
521 }
522 
523 static char *short_opts;
524 static struct option *long_opts;
525 
os_parse_args(struct sandbox_state * state,int argc,char * argv[])526 int os_parse_args(struct sandbox_state *state, int argc, char *argv[])
527 {
528 	struct sandbox_cmdline_option **sb_opt =
529 		__u_boot_sandbox_option_start();
530 	size_t num_options = __u_boot_sandbox_option_count();
531 	size_t i;
532 
533 	int hidden_short_opt;
534 	size_t si;
535 
536 	int c;
537 
538 	if (short_opts || long_opts)
539 		return 1;
540 
541 	state->argc = argc;
542 	state->argv = argv;
543 
544 	/* dynamically construct the arguments to the system getopt_long */
545 	short_opts = os_malloc(sizeof(*short_opts) * num_options * 2 + 1);
546 	long_opts = os_malloc(sizeof(*long_opts) * (num_options + 1));
547 	if (!short_opts || !long_opts)
548 		return 1;
549 
550 	/*
551 	 * getopt_long requires "val" to be unique (since that is what the
552 	 * func returns), so generate unique values automatically for flags
553 	 * that don't have a short option.  pick 0x100 as that is above the
554 	 * single byte range (where ASCII/ISO-XXXX-X charsets live).
555 	 */
556 	hidden_short_opt = 0x100;
557 	si = 0;
558 	for (i = 0; i < num_options; ++i) {
559 		long_opts[i].name = sb_opt[i]->flag;
560 		long_opts[i].has_arg = sb_opt[i]->has_arg ?
561 			required_argument : no_argument;
562 		long_opts[i].flag = NULL;
563 
564 		if (sb_opt[i]->flag_short) {
565 			short_opts[si++] = long_opts[i].val = sb_opt[i]->flag_short;
566 			if (long_opts[i].has_arg == required_argument)
567 				short_opts[si++] = ':';
568 		} else
569 			long_opts[i].val = sb_opt[i]->flag_short = hidden_short_opt++;
570 	}
571 	short_opts[si] = '\0';
572 
573 	/* we need to handle output ourselves since u-boot provides printf */
574 	opterr = 0;
575 
576 	memset(&long_opts[num_options], '\0', sizeof(*long_opts));
577 	/*
578 	 * walk all of the options the user gave us on the command line,
579 	 * figure out what u-boot option structure they belong to (via
580 	 * the unique short val key), and call the appropriate callback.
581 	 */
582 	while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
583 		for (i = 0; i < num_options; ++i) {
584 			if (sb_opt[i]->flag_short == c) {
585 				if (sb_opt[i]->callback(state, optarg)) {
586 					state->parse_err = sb_opt[i]->flag;
587 					return 0;
588 				}
589 				break;
590 			}
591 		}
592 		if (i == num_options) {
593 			/*
594 			 * store the faulting flag for later display.  we have to
595 			 * store the flag itself as the getopt parsing itself is
596 			 * tricky: need to handle the following flags (assume all
597 			 * of the below are unknown):
598 			 *   -a        optopt='a' optind=<next>
599 			 *   -abbbb    optopt='a' optind=<this>
600 			 *   -aaaaa    optopt='a' optind=<this>
601 			 *   --a       optopt=0   optind=<this>
602 			 * as you can see, it is impossible to determine the exact
603 			 * faulting flag without doing the parsing ourselves, so
604 			 * we just report the specific flag that failed.
605 			 */
606 			if (optopt) {
607 				static char parse_err[3] = { '-', 0, '\0', };
608 				parse_err[1] = optopt;
609 				state->parse_err = parse_err;
610 			} else
611 				state->parse_err = argv[optind - 1];
612 			break;
613 		}
614 	}
615 
616 	return 0;
617 }
618 
os_dirent_free(struct os_dirent_node * node)619 void os_dirent_free(struct os_dirent_node *node)
620 {
621 	struct os_dirent_node *next;
622 
623 	while (node) {
624 		next = node->next;
625 		os_free(node);
626 		node = next;
627 	}
628 }
629 
os_dirent_ls(const char * dirname,struct os_dirent_node ** headp)630 int os_dirent_ls(const char *dirname, struct os_dirent_node **headp)
631 {
632 	struct dirent *entry;
633 	struct os_dirent_node *head, *node, *next;
634 	struct stat buf;
635 	DIR *dir;
636 	int ret;
637 	char *fname;
638 	char *old_fname;
639 	int len;
640 	int dirlen;
641 
642 	*headp = NULL;
643 	dir = opendir(dirname);
644 	if (!dir)
645 		return -1;
646 
647 	/* Create a buffer upfront, with typically sufficient size */
648 	dirlen = strlen(dirname) + 2;
649 	len = dirlen + 256;
650 	fname = os_malloc(len);
651 	if (!fname) {
652 		ret = -ENOMEM;
653 		goto done;
654 	}
655 
656 	for (node = head = NULL;; node = next) {
657 		errno = 0;
658 		entry = readdir(dir);
659 		if (!entry) {
660 			ret = errno;
661 			break;
662 		}
663 		next = os_malloc(sizeof(*node) + strlen(entry->d_name) + 1);
664 		if (!next) {
665 			os_dirent_free(head);
666 			ret = -ENOMEM;
667 			goto done;
668 		}
669 		if (dirlen + strlen(entry->d_name) > len) {
670 			len = dirlen + strlen(entry->d_name);
671 			old_fname = fname;
672 			fname = os_realloc(fname, len);
673 			if (!fname) {
674 				os_free(old_fname);
675 				os_free(next);
676 				os_dirent_free(head);
677 				ret = -ENOMEM;
678 				goto done;
679 			}
680 		}
681 		next->next = NULL;
682 		strcpy(next->name, entry->d_name);
683 		switch (entry->d_type) {
684 		case DT_REG:
685 			next->type = OS_FILET_REG;
686 			break;
687 		case DT_DIR:
688 			next->type = OS_FILET_DIR;
689 			break;
690 		case DT_LNK:
691 			next->type = OS_FILET_LNK;
692 			break;
693 		default:
694 			next->type = OS_FILET_UNKNOWN;
695 		}
696 		next->size = 0;
697 		snprintf(fname, len, "%s/%s", dirname, next->name);
698 		if (!stat(fname, &buf))
699 			next->size = buf.st_size;
700 		if (node)
701 			node->next = next;
702 		else
703 			head = next;
704 	}
705 	*headp = head;
706 
707 done:
708 	closedir(dir);
709 	os_free(fname);
710 	return ret;
711 }
712 
713 const char *os_dirent_typename[OS_FILET_COUNT] = {
714 	"   ",
715 	"SYM",
716 	"DIR",
717 	"???",
718 };
719 
os_dirent_get_typename(enum os_dirent_t type)720 const char *os_dirent_get_typename(enum os_dirent_t type)
721 {
722 	if (type >= OS_FILET_REG && type < OS_FILET_COUNT)
723 		return os_dirent_typename[type];
724 
725 	return os_dirent_typename[OS_FILET_UNKNOWN];
726 }
727 
728 /*
729  * For compatibility reasons avoid loff_t here.
730  * U-Boot defines loff_t as long long.
731  * But /usr/include/linux/types.h may not define it at all.
732  * Alpine Linux being one example.
733  */
os_get_filesize(const char * fname,long long * size)734 int os_get_filesize(const char *fname, long long *size)
735 {
736 	struct stat buf;
737 	int ret;
738 
739 	ret = stat(fname, &buf);
740 	if (ret)
741 		return ret;
742 	*size = buf.st_size;
743 	return 0;
744 }
745 
os_putc(int ch)746 void os_putc(int ch)
747 {
748 	os_write(1, &ch, 1);
749 }
750 
os_puts(const char * str)751 void os_puts(const char *str)
752 {
753 	while (*str)
754 		os_putc(*str++);
755 }
756 
os_flush(void)757 void os_flush(void)
758 {
759 	fflush(stdout);
760 }
761 
os_write_ram_buf(const char * fname)762 int os_write_ram_buf(const char *fname)
763 {
764 	struct sandbox_state *state = state_get_current();
765 	int fd, ret;
766 
767 	fd = open(fname, O_CREAT | O_WRONLY, 0644);
768 	if (fd < 0)
769 		return -ENOENT;
770 	ret = write(fd, state->ram_buf, state->ram_size);
771 	close(fd);
772 	if (ret != state->ram_size)
773 		return -EIO;
774 
775 	return 0;
776 }
777 
os_read_ram_buf(const char * fname)778 int os_read_ram_buf(const char *fname)
779 {
780 	struct sandbox_state *state = state_get_current();
781 	int fd, ret;
782 	long long size;
783 
784 	ret = os_get_filesize(fname, &size);
785 	if (ret < 0)
786 		return ret;
787 	if (size != state->ram_size)
788 		return -ENOSPC;
789 	fd = open(fname, O_RDONLY);
790 	if (fd < 0)
791 		return -ENOENT;
792 
793 	ret = read(fd, state->ram_buf, state->ram_size);
794 	close(fd);
795 	if (ret != state->ram_size)
796 		return -EIO;
797 
798 	return 0;
799 }
800 
make_exec(char * fname,const void * data,int size)801 static int make_exec(char *fname, const void *data, int size)
802 {
803 	int fd;
804 
805 	strcpy(fname, "/tmp/u-boot.jump.XXXXXX");
806 	fd = mkstemp(fname);
807 	if (fd < 0)
808 		return -ENOENT;
809 	if (write(fd, data, size) < 0)
810 		return -EIO;
811 	close(fd);
812 	if (chmod(fname, 0755))
813 		return -ENOEXEC;
814 
815 	return 0;
816 }
817 
818 /**
819  * add_args() - Allocate a new argv with the given args
820  *
821  * This is used to create a new argv array with all the old arguments and some
822  * new ones that are passed in
823  *
824  * @argvp:  Returns newly allocated args list
825  * @add_args: Arguments to add, each a string
826  * @count: Number of arguments in @add_args
827  * Return: 0 if OK, -ENOMEM if out of memory
828  */
add_args(char *** argvp,const char * add_args[],int count)829 static int add_args(char ***argvp, const char *add_args[], int count)
830 {
831 	char **argv, **ap;
832 	int argc;
833 
834 	for (argc = 0; (*argvp)[argc]; argc++)
835 		;
836 
837 	argv = os_malloc((argc + count + 1) * sizeof(char *));
838 	if (!argv) {
839 		printf("Out of memory for %d argv\n", count);
840 		return -ENOMEM;
841 	}
842 	for (ap = *argvp, argc = 0; *ap; ap++) {
843 		char *arg = *ap;
844 
845 		/* Drop args that we don't want to propagate */
846 		if (*arg == '-' && strlen(arg) == 2) {
847 			switch (arg[1]) {
848 			case 'j':
849 			case 'm':
850 				ap++;
851 				continue;
852 			}
853 		} else if (!strcmp(arg, "--rm_memory")) {
854 			continue;
855 		}
856 		argv[argc++] = arg;
857 	}
858 
859 	memcpy(argv + argc, add_args, count * sizeof(char *));
860 	argv[argc + count] = NULL;
861 
862 	*argvp = argv;
863 	return 0;
864 }
865 
866 /**
867  * os_jump_to_file() - Jump to a new program
868  *
869  * This saves the memory buffer, sets up arguments to the new process, then
870  * execs it.
871  *
872  * @fname: Filename to exec
873  * Return: does not return on success, any return value is an error
874  */
os_jump_to_file(const char * fname,bool delete_it)875 static int os_jump_to_file(const char *fname, bool delete_it)
876 {
877 	struct sandbox_state *state = state_get_current();
878 	char mem_fname[30];
879 	int fd, err;
880 	const char *extra_args[5];
881 	char **argv = state->argv;
882 	int argc;
883 #ifdef DEBUG
884 	int i;
885 #endif
886 
887 	strcpy(mem_fname, "/tmp/u-boot.mem.XXXXXX");
888 	fd = mkstemp(mem_fname);
889 	if (fd < 0)
890 		return -ENOENT;
891 	close(fd);
892 	err = os_write_ram_buf(mem_fname);
893 	if (err)
894 		return err;
895 
896 	os_fd_restore();
897 
898 	argc = 0;
899 	if (delete_it) {
900 		extra_args[argc++] = "-j";
901 		extra_args[argc++] = (char *)fname;
902 	}
903 	extra_args[argc++] = "-m";
904 	extra_args[argc++] = mem_fname;
905 	if (state->ram_buf_rm)
906 		extra_args[argc++] = "--rm_memory";
907 	err = add_args(&argv, extra_args, argc);
908 	if (err)
909 		return err;
910 	argv[0] = (char *)fname;
911 
912 #ifdef DEBUG
913 	for (i = 0; argv[i]; i++)
914 		printf("%d %s\n", i, argv[i]);
915 #endif
916 
917 	if (state_uninit())
918 		os_exit(2);
919 
920 	err = execv(fname, argv);
921 	os_free(argv);
922 	if (err) {
923 		perror("Unable to run image");
924 		printf("Image filename '%s'\n", fname);
925 		return err;
926 	}
927 
928 	if (delete_it)
929 		return unlink(fname);
930 
931 	return -EFAULT;
932 }
933 
os_jump_to_image(const void * dest,int size)934 int os_jump_to_image(const void *dest, int size)
935 {
936 	char fname[30];
937 	int err;
938 
939 	err = make_exec(fname, dest, size);
940 	if (err)
941 		return err;
942 
943 	return os_jump_to_file(fname, true);
944 }
945 
os_find_u_boot(char * fname,int maxlen,bool use_img,const char * cur_prefix,const char * next_prefix)946 int os_find_u_boot(char *fname, int maxlen, bool use_img,
947 		   const char *cur_prefix, const char *next_prefix)
948 {
949 	struct sandbox_state *state = state_get_current();
950 	const char *progname = state->argv[0];
951 	int len = strlen(progname);
952 	char subdir[10];
953 	char *suffix;
954 	char *p;
955 	int fd;
956 
957 	if (len >= maxlen || len < 4)
958 		return -ENOSPC;
959 
960 	strcpy(fname, progname);
961 	suffix = fname + len - 4;
962 
963 	/* Change the existing suffix to the new one */
964 	if (*suffix != '-')
965 		return -EINVAL;
966 
967 	if (*next_prefix)
968 		strcpy(suffix + 1, next_prefix);  /* e.g. "-tpl" to "-spl" */
969 	else
970 		*suffix = '\0';  /* e.g. "-spl" to "" */
971 	fd = os_open(fname, O_RDONLY);
972 	if (fd >= 0) {
973 		close(fd);
974 		return 0;
975 	}
976 
977 	/*
978 	 * We didn't find it, so try looking for 'u-boot-xxx' in the xxx/
979 	 * directory. Replace the old dirname with the new one.
980 	 */
981 	snprintf(subdir, sizeof(subdir), "/%s/", cur_prefix);
982 	p = strstr(fname, subdir);
983 	if (p) {
984 		if (*next_prefix)
985 			/* e.g. ".../tpl/u-boot-spl"  to ".../spl/u-boot-spl" */
986 			memcpy(p + 1, next_prefix, strlen(next_prefix));
987 		else
988 			/* e.g. ".../spl/u-boot" to ".../u-boot" */
989 			strcpy(p, p + 1 + strlen(cur_prefix));
990 		if (use_img)
991 			strcat(p, ".img");
992 
993 		fd = os_open(fname, O_RDONLY);
994 		if (fd >= 0) {
995 			close(fd);
996 			return 0;
997 		}
998 	}
999 
1000 	return -ENOENT;
1001 }
1002 
os_spl_to_uboot(const char * fname)1003 int os_spl_to_uboot(const char *fname)
1004 {
1005 	struct sandbox_state *state = state_get_current();
1006 
1007 	/* U-Boot will delete ram buffer after read: "--rm_memory"*/
1008 	state->ram_buf_rm = true;
1009 
1010 	return os_jump_to_file(fname, false);
1011 }
1012 
os_get_time_offset(void)1013 long os_get_time_offset(void)
1014 {
1015 	const char *offset;
1016 
1017 	offset = getenv(ENV_TIME_OFFSET);
1018 	if (offset)
1019 		return strtol(offset, NULL, 0);
1020 	return 0;
1021 }
1022 
os_set_time_offset(long offset)1023 void os_set_time_offset(long offset)
1024 {
1025 	char buf[21];
1026 	int ret;
1027 
1028 	snprintf(buf, sizeof(buf), "%ld", offset);
1029 	ret = setenv(ENV_TIME_OFFSET, buf, true);
1030 	if (ret)
1031 		printf("Could not set environment variable %s\n",
1032 		       ENV_TIME_OFFSET);
1033 }
1034 
os_localtime(struct rtc_time * rt)1035 void os_localtime(struct rtc_time *rt)
1036 {
1037 	time_t t = time(NULL);
1038 	struct tm *tm;
1039 
1040 	tm = localtime(&t);
1041 	rt->tm_sec = tm->tm_sec;
1042 	rt->tm_min = tm->tm_min;
1043 	rt->tm_hour = tm->tm_hour;
1044 	rt->tm_mday = tm->tm_mday;
1045 	rt->tm_mon = tm->tm_mon + 1;
1046 	rt->tm_year = tm->tm_year + 1900;
1047 	rt->tm_wday = tm->tm_wday;
1048 	rt->tm_yday = tm->tm_yday;
1049 	rt->tm_isdst = tm->tm_isdst;
1050 }
1051 
os_abort(void)1052 void os_abort(void)
1053 {
1054 	abort();
1055 }
1056 
os_mprotect_allow(void * start,size_t len)1057 int os_mprotect_allow(void *start, size_t len)
1058 {
1059 	int page_size = getpagesize();
1060 
1061 	/* Move start to the start of a page, len to the end */
1062 	start = (void *)(((ulong)start) & ~(page_size - 1));
1063 	len = (len + page_size * 2) & ~(page_size - 1);
1064 
1065 	return mprotect(start, len, PROT_READ | PROT_WRITE);
1066 }
1067 
os_find_text_base(void)1068 void *os_find_text_base(void)
1069 {
1070 	char line[500];
1071 	void *base = NULL;
1072 	int len;
1073 	int fd;
1074 
1075 	/*
1076 	 * This code assumes that the first line of /proc/self/maps holds
1077 	 * information about the text, for example:
1078 	 *
1079 	 * 5622d9907000-5622d9a55000 r-xp 00000000 08:01 15067168   u-boot
1080 	 *
1081 	 * The first hex value is assumed to be the address.
1082 	 *
1083 	 * This is tested in Linux 4.15.
1084 	 */
1085 	fd = open("/proc/self/maps", O_RDONLY);
1086 	if (fd == -1)
1087 		return NULL;
1088 	len = read(fd, line, sizeof(line));
1089 	if (len > 0) {
1090 		char *end = memchr(line, '-', len);
1091 
1092 		if (end) {
1093 			uintptr_t addr;
1094 
1095 			*end = '\0';
1096 			if (sscanf(line, "%zx", &addr) == 1)
1097 				base = (void *)addr;
1098 		}
1099 	}
1100 	close(fd);
1101 
1102 	return base;
1103 }
1104 
1105 /**
1106  * os_unblock_signals() - unblock all signals
1107  *
1108  * If we are relaunching the sandbox in a signal handler, we have to unblock
1109  * the respective signal before calling execv(). See signal(7) man-page.
1110  */
os_unblock_signals(void)1111 static void os_unblock_signals(void)
1112 {
1113 	sigset_t sigs;
1114 
1115 	sigfillset(&sigs);
1116 	sigprocmask(SIG_UNBLOCK, &sigs, NULL);
1117 }
1118 
os_relaunch(char * argv[])1119 void os_relaunch(char *argv[])
1120 {
1121 	os_unblock_signals();
1122 
1123 	execv(argv[0], argv);
1124 	os_exit(1);
1125 }
1126 
1127 #ifdef CONFIG_FUZZ
fuzzer_thread(void * ptr)1128 static void *fuzzer_thread(void * ptr)
1129 {
1130 	char cmd[64];
1131 	char *argv[5] = {"./u-boot", "-T", "-c", cmd, NULL};
1132 	const char *fuzz_test;
1133 
1134 	/* Find which test to run from an environment variable. */
1135 	fuzz_test = getenv("UBOOT_SB_FUZZ_TEST");
1136 	if (!fuzz_test)
1137 		os_abort();
1138 
1139 	snprintf(cmd, sizeof(cmd), "fuzz %s", fuzz_test);
1140 
1141 	sandbox_main(4, argv);
1142 	os_abort();
1143 	return NULL;
1144 }
1145 
1146 static bool fuzzer_initialized = false;
1147 static pthread_mutex_t fuzzer_mutex = PTHREAD_MUTEX_INITIALIZER;
1148 static pthread_cond_t fuzzer_cond = PTHREAD_COND_INITIALIZER;
1149 static const uint8_t *fuzzer_data;
1150 static size_t fuzzer_size;
1151 
sandbox_fuzzing_engine_get_input(const uint8_t ** data,size_t * size)1152 int sandbox_fuzzing_engine_get_input(const uint8_t **data, size_t *size)
1153 {
1154 	if (!fuzzer_initialized)
1155 		return -ENOSYS;
1156 
1157 	/* Tell the main thread we need new inputs then wait for them. */
1158 	pthread_mutex_lock(&fuzzer_mutex);
1159 	pthread_cond_signal(&fuzzer_cond);
1160 	pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1161 	*data = fuzzer_data;
1162 	*size = fuzzer_size;
1163 	pthread_mutex_unlock(&fuzzer_mutex);
1164 	return 0;
1165 }
1166 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)1167 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
1168 {
1169 	static pthread_t tid;
1170 
1171 	pthread_mutex_lock(&fuzzer_mutex);
1172 
1173 	/* Initialize the sandbox on another thread. */
1174 	if (!fuzzer_initialized) {
1175 		fuzzer_initialized = true;
1176 		if (pthread_create(&tid, NULL, fuzzer_thread, NULL))
1177 			os_abort();
1178 		pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1179 	}
1180 
1181 	/* Hand over the input. */
1182 	fuzzer_data = data;
1183 	fuzzer_size = size;
1184 	pthread_cond_signal(&fuzzer_cond);
1185 
1186 	/* Wait for the inputs to be finished with. */
1187 	pthread_cond_wait(&fuzzer_cond, &fuzzer_mutex);
1188 	pthread_mutex_unlock(&fuzzer_mutex);
1189 
1190 	return 0;
1191 }
1192 #else
main(int argc,char * argv[])1193 int main(int argc, char *argv[])
1194 {
1195 	return sandbox_main(argc, argv);
1196 }
1197 #endif
1198