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