• 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 #include <math.h>
18 
19 #define TST_NO_DEFAULT_MAIN
20 #include "tst_test.h"
21 #include "tst_device.h"
22 #include "lapi/abisize.h"
23 #include "lapi/futex.h"
24 #include "lapi/syscalls.h"
25 #include "tst_ansi_color.h"
26 #include "tst_safe_stdio.h"
27 #include "tst_timer_test.h"
28 #include "tst_clocks.h"
29 #include "tst_timer.h"
30 #include "tst_wallclock.h"
31 #include "tst_sys_conf.h"
32 #include "tst_kconfig.h"
33 #include "tst_private.h"
34 #include "old_resource.h"
35 #include "old_device.h"
36 #include "old_tmpdir.h"
37 #include "ltp-version.h"
38 
39 /*
40  * Hack to get TCID defined in newlib tests
41  */
42 const char *TCID __attribute__((weak));
43 
44 /* update also docparse/testinfo.pl */
45 #define LINUX_GIT_URL "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id="
46 #define LINUX_STABLE_GIT_URL "https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/commit/?id="
47 #define GLIBC_GIT_URL "https://sourceware.org/git/?p=glibc.git;a=commit;h="
48 #define MUSL_GIT_URL "https://git.musl-libc.org/cgit/musl/commit/src/linux/clone.c?id="
49 #define CVE_DB_URL "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-"
50 
51 #define DEFAULT_TIMEOUT 30
52 
53 struct tst_test *tst_test;
54 
55 static const char *tid;
56 static int iterations = 1;
57 static float duration = -1;
58 static float timeout_mul = -1;
59 static pid_t main_pid, lib_pid;
60 static int mntpoint_mounted;
61 static int ovl_mounted;
62 static struct timespec tst_start_time; /* valid only for test pid */
63 static int tdebug;
64 
65 struct results {
66 	int passed;
67 	int skipped;
68 	int failed;
69 	int warnings;
70 	int broken;
71 	unsigned int timeout;
72 	int max_runtime;
73 };
74 
75 static struct results *results;
76 
77 static int ipc_fd;
78 
79 extern void *tst_futexes;
80 extern unsigned int tst_max_futexes;
81 
82 static char ipc_path[1064];
83 const char *tst_ipc_path = ipc_path;
84 
85 static char shm_path[1024];
86 
87 int TST_ERR;
88 int TST_PASS;
89 long TST_RET;
90 
91 static void do_cleanup(void);
92 static void do_exit(int ret) __attribute__ ((noreturn));
93 
setup_ipc(void)94 static void setup_ipc(void)
95 {
96 	size_t size = getpagesize();
97 
98 	if (access("/dev/shm", F_OK) == 0) {
99 		snprintf(shm_path, sizeof(shm_path), "/dev/shm/ltp_%s_%d",
100 			 tid, getpid());
101 	} else {
102 		char *tmpdir;
103 
104 		if (!tst_tmpdir_created())
105 			tst_tmpdir();
106 
107 		tmpdir = tst_get_tmpdir();
108 		snprintf(shm_path, sizeof(shm_path), "%s/ltp_%s_%d",
109 			 tmpdir, tid, getpid());
110 		free(tmpdir);
111 	}
112 
113 	ipc_fd = open(shm_path, O_CREAT | O_EXCL | O_RDWR, 0600);
114 	if (ipc_fd < 0)
115 		tst_brk(TBROK | TERRNO, "open(%s)", shm_path);
116 	SAFE_CHMOD(shm_path, 0666);
117 
118 	SAFE_FTRUNCATE(ipc_fd, size);
119 
120 	results = SAFE_MMAP(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, ipc_fd, 0);
121 
122 	/* Checkpoints needs to be accessible from processes started by exec() */
123 	if (tst_test->needs_checkpoints || tst_test->child_needs_reinit) {
124 		sprintf(ipc_path, IPC_ENV_VAR "=%s", shm_path);
125 		putenv(ipc_path);
126 	} else {
127 		SAFE_UNLINK(shm_path);
128 	}
129 
130 	SAFE_CLOSE(ipc_fd);
131 
132 	if (tst_test->needs_checkpoints) {
133 		tst_futexes = (char *)results + sizeof(struct results);
134 		tst_max_futexes = (size - sizeof(struct results))/sizeof(futex_t);
135 	}
136 }
137 
cleanup_ipc(void)138 static void cleanup_ipc(void)
139 {
140 	size_t size = getpagesize();
141 
142 	if (ipc_fd > 0 && close(ipc_fd))
143 		tst_res(TWARN | TERRNO, "close(ipc_fd) failed");
144 
145 	if (shm_path[0] && !access(shm_path, F_OK) && unlink(shm_path))
146 		tst_res(TWARN | TERRNO, "unlink(%s) failed", shm_path);
147 
148 	if (results) {
149 		msync((void *)results, size, MS_SYNC);
150 		munmap((void *)results, size);
151 		results = NULL;
152 	}
153 }
154 
tst_reinit(void)155 void tst_reinit(void)
156 {
157 	const char *path = getenv(IPC_ENV_VAR);
158 	size_t size = getpagesize();
159 	int fd;
160 
161 	if (!path)
162 		tst_brk(TBROK, IPC_ENV_VAR" is not defined");
163 
164 	if (access(path, F_OK))
165 		tst_brk(TBROK, "File %s does not exist!", path);
166 
167 	fd = SAFE_OPEN(path, O_RDWR);
168 
169 	results = SAFE_MMAP(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
170 	tst_futexes = (char *)results + sizeof(struct results);
171 	tst_max_futexes = (size - sizeof(struct results))/sizeof(futex_t);
172 
173 	SAFE_CLOSE(fd);
174 }
175 
update_results(int ttype)176 static void update_results(int ttype)
177 {
178 	if (!results)
179 		return;
180 
181 	switch (ttype) {
182 	case TCONF:
183 		tst_atomic_inc(&results->skipped);
184 	break;
185 	case TPASS:
186 		tst_atomic_inc(&results->passed);
187 	break;
188 	case TWARN:
189 		tst_atomic_inc(&results->warnings);
190 	break;
191 	case TFAIL:
192 		tst_atomic_inc(&results->failed);
193 	break;
194 	case TBROK:
195 		tst_atomic_inc(&results->broken);
196 	break;
197 	}
198 }
199 
print_result(const char * file,const int lineno,int ttype,const char * fmt,va_list va)200 static void print_result(const char *file, const int lineno, int ttype,
201 			 const char *fmt, va_list va)
202 {
203 	char buf[1024];
204 	char *str = buf;
205 	int ret, size = sizeof(buf), ssize, int_errno, buflen;
206 	const char *str_errno = NULL;
207 	const char *res;
208 
209 	switch (TTYPE_RESULT(ttype)) {
210 	case TPASS:
211 		res = "TPASS";
212 	break;
213 	case TFAIL:
214 		res = "TFAIL";
215 	break;
216 	case TBROK:
217 		res = "TBROK";
218 	break;
219 	case TCONF:
220 		res = "TCONF";
221 	break;
222 	case TWARN:
223 		res = "TWARN";
224 	break;
225 	case TINFO:
226 		res = "TINFO";
227 	break;
228 	case TDEBUG:
229 		res = "TDEBUG";
230 	break;
231 	default:
232 		tst_brk(TBROK, "Invalid ttype value %i", ttype);
233 		abort();
234 	}
235 
236 	if (ttype & TERRNO) {
237 		str_errno = tst_strerrno(errno);
238 		int_errno = errno;
239 	}
240 
241 	if (ttype & TTERRNO) {
242 		str_errno = tst_strerrno(TST_ERR);
243 		int_errno = TST_ERR;
244 	}
245 
246 	if (ttype & TRERRNO) {
247 		int_errno = TST_RET < 0 ? -(int)TST_RET : (int)TST_RET;
248 		str_errno = tst_strerrno(int_errno);
249 	}
250 
251 	ret = snprintf(str, size, "%s:%i: ", file, lineno);
252 	str += ret;
253 	size -= ret;
254 
255 	if (tst_color_enabled(STDERR_FILENO))
256 		ret = snprintf(str, size, "%s%s: %s", tst_ttype2color(ttype),
257 			       res, ANSI_COLOR_RESET);
258 	else
259 		ret = snprintf(str, size, "%s: ", res);
260 	str += ret;
261 	size -= ret;
262 
263 	ssize = size - 2;
264 	ret = vsnprintf(str, size, fmt, va);
265 	str += MIN(ret, ssize);
266 	size -= MIN(ret, ssize);
267 	if (ret >= ssize) {
268 		tst_res_(file, lineno, TWARN,
269 				"Next message is too long and truncated:");
270 	} else if (str_errno) {
271 		ssize = size - 2;
272 		ret = snprintf(str, size, ": %s (%d)", str_errno, int_errno);
273 		str += MIN(ret, ssize);
274 		size -= MIN(ret, ssize);
275 		if (ret >= ssize)
276 			tst_res_(file, lineno, TWARN,
277 				"Next message is too long and truncated:");
278 	}
279 
280 	snprintf(str, size, "\n");
281 
282 	/* we might be called from signal handler, so use write() */
283 	buflen = str - buf + 1;
284 	str = buf;
285 	while (buflen) {
286 		ret = write(STDERR_FILENO, str, buflen);
287 		if (ret <= 0)
288 			break;
289 
290 		str += ret;
291 		buflen -= ret;
292 	}
293 }
294 
tst_vres_(const char * file,const int lineno,int ttype,const char * fmt,va_list va)295 void tst_vres_(const char *file, const int lineno, int ttype, const char *fmt,
296 	       va_list va)
297 {
298 	print_result(file, lineno, ttype, fmt, va);
299 
300 	update_results(TTYPE_RESULT(ttype));
301 }
302 
303 void tst_vbrk_(const char *file, const int lineno, int ttype, const char *fmt,
304 	       va_list va);
305 
306 static void (*tst_brk_handler)(const char *file, const int lineno, int ttype,
307 			       const char *fmt, va_list va) = tst_vbrk_;
308 
tst_cvres(const char * file,const int lineno,int ttype,const char * fmt,va_list va)309 static void tst_cvres(const char *file, const int lineno, int ttype,
310 		      const char *fmt, va_list va)
311 {
312 	if (TTYPE_RESULT(ttype) == TBROK) {
313 		ttype &= ~TTYPE_MASK;
314 		ttype |= TWARN;
315 	}
316 
317 	print_result(file, lineno, ttype, fmt, va);
318 	update_results(TTYPE_RESULT(ttype));
319 }
320 
do_test_cleanup(void)321 static void do_test_cleanup(void)
322 {
323 	tst_brk_handler = tst_cvres;
324 
325 	if (tst_test->cleanup)
326 		tst_test->cleanup();
327 
328 	tst_free_all();
329 
330 	tst_brk_handler = tst_vbrk_;
331 }
332 
tst_vbrk_(const char * file,const int lineno,int ttype,const char * fmt,va_list va)333 void tst_vbrk_(const char *file, const int lineno, int ttype, const char *fmt,
334 	       va_list va)
335 {
336 	print_result(file, lineno, ttype, fmt, va);
337 	update_results(TTYPE_RESULT(ttype));
338 
339 	/*
340 	 * The getpid implementation in some C library versions may cause cloned
341 	 * test threads to show the same pid as their parent when CLONE_VM is
342 	 * specified but CLONE_THREAD is not. Use direct syscall to avoid
343 	 * cleanup running in the child.
344 	 */
345 	if (tst_getpid() == main_pid)
346 		do_test_cleanup();
347 
348 	if (getpid() == lib_pid)
349 		do_exit(TTYPE_RESULT(ttype));
350 
351 	exit(TTYPE_RESULT(ttype));
352 }
353 
tst_res_(const char * file,const int lineno,int ttype,const char * fmt,...)354 void tst_res_(const char *file, const int lineno, int ttype,
355 	      const char *fmt, ...)
356 {
357 	va_list va;
358 
359 	if (ttype == TDEBUG && !tdebug)
360 		return;
361 
362 	va_start(va, fmt);
363 	tst_vres_(file, lineno, ttype, fmt, va);
364 	va_end(va);
365 }
366 
tst_brk_(const char * file,const int lineno,int ttype,const char * fmt,...)367 void tst_brk_(const char *file, const int lineno, int ttype,
368 	      const char *fmt, ...)
369 {
370 	va_list va;
371 
372 	va_start(va, fmt);
373 	tst_brk_handler(file, lineno, ttype, fmt, va);
374 	va_end(va);
375 }
376 
tst_printf(const char * const fmt,...)377 void tst_printf(const char *const fmt, ...)
378 {
379 	va_list va;
380 
381 	va_start(va, fmt);
382 	vdprintf(STDERR_FILENO, fmt, va);
383 	va_end(va);
384 }
385 
check_child_status(pid_t pid,int status)386 static void check_child_status(pid_t pid, int status)
387 {
388 	int ret;
389 
390 	if (WIFSIGNALED(status)) {
391 		tst_brk(TBROK, "Child (%i) killed by signal %s", pid,
392 			tst_strsig(WTERMSIG(status)));
393 	}
394 
395 	if (!(WIFEXITED(status)))
396 		tst_brk(TBROK, "Child (%i) exited abnormally", pid);
397 
398 	ret = WEXITSTATUS(status);
399 	switch (ret) {
400 	case TPASS:
401 	case TBROK:
402 	case TCONF:
403 	break;
404 	default:
405 		tst_brk(TBROK, "Invalid child (%i) exit value %i", pid, ret);
406 	}
407 }
408 
tst_reap_children(void)409 void tst_reap_children(void)
410 {
411 	int status;
412 	pid_t pid;
413 
414 	for (;;) {
415 		pid = wait(&status);
416 
417 		if (pid > 0) {
418 			check_child_status(pid, status);
419 			continue;
420 		}
421 
422 		if (errno == ECHILD)
423 			break;
424 
425 		if (errno == EINTR)
426 			continue;
427 
428 		tst_brk(TBROK | TERRNO, "wait() failed");
429 	}
430 }
431 
432 
safe_fork(const char * filename,unsigned int lineno)433 pid_t safe_fork(const char *filename, unsigned int lineno)
434 {
435 	pid_t pid;
436 
437 	if (!tst_test->forks_child)
438 		tst_brk(TBROK, "test.forks_child must be set!");
439 
440 	tst_flush();
441 
442 	pid = fork();
443 	if (pid < 0)
444 		tst_brk_(filename, lineno, TBROK | TERRNO, "fork() failed");
445 
446 	if (!pid)
447 		atexit(tst_free_all);
448 
449 	return pid;
450 }
451 
452 /* too fast creating namespaces => retrying */
453 #define TST_CHECK_ENOSPC(x) ((x) >= 0 || !(errno == ENOSPC))
454 
safe_clone(const char * file,const int lineno,const struct tst_clone_args * args)455 pid_t safe_clone(const char *file, const int lineno,
456 		 const struct tst_clone_args *args)
457 {
458 	pid_t pid;
459 
460 	if (!tst_test->forks_child)
461 		tst_brk(TBROK, "test.forks_child must be set!");
462 
463 	pid = TST_RETRY_FUNC(tst_clone(args), TST_CHECK_ENOSPC);
464 
465 	switch (pid) {
466 	case -1:
467 		tst_brk_(file, lineno, TBROK | TERRNO, "clone3 failed");
468 		break;
469 	case -2:
470 		tst_brk_(file, lineno, TBROK | TERRNO, "clone failed");
471 		return -1;
472 	}
473 
474 	if (!pid)
475 		atexit(tst_free_all);
476 
477 	return pid;
478 }
479 
parse_mul(float * mul,const char * env_name,float min,float max)480 static void parse_mul(float *mul, const char *env_name, float min, float max)
481 {
482 	char *str_mul;
483 	int ret;
484 
485 	if (*mul > 0)
486 		return;
487 
488 	str_mul = getenv(env_name);
489 
490 	if (!str_mul) {
491 		*mul = 1;
492 		return;
493 	}
494 
495 	ret = tst_parse_float(str_mul, mul, min, max);
496 	if (ret) {
497 		tst_brk(TBROK, "Failed to parse %s: %s",
498 			env_name, tst_strerrno(ret));
499 	}
500 }
501 
multiply_runtime(int max_runtime)502 static int multiply_runtime(int max_runtime)
503 {
504 	static float runtime_mul = -1;
505 
506 	if (max_runtime <= 0)
507 		return max_runtime;
508 
509 	parse_mul(&runtime_mul, "LTP_RUNTIME_MUL", 0.0099, 100);
510 
511 	return max_runtime * runtime_mul;
512 }
513 
514 static struct option {
515 	char *optstr;
516 	char *help;
517 } options[] = {
518 	{"h",  "-h       Prints this help"},
519 	{"i:", "-i n     Execute test n times"},
520 	{"I:", "-I x     Execute test for n seconds"},
521 	{"D",  "-D       Prints debug information"},
522 	{"V",  "-V       Prints LTP version"},
523 	{"C:", "-C ARG   Run child process with ARG arguments (used internally)"},
524 };
525 
print_help(void)526 static void print_help(void)
527 {
528 	unsigned int i;
529 	int timeout, runtime;
530 
531 	/* see doc/User-Guidelines.asciidoc, which lists also shell API variables */
532 	fprintf(stderr, "Environment Variables\n");
533 	fprintf(stderr, "---------------------\n");
534 	fprintf(stderr, "KCONFIG_PATH         Specify kernel config file\n");
535 	fprintf(stderr, "KCONFIG_SKIP_CHECK   Skip kernel config check if variable set (not set by default)\n");
536 	fprintf(stderr, "LTPROOT              Prefix for installed LTP (default: /opt/ltp)\n");
537 	fprintf(stderr, "LTP_COLORIZE_OUTPUT  Force colorized output behaviour (y/1 always, n/0: never)\n");
538 	fprintf(stderr, "LTP_DEV              Path to the block device to be used (for .needs_device)\n");
539 	fprintf(stderr, "LTP_DEV_FS_TYPE      Filesystem used for testing (default: %s)\n", DEFAULT_FS_TYPE);
540 	fprintf(stderr, "LTP_SINGLE_FS_TYPE   Testing only - specifies filesystem instead all supported (for .all_filesystems)\n");
541 	fprintf(stderr, "LTP_TIMEOUT_MUL      Timeout multiplier (must be a number >=1)\n");
542 	fprintf(stderr, "LTP_RUNTIME_MUL      Runtime multiplier (must be a number >=1)\n");
543 	fprintf(stderr, "LTP_VIRT_OVERRIDE    Overrides virtual machine detection (values: \"\"|kvm|microsoft|xen|zvm)\n");
544 	fprintf(stderr, "TMPDIR               Base directory for template directory (for .needs_tmpdir, default: %s)\n", TEMPDIR);
545 	fprintf(stderr, "\n");
546 
547 	fprintf(stderr, "Timeout and runtime\n");
548 	fprintf(stderr, "-------------------\n");
549 
550 	if (tst_test->max_runtime) {
551 		runtime = multiply_runtime(tst_test->max_runtime);
552 
553 		if (runtime == TST_UNLIMITED_RUNTIME) {
554 			fprintf(stderr, "Test iteration runtime is not limited\n");
555 		} else {
556 			fprintf(stderr, "Test iteration runtime cap %ih %im %is\n",
557 				runtime/3600, (runtime%3600)/60, runtime % 60);
558 		}
559 	}
560 
561 	timeout = tst_multiply_timeout(DEFAULT_TIMEOUT);
562 
563 	fprintf(stderr, "Test timeout (not including runtime) %ih %im %is\n",
564 		timeout/3600, (timeout%3600)/60, timeout % 60);
565 
566 	fprintf(stderr, "\n");
567 
568 	fprintf(stderr, "Options\n");
569 	fprintf(stderr, "-------\n");
570 
571 	for (i = 0; i < ARRAY_SIZE(options); i++)
572 		fprintf(stderr, "%s\n", options[i].help);
573 
574 	if (!tst_test->options)
575 		return;
576 
577 	for (i = 0; tst_test->options[i].optstr; i++) {
578 		fprintf(stderr, "-%c\t %s\n",
579 			tst_test->options[i].optstr[0],
580 			tst_test->options[i].help);
581 	}
582 }
583 
print_test_tags(void)584 static void print_test_tags(void)
585 {
586 	unsigned int i;
587 	const struct tst_tag *tags = tst_test->tags;
588 
589 	if (!tags)
590 		return;
591 
592 	fprintf(stderr, "\nTags\n");
593 	fprintf(stderr, "----\n");
594 
595 	for (i = 0; tags[i].name; i++) {
596 		if (!strcmp(tags[i].name, "CVE"))
597 			fprintf(stderr, CVE_DB_URL "%s\n", tags[i].value);
598 		else if (!strcmp(tags[i].name, "linux-git"))
599 			fprintf(stderr, LINUX_GIT_URL "%s\n", tags[i].value);
600 		else if (!strcmp(tags[i].name, "linux-stable-git"))
601 			fprintf(stderr, LINUX_STABLE_GIT_URL "%s\n", tags[i].value);
602 		else if (!strcmp(tags[i].name, "glibc-git"))
603 			fprintf(stderr, GLIBC_GIT_URL "%s\n", tags[i].value);
604 		else if (!strcmp(tags[i].name, "musl-git"))
605 			fprintf(stderr, MUSL_GIT_URL "%s\n", tags[i].value);
606 		else
607 			fprintf(stderr, "%s: %s\n", tags[i].name, tags[i].value);
608 	}
609 
610 	fprintf(stderr, "\n");
611 }
612 
check_option_collision(void)613 static void check_option_collision(void)
614 {
615 	unsigned int i, j;
616 	struct tst_option *toptions = tst_test->options;
617 
618 	if (!toptions)
619 		return;
620 
621 	for (i = 0; toptions[i].optstr; i++) {
622 		for (j = 0; j < ARRAY_SIZE(options); j++) {
623 			if (toptions[i].optstr[0] == options[j].optstr[0]) {
624 				tst_brk(TBROK, "Option collision '%s'",
625 					options[j].help);
626 			}
627 		}
628 	}
629 }
630 
count_options(void)631 static unsigned int count_options(void)
632 {
633 	unsigned int i;
634 
635 	if (!tst_test->options)
636 		return 0;
637 
638 	for (i = 0; tst_test->options[i].optstr; i++)
639 		;
640 
641 	return i;
642 }
643 
parse_topt(unsigned int topts_len,int opt,char * optarg)644 static void parse_topt(unsigned int topts_len, int opt, char *optarg)
645 {
646 	unsigned int i;
647 	struct tst_option *toptions = tst_test->options;
648 
649 	for (i = 0; i < topts_len; i++) {
650 		if (toptions[i].optstr[0] == opt)
651 			break;
652 	}
653 
654 	if (i >= topts_len)
655 		tst_brk(TBROK, "Invalid option '%c' (should not happen)", opt);
656 
657 	if (*toptions[i].arg)
658 		tst_res(TWARN, "Option -%c passed multiple times", opt);
659 
660 	*(toptions[i].arg) = optarg ? optarg : "";
661 }
662 
663 /* see self_exec.c */
664 #ifdef UCLINUX
665 extern char *child_args;
666 #endif
667 
parse_opts(int argc,char * argv[])668 static void parse_opts(int argc, char *argv[])
669 {
670 	unsigned int i, topts_len = count_options();
671 	char optstr[2 * ARRAY_SIZE(options) + 2 * topts_len];
672 	int opt;
673 
674 	check_option_collision();
675 
676 	optstr[0] = 0;
677 
678 	for (i = 0; i < ARRAY_SIZE(options); i++)
679 		strcat(optstr, options[i].optstr);
680 
681 	for (i = 0; i < topts_len; i++)
682 		strcat(optstr, tst_test->options[i].optstr);
683 
684 	while ((opt = getopt(argc, argv, optstr)) > 0) {
685 		switch (opt) {
686 		case '?':
687 			print_help();
688 			tst_brk(TBROK, "Invalid option");
689 		break;
690 		case 'D':
691 			tst_res(TINFO, "Enabling debug info");
692 			tdebug = 1;
693 		break;
694 		case 'h':
695 			print_help();
696 			print_test_tags();
697 			exit(0);
698 		case 'i':
699 			iterations = SAFE_STRTOL(optarg, 0, INT_MAX);
700 		break;
701 		case 'I':
702 			if (tst_test->max_runtime > 0)
703 				tst_test->max_runtime = SAFE_STRTOL(optarg, 1, INT_MAX);
704 			else
705 				duration = SAFE_STRTOF(optarg, 0.1, HUGE_VALF);
706 		break;
707 		case 'V':
708 			fprintf(stderr, "LTP version: " LTP_VERSION "\n");
709 			exit(0);
710 		break;
711 		case 'C':
712 #ifdef UCLINUX
713 			child_args = optarg;
714 #endif
715 		break;
716 		default:
717 			parse_topt(topts_len, opt, optarg);
718 		}
719 	}
720 
721 	if (optind < argc)
722 		tst_brk(TBROK, "Unexpected argument(s) '%s'...", argv[optind]);
723 }
724 
tst_parse_int(const char * str,int * val,int min,int max)725 int tst_parse_int(const char *str, int *val, int min, int max)
726 {
727 	long rval;
728 
729 	if (!str)
730 		return 0;
731 
732 	int ret = tst_parse_long(str, &rval, min, max);
733 
734 	if (ret)
735 		return ret;
736 
737 	*val = (int)rval;
738 	return 0;
739 }
740 
tst_parse_long(const char * str,long * val,long min,long max)741 int tst_parse_long(const char *str, long *val, long min, long max)
742 {
743 	long rval;
744 	char *end;
745 
746 	if (!str)
747 		return 0;
748 
749 	errno = 0;
750 	rval = strtol(str, &end, 10);
751 
752 	if (str == end || *end != '\0')
753 		return EINVAL;
754 
755 	if (errno)
756 		return errno;
757 
758 	if (rval > max || rval < min)
759 		return ERANGE;
760 
761 	*val = rval;
762 	return 0;
763 }
764 
tst_parse_float(const char * str,float * val,float min,float max)765 int tst_parse_float(const char *str, float *val, float min, float max)
766 {
767 	double rval;
768 	char *end;
769 
770 	if (!str)
771 		return 0;
772 
773 	errno = 0;
774 	rval = strtod(str, &end);
775 
776 	if (str == end || *end != '\0')
777 		return EINVAL;
778 
779 	if (errno)
780 		return errno;
781 
782 	if (rval > (double)max || rval < (double)min)
783 		return ERANGE;
784 
785 	*val = (float)rval;
786 	return 0;
787 }
788 
tst_parse_filesize(const char * str,long long * val,long long min,long long max)789 int tst_parse_filesize(const char *str, long long *val, long long min, long long max)
790 {
791 	long long rval;
792 	char *end;
793 
794 	if (!str)
795 		return 0;
796 
797 	errno = 0;
798 	rval = strtoll(str, &end, 0);
799 
800 	if (str == end || (end[0] && end[1]))
801 		return EINVAL;
802 
803 	if (errno)
804 		return errno;
805 
806 	switch (*end) {
807 	case 'g':
808 	case 'G':
809 		rval *= (1024 * 1024 * 1024);
810 		break;
811 	case 'm':
812 	case 'M':
813 		rval *= (1024 * 1024);
814 		break;
815 	case 'k':
816 	case 'K':
817 		rval *= 1024;
818 		break;
819 	default:
820 		break;
821 	}
822 
823 	if (rval > max || rval < min)
824 		return ERANGE;
825 
826 	*val = rval;
827 	return 0;
828 }
829 
print_colored(const char * str)830 static void print_colored(const char *str)
831 {
832 	if (tst_color_enabled(STDOUT_FILENO))
833 		fprintf(stderr, "%s%s%s", ANSI_COLOR_YELLOW, str, ANSI_COLOR_RESET);
834 	else
835 		fprintf(stderr, "%s", str);
836 }
837 
print_failure_hint(const char * tag,const char * hint,const char * url)838 static void print_failure_hint(const char *tag, const char *hint,
839 			       const char *url)
840 {
841 	const struct tst_tag *tags = tst_test->tags;
842 
843 	if (!tags)
844 		return;
845 
846 	unsigned int i;
847 	int hint_printed = 0;
848 
849 	for (i = 0; tags[i].name; i++) {
850 		if (!strcmp(tags[i].name, tag)) {
851 			if (!hint_printed) {
852 				hint_printed = 1;
853 				fprintf(stderr, "\n");
854 				print_colored("HINT: ");
855 				fprintf(stderr, "You _MAY_ be %s:\n\n", hint);
856 			}
857 
858 			if (url)
859 				fprintf(stderr, "%s%s\n", url, tags[i].value);
860 			else
861 				fprintf(stderr, "%s\n", tags[i].value);
862 		}
863 	}
864 }
865 
866 /* update also docparse/testinfo.pl */
print_failure_hints(void)867 static void print_failure_hints(void)
868 {
869 	print_failure_hint("linux-git", "missing kernel fixes", LINUX_GIT_URL);
870 	print_failure_hint("linux-stable-git", "missing stable kernel fixes",
871 					   LINUX_STABLE_GIT_URL);
872 	print_failure_hint("glibc-git", "missing glibc fixes", GLIBC_GIT_URL);
873 	print_failure_hint("musl-git", "missing musl fixes", MUSL_GIT_URL);
874 	print_failure_hint("CVE", "vulnerable to CVE(s)", CVE_DB_URL);
875 	print_failure_hint("known-fail", "hit by known kernel failures", NULL);
876 }
877 
do_exit(int ret)878 static void do_exit(int ret)
879 {
880 	if (results) {
881 		if (results->passed && ret == TCONF)
882 			ret = 0;
883 
884 		if (results->failed) {
885 			ret |= TFAIL;
886 			print_failure_hints();
887 		}
888 
889 		if (results->skipped && !results->passed)
890 			ret |= TCONF;
891 
892 		if (results->warnings)
893 			ret |= TWARN;
894 
895 		if (results->broken) {
896 			ret |= TBROK;
897 			print_failure_hints();
898 		}
899 
900 		fprintf(stderr, "\nSummary:\n");
901 		fprintf(stderr, "passed   %d\n", results->passed);
902 		fprintf(stderr, "failed   %d\n", results->failed);
903 		fprintf(stderr, "broken   %d\n", results->broken);
904 		fprintf(stderr, "skipped  %d\n", results->skipped);
905 		fprintf(stderr, "warnings %d\n", results->warnings);
906 	}
907 
908 	do_cleanup();
909 
910 	exit(ret);
911 }
912 
check_kver(void)913 void check_kver(void)
914 {
915 	int v1, v2, v3;
916 
917 	if (tst_parse_kver(tst_test->min_kver, &v1, &v2, &v3)) {
918 		tst_res(TWARN,
919 			"Invalid kernel version %s, expected %%d.%%d.%%d",
920 			tst_test->min_kver);
921 	}
922 
923 	if (tst_kvercmp(v1, v2, v3) < 0) {
924 		tst_brk(TCONF, "The test requires kernel %s or newer",
925 			tst_test->min_kver);
926 	}
927 }
928 
results_equal(struct results * a,struct results * b)929 static int results_equal(struct results *a, struct results *b)
930 {
931 	if (a->passed != b->passed)
932 		return 0;
933 
934 	if (a->failed != b->failed)
935 		return 0;
936 
937 	if (a->skipped != b->skipped)
938 		return 0;
939 
940 	if (a->broken != b->broken)
941 		return 0;
942 
943 	return 1;
944 }
945 
needs_tmpdir(void)946 static int needs_tmpdir(void)
947 {
948 	return tst_test->needs_tmpdir ||
949 	       tst_test->needs_device ||
950 	       tst_test->mntpoint ||
951 	       tst_test->resource_files ||
952 	       tst_test->needs_checkpoints;
953 }
954 
copy_resources(void)955 static void copy_resources(void)
956 {
957 	unsigned int i;
958 
959 	for (i = 0; tst_test->resource_files[i]; i++)
960 		TST_RESOURCE_COPY(NULL, tst_test->resource_files[i], NULL);
961 }
962 
get_tid(char * argv[])963 static const char *get_tid(char *argv[])
964 {
965 	char *p;
966 
967 	if (!argv[0] || !argv[0][0]) {
968 		tst_res(TINFO, "argv[0] is empty!");
969 		return "ltp_empty_argv";
970 	}
971 
972 	p = strrchr(argv[0], '/');
973 	if (p)
974 		return p+1;
975 
976 	return argv[0];
977 }
978 
979 static struct tst_device tdev;
980 struct tst_device *tst_device;
981 
assert_test_fn(void)982 static void assert_test_fn(void)
983 {
984 	int cnt = 0;
985 
986 	if (tst_test->test)
987 		cnt++;
988 
989 	if (tst_test->test_all)
990 		cnt++;
991 
992 	if (tst_test->sample)
993 		cnt++;
994 
995 	if (!cnt)
996 		tst_brk(TBROK, "No test function specified");
997 
998 	if (cnt != 1)
999 		tst_brk(TBROK, "You can define only one test function");
1000 
1001 	if (tst_test->test && !tst_test->tcnt)
1002 		tst_brk(TBROK, "Number of tests (tcnt) must be > 0");
1003 
1004 	if (!tst_test->test && tst_test->tcnt)
1005 		tst_brk(TBROK, "You can define tcnt only for test()");
1006 }
1007 
prepare_and_mount_ro_fs(const char * dev,const char * mntpoint,const char * fs_type)1008 static int prepare_and_mount_ro_fs(const char *dev, const char *mntpoint,
1009 				   const char *fs_type)
1010 {
1011 	char buf[PATH_MAX];
1012 
1013 	if (mount(dev, mntpoint, fs_type, 0, NULL)) {
1014 		tst_res(TINFO | TERRNO, "Can't mount %s at %s (%s)",
1015 			dev, mntpoint, fs_type);
1016 		return 1;
1017 	}
1018 
1019 	mntpoint_mounted = 1;
1020 
1021 	snprintf(buf, sizeof(buf), "%s/dir/", mntpoint);
1022 	SAFE_MKDIR(buf, 0777);
1023 
1024 	snprintf(buf, sizeof(buf), "%s/file", mntpoint);
1025 	SAFE_FILE_PRINTF(buf, "file content");
1026 	SAFE_CHMOD(buf, 0777);
1027 
1028 	SAFE_MOUNT(dev, mntpoint, fs_type, MS_REMOUNT | MS_RDONLY, NULL);
1029 
1030 	return 0;
1031 }
1032 
prepare_and_mount_dev_fs(const char * mntpoint)1033 static void prepare_and_mount_dev_fs(const char *mntpoint)
1034 {
1035 	const char *flags[] = {"nodev", NULL};
1036 	int mounted_nodev;
1037 
1038 	mounted_nodev = tst_path_has_mnt_flags(NULL, flags);
1039 	if (mounted_nodev) {
1040 		tst_res(TINFO, "tmpdir isn't suitable for creating devices, "
1041 			"mounting tmpfs without nodev on %s", mntpoint);
1042 		SAFE_MOUNT(NULL, mntpoint, "tmpfs", 0, NULL);
1043 		mntpoint_mounted = 1;
1044 	}
1045 }
1046 
prepare_and_mount_hugetlb_fs(void)1047 static void prepare_and_mount_hugetlb_fs(void)
1048 {
1049 	SAFE_MOUNT("none", tst_test->mntpoint, "hugetlbfs", 0, NULL);
1050 	mntpoint_mounted = 1;
1051 }
1052 
tst_creat_unlinked(const char * path,int flags)1053 int tst_creat_unlinked(const char *path, int flags)
1054 {
1055 	char template[PATH_MAX];
1056 	int len, c, range;
1057 	int fd;
1058 	int start[3] = {'0', 'a', 'A'};
1059 
1060 	snprintf(template, PATH_MAX, "%s/ltp_%.3sXXXXXX",
1061 			path, tid);
1062 
1063 	len = strlen(template) - 1;
1064 	while (template[len] == 'X') {
1065 		c = rand() % 3;
1066 		range = start[c] == '0' ? 10 : 26;
1067 		c = start[c] + (rand() % range);
1068 		template[len--] = (char)c;
1069 	}
1070 
1071 	flags |= O_CREAT|O_EXCL|O_RDWR;
1072 	fd = SAFE_OPEN(template, flags);
1073 	SAFE_UNLINK(template);
1074 	return fd;
1075 }
1076 
limit_tmpfs_mount_size(const char * mnt_data,char * buf,size_t buf_size,const char * fs_type)1077 static const char *limit_tmpfs_mount_size(const char *mnt_data,
1078 		char *buf, size_t buf_size, const char *fs_type)
1079 {
1080 	unsigned int tmpfs_size;
1081 
1082 	if (strcmp(fs_type, "tmpfs"))
1083 		return mnt_data;
1084 
1085 	if (!tst_test->dev_min_size)
1086 		tmpfs_size = 32;
1087 	else
1088 		tmpfs_size = tdev.size;
1089 
1090 	if ((tst_available_mem() / 1024) < (tmpfs_size * 2))
1091 		tst_brk(TCONF, "No enough memory for tmpfs use");
1092 
1093 	if (mnt_data)
1094 		snprintf(buf, buf_size, "%s,size=%uM", mnt_data, tmpfs_size);
1095 	else
1096 		snprintf(buf, buf_size, "size=%uM", tmpfs_size);
1097 
1098 	tst_res(TINFO, "Limiting tmpfs size to %uMB", tmpfs_size);
1099 
1100 	return buf;
1101 }
1102 
get_device_name(const char * fs_type)1103 static const char *get_device_name(const char *fs_type)
1104 {
1105 	if (!strcmp(fs_type, "tmpfs"))
1106 		return "ltp-tmpfs";
1107 	else
1108 		return tdev.dev;
1109 }
1110 
prepare_device(void)1111 static void prepare_device(void)
1112 {
1113 	const char *mnt_data;
1114 	char buf[1024];
1115 
1116 	if (tst_test->format_device) {
1117 		SAFE_MKFS(tdev.dev, tdev.fs_type, tst_test->dev_fs_opts,
1118 			  tst_test->dev_extra_opts);
1119 	}
1120 
1121 	if (tst_test->needs_rofs) {
1122 		prepare_and_mount_ro_fs(tdev.dev, tst_test->mntpoint,
1123 					tdev.fs_type);
1124 		return;
1125 	}
1126 
1127 	if (tst_test->mount_device) {
1128 		mnt_data = limit_tmpfs_mount_size(tst_test->mnt_data,
1129 				buf, sizeof(buf), tdev.fs_type);
1130 
1131 		SAFE_MOUNT(get_device_name(tdev.fs_type), tst_test->mntpoint,
1132 				tdev.fs_type, tst_test->mnt_flags, mnt_data);
1133 		mntpoint_mounted = 1;
1134 	}
1135 }
1136 
do_cgroup_requires(void)1137 static void do_cgroup_requires(void)
1138 {
1139 	const struct tst_cg_opts cg_opts = {
1140 		.needs_ver = tst_test->needs_cgroup_ver,
1141 	};
1142 	const char *const *ctrl_names = tst_test->needs_cgroup_ctrls;
1143 
1144 	for (; *ctrl_names; ctrl_names++)
1145 		tst_cg_require(*ctrl_names, &cg_opts);
1146 
1147 	tst_cg_init();
1148 }
1149 
do_setup(int argc,char * argv[])1150 static void do_setup(int argc, char *argv[])
1151 {
1152 	char *tdebug_env = getenv("LTP_ENABLE_DEBUG");
1153 
1154 	if (!tst_test)
1155 		tst_brk(TBROK, "No tests to run");
1156 
1157 	if (tst_test->max_runtime < -1) {
1158 		tst_brk(TBROK, "Invalid runtime value %i",
1159 			results->max_runtime);
1160 	}
1161 
1162 	if (tst_test->tconf_msg)
1163 		tst_brk(TCONF, "%s", tst_test->tconf_msg);
1164 
1165 	assert_test_fn();
1166 
1167 	TCID = tid = get_tid(argv);
1168 
1169 	if (tst_test->sample)
1170 		tst_test = tst_timer_test_setup(tst_test);
1171 
1172 	parse_opts(argc, argv);
1173 
1174 	if (tdebug_env && (!strcmp(tdebug_env, "1") || !strcmp(tdebug_env, "y"))) {
1175 		tst_res(TINFO, "Enabling debug info");
1176 		tdebug = 1;
1177 	}
1178 
1179 	if (tst_test->needs_kconfigs && tst_kconfig_check(tst_test->needs_kconfigs))
1180 		tst_brk(TCONF, "Aborting due to unsuitable kernel config, see above!");
1181 
1182 	if (tst_test->needs_root && geteuid() != 0)
1183 		tst_brk(TCONF, "Test needs to be run as root");
1184 
1185 	if (tst_test->min_kver)
1186 		check_kver();
1187 
1188 	if (tst_test->supported_archs && !tst_is_on_arch(tst_test->supported_archs))
1189 		tst_brk(TCONF, "This arch '%s' is not supported for test!", tst_arch.name);
1190 
1191 	if (tst_test->skip_in_lockdown && tst_lockdown_enabled() > 0)
1192 		tst_brk(TCONF, "Kernel is locked down, skipping test");
1193 
1194 	if (tst_test->skip_in_secureboot && tst_secureboot_enabled() > 0)
1195 		tst_brk(TCONF, "SecureBoot enabled, skipping test");
1196 
1197 	if (tst_test->skip_in_compat && TST_ABI != tst_kernel_bits())
1198 		tst_brk(TCONF, "Not supported in 32-bit compat mode");
1199 
1200 	if (tst_test->needs_cmds) {
1201 		const char *cmd;
1202 		int i;
1203 
1204 		for (i = 0; (cmd = tst_test->needs_cmds[i]); ++i)
1205 			tst_check_cmd(cmd);
1206 	}
1207 
1208 	if (tst_test->needs_drivers) {
1209 		const char *name;
1210 		int i;
1211 
1212 		for (i = 0; (name = tst_test->needs_drivers[i]); ++i)
1213 			if (tst_check_driver(name))
1214 				tst_brk(TCONF, "%s driver not available", name);
1215 	}
1216 
1217 	if (tst_test->mount_device)
1218 		tst_test->format_device = 1;
1219 
1220 	if (tst_test->format_device)
1221 		tst_test->needs_device = 1;
1222 
1223 	if (tst_test->all_filesystems)
1224 		tst_test->needs_device = 1;
1225 
1226 	if (tst_test->min_cpus > (unsigned long)tst_ncpus())
1227 		tst_brk(TCONF, "Test needs at least %lu CPUs online", tst_test->min_cpus);
1228 
1229 	if (tst_test->min_mem_avail > (unsigned long)(tst_available_mem() / 1024))
1230 		tst_brk(TCONF, "Test needs at least %luMB MemAvailable", tst_test->min_mem_avail);
1231 
1232 	if (tst_test->min_swap_avail > (unsigned long)(tst_available_swap() / 1024))
1233 		tst_brk(TCONF, "Test needs at least %luMB SwapFree", tst_test->min_swap_avail);
1234 
1235 	if (tst_test->hugepages.number)
1236 		tst_reserve_hugepages(&tst_test->hugepages);
1237 
1238 	setup_ipc();
1239 
1240 	if (tst_test->bufs)
1241 		tst_buffers_alloc(tst_test->bufs);
1242 
1243 	if (needs_tmpdir() && !tst_tmpdir_created())
1244 		tst_tmpdir();
1245 
1246 	if (tst_test->save_restore) {
1247 		const struct tst_path_val *pvl = tst_test->save_restore;
1248 
1249 		while (pvl->path) {
1250 			tst_sys_conf_save(pvl);
1251 			pvl++;
1252 		}
1253 	}
1254 
1255 	if (tst_test->mntpoint)
1256 		SAFE_MKDIR(tst_test->mntpoint, 0777);
1257 
1258 	if ((tst_test->needs_devfs || tst_test->needs_rofs ||
1259 	     tst_test->mount_device || tst_test->all_filesystems ||
1260 		 tst_test->needs_hugetlbfs) &&
1261 	     !tst_test->mntpoint) {
1262 		tst_brk(TBROK, "tst_test->mntpoint must be set!");
1263 	}
1264 
1265 	if (!!tst_test->needs_rofs + !!tst_test->needs_devfs +
1266 	    !!tst_test->needs_device + !!tst_test->needs_hugetlbfs > 1) {
1267 		tst_brk(TBROK,
1268 			"Two or more of needs_{rofs, devfs, device, hugetlbfs} are set");
1269 	}
1270 
1271 	if (tst_test->needs_devfs)
1272 		prepare_and_mount_dev_fs(tst_test->mntpoint);
1273 
1274 	if (tst_test->needs_rofs) {
1275 		/* If we failed to mount read-only tmpfs. Fallback to
1276 		 * using a device with read-only filesystem.
1277 		 */
1278 		if (prepare_and_mount_ro_fs(NULL, tst_test->mntpoint, "tmpfs")) {
1279 			tst_res(TINFO, "Can't mount tmpfs read-only, "
1280 				"falling back to block device...");
1281 			tst_test->needs_device = 1;
1282 			tst_test->format_device = 1;
1283 		}
1284 	}
1285 
1286 	if (tst_test->needs_hugetlbfs)
1287 		prepare_and_mount_hugetlb_fs();
1288 
1289 	if (tst_test->needs_device && !mntpoint_mounted) {
1290 		tdev.dev = tst_acquire_device_(NULL, tst_test->dev_min_size);
1291 
1292 		if (!tdev.dev)
1293 			tst_brk(TCONF, "Failed to acquire device");
1294 
1295 		tdev.size = tst_get_device_size(tdev.dev);
1296 
1297 		tst_device = &tdev;
1298 
1299 		if (tst_test->dev_fs_type)
1300 			tdev.fs_type = tst_test->dev_fs_type;
1301 		else
1302 			tdev.fs_type = tst_dev_fs_type();
1303 
1304 		if (!tst_test->all_filesystems)
1305 			prepare_device();
1306 	}
1307 
1308 	if (tst_test->needs_overlay && !tst_test->mount_device)
1309 		tst_brk(TBROK, "tst_test->mount_device must be set");
1310 
1311 	if (tst_test->needs_overlay && !mntpoint_mounted)
1312 		tst_brk(TBROK, "tst_test->mntpoint must be mounted");
1313 
1314 	if (tst_test->needs_overlay && !ovl_mounted) {
1315 		SAFE_MOUNT_OVERLAY();
1316 		ovl_mounted = 1;
1317 	}
1318 
1319 	if (tst_test->resource_files)
1320 		copy_resources();
1321 
1322 	if (tst_test->restore_wallclock)
1323 		tst_wallclock_save();
1324 
1325 	if (tst_test->taint_check)
1326 		tst_taint_init(tst_test->taint_check);
1327 
1328 	if (tst_test->needs_cgroup_ctrls)
1329 		do_cgroup_requires();
1330 	else if (tst_test->needs_cgroup_ver)
1331 		tst_brk(TBROK, "tst_test->needs_cgroup_ctrls must be set");
1332 }
1333 
do_test_setup(void)1334 static void do_test_setup(void)
1335 {
1336 	main_pid = getpid();
1337 
1338 	if (!tst_test->all_filesystems && tst_test->skip_filesystems) {
1339 		long fs_type = tst_fs_type(".");
1340 		const char *fs_name = tst_fs_type_name(fs_type);
1341 
1342 		if (tst_fs_in_skiplist(fs_name, tst_test->skip_filesystems)) {
1343 			tst_brk(TCONF, "%s is not supported by the test",
1344 				fs_name);
1345 		}
1346 
1347 		tst_res(TINFO, "%s is supported by the test", fs_name);
1348 	}
1349 
1350 	if (tst_test->caps)
1351 		tst_cap_setup(tst_test->caps, TST_CAP_REQ);
1352 
1353 	if (tst_test->setup)
1354 		tst_test->setup();
1355 
1356 	if (main_pid != tst_getpid())
1357 		tst_brk(TBROK, "Runaway child in setup()!");
1358 
1359 	if (tst_test->caps)
1360 		tst_cap_setup(tst_test->caps, TST_CAP_DROP);
1361 }
1362 
do_cleanup(void)1363 static void do_cleanup(void)
1364 {
1365 	if (tst_test->needs_cgroup_ctrls)
1366 		tst_cg_cleanup();
1367 
1368 	if (ovl_mounted)
1369 		SAFE_UMOUNT(OVL_MNT);
1370 
1371 	if (mntpoint_mounted)
1372 		tst_umount(tst_test->mntpoint);
1373 
1374 	if (tst_test->needs_device && tdev.dev)
1375 		tst_release_device(tdev.dev);
1376 
1377 	if (tst_tmpdir_created()) {
1378 		/* avoid munmap() on wrong pointer in tst_rmdir() */
1379 		tst_futexes = NULL;
1380 		tst_rmdir();
1381 	}
1382 
1383 	tst_sys_conf_restore(0);
1384 
1385 	if (tst_test->restore_wallclock)
1386 		tst_wallclock_restore();
1387 
1388 	cleanup_ipc();
1389 }
1390 
heartbeat(void)1391 static void heartbeat(void)
1392 {
1393 	if (tst_clock_gettime(CLOCK_MONOTONIC, &tst_start_time))
1394 		tst_res(TWARN | TERRNO, "tst_clock_gettime() failed");
1395 
1396 	if (getppid() == 1) {
1397 		tst_res(TFAIL, "Main test process might have exit!");
1398 		/*
1399 		 * We need kill the task group immediately since the
1400 		 * main process has exit.
1401 		 */
1402 		kill(0, SIGKILL);
1403 		exit(TBROK);
1404 	}
1405 
1406 	kill(getppid(), SIGUSR1);
1407 }
1408 
run_tests(void)1409 static void run_tests(void)
1410 {
1411 	unsigned int i;
1412 	struct results saved_results;
1413 
1414 	if (!tst_test->test) {
1415 		saved_results = *results;
1416 		heartbeat();
1417 		tst_test->test_all();
1418 
1419 		if (tst_getpid() != main_pid)
1420 			exit(0);
1421 
1422 		tst_reap_children();
1423 
1424 		if (results_equal(&saved_results, results))
1425 			tst_brk(TBROK, "Test haven't reported results!");
1426 		return;
1427 	}
1428 
1429 	for (i = 0; i < tst_test->tcnt; i++) {
1430 		saved_results = *results;
1431 		heartbeat();
1432 		tst_test->test(i);
1433 
1434 		if (tst_getpid() != main_pid)
1435 			exit(0);
1436 
1437 		tst_reap_children();
1438 
1439 		if (results_equal(&saved_results, results))
1440 			tst_brk(TBROK, "Test %i haven't reported results!", i);
1441 	}
1442 }
1443 
get_time_ms(void)1444 static unsigned long long get_time_ms(void)
1445 {
1446 	struct timespec ts;
1447 
1448 	if (tst_clock_gettime(CLOCK_MONOTONIC, &ts))
1449 		tst_brk(TBROK | TERRNO, "tst_clock_gettime()");
1450 
1451 	return tst_timespec_to_ms(ts);
1452 }
1453 
add_paths(void)1454 static void add_paths(void)
1455 {
1456 	char *old_path = getenv("PATH");
1457 	const char *start_dir;
1458 	char *new_path;
1459 
1460 	start_dir = tst_get_startwd();
1461 
1462 	if (old_path)
1463 		SAFE_ASPRINTF(&new_path, "%s::%s", old_path, start_dir);
1464 	else
1465 		SAFE_ASPRINTF(&new_path, "::%s", start_dir);
1466 
1467 	SAFE_SETENV("PATH", new_path, 1);
1468 	free(new_path);
1469 }
1470 
testrun(void)1471 static void testrun(void)
1472 {
1473 	unsigned int i = 0;
1474 	unsigned long long stop_time = 0;
1475 	int cont = 1;
1476 
1477 	heartbeat();
1478 	add_paths();
1479 	do_test_setup();
1480 
1481 	if (duration > 0)
1482 		stop_time = get_time_ms() + (unsigned long long)(duration * 1000);
1483 
1484 	for (;;) {
1485 		cont = 0;
1486 
1487 		if (i < (unsigned int)iterations) {
1488 			i++;
1489 			cont = 1;
1490 		}
1491 
1492 		if (stop_time && get_time_ms() < stop_time)
1493 			cont = 1;
1494 
1495 		if (!cont)
1496 			break;
1497 
1498 		run_tests();
1499 		heartbeat();
1500 	}
1501 
1502 	do_test_cleanup();
1503 	exit(0);
1504 }
1505 
1506 static pid_t test_pid;
1507 
1508 
1509 static volatile sig_atomic_t sigkill_retries;
1510 
1511 #define WRITE_MSG(msg) do { \
1512 	if (write(2, msg, sizeof(msg) - 1)) { \
1513 		/* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425 */ \
1514 	} \
1515 } while (0)
1516 
alarm_handler(int sig LTP_ATTRIBUTE_UNUSED)1517 static void alarm_handler(int sig LTP_ATTRIBUTE_UNUSED)
1518 {
1519 	WRITE_MSG("Test timeouted, sending SIGKILL!\n");
1520 	kill(-test_pid, SIGKILL);
1521 	alarm(5);
1522 
1523 	if (++sigkill_retries > 10) {
1524 		WRITE_MSG("Cannot kill test processes!\n");
1525 		WRITE_MSG("Congratulation, likely test hit a kernel bug.\n");
1526 		WRITE_MSG("Exiting uncleanly...\n");
1527 		_exit(TFAIL);
1528 	}
1529 }
1530 
heartbeat_handler(int sig LTP_ATTRIBUTE_UNUSED)1531 static void heartbeat_handler(int sig LTP_ATTRIBUTE_UNUSED)
1532 {
1533 	alarm(results->timeout);
1534 	sigkill_retries = 0;
1535 }
1536 
sigint_handler(int sig LTP_ATTRIBUTE_UNUSED)1537 static void sigint_handler(int sig LTP_ATTRIBUTE_UNUSED)
1538 {
1539 	if (test_pid > 0) {
1540 		WRITE_MSG("Sending SIGKILL to test process...\n");
1541 		kill(-test_pid, SIGKILL);
1542 	}
1543 }
1544 
tst_remaining_runtime(void)1545 unsigned int tst_remaining_runtime(void)
1546 {
1547 	static struct timespec now;
1548 	int elapsed;
1549 
1550 	if (results->max_runtime == TST_UNLIMITED_RUNTIME)
1551 		return UINT_MAX;
1552 
1553 	if (results->max_runtime == 0)
1554 		tst_brk(TBROK, "Runtime not set!");
1555 
1556 	if (tst_clock_gettime(CLOCK_MONOTONIC, &now))
1557 		tst_res(TWARN | TERRNO, "tst_clock_gettime() failed");
1558 
1559 	elapsed = tst_timespec_diff_ms(now, tst_start_time) / 1000;
1560 	if (results->max_runtime > elapsed)
1561 		return results->max_runtime - elapsed;
1562 
1563 	return 0;
1564 }
1565 
1566 
tst_multiply_timeout(unsigned int timeout)1567 unsigned int tst_multiply_timeout(unsigned int timeout)
1568 {
1569 	parse_mul(&timeout_mul, "LTP_TIMEOUT_MUL", 0.099, 10000);
1570 
1571 	if (timeout < 1)
1572 		tst_brk(TBROK, "timeout must to be >= 1! (%d)", timeout);
1573 
1574 	return timeout * timeout_mul;
1575 }
1576 
set_timeout(void)1577 static void set_timeout(void)
1578 {
1579 	unsigned int timeout = DEFAULT_TIMEOUT;
1580 
1581 	if (results->max_runtime == TST_UNLIMITED_RUNTIME) {
1582 		tst_res(TINFO, "Timeout per run is disabled");
1583 		return;
1584 	}
1585 
1586 	if (results->max_runtime < 0) {
1587 		tst_brk(TBROK, "max_runtime must to be >= -1! (%d)",
1588 			results->max_runtime);
1589 	}
1590 
1591 	results->timeout = tst_multiply_timeout(timeout) + results->max_runtime;
1592 
1593 	tst_res(TINFO, "Timeout per run is %uh %02um %02us",
1594 		results->timeout/3600, (results->timeout%3600)/60,
1595 		results->timeout % 60);
1596 }
1597 
tst_set_max_runtime(int max_runtime)1598 void tst_set_max_runtime(int max_runtime)
1599 {
1600 	results->max_runtime = multiply_runtime(max_runtime);
1601 	tst_res(TINFO, "Updating max runtime to %uh %02um %02us",
1602 		max_runtime/3600, (max_runtime%3600)/60, max_runtime % 60);
1603 	set_timeout();
1604 	heartbeat();
1605 }
1606 
fork_testrun(void)1607 static int fork_testrun(void)
1608 {
1609 	int status;
1610 
1611 	SAFE_SIGNAL(SIGINT, sigint_handler);
1612 	SAFE_SIGNAL(SIGTERM, sigint_handler);
1613 
1614 	alarm(results->timeout);
1615 
1616 	test_pid = fork();
1617 	if (test_pid < 0)
1618 		tst_brk(TBROK | TERRNO, "fork()");
1619 
1620 	if (!test_pid) {
1621 		tst_disable_oom_protection(0);
1622 		SAFE_SIGNAL(SIGALRM, SIG_DFL);
1623 		SAFE_SIGNAL(SIGUSR1, SIG_DFL);
1624 		SAFE_SIGNAL(SIGTERM, SIG_DFL);
1625 		SAFE_SIGNAL(SIGINT, SIG_DFL);
1626 		SAFE_SETPGID(0, 0);
1627 		testrun();
1628 	}
1629 
1630 	SAFE_WAITPID(test_pid, &status, 0);
1631 	alarm(0);
1632 	SAFE_SIGNAL(SIGTERM, SIG_DFL);
1633 	SAFE_SIGNAL(SIGINT, SIG_DFL);
1634 
1635 	if (tst_test->taint_check && tst_taint_check()) {
1636 		tst_res(TFAIL, "Kernel is now tainted.");
1637 		return TFAIL;
1638 	}
1639 
1640 	if (tst_test->forks_child && kill(-test_pid, SIGKILL) == 0)
1641 		tst_res(TINFO, "Killed the leftover descendant processes");
1642 
1643 	if (WIFEXITED(status) && WEXITSTATUS(status))
1644 		return WEXITSTATUS(status);
1645 
1646 	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL) {
1647 		tst_res(TINFO, "If you are running on slow machine, "
1648 			       "try exporting LTP_TIMEOUT_MUL > 1");
1649 		tst_brk(TBROK, "Test killed! (timeout?)");
1650 	}
1651 
1652 	if (WIFSIGNALED(status))
1653 		tst_brk(TBROK, "Test killed by %s!", tst_strsig(WTERMSIG(status)));
1654 
1655 	return 0;
1656 }
1657 
run_tcases_per_fs(void)1658 static int run_tcases_per_fs(void)
1659 {
1660 	int ret = 0;
1661 	unsigned int i;
1662 	const char *const *filesystems = tst_get_supported_fs_types(tst_test->skip_filesystems);
1663 
1664 	if (!filesystems[0])
1665 		tst_brk(TCONF, "There are no supported filesystems");
1666 
1667 	for (i = 0; filesystems[i]; i++) {
1668 
1669 		tst_res(TINFO, "=== Testing on %s ===", filesystems[i]);
1670 		tdev.fs_type = filesystems[i];
1671 
1672 		prepare_device();
1673 
1674 		ret = fork_testrun();
1675 
1676 		if (mntpoint_mounted) {
1677 			tst_umount(tst_test->mntpoint);
1678 			mntpoint_mounted = 0;
1679 		}
1680 
1681 		if (ret == TCONF)
1682 			continue;
1683 
1684 		if (ret == 0)
1685 			continue;
1686 
1687 		do_exit(ret);
1688 	}
1689 
1690 	return ret;
1691 }
1692 
1693 unsigned int tst_variant;
1694 
tst_run_tcases(int argc,char * argv[],struct tst_test * self)1695 void tst_run_tcases(int argc, char *argv[], struct tst_test *self)
1696 {
1697 	int ret = 0;
1698 	unsigned int test_variants = 1;
1699 
1700 	lib_pid = getpid();
1701 	tst_test = self;
1702 
1703 	do_setup(argc, argv);
1704 	tst_enable_oom_protection(lib_pid);
1705 
1706 	SAFE_SIGNAL(SIGALRM, alarm_handler);
1707 	SAFE_SIGNAL(SIGUSR1, heartbeat_handler);
1708 
1709 	tst_res(TINFO, "LTP version: "LTP_VERSION);
1710 
1711 	if (tst_test->max_runtime)
1712 		results->max_runtime = multiply_runtime(tst_test->max_runtime);
1713 
1714 	set_timeout();
1715 
1716 	if (tst_test->test_variants)
1717 		test_variants = tst_test->test_variants;
1718 
1719 	for (tst_variant = 0; tst_variant < test_variants; tst_variant++) {
1720 		if (tst_test->all_filesystems)
1721 			ret |= run_tcases_per_fs();
1722 		else
1723 			ret |= fork_testrun();
1724 
1725 		if (ret & ~(TCONF))
1726 			goto exit;
1727 	}
1728 
1729 exit:
1730 	do_exit(ret);
1731 }
1732 
1733 
tst_flush(void)1734 void tst_flush(void)
1735 {
1736 	int rval;
1737 
1738 	rval = fflush(stderr);
1739 	if (rval != 0)
1740 		tst_brk(TBROK | TERRNO, "fflush(stderr) failed");
1741 
1742 	rval = fflush(stdout);
1743 	if (rval != 0)
1744 		tst_brk(TBROK | TERRNO, "fflush(stdout) failed");
1745 
1746 }
1747