• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2015-2016 Cyril Hrubis <chrubis@suse.cz>
4  * Copyright (c) Linux Test Project, 2016-2021
5  */
6 
7 #include <limits.h>
8 #include <stdio.h>
9 #include <stdarg.h>
10 #include <unistd.h>
11 #include <string.h>
12 #include <stdlib.h>
13 #include <errno.h>
14 #include <sys/mount.h>
15 #include <sys/types.h>
16 #include <sys/wait.h>
17 
18 #define TST_NO_DEFAULT_MAIN
19 #include "tst_test.h"
20 #include "tst_device.h"
21 #include "lapi/futex.h"
22 #include "lapi/syscalls.h"
23 #include "tst_ansi_color.h"
24 #include "tst_safe_stdio.h"
25 #include "tst_timer_test.h"
26 #include "tst_clocks.h"
27 #include "tst_timer.h"
28 #include "tst_wallclock.h"
29 #include "tst_sys_conf.h"
30 #include "tst_kconfig.h"
31 
32 #include "old_resource.h"
33 #include "old_device.h"
34 #include "old_tmpdir.h"
35 
36 /*
37  * Hack to get TCID defined in newlib tests
38  */
39 const char *TCID __attribute__((weak));
40 
41 /* update also docparse/testinfo.pl */
42 #define LINUX_GIT_URL "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id="
43 #define LINUX_STABLE_GIT_URL "https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/commit/?id="
44 #define GLIBC_GIT_URL "https://sourceware.org/git/?p=glibc.git;a=commit;h="
45 #define CVE_DB_URL "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-"
46 
47 struct tst_test *tst_test;
48 
49 static const char *tid;
50 static int iterations = 1;
51 static float duration = -1;
52 static float timeout_mul = -1;
53 static pid_t main_pid, lib_pid;
54 static int mntpoint_mounted;
55 static int ovl_mounted;
56 static struct timespec tst_start_time; /* valid only for test pid */
57 
58 struct results {
59 	int passed;
60 	int skipped;
61 	int failed;
62 	int warnings;
63 	int broken;
64 	unsigned int timeout;
65 };
66 
67 static struct results *results;
68 
69 static int ipc_fd;
70 
71 extern void *tst_futexes;
72 extern unsigned int tst_max_futexes;
73 
74 #define IPC_ENV_VAR "LTP_IPC_PATH"
75 
76 static char ipc_path[1064];
77 const char *tst_ipc_path = ipc_path;
78 
79 static char shm_path[1024];
80 
81 int TST_ERR;
82 int TST_PASS;
83 long TST_RET;
84 
85 static void do_cleanup(void);
86 static void do_exit(int ret) __attribute__ ((noreturn));
87 
setup_ipc(void)88 static void setup_ipc(void)
89 {
90 	size_t size = getpagesize();
91 
92 	if (access("/dev/shm", F_OK) == 0) {
93 		snprintf(shm_path, sizeof(shm_path), "/dev/shm/ltp_%s_%d",
94 		         tid, getpid());
95 	} else {
96 		char *tmpdir;
97 
98 		if (!tst_tmpdir_created())
99 			tst_tmpdir();
100 
101 		tmpdir = tst_get_tmpdir();
102 		snprintf(shm_path, sizeof(shm_path), "%s/ltp_%s_%d",
103 		         tmpdir, tid, getpid());
104 		free(tmpdir);
105 	}
106 
107 	ipc_fd = open(shm_path, O_CREAT | O_EXCL | O_RDWR, 0600);
108 	if (ipc_fd < 0)
109 		tst_brk(TBROK | TERRNO, "open(%s)", shm_path);
110 	SAFE_CHMOD(shm_path, 0666);
111 
112 	SAFE_FTRUNCATE(ipc_fd, size);
113 
114 	results = SAFE_MMAP(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, ipc_fd, 0);
115 
116 	/* Checkpoints needs to be accessible from processes started by exec() */
117 	if (tst_test->needs_checkpoints || tst_test->child_needs_reinit) {
118 		sprintf(ipc_path, IPC_ENV_VAR "=%s", shm_path);
119 		putenv(ipc_path);
120 	} else {
121 		SAFE_UNLINK(shm_path);
122 	}
123 
124 	SAFE_CLOSE(ipc_fd);
125 
126 	if (tst_test->needs_checkpoints) {
127 		tst_futexes = (char*)results + sizeof(struct results);
128 		tst_max_futexes = (size - sizeof(struct results))/sizeof(futex_t);
129 	}
130 }
131 
cleanup_ipc(void)132 static void cleanup_ipc(void)
133 {
134 	size_t size = getpagesize();
135 
136 	if (ipc_fd > 0 && close(ipc_fd))
137 		tst_res(TWARN | TERRNO, "close(ipc_fd) failed");
138 
139 	if (shm_path[0] && !access(shm_path, F_OK) && unlink(shm_path))
140 		tst_res(TWARN | TERRNO, "unlink(%s) failed", shm_path);
141 
142 	if (results) {
143 		msync((void*)results, size, MS_SYNC);
144 		munmap((void*)results, size);
145 		results = NULL;
146 	}
147 }
148 
tst_reinit(void)149 void tst_reinit(void)
150 {
151 	const char *path = getenv(IPC_ENV_VAR);
152 	size_t size = getpagesize();
153 	int fd;
154 
155 	if (!path)
156 		tst_brk(TBROK, IPC_ENV_VAR" is not defined");
157 
158 	if (access(path, F_OK))
159 		tst_brk(TBROK, "File %s does not exist!", path);
160 
161 	fd = SAFE_OPEN(path, O_RDWR);
162 
163 	results = SAFE_MMAP(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
164 	tst_futexes = (char*)results + sizeof(struct results);
165 	tst_max_futexes = (size - sizeof(struct results))/sizeof(futex_t);
166 
167 	SAFE_CLOSE(fd);
168 }
169 
update_results(int ttype)170 static void update_results(int ttype)
171 {
172 	if (!results)
173 		return;
174 
175 	switch (ttype) {
176 	case TCONF:
177 		tst_atomic_inc(&results->skipped);
178 	break;
179 	case TPASS:
180 		tst_atomic_inc(&results->passed);
181 	break;
182 	case TWARN:
183 		tst_atomic_inc(&results->warnings);
184 	break;
185 	case TFAIL:
186 		tst_atomic_inc(&results->failed);
187 	break;
188 	case TBROK:
189 		tst_atomic_inc(&results->broken);
190 	break;
191 	}
192 }
193 
print_result(const char * file,const int lineno,int ttype,const char * fmt,va_list va)194 static void print_result(const char *file, const int lineno, int ttype,
195                          const char *fmt, va_list va)
196 {
197 	char buf[1024];
198 	char *str = buf;
199 	int ret, size = sizeof(buf), ssize, int_errno, buflen;
200 	const char *str_errno = NULL;
201 	const char *res;
202 
203 	switch (TTYPE_RESULT(ttype)) {
204 	case TPASS:
205 		res = "TPASS";
206 	break;
207 	case TFAIL:
208 		res = "TFAIL";
209 	break;
210 	case TBROK:
211 		res = "TBROK";
212 	break;
213 	case TCONF:
214 		res = "TCONF";
215 	break;
216 	case TWARN:
217 		res = "TWARN";
218 	break;
219 	case TINFO:
220 		res = "TINFO";
221 	break;
222 	default:
223 		tst_brk(TBROK, "Invalid ttype value %i", ttype);
224 		abort();
225 	}
226 
227 	if (ttype & TERRNO) {
228 		str_errno = tst_strerrno(errno);
229 		int_errno = errno;
230 	}
231 
232 	if (ttype & TTERRNO) {
233 		str_errno = tst_strerrno(TST_ERR);
234 		int_errno = TST_ERR;
235 	}
236 
237 	if (ttype & TRERRNO) {
238 		int_errno = TST_RET < 0 ? -(int)TST_RET : (int)TST_RET;
239 		str_errno = tst_strerrno(int_errno);
240 	}
241 
242 	ret = snprintf(str, size, "%s:%i: ", file, lineno);
243 	str += ret;
244 	size -= ret;
245 
246 	if (tst_color_enabled(STDERR_FILENO))
247 		ret = snprintf(str, size, "%s%s: %s", tst_ttype2color(ttype),
248 			       res, ANSI_COLOR_RESET);
249 	else
250 		ret = snprintf(str, size, "%s: ", res);
251 	str += ret;
252 	size -= ret;
253 
254 	ssize = size - 2;
255 	ret = vsnprintf(str, size, fmt, va);
256 	str += MIN(ret, ssize);
257 	size -= MIN(ret, ssize);
258 	if (ret >= ssize) {
259 		tst_res_(file, lineno, TWARN,
260 				"Next message is too long and truncated:");
261 	} else if (str_errno) {
262 		ssize = size - 2;
263 		ret = snprintf(str, size, ": %s (%d)", str_errno, int_errno);
264 		str += MIN(ret, ssize);
265 		size -= MIN(ret, ssize);
266 		if (ret >= ssize)
267 			tst_res_(file, lineno, TWARN,
268 				"Next message is too long and truncated:");
269 	}
270 
271 	snprintf(str, size, "\n");
272 
273 	/* we might be called from signal handler, so use write() */
274 	buflen = str - buf + 1;
275 	str = buf;
276 	while (buflen) {
277 		ret = write(STDERR_FILENO, str, buflen);
278 		if (ret <= 0)
279 			break;
280 
281 		str += ret;
282 		buflen -= ret;
283 	}
284 }
285 
tst_vres_(const char * file,const int lineno,int ttype,const char * fmt,va_list va)286 void tst_vres_(const char *file, const int lineno, int ttype,
287                const char *fmt, va_list va)
288 {
289 	print_result(file, lineno, ttype, fmt, va);
290 
291 	update_results(TTYPE_RESULT(ttype));
292 }
293 
294 void tst_vbrk_(const char *file, const int lineno, int ttype,
295                const char *fmt, va_list va);
296 
297 static void (*tst_brk_handler)(const char *file, const int lineno, int ttype,
298 			       const char *fmt, va_list va) = tst_vbrk_;
299 
tst_cvres(const char * file,const int lineno,int ttype,const char * fmt,va_list va)300 static void tst_cvres(const char *file, const int lineno, int ttype,
301 		      const char *fmt, va_list va)
302 {
303 	if (TTYPE_RESULT(ttype) == TBROK) {
304 		ttype &= ~TTYPE_MASK;
305 		ttype |= TWARN;
306 	}
307 
308 	print_result(file, lineno, ttype, fmt, va);
309 	update_results(TTYPE_RESULT(ttype));
310 }
311 
do_test_cleanup(void)312 static void do_test_cleanup(void)
313 {
314 	tst_brk_handler = tst_cvres;
315 
316 	if (tst_test->cleanup)
317 		tst_test->cleanup();
318 
319 	tst_free_all();
320 
321 	tst_brk_handler = tst_vbrk_;
322 }
323 
tst_vbrk_(const char * file,const int lineno,int ttype,const char * fmt,va_list va)324 void tst_vbrk_(const char *file, const int lineno, int ttype,
325                const char *fmt, va_list va)
326 {
327 	print_result(file, lineno, ttype, fmt, va);
328 	update_results(TTYPE_RESULT(ttype));
329 
330 	/*
331 	 * The getpid implementation in some C library versions may cause cloned
332 	 * test threads to show the same pid as their parent when CLONE_VM is
333 	 * specified but CLONE_THREAD is not. Use direct syscall to avoid
334 	 * cleanup running in the child.
335 	 */
336 	if (syscall(SYS_getpid) == main_pid)
337 		do_test_cleanup();
338 
339 	if (getpid() == lib_pid)
340 		do_exit(TTYPE_RESULT(ttype));
341 
342 	exit(TTYPE_RESULT(ttype));
343 }
344 
tst_res_(const char * file,const int lineno,int ttype,const char * fmt,...)345 void tst_res_(const char *file, const int lineno, int ttype,
346               const char *fmt, ...)
347 {
348 	va_list va;
349 
350 	va_start(va, fmt);
351 	tst_vres_(file, lineno, ttype, fmt, va);
352 	va_end(va);
353 }
354 
tst_brk_(const char * file,const int lineno,int ttype,const char * fmt,...)355 void tst_brk_(const char *file, const int lineno, int ttype,
356               const char *fmt, ...)
357 {
358 	va_list va;
359 
360 	va_start(va, fmt);
361 	tst_brk_handler(file, lineno, ttype, fmt, va);
362 	va_end(va);
363 }
364 
check_child_status(pid_t pid,int status)365 static void check_child_status(pid_t pid, int status)
366 {
367 	int ret;
368 
369 	if (WIFSIGNALED(status)) {
370 		tst_brk(TBROK, "Child (%i) killed by signal %s",
371 		        pid, tst_strsig(WTERMSIG(status)));
372 	}
373 
374 	if (!(WIFEXITED(status)))
375 		tst_brk(TBROK, "Child (%i) exited abnormally", pid);
376 
377 	ret = WEXITSTATUS(status);
378 	switch (ret) {
379 	case TPASS:
380 	case TBROK:
381 	case TCONF:
382 	break;
383 	default:
384 		tst_brk(TBROK, "Invalid child (%i) exit value %i", pid, ret);
385 	}
386 }
387 
tst_reap_children(void)388 void tst_reap_children(void)
389 {
390 	int status;
391 	pid_t pid;
392 
393 	for (;;) {
394 		pid = wait(&status);
395 
396 		if (pid > 0) {
397 			check_child_status(pid, status);
398 			continue;
399 		}
400 
401 		if (errno == ECHILD)
402 			break;
403 
404 		if (errno == EINTR)
405 			continue;
406 
407 		tst_brk(TBROK | TERRNO, "wait() failed");
408 	}
409 }
410 
411 
safe_fork(const char * filename,unsigned int lineno)412 pid_t safe_fork(const char *filename, unsigned int lineno)
413 {
414 	pid_t pid;
415 
416 	if (!tst_test->forks_child)
417 		tst_brk(TBROK, "test.forks_child must be set!");
418 
419 	tst_flush();
420 
421 	pid = fork();
422 	if (pid < 0)
423 		tst_brk_(filename, lineno, TBROK | TERRNO, "fork() failed");
424 
425 	if (!pid)
426 		atexit(tst_free_all);
427 
428 	return pid;
429 }
430 
safe_clone(const char * file,const int lineno,const struct tst_clone_args * args)431 pid_t safe_clone(const char *file, const int lineno,
432 		 const struct tst_clone_args *args)
433 {
434 	pid_t pid;
435 
436 	if (!tst_test->forks_child)
437 		tst_brk(TBROK, "test.forks_child must be set!");
438 
439 	pid = tst_clone(args);
440 
441 	switch (pid) {
442 	case -1:
443 		tst_brk_(file, lineno, TBROK | TERRNO, "clone3 failed");
444 		break;
445 	case -2:
446 		tst_brk_(file, lineno, TBROK | TERRNO, "clone failed");
447 		return -1;
448 	}
449 
450 	if (!pid)
451 		atexit(tst_free_all);
452 
453 	return pid;
454 }
455 
456 static struct option {
457 	char *optstr;
458 	char *help;
459 } options[] = {
460 	{"h",  "-h       Prints this help"},
461 	{"i:", "-i n     Execute test n times"},
462 	{"I:", "-I x     Execute test for n seconds"},
463 	{"C:", "-C ARG   Run child process with ARG arguments (used internally)"},
464 };
465 
print_help(void)466 static void print_help(void)
467 {
468 	unsigned int i;
469 
470 	fprintf(stderr, "Options\n");
471 	fprintf(stderr, "-------\n");
472 
473 	for (i = 0; i < ARRAY_SIZE(options); i++)
474 		fprintf(stderr, "%s\n", options[i].help);
475 
476 	if (!tst_test->options)
477 		return;
478 
479 	for (i = 0; tst_test->options[i].optstr; i++)
480 		fprintf(stderr, "%s\n", tst_test->options[i].help);
481 }
482 
print_test_tags(void)483 static void print_test_tags(void)
484 {
485 	unsigned int i;
486 	const struct tst_tag *tags = tst_test->tags;
487 
488 	if (!tags)
489 		return;
490 
491 	printf("\nTags\n");
492 	printf("----\n");
493 
494 	for (i = 0; tags[i].name; i++) {
495 		if (!strcmp(tags[i].name, "CVE"))
496 			printf(CVE_DB_URL "%s\n", tags[i].value);
497 		else if (!strcmp(tags[i].name, "linux-git"))
498 			printf(LINUX_GIT_URL "%s\n", tags[i].value);
499 		else if (!strcmp(tags[i].name, "linux-stable-git"))
500 			printf(LINUX_STABLE_GIT_URL "%s\n", tags[i].value);
501 		else if (!strcmp(tags[i].name, "glibc-git"))
502 			printf(GLIBC_GIT_URL "%s\n", tags[i].value);
503 		else
504 			printf("%s: %s\n", tags[i].name, tags[i].value);
505 	}
506 
507 	printf("\n");
508 }
509 
check_option_collision(void)510 static void check_option_collision(void)
511 {
512 	unsigned int i, j;
513 	struct tst_option *toptions = tst_test->options;
514 
515 	if (!toptions)
516 		return;
517 
518 	for (i = 0; toptions[i].optstr; i++) {
519 		for (j = 0; j < ARRAY_SIZE(options); j++) {
520 			if (toptions[i].optstr[0] == options[j].optstr[0]) {
521 				tst_brk(TBROK, "Option collision '%s'",
522 				        options[j].help);
523 			}
524 		}
525 	}
526 }
527 
count_options(void)528 static unsigned int count_options(void)
529 {
530 	unsigned int i;
531 
532 	if (!tst_test->options)
533 		return 0;
534 
535 	for (i = 0; tst_test->options[i].optstr; i++);
536 
537 	return i;
538 }
539 
parse_topt(unsigned int topts_len,int opt,char * optarg)540 static void parse_topt(unsigned int topts_len, int opt, char *optarg)
541 {
542 	unsigned int i;
543 	struct tst_option *toptions = tst_test->options;
544 
545 	for (i = 0; i < topts_len; i++) {
546 		if (toptions[i].optstr[0] == opt)
547 			break;
548 	}
549 
550 	if (i >= topts_len)
551 		tst_brk(TBROK, "Invalid option '%c' (should not happen)", opt);
552 
553 	if (*toptions[i].arg)
554 		tst_res(TWARN, "Option -%c passed multiple times", opt);
555 
556 	*(toptions[i].arg) = optarg ? optarg : "";
557 }
558 
559 /* see self_exec.c */
560 #ifdef UCLINUX
561 extern char *child_args;
562 #endif
563 
parse_opts(int argc,char * argv[])564 static void parse_opts(int argc, char *argv[])
565 {
566 	unsigned int i, topts_len = count_options();
567 	char optstr[2 * ARRAY_SIZE(options) + 2 * topts_len];
568 	int opt;
569 
570 	check_option_collision();
571 
572 	optstr[0] = 0;
573 
574 	for (i = 0; i < ARRAY_SIZE(options); i++)
575 		strcat(optstr, options[i].optstr);
576 
577 	for (i = 0; i < topts_len; i++)
578 		strcat(optstr, tst_test->options[i].optstr);
579 
580 	while ((opt = getopt(argc, argv, optstr)) > 0) {
581 		switch (opt) {
582 		case '?':
583 			print_help();
584 			tst_brk(TBROK, "Invalid option");
585 		break;
586 		case 'h':
587 			print_help();
588 			print_test_tags();
589 			exit(0);
590 		case 'i':
591 			iterations = atoi(optarg);
592 		break;
593 		case 'I':
594 			duration = atof(optarg);
595 		break;
596 		case 'C':
597 #ifdef UCLINUX
598 			child_args = optarg;
599 #endif
600 		break;
601 		default:
602 			parse_topt(topts_len, opt, optarg);
603 		}
604 	}
605 
606 	if (optind < argc)
607 		tst_brk(TBROK, "Unexpected argument(s) '%s'...", argv[optind]);
608 }
609 
tst_parse_int(const char * str,int * val,int min,int max)610 int tst_parse_int(const char *str, int *val, int min, int max)
611 {
612 	long rval;
613 
614 	if (!str)
615 		return 0;
616 
617 	int ret = tst_parse_long(str, &rval, min, max);
618 
619 	if (ret)
620 		return ret;
621 
622 	*val = (int)rval;
623 	return 0;
624 }
625 
tst_parse_long(const char * str,long * val,long min,long max)626 int tst_parse_long(const char *str, long *val, long min, long max)
627 {
628 	long rval;
629 	char *end;
630 
631 	if (!str)
632 		return 0;
633 
634 	errno = 0;
635 	rval = strtol(str, &end, 10);
636 
637 	if (str == end || *end != '\0')
638 		return EINVAL;
639 
640 	if (errno)
641 		return errno;
642 
643 	if (rval > max || rval < min)
644 		return ERANGE;
645 
646 	*val = rval;
647 	return 0;
648 }
649 
tst_parse_float(const char * str,float * val,float min,float max)650 int tst_parse_float(const char *str, float *val, float min, float max)
651 {
652 	double rval;
653 	char *end;
654 
655 	if (!str)
656 		return 0;
657 
658 	errno = 0;
659 	rval = strtod(str, &end);
660 
661 	if (str == end || *end != '\0')
662 		return EINVAL;
663 
664 	if (errno)
665 		return errno;
666 
667 	if (rval > (double)max || rval < (double)min)
668 		return ERANGE;
669 
670 	*val = (float)rval;
671 	return 0;
672 }
673 
print_colored(const char * str)674 static void print_colored(const char *str)
675 {
676 	if (tst_color_enabled(STDOUT_FILENO))
677 		printf("%s%s%s", ANSI_COLOR_YELLOW, str, ANSI_COLOR_RESET);
678 	else
679 		printf("%s", str);
680 }
681 
print_failure_hint(const char * tag,const char * hint,const char * url)682 static void print_failure_hint(const char *tag, const char *hint,
683 			       const char *url)
684 {
685 	const struct tst_tag *tags = tst_test->tags;
686 
687 	if (!tags)
688 		return;
689 
690 	unsigned int i;
691 	int hint_printed = 0;
692 
693 	for (i = 0; tags[i].name; i++) {
694 		if (!strcmp(tags[i].name, tag)) {
695 			if (!hint_printed) {
696 				hint_printed = 1;
697 				printf("\n");
698 				print_colored("HINT: ");
699 				printf("You _MAY_ be %s, see:\n\n", hint);
700 			}
701 
702 			printf("%s%s\n", url, tags[i].value);
703 		}
704 	}
705 }
706 
707 /* update also docparse/testinfo.pl */
print_failure_hints(void)708 static void print_failure_hints(void)
709 {
710 	print_failure_hint("linux-git", "missing kernel fixes", LINUX_GIT_URL);
711 	print_failure_hint("linux-stable-git", "missing stable kernel fixes",
712 					   LINUX_STABLE_GIT_URL);
713 	print_failure_hint("glibc-git", "missing glibc fixes", GLIBC_GIT_URL);
714 	print_failure_hint("CVE", "vulnerable to CVE(s)", CVE_DB_URL);
715 }
716 
do_exit(int ret)717 static void do_exit(int ret)
718 {
719 	if (results) {
720 		if (results->passed && ret == TCONF)
721 			ret = 0;
722 
723 		if (results->failed) {
724 			ret |= TFAIL;
725 			print_failure_hints();
726 		}
727 
728 		if (results->skipped && !results->passed)
729 			ret |= TCONF;
730 
731 		if (results->warnings)
732 			ret |= TWARN;
733 
734 		if (results->broken)
735 			ret |= TBROK;
736 
737 		printf("\nSummary:\n");
738 		printf("passed   %d\n", results->passed);
739 		printf("failed   %d\n", results->failed);
740 		printf("broken   %d\n", results->broken);
741 		printf("skipped  %d\n", results->skipped);
742 		printf("warnings %d\n", results->warnings);
743 	}
744 
745 	do_cleanup();
746 
747 	exit(ret);
748 }
749 
check_kver(void)750 void check_kver(void)
751 {
752 	int v1, v2, v3;
753 
754 	if (tst_parse_kver(tst_test->min_kver, &v1, &v2, &v3)) {
755 		tst_res(TWARN,
756 		        "Invalid kernel version %s, expected %%d.%%d.%%d",
757 		        tst_test->min_kver);
758 	}
759 
760 	if (tst_kvercmp(v1, v2, v3) < 0) {
761 		tst_brk(TCONF, "The test requires kernel %s or newer",
762 		        tst_test->min_kver);
763 	}
764 }
765 
results_equal(struct results * a,struct results * b)766 static int results_equal(struct results *a, struct results *b)
767 {
768 	if (a->passed != b->passed)
769 		return 0;
770 
771 	if (a->failed != b->failed)
772 		return 0;
773 
774 	if (a->skipped != b->skipped)
775 		return 0;
776 
777 	if (a->broken != b->broken)
778 		return 0;
779 
780 	return 1;
781 }
782 
needs_tmpdir(void)783 static int needs_tmpdir(void)
784 {
785 	return tst_test->needs_tmpdir ||
786 	       tst_test->needs_device ||
787 	       tst_test->mntpoint ||
788 	       tst_test->resource_files ||
789 	       tst_test->needs_checkpoints;
790 }
791 
copy_resources(void)792 static void copy_resources(void)
793 {
794 	unsigned int i;
795 
796 	for (i = 0; tst_test->resource_files[i]; i++)
797 		TST_RESOURCE_COPY(NULL, tst_test->resource_files[i], NULL);
798 }
799 
get_tid(char * argv[])800 static const char *get_tid(char *argv[])
801 {
802 	char *p;
803 
804 	if (!argv[0] || !argv[0][0]) {
805 		tst_res(TINFO, "argv[0] is empty!");
806 		return "ltp_empty_argv";
807 	}
808 
809 	p = strrchr(argv[0], '/');
810 	if (p)
811 		return p+1;
812 
813 	return argv[0];
814 }
815 
816 static struct tst_device tdev;
817 struct tst_device *tst_device;
818 
assert_test_fn(void)819 static void assert_test_fn(void)
820 {
821 	int cnt = 0;
822 
823 	if (tst_test->test)
824 		cnt++;
825 
826 	if (tst_test->test_all)
827 		cnt++;
828 
829 	if (tst_test->sample)
830 		cnt++;
831 
832 	if (!cnt)
833 		tst_brk(TBROK, "No test function specified");
834 
835 	if (cnt != 1)
836 		tst_brk(TBROK, "You can define only one test function");
837 
838 	if (tst_test->test && !tst_test->tcnt)
839 		tst_brk(TBROK, "Number of tests (tcnt) must be > 0");
840 
841 	if (!tst_test->test && tst_test->tcnt)
842 		tst_brk(TBROK, "You can define tcnt only for test()");
843 }
844 
prepare_and_mount_ro_fs(const char * dev,const char * mntpoint,const char * fs_type)845 static int prepare_and_mount_ro_fs(const char *dev,
846                                    const char *mntpoint,
847                                    const char *fs_type)
848 {
849 	char buf[PATH_MAX];
850 
851 	if (mount(dev, mntpoint, fs_type, 0, NULL)) {
852 		tst_res(TINFO | TERRNO, "Can't mount %s at %s (%s)",
853 			dev, mntpoint, fs_type);
854 		return 1;
855 	}
856 
857 	mntpoint_mounted = 1;
858 
859 	snprintf(buf, sizeof(buf), "%s/dir/", mntpoint);
860 	SAFE_MKDIR(buf, 0777);
861 
862 	snprintf(buf, sizeof(buf), "%s/file", mntpoint);
863 	SAFE_FILE_PRINTF(buf, "file content");
864 	SAFE_CHMOD(buf, 0777);
865 
866 	SAFE_MOUNT(dev, mntpoint, fs_type, MS_REMOUNT | MS_RDONLY, NULL);
867 
868 	return 0;
869 }
870 
prepare_and_mount_dev_fs(const char * mntpoint)871 static void prepare_and_mount_dev_fs(const char *mntpoint)
872 {
873 	const char *flags[] = {"nodev", NULL};
874 	int mounted_nodev;
875 
876 	mounted_nodev = tst_path_has_mnt_flags(NULL, flags);
877 	if (mounted_nodev) {
878 		tst_res(TINFO, "tmpdir isn't suitable for creating devices, "
879 			"mounting tmpfs without nodev on %s", mntpoint);
880 		SAFE_MOUNT(NULL, mntpoint, "tmpfs", 0, NULL);
881 		mntpoint_mounted = 1;
882 	}
883 }
884 
prepare_device(void)885 static void prepare_device(void)
886 {
887 	if (tst_test->format_device) {
888 		SAFE_MKFS(tdev.dev, tdev.fs_type, tst_test->dev_fs_opts,
889 			  tst_test->dev_extra_opts);
890 	}
891 
892 	if (tst_test->needs_rofs) {
893 		prepare_and_mount_ro_fs(tdev.dev, tst_test->mntpoint,
894 		                        tdev.fs_type);
895 		return;
896 	}
897 
898 	if (tst_test->mount_device) {
899 		SAFE_MOUNT(tdev.dev, tst_test->mntpoint, tdev.fs_type,
900 			   tst_test->mnt_flags, tst_test->mnt_data);
901 		mntpoint_mounted = 1;
902 	}
903 }
904 
do_setup(int argc,char * argv[])905 static void do_setup(int argc, char *argv[])
906 {
907 	if (!tst_test)
908 		tst_brk(TBROK, "No tests to run");
909 
910 	if (tst_test->tconf_msg)
911 		tst_brk(TCONF, "%s", tst_test->tconf_msg);
912 
913 	if (tst_test->needs_kconfigs)
914 		tst_kconfig_check(tst_test->needs_kconfigs);
915 
916 	assert_test_fn();
917 
918 	TCID = tid = get_tid(argv);
919 
920 	if (tst_test->sample)
921 		tst_test = tst_timer_test_setup(tst_test);
922 
923 	parse_opts(argc, argv);
924 
925 	if (tst_test->needs_root && geteuid() != 0)
926 		tst_brk(TCONF, "Test needs to be run as root");
927 
928 	if (tst_test->min_kver)
929 		check_kver();
930 
931 	if (tst_test->needs_cmds) {
932 		const char *cmd;
933 		char path[PATH_MAX];
934 		int i;
935 
936 		for (i = 0; (cmd = tst_test->needs_cmds[i]); ++i)
937 			if (tst_get_path(cmd, path, sizeof(path)))
938 				tst_brk(TCONF, "Couldn't find '%s' in $PATH", cmd);
939 	}
940 
941 	if (tst_test->needs_drivers) {
942 		const char *name;
943 		int i;
944 
945 		for (i = 0; (name = tst_test->needs_drivers[i]); ++i)
946 			if (tst_check_driver(name))
947 				tst_brk(TCONF, "%s driver not available", name);
948 	}
949 
950 	if (tst_test->mount_device)
951 		tst_test->format_device = 1;
952 
953 	if (tst_test->format_device)
954 		tst_test->needs_device = 1;
955 
956 	if (tst_test->all_filesystems)
957 		tst_test->needs_device = 1;
958 
959 	if (tst_test->min_cpus > (unsigned long)tst_ncpus())
960 		tst_brk(TCONF, "Test needs at least %lu CPUs online", tst_test->min_cpus);
961 
962 	if (tst_test->request_hugepages)
963 		tst_request_hugepages(tst_test->request_hugepages);
964 
965 	setup_ipc();
966 
967 	if (tst_test->bufs)
968 		tst_buffers_alloc(tst_test->bufs);
969 
970 	if (needs_tmpdir() && !tst_tmpdir_created())
971 		tst_tmpdir();
972 
973 	if (tst_test->save_restore) {
974 		const char * const *name = tst_test->save_restore;
975 
976 		while (*name) {
977 			tst_sys_conf_save(*name);
978 			name++;
979 		}
980 	}
981 
982 	if (tst_test->mntpoint)
983 		SAFE_MKDIR(tst_test->mntpoint, 0777);
984 
985 	if ((tst_test->needs_devfs || tst_test->needs_rofs ||
986 	     tst_test->mount_device || tst_test->all_filesystems) &&
987 	     !tst_test->mntpoint) {
988 		tst_brk(TBROK, "tst_test->mntpoint must be set!");
989 	}
990 
991 	if (!!tst_test->needs_rofs + !!tst_test->needs_devfs +
992 	    !!tst_test->needs_device > 1) {
993 		tst_brk(TBROK,
994 			"Two or more of needs_{rofs, devfs, device} are set");
995 	}
996 
997 	if (tst_test->needs_devfs)
998 		prepare_and_mount_dev_fs(tst_test->mntpoint);
999 
1000 	if (tst_test->needs_rofs) {
1001 		/* If we failed to mount read-only tmpfs. Fallback to
1002 		 * using a device with read-only filesystem.
1003 		 */
1004 		if (prepare_and_mount_ro_fs(NULL, tst_test->mntpoint, "tmpfs")) {
1005 			tst_res(TINFO, "Can't mount tmpfs read-only, "
1006 			        "falling back to block device...");
1007 			tst_test->needs_device = 1;
1008 			tst_test->format_device = 1;
1009 		}
1010 	}
1011 
1012 	if (tst_test->needs_device && !mntpoint_mounted) {
1013 		tdev.dev = tst_acquire_device_(NULL, tst_test->dev_min_size);
1014 
1015 		if (!tdev.dev)
1016 			tst_brk(TCONF, "Failed to acquire device");
1017 
1018 		tst_device = &tdev;
1019 
1020 		if (tst_test->dev_fs_type)
1021 			tdev.fs_type = tst_test->dev_fs_type;
1022 		else
1023 			tdev.fs_type = tst_dev_fs_type();
1024 
1025 		if (!tst_test->all_filesystems)
1026 			prepare_device();
1027 	}
1028 
1029 	if (tst_test->needs_overlay && !tst_test->mount_device) {
1030 		tst_brk(TBROK, "tst_test->mount_device must be set");
1031 	}
1032 	if (tst_test->needs_overlay && !mntpoint_mounted) {
1033 		tst_brk(TBROK, "tst_test->mntpoint must be mounted");
1034 	}
1035 	if (tst_test->needs_overlay && !ovl_mounted) {
1036 		SAFE_MOUNT_OVERLAY();
1037 		ovl_mounted = 1;
1038 	}
1039 
1040 	if (tst_test->resource_files)
1041 		copy_resources();
1042 
1043 	if (tst_test->restore_wallclock)
1044 		tst_wallclock_save();
1045 
1046 	if (tst_test->taint_check)
1047 		tst_taint_init(tst_test->taint_check);
1048 }
1049 
do_test_setup(void)1050 static void do_test_setup(void)
1051 {
1052 	main_pid = getpid();
1053 
1054 	if (!tst_test->all_filesystems && tst_test->skip_filesystems) {
1055 		long fs_type = tst_fs_type(".");
1056 		const char *fs_name = tst_fs_type_name(fs_type);
1057 
1058 		if (tst_fs_in_skiplist(fs_name, tst_test->skip_filesystems)) {
1059 			tst_brk(TCONF, "%s is not supported by the test",
1060 				fs_name);
1061 		}
1062 
1063 		tst_res(TINFO, "%s is supported by the test", fs_name);
1064 	}
1065 
1066 	if (tst_test->caps)
1067 		tst_cap_setup(tst_test->caps, TST_CAP_REQ);
1068 
1069 	if (tst_test->setup)
1070 		tst_test->setup();
1071 
1072 	if (main_pid != getpid())
1073 		tst_brk(TBROK, "Runaway child in setup()!");
1074 
1075 	if (tst_test->caps)
1076 		tst_cap_setup(tst_test->caps, TST_CAP_DROP);
1077 }
1078 
do_cleanup(void)1079 static void do_cleanup(void)
1080 {
1081 	if (ovl_mounted)
1082 		SAFE_UMOUNT(OVL_MNT);
1083 
1084 	if (mntpoint_mounted)
1085 		tst_umount(tst_test->mntpoint);
1086 
1087 	if (tst_test->needs_device && tdev.dev)
1088 		tst_release_device(tdev.dev);
1089 
1090 	if (tst_tmpdir_created()) {
1091 		/* avoid munmap() on wrong pointer in tst_rmdir() */
1092 		tst_futexes = NULL;
1093 		tst_rmdir();
1094 	}
1095 
1096 	tst_sys_conf_restore(0);
1097 
1098 	if (tst_test->restore_wallclock)
1099 		tst_wallclock_restore();
1100 
1101 	cleanup_ipc();
1102 }
1103 
run_tests(void)1104 static void run_tests(void)
1105 {
1106 	unsigned int i;
1107 	struct results saved_results;
1108 
1109 	if (!tst_test->test) {
1110 		saved_results = *results;
1111 		tst_test->test_all();
1112 
1113 		if (getpid() != main_pid) {
1114 			exit(0);
1115 		}
1116 
1117 		tst_reap_children();
1118 
1119 		if (results_equal(&saved_results, results))
1120 			tst_brk(TBROK, "Test haven't reported results!");
1121 		return;
1122 	}
1123 
1124 	for (i = 0; i < tst_test->tcnt; i++) {
1125 		saved_results = *results;
1126 		tst_test->test(i);
1127 
1128 		if (getpid() != main_pid) {
1129 			exit(0);
1130 		}
1131 
1132 		tst_reap_children();
1133 
1134 		if (results_equal(&saved_results, results))
1135 			tst_brk(TBROK, "Test %i haven't reported results!", i);
1136 	}
1137 }
1138 
get_time_ms(void)1139 static unsigned long long get_time_ms(void)
1140 {
1141 	struct timespec ts;
1142 
1143 	if (tst_clock_gettime(CLOCK_MONOTONIC, &ts))
1144 		tst_brk(TBROK | TERRNO, "tst_clock_gettime()");
1145 
1146 	return tst_timespec_to_ms(ts);
1147 }
1148 
add_paths(void)1149 static void add_paths(void)
1150 {
1151 	char *old_path = getenv("PATH");
1152 	const char *start_dir;
1153 	char *new_path;
1154 
1155 	start_dir = tst_get_startwd();
1156 
1157 	if (old_path)
1158 		SAFE_ASPRINTF(&new_path, "%s::%s", old_path, start_dir);
1159 	else
1160 		SAFE_ASPRINTF(&new_path, "::%s", start_dir);
1161 
1162 	SAFE_SETENV("PATH", new_path, 1);
1163 	free(new_path);
1164 }
1165 
heartbeat(void)1166 static void heartbeat(void)
1167 {
1168 	if (tst_clock_gettime(CLOCK_MONOTONIC, &tst_start_time))
1169 		tst_res(TWARN | TERRNO, "tst_clock_gettime() failed");
1170 
1171 	if (getppid() == 1) {
1172 		tst_res(TFAIL, "Main test process might have exit!");
1173 		/*
1174 		 * We need kill the task group immediately since the
1175 		 * main process has exit.
1176 		 */
1177 		kill(0, SIGKILL);
1178 		exit(TBROK);
1179 	}
1180 
1181 	kill(getppid(), SIGUSR1);
1182 }
1183 
testrun(void)1184 static void testrun(void)
1185 {
1186 	unsigned int i = 0;
1187 	unsigned long long stop_time = 0;
1188 	int cont = 1;
1189 
1190 	heartbeat();
1191 	add_paths();
1192 	do_test_setup();
1193 
1194 	if (duration > 0)
1195 		stop_time = get_time_ms() + (unsigned long long)(duration * 1000);
1196 
1197 	for (;;) {
1198 		cont = 0;
1199 
1200 		if (i < (unsigned int)iterations) {
1201 			i++;
1202 			cont = 1;
1203 		}
1204 
1205 		if (stop_time && get_time_ms() < stop_time)
1206 			cont = 1;
1207 
1208 		if (!cont)
1209 			break;
1210 
1211 		run_tests();
1212 		heartbeat();
1213 	}
1214 
1215 	do_test_cleanup();
1216 	exit(0);
1217 }
1218 
1219 static pid_t test_pid;
1220 
1221 
1222 static volatile sig_atomic_t sigkill_retries;
1223 
1224 #define WRITE_MSG(msg) do { \
1225 	if (write(2, msg, sizeof(msg) - 1)) { \
1226 		/* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425 */ \
1227 	} \
1228 } while (0)
1229 
alarm_handler(int sig LTP_ATTRIBUTE_UNUSED)1230 static void alarm_handler(int sig LTP_ATTRIBUTE_UNUSED)
1231 {
1232 	WRITE_MSG("Test timeouted, sending SIGKILL!\n");
1233 	kill(-test_pid, SIGKILL);
1234 	alarm(5);
1235 
1236 	if (++sigkill_retries > 10) {
1237 		WRITE_MSG("Cannot kill test processes!\n");
1238 		WRITE_MSG("Congratulation, likely test hit a kernel bug.\n");
1239 		WRITE_MSG("Exiting uncleanly...\n");
1240 		_exit(TFAIL);
1241 	}
1242 }
1243 
heartbeat_handler(int sig LTP_ATTRIBUTE_UNUSED)1244 static void heartbeat_handler(int sig LTP_ATTRIBUTE_UNUSED)
1245 {
1246 	alarm(results->timeout);
1247 	sigkill_retries = 0;
1248 }
1249 
sigint_handler(int sig LTP_ATTRIBUTE_UNUSED)1250 static void sigint_handler(int sig LTP_ATTRIBUTE_UNUSED)
1251 {
1252 	if (test_pid > 0) {
1253 		WRITE_MSG("Sending SIGKILL to test process...\n");
1254 		kill(-test_pid, SIGKILL);
1255 	}
1256 }
1257 
tst_timeout_remaining(void)1258 unsigned int tst_timeout_remaining(void)
1259 {
1260 	static struct timespec now;
1261 	unsigned int elapsed;
1262 
1263 	if (tst_clock_gettime(CLOCK_MONOTONIC, &now))
1264 		tst_res(TWARN | TERRNO, "tst_clock_gettime() failed");
1265 
1266 	elapsed = (tst_timespec_diff_ms(now, tst_start_time) + 500) / 1000;
1267 	if (results->timeout > elapsed)
1268 		return results->timeout - elapsed;
1269 
1270 	return 0;
1271 }
1272 
tst_multiply_timeout(unsigned int timeout)1273 unsigned int tst_multiply_timeout(unsigned int timeout)
1274 {
1275 	char *mul;
1276 	int ret;
1277 
1278 	if (timeout_mul == -1) {
1279 		mul = getenv("LTP_TIMEOUT_MUL");
1280 		if (mul) {
1281 			if ((ret = tst_parse_float(mul, &timeout_mul, 1, 10000))) {
1282 				tst_brk(TBROK, "Failed to parse LTP_TIMEOUT_MUL: %s",
1283 						tst_strerrno(ret));
1284 			}
1285 		} else {
1286 			timeout_mul = 1;
1287 		}
1288 	}
1289 	if (timeout_mul < 1)
1290 		tst_brk(TBROK, "LTP_TIMEOUT_MUL must to be int >= 1! (%.2f)",
1291 				timeout_mul);
1292 
1293 	if (timeout < 1)
1294 		tst_brk(TBROK, "timeout must to be >= 1! (%d)", timeout);
1295 
1296 	return timeout * timeout_mul;
1297 }
1298 
tst_set_timeout(int timeout)1299 void tst_set_timeout(int timeout)
1300 {
1301 	if (timeout == -1) {
1302 		tst_res(TINFO, "Timeout per run is disabled");
1303 		return;
1304 	}
1305 
1306 	if (timeout < 1)
1307 		tst_brk(TBROK, "timeout must to be >= 1! (%d)", timeout);
1308 
1309 	results->timeout = tst_multiply_timeout(timeout);
1310 
1311 	tst_res(TINFO, "Timeout per run is %uh %02um %02us",
1312 		results->timeout/3600, (results->timeout%3600)/60,
1313 		results->timeout % 60);
1314 
1315 	if (getpid() == lib_pid)
1316 		alarm(results->timeout);
1317 	else
1318 		heartbeat();
1319 }
1320 
fork_testrun(void)1321 static int fork_testrun(void)
1322 {
1323 	int status;
1324 
1325 	if (tst_test->timeout)
1326 		tst_set_timeout(tst_test->timeout);
1327 	else
1328 		tst_set_timeout(300);
1329 
1330 	SAFE_SIGNAL(SIGINT, sigint_handler);
1331 
1332 	test_pid = fork();
1333 	if (test_pid < 0)
1334 		tst_brk(TBROK | TERRNO, "fork()");
1335 
1336 	if (!test_pid) {
1337 		SAFE_SIGNAL(SIGALRM, SIG_DFL);
1338 		SAFE_SIGNAL(SIGUSR1, SIG_DFL);
1339 		SAFE_SIGNAL(SIGINT, SIG_DFL);
1340 		SAFE_SETPGID(0, 0);
1341 		testrun();
1342 	}
1343 
1344 	SAFE_WAITPID(test_pid, &status, 0);
1345 	alarm(0);
1346 	SAFE_SIGNAL(SIGINT, SIG_DFL);
1347 
1348 	if (tst_test->taint_check && tst_taint_check()) {
1349 		tst_res(TFAIL, "Kernel is now tainted.");
1350 		return TFAIL;
1351 	}
1352 
1353 	if (WIFEXITED(status) && WEXITSTATUS(status))
1354 		return WEXITSTATUS(status);
1355 
1356 	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL) {
1357 		tst_res(TINFO, "If you are running on slow machine, "
1358 			       "try exporting LTP_TIMEOUT_MUL > 1");
1359 		tst_brk(TBROK, "Test killed! (timeout?)");
1360 	}
1361 
1362 	if (WIFSIGNALED(status))
1363 		tst_brk(TBROK, "Test killed by %s!", tst_strsig(WTERMSIG(status)));
1364 
1365 	return 0;
1366 }
1367 
run_tcases_per_fs(void)1368 static int run_tcases_per_fs(void)
1369 {
1370 	int ret = 0;
1371 	unsigned int i;
1372 	const char *const *filesystems = tst_get_supported_fs_types(tst_test->skip_filesystems);
1373 
1374 	if (!filesystems[0])
1375 		tst_brk(TCONF, "There are no supported filesystems");
1376 
1377 	for (i = 0; filesystems[i]; i++) {
1378 
1379 		tst_res(TINFO, "Testing on %s", filesystems[i]);
1380 		tdev.fs_type = filesystems[i];
1381 
1382 		prepare_device();
1383 
1384 		ret = fork_testrun();
1385 
1386 		if (mntpoint_mounted) {
1387 			tst_umount(tst_test->mntpoint);
1388 			mntpoint_mounted = 0;
1389 		}
1390 
1391 		if (ret == TCONF)
1392 			continue;
1393 
1394 		if (ret == 0)
1395 			continue;
1396 
1397 		do_exit(ret);
1398 	}
1399 
1400 	return ret;
1401 }
1402 
1403 unsigned int tst_variant;
1404 
tst_run_tcases(int argc,char * argv[],struct tst_test * self)1405 void tst_run_tcases(int argc, char *argv[], struct tst_test *self)
1406 {
1407 	int ret = 0;
1408 	unsigned int test_variants = 1;
1409 
1410 	lib_pid = getpid();
1411 	tst_test = self;
1412 
1413 	do_setup(argc, argv);
1414 
1415 	SAFE_SIGNAL(SIGALRM, alarm_handler);
1416 	SAFE_SIGNAL(SIGUSR1, heartbeat_handler);
1417 
1418 	if (tst_test->test_variants)
1419 		test_variants = tst_test->test_variants;
1420 
1421 	for (tst_variant = 0; tst_variant < test_variants; tst_variant++) {
1422 		if (tst_test->all_filesystems)
1423 			ret |= run_tcases_per_fs();
1424 		else
1425 			ret |= fork_testrun();
1426 
1427 		if (ret & ~(TCONF))
1428 			goto exit;
1429 	}
1430 
1431 exit:
1432 	do_exit(ret);
1433 }
1434 
1435 
tst_flush(void)1436 void tst_flush(void)
1437 {
1438 	int rval;
1439 
1440 	rval = fflush(stderr);
1441 	if (rval != 0)
1442 		tst_brk(TBROK | TERRNO, "fflush(stderr) failed");
1443 
1444 	rval = fflush(stdout);
1445 	if (rval != 0)
1446 		tst_brk(TBROK | TERRNO, "fflush(stdout) failed");
1447 
1448 }
1449