• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2007, 2011, 2013, 2014 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *    Daniel Vetter <daniel.vetter@ffwll.ch>
26  *
27  */
28 
29 #ifdef HAVE_LIBGEN_H
30 #include <libgen.h>
31 #endif
32 #include <stdio.h>
33 #include <assert.h>
34 #include <fcntl.h>
35 #include <sys/stat.h>
36 #include <sys/ioctl.h>
37 #include <string.h>
38 #include <sys/mman.h>
39 #include <signal.h>
40 #include <pciaccess.h>
41 #include <getopt.h>
42 #include <stdlib.h>
43 #include <unistd.h>
44 #include <sys/wait.h>
45 #include <sys/types.h>
46 #ifdef __linux__
47 #include <sys/syscall.h>
48 #endif
49 #include <pthread.h>
50 #include <sys/utsname.h>
51 #include <termios.h>
52 #include <errno.h>
53 #include <time.h>
54 #include <ctype.h>
55 #include <limits.h>
56 #include <locale.h>
57 #include <uwildmat/uwildmat.h>
58 #include <glib.h>
59 
60 #include "drmtest.h"
61 #include "intel_chipset.h"
62 #include "intel_io.h"
63 #include "igt_debugfs.h"
64 #include "igt_dummyload.h"
65 #include "version.h"
66 #include "config.h"
67 
68 #include "igt_core.h"
69 #include "igt_aux.h"
70 #include "igt_sysfs.h"
71 #include "igt_sysrq.h"
72 #include "igt_rc.h"
73 #include "igt_list.h"
74 
75 #ifndef ANDROID
76 #define UNW_LOCAL_ONLY
77 #include <libunwind.h>
78 #endif
79 
80 #include <elfutils/libdwfl.h>
81 
82 #ifdef HAVE_LIBGEN_H
83 #include <libgen.h>   /* for basename() on Solaris */
84 #endif
85 
86 /**
87  * SECTION:igt_core
88  * @short_description: Core i-g-t testing support
89  * @title: Core
90  * @include: igt.h
91  *
92  * This library implements the core of the i-g-t test support infrastructure.
93  * Main features are the subtest enumeration, cmdline option parsing helpers for
94  * subtest handling and various helpers to structure testcases with subtests and
95  * handle subtest test results.
96  *
97  * Auxiliary code provides exit handlers, support for forked processes with test
98  * result propagation. Other generally useful functionality includes optional
99  * structure logging infrastructure and some support code for running reduced
100  * test set on in simulated hardware environments.
101  *
102  * When writing tests with subtests it is extremely important that nothing
103  * interferes with the subtest enumeration. In i-g-t subtests are enumerated at
104  * runtime, which allows powerful testcase enumeration. But it makes subtest
105  * enumeration a bit more tricky since the test code needs to be careful to
106  * never run any code which might fail (like trying to do privileged operations
107  * or opening device driver nodes).
108  *
109  * To allow this i-g-t provides #igt_fixture code blocks for setup code outside
110  * of subtests and automatically skips the subtest code blocks themselves. For
111  * special cases igt_only_list_subtests() is also provided. For setup code only
112  * shared by a group of subtest encapsulate the #igt_fixture block and all the
113  * subtestest in a #igt_subtest_group block.
114  *
115  * # Magic Control Blocks
116  *
117  * i-g-t makes heavy use of C macros which serve as magic control blocks. They
118  * work fairly well and transparently but since C doesn't have full-blown
119  * closures there are caveats:
120  *
121  * - Asynchronous blocks which are used to spawn children internally use fork().
122  *   Which means that nonsensical control flow like jumping out of the control
123  *   block is possible, but it will badly confuse the i-g-t library code. And of
124  *   course all caveats of a real fork() call apply, namely that file
125  *   descriptors are copied, but still point at the original file. This will
126  *   terminally upset the libdrm buffer manager if both parent and child keep on
127  *   using the same open instance of the drm device. Usually everything related
128  *   to interacting with the kernel driver must be reinitialized to avoid such
129  *   issues.
130  *
131  * - Code blocks with magic control flow are implemented with setjmp() and
132  *   longjmp(). This applies to #igt_fixture and #igt_subtest blocks and all the
133  *   three variants to finish test: igt_success(), igt_skip() and igt_fail().
134  *   Mostly this is of no concern, except when such a control block changes
135  *   stack variables defined in the same function as the control block resides.
136  *   Any store/load behaviour after a longjmp() is ill-defined for these
137  *   variables. Avoid such code.
138  *
139  *   Quoting the man page for longjmp():
140  *
141  *   "The values of automatic variables are unspecified after a call to
142  *   longjmp() if they meet all the following criteria:"
143  *    - "they are local to the function that made the corresponding setjmp() call;
144  *    - "their values are changed between the calls to setjmp() and longjmp(); and
145  *    - "they are not declared as volatile."
146  *
147  * # Best Practices for Test Helper Libraries Design
148  *
149  * Kernel tests itself tend to have fairly complex logic already. It is
150  * therefore paramount that helper code, both in libraries and test-private
151  * functions, add as little boilerplate code to the main test logic as possible.
152  * But then dense code is hard to understand without constantly consulting
153  * the documentation and implementation of all the helper functions if it
154  * doesn't follow some clear patterns. Hence follow these established best
155  * practices:
156  *
157  * - Make extensive use of the implicit control flow afforded by igt_skip(),
158  *   igt_fail and igt_success(). When dealing with optional kernel features
159  *   combine igt_skip() with igt_fail() to skip when the kernel support isn't
160  *   available but fail when anything else goes awry. void should be the most
161  *   common return type in all your functions, except object constructors of
162  *   course.
163  *
164  * - The main test logic should have no explicit control flow for failure
165  *   conditions, but instead such assumptions should be written in a declarative
166  *   style.  Use one of the many macros which encapsulate i-g-t's implicit
167  *   control flow.  Pick the most suitable one to have as much debug output as
168  *   possible without polluting the code unnecessarily. For example
169  *   igt_assert_cmpint() for comparing integers or do_ioctl() for running ioctls
170  *   and checking their results.  Feel free to add new ones to the library or
171  *   wrap up a set of checks into a private function to further condense your
172  *   test logic.
173  *
174  * - When adding a new feature test function which uses igt_skip() internally,
175  *   use the {prefix}_require_{feature_name} naming scheme. When you
176  *   instead add a feature test function which returns a boolean, because your
177  *   main test logic must take different actions depending upon the feature's
178  *   availability, then instead use the {prefix}_has_{feature_name}.
179  *
180  * - As already mentioned eschew explicit error handling logic as much as
181  *   possible. If your test absolutely has to handle the error of some function
182  *   the customary naming pattern is to prefix those variants with __. Try to
183  *   restrict explicit error handling to leaf functions. For the main test flow
184  *   simply pass the expected error condition down into your helper code, which
185  *   results in tidy and declarative test logic.
186  *
187  * - Make your library functions as simple to use as possible. Automatically
188  *   register cleanup handlers through igt_install_exit_handler(). Reduce the
189  *   amount of setup boilerplate needed by using implicit singletons and lazy
190  *   structure initialization and similar design patterns.
191  *
192  * - Don't shy away from refactoring common code, even when there are just 2-3
193  *   users and even if it's not a net reduction in code. As long as it helps to
194  *   remove boilerplate and makes the code more declarative the resulting
195  *   clearer test flow is worth it. All i-g-t library code has been organically
196  *   extracted from testcases in this fashion.
197  *
198  * - For general coding style issues please follow the kernel's rules laid out
199  *   in
200  *   [CodingStyle](https://www.kernel.org/doc/Documentation/CodingStyle).
201  *
202  * # Interface with Testrunners
203  *
204  * i-g-t testcase are all executables which should be run as root on an
205  * otherwise completely idle system. The test status is reflected in the
206  * exitcode. #IGT_EXIT_SUCCESS means "success", #IGT_EXIT_SKIP "skip",
207  * #IGT_EXIT_TIMEOUT that some operation "timed out".  All other exit codes
208  * encode a failed test result, including any abnormal termination of the test
209  * (e.g. by SIGKILL).
210  *
211  * On top of that tests may report unexpected results and minor issues to
212  * stderr. If stderr is non-empty the test result should be treated as "warn".
213  *
214  * The test lists are generated at build time. Simple testcases are listed in
215  * tests/single-tests.txt and tests with subtests are listed in
216  * tests/multi-tests.txt. When running tests with subtest from a test runner it
217  * is recommend to run each subtest individually, since otherwise the return
218  * code will only reflect the overall result.
219  *
220  * To do that obtain the lists of subtests with "--list-subtests", which can be
221  * run as non-root and doesn't require a DRM driver to be loaded (or any GPU to
222  * be present). Then individual subtests can be run with "--run-subtest". Usage
223  * help for tests with subtests can be obtained with the "--help" command line
224  * option.
225  *
226  * A wildcard expression can be given to --run-subtest to specify a subset of
227  * subtests to run. See https://tools.ietf.org/html/rfc3977#section-4 for a
228  * description of allowed wildcard expressions.
229  * Some examples of allowed wildcard expressions are:
230  *
231  * - '*basic*' match any subtest containing basic
232  * - 'basic-???' match any subtest named basic- with 3 characters after -
233  * - 'basic-[0-9]' match any subtest named basic- with a single number after -
234  * - 'basic-[^0-9]' match any subtest named basic- with a single non numerical character after -
235  * - 'basic*,advanced*' match any subtest starting basic or advanced
236  * - '*,!basic*' match any subtest not starting basic
237  * - 'basic*,!basic-render*' match any subtest starting basic but not starting basic-render
238  *
239  * # Configuration
240  *
241  * Some of IGT's behavior can be configured through a configuration file.
242  * By default, this file is expected to exist in ~/.igtrc . The directory for
243  * this can be overridden by setting the environment variable %IGT_CONFIG_PATH.
244  * An example configuration follows:
245  *
246  * |[<!-- language="plain" -->
247  *	&num; The common configuration section follows.
248  *	[Common]
249  *	FrameDumpPath=/tmp # The path to dump frames that fail comparison checks
250  *
251  *	&num; The following section is used for configuring the Device Under Test.
252  *	&num; It is not mandatory and allows overriding default values.
253  *	[DUT]
254  *	SuspendResumeDelay=10
255  * ]|
256  *
257  * Some specific configuration options may be used by specific parts of IGT,
258  * such as those related to Chamelium support.
259  */
260 
261 jmp_buf igt_subtest_jmpbuf;
262 
263 static unsigned int exit_handler_count;
264 const char *igt_interactive_debug;
265 bool igt_skip_crc_compare;
266 
267 /* subtests helpers */
268 static bool list_subtests = false;
269 static bool describe_subtests = false;
270 static char *run_single_subtest = NULL;
271 static bool run_single_subtest_found = false;
272 static const char *in_subtest = NULL;
273 static struct timespec subtest_time;
274 static clockid_t igt_clock = (clockid_t)-1;
275 static bool in_fixture = false;
276 static bool test_with_subtests = false;
277 static bool in_atexit_handler = false;
278 static enum {
279 	CONT = 0, SKIP, FAIL
280 } skip_subtests_henceforth = CONT;
281 
282 static char __current_description[512];
283 
284 struct description_node {
285 	char desc[sizeof(__current_description)];
286 	struct igt_list link;
287 };
288 
289 static struct igt_list subgroup_descriptions;
290 
291 
292 bool __igt_plain_output = false;
293 
294 /* fork support state */
295 pid_t *test_children;
296 int num_test_children;
297 int test_children_sz;
298 bool test_child;
299 
300 enum {
301 	/*
302 	 * Let the first values be used by individual tests so options don't
303 	 * conflict with core ones
304 	 */
305 	OPT_LIST_SUBTESTS = 500,
306 	OPT_DESCRIBE_SUBTESTS,
307 	OPT_RUN_SUBTEST,
308 	OPT_DESCRIPTION,
309 	OPT_DEBUG,
310 	OPT_INTERACTIVE_DEBUG,
311 	OPT_SKIP_CRC,
312 	OPT_HELP = 'h'
313 };
314 
315 static int igt_exitcode = IGT_EXIT_SUCCESS;
316 static const char *command_str;
317 
318 static char* igt_log_domain_filter;
319 static struct {
320 	char *entries[256];
321 	uint8_t start, end;
322 } log_buffer;
323 static pthread_mutex_t log_buffer_mutex = PTHREAD_MUTEX_INITIALIZER;
324 
325 GKeyFile *igt_key_file;
326 
327 char *igt_frame_dump_path;
328 
329 static bool stderr_needs_sentinel = false;
330 
igt_test_name(void)331 const char *igt_test_name(void)
332 {
333 	return command_str;
334 }
335 
_igt_log_buffer_append(char * line)336 static void _igt_log_buffer_append(char *line)
337 {
338 	pthread_mutex_lock(&log_buffer_mutex);
339 
340 	free(log_buffer.entries[log_buffer.end]);
341 	log_buffer.entries[log_buffer.end] = line;
342 	log_buffer.end++;
343 	if (log_buffer.end == log_buffer.start)
344 		log_buffer.start++;
345 
346 	pthread_mutex_unlock(&log_buffer_mutex);
347 }
348 
_igt_log_buffer_reset(void)349 static void _igt_log_buffer_reset(void)
350 {
351 	pthread_mutex_lock(&log_buffer_mutex);
352 
353 	log_buffer.start = log_buffer.end = 0;
354 
355 	pthread_mutex_unlock(&log_buffer_mutex);
356 }
357 
_igt_log_buffer_dump(void)358 static void _igt_log_buffer_dump(void)
359 {
360 	uint8_t i;
361 
362 	if (in_subtest)
363 		fprintf(stderr, "Subtest %s failed.\n", in_subtest);
364 	else
365 		fprintf(stderr, "Test %s failed.\n", command_str);
366 
367 	if (log_buffer.start == log_buffer.end) {
368 		fprintf(stderr, "No log.\n");
369 		return;
370 	}
371 
372 	pthread_mutex_lock(&log_buffer_mutex);
373 	fprintf(stderr, "**** DEBUG ****\n");
374 
375 	i = log_buffer.start;
376 	do {
377 		char *last_line = log_buffer.entries[i];
378 		fprintf(stderr, "%s", last_line);
379 		i++;
380 	} while (i != log_buffer.start && i != log_buffer.end);
381 
382 	/* reset the buffer */
383 	log_buffer.start = log_buffer.end = 0;
384 
385 	fprintf(stderr, "****  END  ****\n");
386 	pthread_mutex_unlock(&log_buffer_mutex);
387 }
388 
389 /**
390  * igt_log_buffer_inspect:
391  *
392  * Provides a way to replay the internal igt log buffer for inspection.
393  * @check: A user-specified handler that gets invoked for each line of
394  *         the log buffer. The handler should return true to stop
395  *         inspecting the rest of the buffer.
396  * @data: passed as a user argument to the inspection function.
397  */
igt_log_buffer_inspect(igt_buffer_log_handler_t check,void * data)398 void igt_log_buffer_inspect(igt_buffer_log_handler_t check, void *data)
399 {
400 	uint8_t i;
401 	pthread_mutex_lock(&log_buffer_mutex);
402 
403 	i = log_buffer.start;
404 	do {
405 		if (check(log_buffer.entries[i], data))
406 			break;
407 		i++;
408 	} while (i != log_buffer.start && i != log_buffer.end);
409 
410 	pthread_mutex_unlock(&log_buffer_mutex);
411 }
412 
igt_kmsg(const char * format,...)413 void igt_kmsg(const char *format, ...)
414 {
415 	va_list ap;
416 	FILE *file;
417 
418 	file = fopen("/dev/kmsg", "w");
419 	if (file == NULL)
420 		return;
421 
422 	va_start(ap, format);
423 	vfprintf(file, format, ap);
424 	va_end(ap);
425 
426 	fclose(file);
427 }
428 
429 #define time_valid(ts) ((ts)->tv_sec || (ts)->tv_nsec)
430 
igt_time_elapsed(struct timespec * then,struct timespec * now)431 double igt_time_elapsed(struct timespec *then,
432 			struct timespec *now)
433 {
434 	double elapsed = -1.;
435 
436 	if (time_valid(then) && time_valid(now)) {
437 		elapsed = now->tv_sec - then->tv_sec;
438 		elapsed += (now->tv_nsec - then->tv_nsec) * 1e-9;
439 	}
440 
441 	return elapsed;
442 }
443 
igt_gettime(struct timespec * ts)444 int igt_gettime(struct timespec *ts)
445 {
446 	memset(ts, 0, sizeof(*ts));
447 	errno = 0;
448 
449 	/* Stay on the same clock for consistency. */
450 	if (igt_clock != (clockid_t)-1) {
451 		if (clock_gettime(igt_clock, ts))
452 			goto error;
453 		return 0;
454 	}
455 
456 #ifdef CLOCK_MONOTONIC_RAW
457 	if (!clock_gettime(igt_clock = CLOCK_MONOTONIC_RAW, ts))
458 		return 0;
459 #endif
460 #ifdef CLOCK_MONOTONIC_COARSE
461 	if (!clock_gettime(igt_clock = CLOCK_MONOTONIC_COARSE, ts))
462 		return 0;
463 #endif
464 	if (!clock_gettime(igt_clock = CLOCK_MONOTONIC, ts))
465 		return 0;
466 error:
467 	igt_warn("Could not read monotonic time: %s\n",
468 		 strerror(errno));
469 
470 	return -errno;
471 }
472 
igt_nsec_elapsed(struct timespec * start)473 uint64_t igt_nsec_elapsed(struct timespec *start)
474 {
475 	struct timespec now;
476 
477 	igt_gettime(&now);
478 	if ((start->tv_sec | start->tv_nsec) == 0) {
479 		*start = now;
480 		return 0;
481 	}
482 
483 	return ((now.tv_nsec - start->tv_nsec) +
484 		(uint64_t)NSEC_PER_SEC*(now.tv_sec - start->tv_sec));
485 }
486 
__igt_fixture(void)487 bool __igt_fixture(void)
488 {
489 	assert(!in_fixture);
490 	assert(test_with_subtests);
491 
492 	if (igt_only_list_subtests())
493 		return false;
494 
495 	if (skip_subtests_henceforth)
496 		return false;
497 
498 	in_fixture = true;
499 	return true;
500 }
501 
__igt_fixture_complete(void)502 void __igt_fixture_complete(void)
503 {
504 	assert(in_fixture);
505 
506 	in_fixture = false;
507 }
508 
__igt_fixture_end(void)509 void __igt_fixture_end(void)
510 {
511 	assert(in_fixture);
512 
513 	in_fixture = false;
514 	siglongjmp(igt_subtest_jmpbuf, 1);
515 }
516 
517 /*
518  * If the test takes out the machine, in addition to the usual dmesg
519  * spam, the kernel may also emit a "death rattle" -- extra debug
520  * information that is overkill for normal successful tests, but
521  * vital for post-mortem analysis.
522  */
ftrace_dump_on_oops(bool enable)523 static void ftrace_dump_on_oops(bool enable)
524 {
525 	int fd;
526 
527 	fd = open("/proc/sys/kernel/ftrace_dump_on_oops", O_WRONLY);
528 	if (fd < 0)
529 		return;
530 
531 	/*
532 	 * If we fail, we do not get the death rattle we wish, but we
533 	 * still want to run the tests anyway.
534 	 */
535 	igt_ignore_warn(write(fd, enable ? "1\n" : "0\n", 2));
536 	close(fd);
537 }
538 
539 bool igt_exit_called;
common_exit_handler(int sig)540 static void common_exit_handler(int sig)
541 {
542 	if (!igt_only_list_subtests()) {
543 		bind_fbcon(true);
544 	}
545 
546 	/* When not killed by a signal check that igt_exit() has been properly
547 	 * called. */
548 	assert(sig != 0 || igt_exit_called);
549 }
550 
print_line_wrapping(const char * indent,const char * text)551 static void print_line_wrapping(const char *indent, const char *text)
552 {
553 	char *copy, *curr, *next_space;
554 	int current_line_length = 0;
555 	bool done = false;
556 
557 	const int total_line_length = 80;
558 	const int line_length = total_line_length - strlen(indent);
559 
560 	copy = malloc(strlen(text) + 1);
561 	memcpy(copy, text, strlen(text) + 1);
562 
563 	curr = copy;
564 
565 	printf("%s", indent);
566 
567 	while (!done) {
568 		next_space = strchr(curr, ' ');
569 
570 		if (!next_space) { /* no more spaces, print everything that is left */
571 			done = true;
572 			next_space = strchr(curr, '\0');
573 		}
574 
575 		*next_space = '\0';
576 
577 		if ((next_space - curr) + current_line_length > line_length && curr != copy) {
578 			printf("\n%s", indent);
579 			current_line_length = 0;
580 		}
581 
582 		if (current_line_length == 0)
583 			printf("%s", curr); /* first word in a line, don't space out */
584 		else
585 			printf(" %s", curr);
586 
587 		current_line_length += next_space - curr;
588 		curr = next_space + 1;
589 	}
590 
591 	printf("\n");
592 
593 	free(copy);
594 }
595 
596 
print_test_description(void)597 static void print_test_description(void)
598 {
599 	if (&__igt_test_description) {
600 		print_line_wrapping("", __igt_test_description);
601 		if (describe_subtests)
602 			printf("\n");
603 	}
604 }
605 
print_version(void)606 static void print_version(void)
607 {
608 	struct utsname uts;
609 
610 	if (list_subtests)
611 		return;
612 
613 	uname(&uts);
614 
615 	igt_info("IGT-Version: %s-%s (%s) (%s: %s %s)\n", PACKAGE_VERSION,
616 		 IGT_GIT_SHA1, TARGET_CPU_PLATFORM,
617 		 uts.sysname, uts.release, uts.machine);
618 }
619 
print_usage(const char * help_str,bool output_on_stderr)620 static void print_usage(const char *help_str, bool output_on_stderr)
621 {
622 	FILE *f = output_on_stderr ? stderr : stdout;
623 
624 	fprintf(f, "Usage: %s [OPTIONS]\n", command_str);
625 	fprintf(f, "  --list-subtests\n"
626 		   "  --run-subtest <pattern>\n"
627 		   "  --debug[=log-domain]\n"
628 		   "  --interactive-debug[=domain]\n"
629 		   "  --skip-crc-compare\n"
630 		   "  --help-description\n"
631 		   "  --describe\n"
632 		   "  --help|-h\n");
633 	if (help_str)
634 		fprintf(f, "%s\n", help_str);
635 }
636 
637 
oom_adjust_for_doom(void)638 static void oom_adjust_for_doom(void)
639 {
640 	int fd;
641 	const char always_kill[] = "1000";
642 
643 	fd = open("/proc/self/oom_score_adj", O_WRONLY);
644 	igt_assert(fd != -1);
645 	igt_assert(write(fd, always_kill, sizeof(always_kill)) == sizeof(always_kill));
646 	close(fd);
647 
648 }
649 
common_init_config(void)650 static void common_init_config(void)
651 {
652 	char *key_file_env = NULL;
653 	char *key_file_loc = NULL;
654 	GError *error = NULL;
655 	int ret;
656 
657 	/* Determine igt config path */
658 	key_file_env = getenv("IGT_CONFIG_PATH");
659 	if (key_file_env) {
660 		key_file_loc = key_file_env;
661 	} else {
662 		key_file_loc = malloc(100);
663 		snprintf(key_file_loc, 100, "%s/.igtrc", g_get_home_dir());
664 	}
665 
666 	/* Load igt config file */
667 	igt_key_file = g_key_file_new();
668 	ret = g_key_file_load_from_file(igt_key_file, key_file_loc,
669 					G_KEY_FILE_NONE, &error);
670 	if (!ret) {
671 		g_error_free(error);
672 		g_key_file_free(igt_key_file);
673 		igt_key_file = NULL;
674 
675 		goto out;
676 	}
677 
678 	g_clear_error(&error);
679 
680 	if (!igt_frame_dump_path)
681 		igt_frame_dump_path =
682 			g_key_file_get_string(igt_key_file, "Common",
683 					      "FrameDumpPath", &error);
684 
685 	g_clear_error(&error);
686 
687 	ret = g_key_file_get_integer(igt_key_file, "DUT", "SuspendResumeDelay",
688 				     &error);
689 	assert(!error || error->code != G_KEY_FILE_ERROR_INVALID_VALUE);
690 
691 	g_clear_error(&error);
692 
693 	if (ret != 0)
694 		igt_set_autoresume_delay(ret);
695 
696 out:
697 	if (!key_file_env && key_file_loc)
698 		free(key_file_loc);
699 }
700 
common_init_env(void)701 static void common_init_env(void)
702 {
703 	const char *env;
704 
705 	if (!isatty(STDOUT_FILENO) || getenv("IGT_PLAIN_OUTPUT"))
706 		__igt_plain_output = true;
707 
708 	errno = 0; /* otherwise may be either ENOTTY or EBADF because of isatty */
709 
710 	if (!__igt_plain_output)
711 		setlocale(LC_ALL, "");
712 
713 	env = getenv("IGT_LOG_LEVEL");
714 	if (env) {
715 		if (strcmp(env, "debug") == 0)
716 			igt_log_level = IGT_LOG_DEBUG;
717 		else if (strcmp(env, "info") == 0)
718 			igt_log_level = IGT_LOG_INFO;
719 		else if (strcmp(env, "warn") == 0)
720 			igt_log_level = IGT_LOG_WARN;
721 		else if (strcmp(env, "none") == 0)
722 			igt_log_level = IGT_LOG_NONE;
723 	}
724 
725 	igt_frame_dump_path = getenv("IGT_FRAME_DUMP_PATH");
726 
727 	stderr_needs_sentinel = getenv("IGT_SENTINEL_ON_STDERR") != NULL;
728 
729 	env = getenv("IGT_FORCE_DRIVER");
730 	if (env) {
731 		__set_forced_driver(env);
732 	}
733 }
734 
common_init(int * argc,char ** argv,const char * extra_short_opts,const struct option * extra_long_opts,const char * help_str,igt_opt_handler_t extra_opt_handler,void * handler_data)735 static int common_init(int *argc, char **argv,
736 		       const char *extra_short_opts,
737 		       const struct option *extra_long_opts,
738 		       const char *help_str,
739 		       igt_opt_handler_t extra_opt_handler,
740 		       void *handler_data)
741 {
742 	int c, option_index = 0, i, x;
743 	static struct option long_options[] = {
744 		{"list-subtests",     no_argument,       NULL, OPT_LIST_SUBTESTS},
745 		{"describe",          optional_argument, NULL, OPT_DESCRIBE_SUBTESTS},
746 		{"run-subtest",       required_argument, NULL, OPT_RUN_SUBTEST},
747 		{"help-description",  no_argument,       NULL, OPT_DESCRIPTION},
748 		{"debug",             optional_argument, NULL, OPT_DEBUG},
749 		{"interactive-debug", optional_argument, NULL, OPT_INTERACTIVE_DEBUG},
750 		{"skip-crc-compare",  no_argument,       NULL, OPT_SKIP_CRC},
751 		{"help",              no_argument,       NULL, OPT_HELP},
752 		{0, 0, 0, 0}
753 	};
754 	char *short_opts;
755 	const char *std_short_opts = "h";
756 	size_t std_short_opts_len = strlen(std_short_opts);
757 	struct option *combined_opts;
758 	int extra_opt_count;
759 	int all_opt_count;
760 	int ret = 0;
761 
762 	common_init_env();
763 	igt_list_init(&subgroup_descriptions);
764 
765 	command_str = argv[0];
766 	if (strrchr(command_str, '/'))
767 		command_str = strrchr(command_str, '/') + 1;
768 
769 	/* Check for conflicts and calculate space for passed-in extra long options */
770 	for  (extra_opt_count = 0; extra_long_opts && extra_long_opts[extra_opt_count].name; extra_opt_count++) {
771 		char *conflicting_char;
772 
773 		/* check for conflicts with standard long option values */
774 		for (i = 0; long_options[i].name; i++) {
775 			if (0 == strcmp(extra_long_opts[extra_opt_count].name, long_options[i].name)) {
776 				igt_critical("Conflicting extra long option defined --%s\n", long_options[i].name);
777 				assert(0);
778 
779 			}
780 
781 			if (extra_long_opts[extra_opt_count].val == long_options[i].val) {
782 				igt_critical("Conflicting long option 'val' representation between --%s and --%s\n",
783 					     extra_long_opts[extra_opt_count].name,
784 					     long_options[i].name);
785 				assert(0);
786 			}
787 		}
788 
789 		/* check for conflicts with standard short options */
790 		if (extra_long_opts[extra_opt_count].val != ':'
791 		    && (conflicting_char = memchr(std_short_opts, extra_long_opts[extra_opt_count].val, std_short_opts_len))) {
792 			igt_critical("Conflicting long and short option 'val' representation between --%s and -%c\n",
793 				     extra_long_opts[extra_opt_count].name,
794 				     *conflicting_char);
795 			assert(0);
796 		}
797 	}
798 
799 	/* check for conflicts in extra short options*/
800 	for (i = 0; extra_short_opts && extra_short_opts[i]; i++) {
801 		if (extra_short_opts[i] == ':')
802 			continue;
803 
804 		/* check for conflicts with standard short options */
805 		if (memchr(std_short_opts, extra_short_opts[i], std_short_opts_len)) {
806 			igt_critical("Conflicting short option: -%c\n", std_short_opts[i]);
807 			assert(0);
808 		}
809 
810 		/* check for conflicts with standard long option values */
811 		for (x = 0; long_options[x].name; x++) {
812 			if (long_options[x].val == extra_short_opts[i]) {
813 				igt_critical("Conflicting short option and long option 'val' representation: --%s and -%c\n",
814 					     long_options[x].name, extra_short_opts[i]);
815 				assert(0);
816 			}
817 		}
818 	}
819 
820 	all_opt_count = extra_opt_count + ARRAY_SIZE(long_options);
821 
822 	combined_opts = malloc(all_opt_count * sizeof(*combined_opts));
823 	if (extra_opt_count > 0)
824 		memcpy(combined_opts, extra_long_opts,
825 		       extra_opt_count * sizeof(*combined_opts));
826 
827 	/* Copy the subtest long options (and the final NULL entry) */
828 	memcpy(&combined_opts[extra_opt_count], long_options,
829 		ARRAY_SIZE(long_options) * sizeof(*combined_opts));
830 
831 	ret = asprintf(&short_opts, "%s%s",
832 		       extra_short_opts ? extra_short_opts : "",
833 		       std_short_opts);
834 	assert(ret >= 0);
835 
836 	while ((c = getopt_long(*argc, argv, short_opts, combined_opts,
837 			       &option_index)) != -1) {
838 		switch(c) {
839 		case OPT_INTERACTIVE_DEBUG:
840 			if (optarg && strlen(optarg) > 0)
841 				igt_interactive_debug = strdup(optarg);
842 			else
843 				igt_interactive_debug = "all";
844 			break;
845 		case OPT_DEBUG:
846 			igt_log_level = IGT_LOG_DEBUG;
847 			if (optarg && strlen(optarg) > 0)
848 				igt_log_domain_filter = strdup(optarg);
849 			break;
850 		case OPT_LIST_SUBTESTS:
851 			if (!run_single_subtest)
852 				list_subtests = true;
853 			break;
854 		case OPT_DESCRIBE_SUBTESTS:
855 			if (optarg)
856 				run_single_subtest = strdup(optarg);
857 			list_subtests = true;
858 			describe_subtests = true;
859 			print_test_description();
860 			break;
861 		case OPT_RUN_SUBTEST:
862 			assert(optarg);
863 			if (!list_subtests)
864 				run_single_subtest = strdup(optarg);
865 			break;
866 		case OPT_DESCRIPTION:
867 			print_test_description();
868 			ret = -1;
869 			goto out;
870 		case OPT_SKIP_CRC:
871 			igt_skip_crc_compare = true;
872 			goto out;
873 		case OPT_HELP:
874 			print_usage(help_str, false);
875 			ret = -1;
876 			goto out;
877 		case '?':
878 			print_usage(help_str, true);
879 			ret = -2;
880 			goto out;
881 		default:
882 			ret = extra_opt_handler(c, option_index, handler_data);
883 			if (ret)
884 				goto out;
885 		}
886 	}
887 
888 	common_init_config();
889 
890 out:
891 	free(short_opts);
892 	free(combined_opts);
893 
894 	/* exit immediately if this test has no subtests and a subtest or the
895 	 * list of subtests has been requested */
896 	if (!test_with_subtests) {
897 		if (run_single_subtest) {
898 			igt_warn("Unknown subtest: %s\n", run_single_subtest);
899 			exit(IGT_EXIT_INVALID);
900 		}
901 		if (list_subtests)
902 			exit(IGT_EXIT_INVALID);
903 	}
904 
905 	if (ret < 0)
906 		/* exit with no error for -h/--help */
907 		exit(ret == -1 ? 0 : IGT_EXIT_INVALID);
908 
909 	if (!list_subtests) {
910 		bind_fbcon(false);
911 		igt_kmsg(KMSG_INFO "%s: executing\n", command_str);
912 		print_version();
913 
914 		sync();
915 		oom_adjust_for_doom();
916 		ftrace_dump_on_oops(true);
917 	}
918 
919 	/* install exit handler, to ensure we clean up */
920 	igt_install_exit_handler(common_exit_handler);
921 
922 	if (!test_with_subtests)
923 		igt_gettime(&subtest_time);
924 
925 	for (i = 0; (optind + i) < *argc; i++)
926 		argv[i + 1] = argv[optind + i];
927 
928 	*argc = *argc - optind + 1;
929 
930 	return ret;
931 }
932 
933 
934 /**
935  * igt_subtest_init_parse_opts:
936  * @argc: argc from the test's main()
937  * @argv: argv from the test's main()
938  * @extra_short_opts: getopt_long() compliant list with additional short options
939  * @extra_long_opts: getopt_long() compliant list with additional long options
940  * @help_str: help string for the additional options
941  * @extra_opt_handler: handler for the additional options
942  * @handler_data: user data given to @extra_opt_handler when invoked
943  *
944  * This function handles the subtest related command line options and allows an
945  * arbitrary set of additional options. This is useful for tests which have
946  * additional knobs to tune when run manually like the number of rounds execute
947  * or the size of the allocated buffer objects.
948  *
949  * Tests should use #igt_main_args instead of their own main()
950  * function and calling this function.
951  *
952  * The @help_str parameter is printed directly after the help text of
953  * standard arguments. The formatting of the string should be:
954  * - One line per option
955  * - Two spaces, option flag, tab character, help text, newline character
956  *
957  * Example: "  -s\tBuffer size\n"
958  *
959  * The opt handler function must return #IGT_OPT_HANDLER_SUCCESS on
960  * successful handling, #IGT_OPT_HANDLER_ERROR on errors.
961  *
962  * Returns: Forwards any option parsing errors from getopt_long.
963  */
igt_subtest_init_parse_opts(int * argc,char ** argv,const char * extra_short_opts,const struct option * extra_long_opts,const char * help_str,igt_opt_handler_t extra_opt_handler,void * handler_data)964 int igt_subtest_init_parse_opts(int *argc, char **argv,
965 				const char *extra_short_opts,
966 				const struct option *extra_long_opts,
967 				const char *help_str,
968 				igt_opt_handler_t extra_opt_handler,
969 				void *handler_data)
970 {
971 	int ret;
972 
973 	test_with_subtests = true;
974 	ret = common_init(argc, argv, extra_short_opts, extra_long_opts,
975 			  help_str, extra_opt_handler, handler_data);
976 
977 	return ret;
978 }
979 
980 enum igt_log_level igt_log_level = IGT_LOG_INFO;
981 
982 /**
983  * igt_simple_init_parse_opts:
984  * @argc: argc from the test's main()
985  * @argv: argv from the test's main()
986  * @extra_short_opts: getopt_long() compliant list with additional short options
987  * @extra_long_opts: getopt_long() compliant list with additional long options
988  * @help_str: help string for the additional options
989  * @extra_opt_handler: handler for the additional options
990  * @handler_data: user data given to @extra_opt_handler when invoked
991  *
992  * This initializes a simple test without any support for subtests and allows
993  * an arbitrary set of additional options. This is useful for tests which have
994  * additional knobs to tune when run manually like the number of rounds execute
995  * or the size of the allocated buffer objects.
996  *
997  * Tests should use #igt_simple_main_args instead of their own main()
998  * function and calling this function.
999  *
1000  * The @help_str parameter is printed directly after the help text of
1001  * standard arguments. The formatting of the string should be:
1002  * - One line per option
1003  * - Two spaces, option flag, tab character, help text, newline character
1004  *
1005  * Example: "  -s\tBuffer size\n"
1006  *
1007  * The opt handler function must return #IGT_OPT_HANDLER_SUCCESS on
1008  * successful handling, #IGT_OPT_HANDLER_ERROR on errors.
1009  */
igt_simple_init_parse_opts(int * argc,char ** argv,const char * extra_short_opts,const struct option * extra_long_opts,const char * help_str,igt_opt_handler_t extra_opt_handler,void * handler_data)1010 void igt_simple_init_parse_opts(int *argc, char **argv,
1011 				const char *extra_short_opts,
1012 				const struct option *extra_long_opts,
1013 				const char *help_str,
1014 				igt_opt_handler_t extra_opt_handler,
1015 				void *handler_data)
1016 {
1017 	common_init(argc, argv, extra_short_opts, extra_long_opts, help_str,
1018 		    extra_opt_handler, handler_data);
1019 }
1020 
_clear_current_description(void)1021 static void _clear_current_description(void) {
1022 	__current_description[0] = '\0';
1023 }
1024 
__igt_print_description(const char * subtest_name,const char * file,int line)1025 static void __igt_print_description(const char *subtest_name, const char *file, int line)
1026 {
1027 	struct description_node *desc;
1028 	const char indent[] = "  ";
1029 	bool has_doc = false;
1030 
1031 
1032 	printf("SUB %s %s:%d:\n", subtest_name, file, line);
1033 
1034 	igt_list_for_each(desc, &subgroup_descriptions, link) {
1035 		print_line_wrapping(indent, desc->desc);
1036 		printf("\n");
1037 		has_doc = true;
1038 	}
1039 
1040 	if (__current_description[0] != '\0') {
1041 		print_line_wrapping(indent, __current_description);
1042 		printf("\n");
1043 		has_doc = true;
1044 	}
1045 
1046 	if (!has_doc)
1047 		printf("%sNO DOCUMENTATION!\n\n", indent);
1048 }
1049 
1050 /*
1051  * Note: Testcases which use these helpers MUST NOT output anything to stdout
1052  * outside of places protected by igt_run_subtest checks - the piglit
1053  * runner adds every line to the subtest list.
1054  */
__igt_run_subtest(const char * subtest_name,const char * file,const int line)1055 bool __igt_run_subtest(const char *subtest_name, const char *file, const int line)
1056 {
1057 	int i;
1058 
1059 	assert(!igt_can_fail());
1060 
1061 	/* check the subtest name only contains a-z, A-Z, 0-9, '-' and '_' */
1062 	for (i = 0; subtest_name[i] != '\0'; i++)
1063 		if (subtest_name[i] != '_' && subtest_name[i] != '-'
1064 		    && !isalnum(subtest_name[i])) {
1065 			igt_critical("Invalid subtest name \"%s\".\n",
1066 				     subtest_name);
1067 			igt_exit();
1068 		}
1069 
1070 	if (run_single_subtest) {
1071 		if (uwildmat(subtest_name, run_single_subtest) == 0) {
1072 			_clear_current_description();
1073 			return false;
1074 		} else {
1075 			run_single_subtest_found = true;
1076 		}
1077 	}
1078 
1079 	if (describe_subtests) {
1080 		__igt_print_description(subtest_name, file, line);
1081 		_clear_current_description();
1082 		return false;
1083 	} else if (list_subtests) {
1084 		printf("%s\n", subtest_name);
1085 		return false;
1086 	}
1087 
1088 
1089 	if (skip_subtests_henceforth) {
1090 		printf("%sSubtest %s: %s%s\n",
1091 		       (!__igt_plain_output) ? "\x1b[1m" : "", subtest_name,
1092 		       skip_subtests_henceforth == SKIP ?
1093 		       "SKIP" : "FAIL", (!__igt_plain_output) ? "\x1b[0m" : "");
1094 		fflush(stdout);
1095 		if (stderr_needs_sentinel)
1096 			fprintf(stderr, "Subtest %s: %s\n", subtest_name,
1097 				skip_subtests_henceforth == SKIP ?
1098 				"SKIP" : "FAIL");
1099 		return false;
1100 	}
1101 
1102 	igt_kmsg(KMSG_INFO "%s: starting subtest %s\n",
1103 		 command_str, subtest_name);
1104 	igt_info("Starting subtest: %s\n", subtest_name);
1105 	fflush(stdout);
1106 	if (stderr_needs_sentinel)
1107 		fprintf(stderr, "Starting subtest: %s\n", subtest_name);
1108 
1109 	_igt_log_buffer_reset();
1110 
1111 	igt_gettime(&subtest_time);
1112 	return (in_subtest = subtest_name);
1113 }
1114 
1115 /**
1116  * igt_subtest_name:
1117  *
1118  * Returns: The name of the currently executed subtest or NULL if called from
1119  * outside a subtest block.
1120  */
igt_subtest_name(void)1121 const char *igt_subtest_name(void)
1122 {
1123 	return in_subtest;
1124 }
1125 
1126 /**
1127  * igt_only_list_subtests:
1128  *
1129  * Returns: Returns true if only subtest should be listed and any setup code
1130  * must be skipped, false otherwise.
1131  */
igt_only_list_subtests(void)1132 bool igt_only_list_subtests(void)
1133 {
1134 	return list_subtests;
1135 }
1136 
1137 
1138 
__igt_subtest_group_save(int * save,int * desc)1139 void __igt_subtest_group_save(int *save, int *desc)
1140 {
1141 	assert(test_with_subtests);
1142 
1143 	if (__current_description[0] != '\0') {
1144 		struct description_node *new = calloc(1, sizeof(*new));
1145 		memcpy(new->desc, __current_description, sizeof(__current_description));
1146 		igt_list_add_tail(&new->link, &subgroup_descriptions);
1147 		_clear_current_description();
1148 		*desc = true;
1149 	}
1150 
1151 	*save = skip_subtests_henceforth;
1152 }
1153 
__igt_subtest_group_restore(int save,int desc)1154 void __igt_subtest_group_restore(int save, int desc)
1155 {
1156 	if (desc) {
1157 		struct description_node *last =
1158 			igt_list_last_entry(&subgroup_descriptions, last, link);
1159 		igt_list_del(&last->link);
1160 		free(last);
1161 	}
1162 
1163 	skip_subtests_henceforth = save;
1164 }
1165 
1166 static bool skipped_one = false;
1167 static bool succeeded_one = false;
1168 static bool failed_one = false;
1169 
1170 static void exit_subtest(const char *) __attribute__((noreturn));
exit_subtest(const char * result)1171 static void exit_subtest(const char *result)
1172 {
1173 	struct timespec now;
1174 
1175 	igt_gettime(&now);
1176 	igt_info("%sSubtest %s: %s (%.3fs)%s\n",
1177 		 (!__igt_plain_output) ? "\x1b[1m" : "",
1178 		 in_subtest, result, igt_time_elapsed(&subtest_time, &now),
1179 		 (!__igt_plain_output) ? "\x1b[0m" : "");
1180 	fflush(stdout);
1181 	if (stderr_needs_sentinel)
1182 		fprintf(stderr, "Subtest %s: %s (%.3fs)\n",
1183 			in_subtest, result, igt_time_elapsed(&subtest_time, &now));
1184 
1185 	igt_terminate_spins();
1186 
1187 	in_subtest = NULL;
1188 	siglongjmp(igt_subtest_jmpbuf, 1);
1189 }
1190 
1191 /**
1192  * igt_skip:
1193  * @f: format string
1194  * @...: optional arguments used in the format string
1195  *
1196  * Subtest aware test skipping. The format string is printed to stderr as the
1197  * reason why the test skipped.
1198  *
1199  * For tests with subtests this will either bail out of the current subtest or
1200  * mark all subsequent subtests as SKIP (presuming some global setup code
1201  * failed).
1202  *
1203  * For normal tests without subtest it will directly exit.
1204  */
igt_skip(const char * f,...)1205 void igt_skip(const char *f, ...)
1206 {
1207 	va_list args;
1208 	skipped_one = true;
1209 
1210 	assert(!test_child);
1211 
1212 	if (!igt_only_list_subtests()) {
1213 		va_start(args, f);
1214 		vprintf(f, args);
1215 		va_end(args);
1216 	}
1217 
1218 	if (in_subtest) {
1219 		exit_subtest("SKIP");
1220 	} else if (test_with_subtests) {
1221 		skip_subtests_henceforth = SKIP;
1222 		assert(in_fixture);
1223 		__igt_fixture_end();
1224 	} else {
1225 		igt_exitcode = IGT_EXIT_SKIP;
1226 		igt_exit();
1227 	}
1228 }
1229 
__igt_skip_check(const char * file,const int line,const char * func,const char * check,const char * f,...)1230 void __igt_skip_check(const char *file, const int line,
1231 		      const char *func, const char *check,
1232 		      const char *f, ...)
1233 {
1234 	va_list args;
1235 	int err = errno;
1236 	char *err_str = NULL;
1237 
1238 	if (err)
1239 		igt_assert_neq(asprintf(&err_str, "Last errno: %i, %s\n", err, strerror(err)),
1240 			       -1);
1241 
1242 	if (f) {
1243 		static char *buf;
1244 
1245 		/* igt_skip never returns, so try to not leak too badly. */
1246 		if (buf)
1247 			free(buf);
1248 
1249 		va_start(args, f);
1250 		igt_assert_neq(vasprintf(&buf, f, args), -1);
1251 		va_end(args);
1252 
1253 		igt_skip("Test requirement not met in function %s, file %s:%i:\n"
1254 			 "Test requirement: %s\n%s"
1255 			 "%s",
1256 			 func, file, line, check, buf, err_str ?: "");
1257 	} else {
1258 		igt_skip("Test requirement not met in function %s, file %s:%i:\n"
1259 			 "Test requirement: %s\n"
1260 			 "%s",
1261 			 func, file, line, check, err_str ?: "");
1262 	}
1263 }
1264 
1265 /**
1266  * igt_success:
1267  *
1268  * Complete a (subtest) as successful
1269  *
1270  * This bails out of a subtests and marks it as successful. For global tests it
1271  * it won't bail out of anything.
1272  */
igt_success(void)1273 void igt_success(void)
1274 {
1275 	succeeded_one = true;
1276 	if (in_subtest)
1277 		exit_subtest("SUCCESS");
1278 }
1279 
1280 /**
1281  * igt_fail:
1282  * @exitcode: exitcode
1283  *
1284  * Fail a testcase. The exitcode is used as the exit code of the test process.
1285  * It may not be 0 (which indicates success) or 77 (which indicates a skipped
1286  * test).
1287  *
1288  * For tests with subtests this will either bail out of the current subtest or
1289  * mark all subsequent subtests as FAIL (presuming some global setup code
1290  * failed).
1291  *
1292  * For normal tests without subtest it will directly exit with the given
1293  * exitcode.
1294  */
igt_fail(int exitcode)1295 void igt_fail(int exitcode)
1296 {
1297 	assert(exitcode != IGT_EXIT_SUCCESS && exitcode != IGT_EXIT_SKIP);
1298 
1299 	igt_debug_wait_for_keypress("failure");
1300 
1301 	/* Exit immediately if the test is already exiting and igt_fail is
1302 	 * called. This can happen if an igt_assert fails in an exit handler */
1303 	if (in_atexit_handler)
1304 		_exit(IGT_EXIT_FAILURE);
1305 
1306 	if (!failed_one)
1307 		igt_exitcode = exitcode;
1308 
1309 	failed_one = true;
1310 
1311 	/* Silent exit, parent will do the yelling. */
1312 	if (test_child)
1313 		exit(exitcode);
1314 
1315 	_igt_log_buffer_dump();
1316 
1317 	if (in_subtest) {
1318 		exit_subtest("FAIL");
1319 	} else {
1320 		assert(igt_can_fail());
1321 
1322 		if (in_fixture) {
1323 			skip_subtests_henceforth = FAIL;
1324 			__igt_fixture_end();
1325 		}
1326 
1327 		igt_exit();
1328 	}
1329 }
1330 
1331 /**
1332  * igt_fatal_error: Stop test execution on fatal errors
1333  *
1334  * Stop test execution or optionally, if the IGT_REBOOT_ON_FATAL_ERROR
1335  * environment variable is set, reboot the machine.
1336  *
1337  * Since out test runner (piglit) does support fatal test exit codes, we
1338  * implement the default behaviour by waiting endlessly.
1339  */
igt_fatal_error(void)1340 void  __attribute__((noreturn)) igt_fatal_error(void)
1341 {
1342 	if (igt_check_boolean_env_var("IGT_REBOOT_ON_FATAL_ERROR", false)) {
1343 		igt_warn("FATAL ERROR - REBOOTING\n");
1344 		igt_sysrq_reboot();
1345 	} else {
1346 		igt_warn("FATAL ERROR\n");
1347 		for (;;)
1348 			pause();
1349 	}
1350 }
1351 
1352 
1353 /**
1354  * igt_can_fail:
1355  *
1356  * Returns true if called from either an #igt_fixture, #igt_subtest or a
1357  * testcase without subtests, i.e. #igt_simple_main. Returns false otherwise. In
1358  * other words, it checks whether it's legal to call igt_fail(), igt_skip_on()
1359  * and all the convenience macros build around those.
1360  *
1361  * This is useful to make sure that library code is called from the right
1362  * places.
1363  */
igt_can_fail(void)1364 bool igt_can_fail(void)
1365 {
1366 	return !test_with_subtests || in_fixture || in_subtest;
1367 }
1368 
1369 /**
1370  * igt_describe_f:
1371  * @fmt: format string containing description
1372  * @...: argument used by the format string
1373  *
1374  * Attach a description to the following #igt_subtest or #igt_subtest_group
1375  * block.
1376  *
1377  * Check #igt_describe for more details.
1378  *
1379  */
igt_describe_f(const char * fmt,...)1380 void igt_describe_f(const char *fmt, ...)
1381 {
1382 	int ret;
1383 	va_list args;
1384 
1385 	if (!describe_subtests)
1386 		return;
1387 
1388 	va_start(args, fmt);
1389 
1390 	ret = vsnprintf(__current_description, sizeof(__current_description), fmt, args);
1391 
1392 	va_end(args);
1393 
1394 	assert(ret < sizeof(__current_description));
1395 }
1396 
running_under_gdb(void)1397 static bool running_under_gdb(void)
1398 {
1399 	char pathname[30], buf[1024];
1400 	ssize_t len;
1401 
1402 	sprintf(pathname, "/proc/%d/exe", getppid());
1403 	len = readlink(pathname, buf, sizeof(buf) - 1);
1404 	if (len < 0)
1405 		return false;
1406 
1407 	buf[len] = '\0';
1408 
1409 	return strncmp(basename(buf), "gdb", 3) == 0;
1410 }
1411 
__write_stderr(const char * str,size_t len)1412 static void __write_stderr(const char *str, size_t len)
1413 {
1414 	igt_ignore_warn(write(STDERR_FILENO, str, len));
1415 }
1416 
write_stderr(const char * str)1417 static void write_stderr(const char *str)
1418 {
1419 	__write_stderr(str, strlen(str));
1420 }
1421 
1422 #ifndef ANDROID
1423 
print_backtrace(void)1424 static void print_backtrace(void)
1425 {
1426 	unw_cursor_t cursor;
1427 	unw_context_t uc;
1428 	int stack_num = 0;
1429 
1430 	Dwfl_Callbacks cbs = {
1431 		.find_elf = dwfl_linux_proc_find_elf,
1432 		.find_debuginfo = dwfl_standard_find_debuginfo,
1433 	};
1434 
1435 	Dwfl *dwfl = dwfl_begin(&cbs);
1436 
1437 	if (dwfl_linux_proc_report(dwfl, getpid())) {
1438 		dwfl_end(dwfl);
1439 		dwfl = NULL;
1440 	} else
1441 		dwfl_report_end(dwfl, NULL, NULL);
1442 
1443 	igt_info("Stack trace:\n");
1444 
1445 	unw_getcontext(&uc);
1446 	unw_init_local(&cursor, &uc);
1447 	while (unw_step(&cursor) > 0) {
1448 		char name[255];
1449 		unw_word_t off, ip;
1450 		Dwfl_Module *mod = NULL;
1451 
1452 		unw_get_reg(&cursor, UNW_REG_IP, &ip);
1453 
1454 		if (dwfl)
1455 			mod = dwfl_addrmodule(dwfl, ip);
1456 
1457 		if (mod) {
1458 			const char *src, *dwfl_name;
1459 			Dwfl_Line *line;
1460 			int lineno;
1461 			GElf_Sym sym;
1462 
1463 			line = dwfl_module_getsrc(mod, ip);
1464 			dwfl_name = dwfl_module_addrsym(mod, ip, &sym, NULL);
1465 
1466 			if (line && dwfl_name) {
1467 				src = dwfl_lineinfo(line, NULL, &lineno, NULL, NULL, NULL);
1468 				igt_info("  #%d %s:%d %s()\n", stack_num++, src, lineno, dwfl_name);
1469 				continue;
1470 			}
1471 		}
1472 
1473 		if (unw_get_proc_name(&cursor, name, 255, &off) < 0)
1474 			igt_info("  #%d [<unknown>+0x%x]\n", stack_num++,
1475 				 (unsigned int) ip);
1476 		else
1477 			igt_info("  #%d [%s+0x%x]\n", stack_num++, name,
1478 				 (unsigned int) off);
1479 	}
1480 
1481 	if (dwfl)
1482 		dwfl_end(dwfl);
1483 }
1484 
1485 static const char hex[] = "0123456789abcdef";
1486 
1487 static void
xputch(int c)1488 xputch(int c)
1489 {
1490 	igt_ignore_warn(write(STDERR_FILENO, (const void *) &c, 1));
1491 }
1492 
1493 static int
xpow(int base,int pow)1494 xpow(int base, int pow)
1495 {
1496 	int i, r = 1;
1497 
1498 	for (i = 0; i < pow; i++)
1499 		r *= base;
1500 
1501 	return r;
1502 }
1503 
1504 static void
printnum(unsigned long long num,unsigned base)1505 printnum(unsigned long long num, unsigned base)
1506 {
1507 	int i = 0;
1508 	unsigned long long __num = num;
1509 
1510 	/* determine from where we should start dividing */
1511 	do {
1512 		__num /= base;
1513 		i++;
1514 	} while (__num);
1515 
1516 	while (i--)
1517 		xputch(hex[num / xpow(base, i) % base]);
1518 }
1519 
1520 static size_t
xstrlcpy(char * dst,const char * src,size_t size)1521 xstrlcpy(char *dst, const char *src, size_t size)
1522 {
1523 	char *dst_in;
1524 
1525 	dst_in = dst;
1526 	if (size > 0) {
1527 		while (--size > 0 && *src != '\0')
1528 			*dst++ = *src++;
1529 		*dst = '\0';
1530 	}
1531 
1532 	return dst - dst_in;
1533 }
1534 
1535 static void
xprintfmt(const char * fmt,va_list ap)1536 xprintfmt(const char *fmt, va_list ap)
1537 {
1538 	const char *p;
1539 	int ch, base;
1540 	unsigned long long num;
1541 
1542 	while (1) {
1543 		while ((ch = *(const unsigned char *) fmt++) != '%') {
1544 			if (ch == '\0') {
1545 				return;
1546 			}
1547 			xputch(ch);
1548 		}
1549 
1550 		ch = *(const unsigned char *) fmt++;
1551 		switch (ch) {
1552 		/* character */
1553 		case 'c':
1554 			xputch(va_arg(ap, int));
1555 			break;
1556 		/* string */
1557 		case 's':
1558 			if ((p = va_arg(ap, char *)) == NULL) {
1559 				p = "(null)";
1560 			}
1561 
1562 			for (; (ch = *p++) != '\0';) {
1563 				if (ch < ' ' || ch > '~') {
1564 					xputch('?');
1565 				} else {
1566 					xputch(ch);
1567 				}
1568 			}
1569 			break;
1570 		/* (signed) decimal */
1571 		case 'd':
1572 			num = va_arg(ap, int);
1573 			if ((long long) num < 0) {
1574 				xputch('-');
1575 				num = -(long long) num;
1576 			}
1577 			base = 10;
1578 			goto number;
1579 		/* unsigned decimal */
1580 		case 'u':
1581 			num = va_arg(ap, unsigned int);
1582 			base = 10;
1583 			goto number;
1584 		/* (unsigned) hexadecimal */
1585 		case 'x':
1586 			num = va_arg(ap, unsigned int);
1587 			base = 16;
1588 number:
1589 			printnum(num, base);
1590 			break;
1591 
1592 		/* The following are not implemented */
1593 
1594 		/* width field */
1595 		case '1': case '2':
1596 		case '3': case '4':
1597 		case '5': case '6':
1598 		case '7': case '8':
1599 		case '9':
1600 		case '.': case '#':
1601 		/* long */
1602 		case 'l':
1603 		/* octal */
1604 		case 'o':
1605 		/* pointer */
1606 		case 'p':
1607 		/* float */
1608 		case 'f':
1609 			abort();
1610 		/* escaped '%' character */
1611 		case '%':
1612 			xputch(ch);
1613 			break;
1614 		/* unrecognized escape sequence - just print it literally */
1615 		default:
1616 			xputch('%');
1617 			for (fmt--; fmt[-1] != '%'; fmt--)
1618 				; /* do nothing */
1619 			break;
1620 		}
1621 	}
1622 }
1623 
1624 /* async-safe printf */
1625 static void
xprintf(const char * fmt,...)1626 xprintf(const char *fmt, ...)
1627 {
1628 	va_list ap;
1629 
1630 	va_start(ap, fmt);
1631 	xprintfmt(fmt, ap);
1632 	va_end(ap);
1633 }
1634 
print_backtrace_sig_safe(void)1635 static void print_backtrace_sig_safe(void)
1636 {
1637 	unw_cursor_t cursor;
1638 	unw_context_t uc;
1639 	int stack_num = 0;
1640 
1641 	write_stderr("Stack trace: \n");
1642 
1643 	unw_getcontext(&uc);
1644 	unw_init_local(&cursor, &uc);
1645 	while (unw_step(&cursor) > 0) {
1646 		char name[255];
1647 		unw_word_t off;
1648 
1649 		if (unw_get_proc_name(&cursor, name, 255, &off) < 0)
1650 			xstrlcpy(name, "<unknown>", 10);
1651 
1652 		xprintf(" #%d [%s+0x%x]\n", stack_num++, name,
1653 				(unsigned int) off);
1654 
1655 	}
1656 }
1657 
1658 #endif
1659 
__igt_fail_assert(const char * domain,const char * file,const int line,const char * func,const char * assertion,const char * f,...)1660 void __igt_fail_assert(const char *domain, const char *file, const int line,
1661 		       const char *func, const char *assertion,
1662 		       const char *f, ...)
1663 {
1664 	va_list args;
1665 	int err = errno;
1666 
1667 	igt_log(domain, IGT_LOG_CRITICAL,
1668 		"Test assertion failure function %s, file %s:%i:\n", func, file,
1669 		line);
1670 	igt_log(domain, IGT_LOG_CRITICAL, "Failed assertion: %s\n", assertion);
1671 	if (err)
1672 		igt_log(domain, IGT_LOG_CRITICAL, "Last errno: %i, %s\n", err,
1673 			strerror(err));
1674 
1675 	if (f) {
1676 		va_start(args, f);
1677 		igt_vlog(domain, IGT_LOG_CRITICAL, f, args);
1678 		va_end(args);
1679 	}
1680 
1681 #ifndef ANDROID
1682 	print_backtrace();
1683 #endif
1684 
1685 	if (running_under_gdb())
1686 		abort();
1687 	igt_fail(IGT_EXIT_FAILURE);
1688 }
1689 
1690 /**
1691  * igt_exit:
1692  *
1693  * exit() for both types (simple and with subtests) of i-g-t tests.
1694  *
1695  * This will exit the test with the right exit code when subtests have been
1696  * skipped. For normal tests it exits with a successful exit code, presuming
1697  * everything has worked out. For subtests it also checks that at least one
1698  * subtest has been run (save when only listing subtests.
1699  *
1700  * It is an error to normally exit a test calling igt_exit() - without it the
1701  * result reporting will be wrong. To avoid such issues it is highly recommended
1702  * to use #igt_main or #igt_simple_main instead of a hand-rolled main() function.
1703  */
igt_exit(void)1704 void igt_exit(void)
1705 {
1706 	int tmp;
1707 
1708 	igt_exit_called = true;
1709 
1710 	if (igt_key_file)
1711 		g_key_file_free(igt_key_file);
1712 
1713 	if (run_single_subtest && !run_single_subtest_found) {
1714 		igt_critical("Unknown subtest: %s\n", run_single_subtest);
1715 		exit(IGT_EXIT_INVALID);
1716 	}
1717 
1718 	if (igt_only_list_subtests())
1719 		exit(IGT_EXIT_SUCCESS);
1720 
1721 	/* Calling this without calling one of the above is a failure */
1722 	assert(!test_with_subtests ||
1723 	       skipped_one ||
1724 	       succeeded_one ||
1725 	       failed_one);
1726 
1727 	if (test_with_subtests && !failed_one) {
1728 		if (succeeded_one)
1729 			igt_exitcode = IGT_EXIT_SUCCESS;
1730 		else
1731 			igt_exitcode = IGT_EXIT_SKIP;
1732 	}
1733 
1734 	if (command_str)
1735 		igt_kmsg(KMSG_INFO "%s: exiting, ret=%d\n",
1736 			 command_str, igt_exitcode);
1737 	igt_debug("Exiting with status code %d\n", igt_exitcode);
1738 
1739 	for (int c = 0; c < num_test_children; c++)
1740 		kill(test_children[c], SIGKILL);
1741 	assert(!num_test_children);
1742 
1743 	assert(waitpid(-1, &tmp, WNOHANG) == -1 && errno == ECHILD);
1744 
1745 	if (!test_with_subtests) {
1746 		struct timespec now;
1747 		const char *result;
1748 
1749 		igt_gettime(&now);
1750 
1751 		switch (igt_exitcode) {
1752 			case IGT_EXIT_SUCCESS:
1753 				result = "SUCCESS";
1754 				break;
1755 			case IGT_EXIT_SKIP:
1756 				result = "SKIP";
1757 				break;
1758 			default:
1759 				result = "FAIL";
1760 		}
1761 
1762 		printf("%s (%.3fs)\n",
1763 		       result, igt_time_elapsed(&subtest_time, &now));
1764 	}
1765 
1766 	exit(igt_exitcode);
1767 }
1768 
1769 /* fork support code */
1770 static int helper_process_count;
1771 static pid_t helper_process_pids[] =
1772 { -1, -1, -1, -1};
1773 
reset_helper_process_list(void)1774 static void reset_helper_process_list(void)
1775 {
1776 	for (int i = 0; i < ARRAY_SIZE(helper_process_pids); i++)
1777 		helper_process_pids[i] = -1;
1778 	helper_process_count = 0;
1779 }
1780 
__waitpid(pid_t pid)1781 static int __waitpid(pid_t pid)
1782 {
1783 	int status = -1;
1784 	while (waitpid(pid, &status, 0) == -1 &&
1785 	       errno == EINTR)
1786 		;
1787 
1788 	return status;
1789 }
1790 
fork_helper_exit_handler(int sig)1791 static void fork_helper_exit_handler(int sig)
1792 {
1793 	/* Inside a signal handler, play safe */
1794 	for (int i = 0; i < ARRAY_SIZE(helper_process_pids); i++) {
1795 		pid_t pid = helper_process_pids[i];
1796 		if (pid != -1) {
1797 			kill(pid, SIGTERM);
1798 			__waitpid(pid);
1799 			helper_process_count--;
1800 		}
1801 	}
1802 
1803 	assert(helper_process_count == 0);
1804 }
1805 
__igt_fork_helper(struct igt_helper_process * proc)1806 bool __igt_fork_helper(struct igt_helper_process *proc)
1807 {
1808 	pid_t pid;
1809 	int id;
1810 	int tmp_count;
1811 
1812 	assert(!proc->running);
1813 	assert(helper_process_count < ARRAY_SIZE(helper_process_pids));
1814 
1815 	for (id = 0; helper_process_pids[id] != -1; id++)
1816 		;
1817 
1818 	igt_install_exit_handler(fork_helper_exit_handler);
1819 
1820 	/*
1821 	 * Avoid races when the parent stops the child before the setup code
1822 	 * had a chance to run. This happens e.g. when skipping tests wrapped in
1823 	 * the signal helper.
1824 	 */
1825 	tmp_count = exit_handler_count;
1826 	exit_handler_count = 0;
1827 
1828 	/* ensure any buffers are flushed before fork */
1829 	fflush(NULL);
1830 
1831 	switch (pid = fork()) {
1832 	case -1:
1833 		exit_handler_count = tmp_count;
1834 		igt_assert(0);
1835 	case 0:
1836 		reset_helper_process_list();
1837 		oom_adjust_for_doom();
1838 
1839 		return true;
1840 	default:
1841 		exit_handler_count = tmp_count;
1842 		proc->running = true;
1843 		proc->pid = pid;
1844 		proc->id = id;
1845 		helper_process_pids[id] = pid;
1846 		helper_process_count++;
1847 
1848 		return false;
1849 	}
1850 
1851 }
1852 
1853 /**
1854  * igt_wait_helper:
1855  * @proc: #igt_helper_process structure
1856  *
1857  * Joins a helper process. It is an error to call this on a helper process which
1858  * hasn't been spawned yet.
1859  */
igt_wait_helper(struct igt_helper_process * proc)1860 int igt_wait_helper(struct igt_helper_process *proc)
1861 {
1862 	int status;
1863 
1864 	assert(proc->running);
1865 
1866 	status = __waitpid(proc->pid);
1867 
1868 	proc->running = false;
1869 
1870 	helper_process_pids[proc->id] = -1;
1871 	helper_process_count--;
1872 
1873 	return status;
1874 }
1875 
helper_was_alive(struct igt_helper_process * proc,int status)1876 static bool helper_was_alive(struct igt_helper_process *proc,
1877 			     int status)
1878 {
1879 	return (WIFSIGNALED(status) &&
1880 		WTERMSIG(status) == (proc->use_SIGKILL ? SIGKILL : SIGTERM));
1881 }
1882 
1883 /**
1884  * igt_stop_helper:
1885  * @proc: #igt_helper_process structure
1886  *
1887  * Terminates a helper process. It is legal to call this on a helper process
1888  * which hasn't been spawned yet, e.g. if the helper was skipped due to
1889  * HW restrictions.
1890  */
igt_stop_helper(struct igt_helper_process * proc)1891 void igt_stop_helper(struct igt_helper_process *proc)
1892 {
1893 	int status;
1894 
1895 	if (!proc->running) /* never even started */
1896 		return;
1897 
1898 	/* failure here means the pid is already dead and so waiting is safe */
1899 	kill(proc->pid, proc->use_SIGKILL ? SIGKILL : SIGTERM);
1900 
1901 	status = igt_wait_helper(proc);
1902 	if (!helper_was_alive(proc, status))
1903 		igt_debug("Helper died too early with status=%d\n", status);
1904 	assert(helper_was_alive(proc, status));
1905 }
1906 
children_exit_handler(int sig)1907 static void children_exit_handler(int sig)
1908 {
1909 	int status;
1910 
1911 	/* The exit handler can be called from a fatal signal, so play safe */
1912 	while (num_test_children-- && wait(&status))
1913 		;
1914 }
1915 
__igt_fork(void)1916 bool __igt_fork(void)
1917 {
1918 	assert(!test_with_subtests || in_subtest);
1919 	assert(!test_child);
1920 
1921 	igt_install_exit_handler(children_exit_handler);
1922 
1923 	if (num_test_children >= test_children_sz) {
1924 		if (!test_children_sz)
1925 			test_children_sz = 4;
1926 		else
1927 			test_children_sz *= 2;
1928 
1929 		test_children = realloc(test_children,
1930 					sizeof(pid_t)*test_children_sz);
1931 		igt_assert(test_children);
1932 	}
1933 
1934 	/* ensure any buffers are flushed before fork */
1935 	fflush(NULL);
1936 
1937 	switch (test_children[num_test_children++] = fork()) {
1938 	case -1:
1939 		igt_assert(0);
1940 	case 0:
1941 		test_child = true;
1942 		exit_handler_count = 0;
1943 		reset_helper_process_list();
1944 		oom_adjust_for_doom();
1945 		igt_unshare_spins();
1946 
1947 		return true;
1948 	default:
1949 		return false;
1950 	}
1951 
1952 }
1953 
__igt_waitchildren(void)1954 int __igt_waitchildren(void)
1955 {
1956 	int err = 0;
1957 	int count;
1958 
1959 	assert(!test_child);
1960 
1961 	count = 0;
1962 	while (count < num_test_children) {
1963 		int status = -1;
1964 		pid_t pid;
1965 		int c;
1966 
1967 		pid = wait(&status);
1968 		if (pid == -1)
1969 			continue;
1970 
1971 		for (c = 0; c < num_test_children; c++)
1972 			if (pid == test_children[c])
1973 				break;
1974 		if (c == num_test_children)
1975 			continue;
1976 
1977 		if (err == 0 && status != 0) {
1978 			if (WIFEXITED(status)) {
1979 				printf("child %i failed with exit status %i\n",
1980 				       c, WEXITSTATUS(status));
1981 				err = WEXITSTATUS(status);
1982 			} else if (WIFSIGNALED(status)) {
1983 				printf("child %i died with signal %i, %s\n",
1984 				       c, WTERMSIG(status),
1985 				       strsignal(WTERMSIG(status)));
1986 				err = 128 + WTERMSIG(status);
1987 			} else {
1988 				printf("Unhandled failure [%d] in child %i\n", status, c);
1989 				err = 256;
1990 			}
1991 
1992 			for (c = 0; c < num_test_children; c++)
1993 				kill(test_children[c], SIGKILL);
1994 		}
1995 
1996 		count++;
1997 	}
1998 
1999 	num_test_children = 0;
2000 	return err;
2001 }
2002 
2003 /**
2004  * igt_waitchildren:
2005  *
2006  * Wait for all children forked with igt_fork.
2007  *
2008  * The magic here is that exit codes from children will be correctly propagated
2009  * to the main thread, including the relevant exit code if a child thread failed.
2010  * Of course if multiple children failed with different exit codes the resulting
2011  * exit code will be non-deterministic.
2012  *
2013  * Note that igt_skip() will not be forwarded, feature tests need to be done
2014  * before spawning threads with igt_fork().
2015  */
igt_waitchildren(void)2016 void igt_waitchildren(void)
2017 {
2018 	int err = __igt_waitchildren();
2019 	if (err)
2020 		igt_fail(err);
2021 }
2022 
igt_alarm_killchildren(int signal)2023 static void igt_alarm_killchildren(int signal)
2024 {
2025 	igt_info("Timed out waiting for children\n");
2026 
2027 	for (int c = 0; c < num_test_children; c++)
2028 		kill(test_children[c], SIGKILL);
2029 }
2030 
2031 /**
2032  * igt_waitchildren_timeout:
2033  * @seconds: timeout in seconds to wait
2034  * @reason: debug string explaining what timedout
2035  *
2036  * Wait for all children forked with igt_fork, for a maximum of @seconds. If the
2037  * timeout expires, kills all children, cleans them up, and then fails by
2038  * calling igt_fail().
2039  */
igt_waitchildren_timeout(int seconds,const char * reason)2040 void igt_waitchildren_timeout(int seconds, const char *reason)
2041 {
2042 	struct sigaction sa;
2043 	int ret;
2044 
2045 	sa.sa_handler = igt_alarm_killchildren;
2046 	sigemptyset(&sa.sa_mask);
2047 	sa.sa_flags = 0;
2048 
2049 	sigaction(SIGALRM, &sa, NULL);
2050 
2051 	alarm(seconds);
2052 
2053 	ret = __igt_waitchildren();
2054 	igt_reset_timeout();
2055 	if (ret)
2056 		igt_fail(ret);
2057 }
2058 
2059 /* exit handler code */
2060 #define MAX_SIGNALS		32
2061 #define MAX_EXIT_HANDLERS	10
2062 
2063 #ifndef HAVE_SIGHANDLER_T
2064 typedef void (*sighandler_t)(int);
2065 #endif
2066 
2067 static struct {
2068 	sighandler_t handler;
2069 	bool installed;
2070 } orig_sig[MAX_SIGNALS];
2071 
2072 static igt_exit_handler_t exit_handler_fn[MAX_EXIT_HANDLERS];
2073 static bool exit_handler_disabled;
2074 static const struct {
2075 	int number;
2076 	const char *name;
2077 	size_t name_len;
2078 } handled_signals[] = {
2079 #define SIGDEF(x) { x, #x, sizeof(#x) - 1 }
2080 #define SILENT(x) { x, NULL, 0 }
2081 
2082 	SILENT(SIGINT),
2083 	SILENT(SIGHUP),
2084 	SILENT(SIGPIPE),
2085 	SILENT(SIGTERM),
2086 
2087 	SIGDEF(SIGQUIT), /* used by igt_runner for its external timeout */
2088 
2089 	SIGDEF(SIGABRT),
2090 	SIGDEF(SIGSEGV),
2091 	SIGDEF(SIGBUS),
2092 	SIGDEF(SIGFPE)
2093 
2094 #undef SILENT
2095 #undef SIGDEF
2096 };
2097 
install_sig_handler(int sig_num,sighandler_t handler)2098 static int install_sig_handler(int sig_num, sighandler_t handler)
2099 {
2100 	orig_sig[sig_num].handler = signal(sig_num, handler);
2101 
2102 	if (orig_sig[sig_num].handler == SIG_ERR)
2103 		return -1;
2104 
2105 	orig_sig[sig_num].installed = true;
2106 
2107 	return 0;
2108 }
2109 
restore_sig_handler(int sig_num)2110 static void restore_sig_handler(int sig_num)
2111 {
2112 	/* Just restore the default so that we properly fall over. */
2113 	signal(sig_num, SIG_DFL);
2114 }
2115 
restore_all_sig_handler(void)2116 static void restore_all_sig_handler(void)
2117 {
2118 	int i;
2119 
2120 	for (i = 0; i < ARRAY_SIZE(orig_sig); i++)
2121 		restore_sig_handler(i);
2122 }
2123 
call_exit_handlers(int sig)2124 static void call_exit_handlers(int sig)
2125 {
2126 	int i;
2127 
2128 	igt_terminate_spins();
2129 
2130 	if (!exit_handler_count) {
2131 		return;
2132 	}
2133 
2134 	for (i = exit_handler_count - 1; i >= 0; i--)
2135 		exit_handler_fn[i](sig);
2136 
2137 	/* ensure we don't get called twice */
2138 	exit_handler_count = 0;
2139 }
2140 
igt_atexit_handler(void)2141 static void igt_atexit_handler(void)
2142 {
2143 	in_atexit_handler = true;
2144 
2145 	restore_all_sig_handler();
2146 
2147 	if (!exit_handler_disabled)
2148 		call_exit_handlers(0);
2149 }
2150 
crash_signal(int sig)2151 static bool crash_signal(int sig)
2152 {
2153 	switch (sig) {
2154 	case SIGILL:
2155 	case SIGBUS:
2156 	case SIGFPE:
2157 	case SIGSEGV:
2158 		return true;
2159 	default:
2160 		return false;
2161 	}
2162 }
2163 
fatal_sig_handler(int sig)2164 static void fatal_sig_handler(int sig)
2165 {
2166 	int i;
2167 
2168 	for (i = 0; i < ARRAY_SIZE(handled_signals); i++) {
2169 		if (handled_signals[i].number != sig)
2170 			continue;
2171 
2172 		if (handled_signals[i].name_len) {
2173 			write_stderr("Received signal ");
2174 			__write_stderr(handled_signals[i].name,
2175 				       handled_signals[i].name_len);
2176 			write_stderr(".\n");
2177 
2178 #ifndef ANDROID
2179 			print_backtrace_sig_safe();
2180 #endif
2181 		}
2182 
2183 		if (crash_signal(sig)) {
2184 			/* Linux standard to return exit code as 128 + signal */
2185 			if (!failed_one)
2186 				igt_exitcode = 128 + sig;
2187 			failed_one = true;
2188 
2189 			if (in_subtest)
2190 				exit_subtest("CRASH");
2191 		}
2192 		break;
2193 	}
2194 
2195 	restore_all_sig_handler();
2196 
2197 	/*
2198 	 * exit_handler_disabled is always false here, since when we set it
2199 	 * we also block signals.
2200 	 */
2201 	call_exit_handlers(sig);
2202 
2203 	{
2204 #ifdef __linux__
2205 	/* Workaround cached PID and TID races on glibc and Bionic libc. */
2206 		pid_t pid = syscall(SYS_getpid);
2207 		pid_t tid = gettid();
2208 
2209 		syscall(SYS_tgkill, pid, tid, sig);
2210 #else
2211 		pthread_t tid = pthread_self();
2212 		union sigval value = { .sival_ptr = NULL };
2213 
2214 		pthread_sigqueue(tid, sig, value);
2215 #endif
2216         }
2217 }
2218 
2219 /**
2220  * igt_install_exit_handler:
2221  * @fn: exit handler function
2222  *
2223  * Set a handler that will be called either when the process calls exit() or
2224  * <!-- -->returns from the main function, or one of the signals in
2225  * 'handled_signals' is raised. MAX_EXIT_HANDLERS handlers can be installed,
2226  * each of which will be called only once, even if a subsequent signal is
2227  * raised. If the exit handlers are called due to a signal, the signal will be
2228  * re-raised with the original signal disposition after all handlers returned.
2229  *
2230  * The handler will be passed the signal number if called due to a signal, or
2231  * 0 otherwise. Exit handlers can also be used from test children spawned with
2232  * igt_fork(), but not from within helper processes spawned with
2233  * igt_fork_helper(). The list of exit handlers is reset when forking to
2234  * avoid issues with children cleanup up the parent's state too early.
2235  */
igt_install_exit_handler(igt_exit_handler_t fn)2236 void igt_install_exit_handler(igt_exit_handler_t fn)
2237 {
2238 	int i;
2239 
2240 	for (i = 0; i < exit_handler_count; i++)
2241 		if (exit_handler_fn[i] == fn)
2242 			return;
2243 
2244 	igt_assert(exit_handler_count < MAX_EXIT_HANDLERS);
2245 
2246 	exit_handler_fn[exit_handler_count] = fn;
2247 	exit_handler_count++;
2248 
2249 	if (exit_handler_count > 1)
2250 		return;
2251 
2252 	for (i = 0; i < ARRAY_SIZE(handled_signals); i++) {
2253 		if (install_sig_handler(handled_signals[i].number,
2254 					fatal_sig_handler))
2255 			goto err;
2256 	}
2257 
2258 	if (atexit(igt_atexit_handler))
2259 		goto err;
2260 
2261 	return;
2262 err:
2263 	restore_all_sig_handler();
2264 	exit_handler_count--;
2265 
2266 	igt_assert_f(0, "failed to install the signal handler\n");
2267 }
2268 
2269 /* simulation enviroment support */
2270 
2271 /**
2272  * igt_run_in_simulation:
2273  *
2274  * This function can be used to select a reduced test set when running in
2275  * simulation environments. This i-g-t mode is selected by setting the
2276  * INTEL_SIMULATION environment variable to 1.
2277  *
2278  * Returns: True when run in simulation mode, false otherwise.
2279  */
igt_run_in_simulation(void)2280 bool igt_run_in_simulation(void)
2281 {
2282 	static int simulation = -1;
2283 
2284 	if (simulation == -1)
2285 		simulation = igt_check_boolean_env_var("INTEL_SIMULATION", false);
2286 
2287 	return simulation;
2288 }
2289 
2290 /**
2291  * igt_skip_on_simulation:
2292  *
2293  * Skip tests when INTEL_SIMULATION environment variable is set. It uses
2294  * igt_skip() internally and hence is fully subtest aware.
2295  *
2296  * Note that in contrast to all other functions which use igt_skip() internally
2297  * it is allowed to use this outside of an #igt_fixture block in a test with
2298  * subtests. This is because in contrast to most other test requirements,
2299  * checking for simulation mode doesn't depend upon the present hardware and it
2300  * so makes a lot of sense to have this check in the outermost #igt_main block.
2301  */
igt_skip_on_simulation(void)2302 void igt_skip_on_simulation(void)
2303 {
2304 	if (igt_only_list_subtests())
2305 		return;
2306 
2307 	if (!igt_can_fail()) {
2308 		igt_fixture
2309 			igt_require(!igt_run_in_simulation());
2310 	} else
2311 		igt_require(!igt_run_in_simulation());
2312 }
2313 
2314 /* structured logging */
2315 
2316 /**
2317  * igt_log:
2318  * @domain: the log domain, or NULL for no domain
2319  * @level: #igt_log_level
2320  * @format: format string
2321  * @...: optional arguments used in the format string
2322  *
2323  * This is the generic structured logging helper function. i-g-t testcase should
2324  * output all normal message to stdout. Warning level message should be printed
2325  * to stderr and the test runner should treat this as an intermediate result
2326  * between SUCCESS and FAILURE.
2327  *
2328  * The log level can be set through the IGT_LOG_LEVEL environment variable with
2329  * values "debug", "info", "warn", "critical" and "none". By default verbose
2330  * debug message are disabled. "none" completely disables all output and is not
2331  * recommended since crucial issues only reported at the IGT_LOG_WARN level are
2332  * ignored.
2333  */
igt_log(const char * domain,enum igt_log_level level,const char * format,...)2334 void igt_log(const char *domain, enum igt_log_level level, const char *format, ...)
2335 {
2336 	va_list args;
2337 
2338 	va_start(args, format);
2339 	igt_vlog(domain, level, format, args);
2340 	va_end(args);
2341 }
2342 
2343 /**
2344  * igt_vlog:
2345  * @domain: the log domain, or NULL for no domain
2346  * @level: #igt_log_level
2347  * @format: format string
2348  * @args: variable arguments lists
2349  *
2350  * This is the generic logging helper function using an explicit varargs
2351  * structure and hence useful to implement domain-specific logging
2352  * functions.
2353  *
2354  * If there is no need to wrap up a vararg list in the caller it is simpler to
2355  * just use igt_log().
2356  */
igt_vlog(const char * domain,enum igt_log_level level,const char * format,va_list args)2357 void igt_vlog(const char *domain, enum igt_log_level level, const char *format, va_list args)
2358 {
2359 	FILE *file;
2360 	char *line, *formatted_line;
2361 	const char *program_name;
2362 	const char *igt_log_level_str[] = {
2363 		"DEBUG",
2364 		"INFO",
2365 		"WARNING",
2366 		"CRITICAL",
2367 		"NONE"
2368 	};
2369 	static bool line_continuation = false;
2370 
2371 	assert(format);
2372 
2373 #ifdef __GLIBC__
2374 	program_name = program_invocation_short_name;
2375 #else
2376 	program_name = command_str;
2377 #endif
2378 
2379 	if (list_subtests && level <= IGT_LOG_WARN)
2380 		return;
2381 
2382 	if (vasprintf(&line, format, args) == -1)
2383 		return;
2384 
2385 	if (line_continuation) {
2386 		formatted_line = strdup(line);
2387 		if (!formatted_line)
2388 			goto out;
2389 	} else if (asprintf(&formatted_line, "(%s:%d) %s%s%s: %s", program_name,
2390 		     getpid(), (domain) ? domain : "", (domain) ? "-" : "",
2391 		     igt_log_level_str[level], line) == -1) {
2392 		goto out;
2393 	}
2394 
2395 	line_continuation = line[strlen(line) - 1] != '\n';
2396 
2397 	/* append log buffer */
2398 	_igt_log_buffer_append(formatted_line);
2399 
2400 	/* check print log level */
2401 	if (igt_log_level > level)
2402 		goto out;
2403 
2404 	/* check domain filter */
2405 	if (igt_log_domain_filter) {
2406 		/* if null domain and filter is not "application", return */
2407 		if (!domain && strcmp(igt_log_domain_filter, "application"))
2408 			goto out;
2409 		/* else if domain and filter do not match, return */
2410 		else if (domain && strcmp(igt_log_domain_filter, domain))
2411 			goto out;
2412 	}
2413 
2414 	/* use stderr for warning messages and above */
2415 	if (level >= IGT_LOG_WARN) {
2416 		file = stderr;
2417 		fflush(stdout);
2418 	}
2419 	else
2420 		file = stdout;
2421 
2422 	/* prepend all except information messages with process, domain and log
2423 	 * level information */
2424 	if (level != IGT_LOG_INFO)
2425 		fwrite(formatted_line, sizeof(char), strlen(formatted_line),
2426 		       file);
2427 	else
2428 		fwrite(line, sizeof(char), strlen(line), file);
2429 
2430 out:
2431 	free(line);
2432 }
2433 
2434 static const char *timeout_op;
igt_alarm_handler(int signal)2435 static void __attribute__((noreturn)) igt_alarm_handler(int signal)
2436 {
2437 	if (timeout_op)
2438 		igt_info("Timed out: %s\n", timeout_op);
2439 	else
2440 		igt_info("Timed out\n");
2441 
2442 	/* exit with failure status */
2443 	igt_fail(IGT_EXIT_FAILURE);
2444 }
2445 
2446 /**
2447  * igt_set_timeout:
2448  * @seconds: number of seconds before timeout
2449  * @op: Optional string to explain what operation has timed out in the debug log
2450  *
2451  * Fail a test and exit with #IGT_EXIT_FAILURE status after the specified
2452  * number of seconds have elapsed. If the current test has subtests and the
2453  * timeout occurs outside a subtest, subsequent subtests will be skipped and
2454  * marked as failed.
2455  *
2456  * Any previous timer is cancelled and no timeout is scheduled if @seconds is
2457  * zero. But for clarity the timeout set with this function should be cleared
2458  * with igt_reset_timeout().
2459  */
igt_set_timeout(unsigned int seconds,const char * op)2460 void igt_set_timeout(unsigned int seconds,
2461 		     const char *op)
2462 {
2463 	struct sigaction sa;
2464 
2465 	sa.sa_handler = igt_alarm_handler;
2466 	sigemptyset(&sa.sa_mask);
2467 	sa.sa_flags = 0;
2468 
2469 	timeout_op = op;
2470 
2471 	if (seconds == 0)
2472 		sigaction(SIGALRM, NULL, NULL);
2473 	else
2474 		sigaction(SIGALRM, &sa, NULL);
2475 
2476 	alarm(seconds);
2477 }
2478 
2479 /**
2480  * igt_reset_timeout:
2481  *
2482  * This function resets a timeout set by igt_set_timeout() and disables any
2483  * timer set up by the former function.
2484  */
igt_reset_timeout(void)2485 void igt_reset_timeout(void)
2486 {
2487 	igt_set_timeout(0, NULL);
2488 }
2489 
__igt_fopen_data(const char * igt_srcdir,const char * igt_datadir,const char * filename)2490 FILE *__igt_fopen_data(const char* igt_srcdir, const char* igt_datadir,
2491 		       const char* filename)
2492 {
2493 	char path[PATH_MAX];
2494 	FILE *fp;
2495 
2496 	snprintf(path, sizeof(path), "%s/%s", igt_datadir, filename);
2497 	fp = fopen(path, "r");
2498 	if (!fp) {
2499 		snprintf(path, sizeof(path), "%s/%s", igt_srcdir, filename);
2500 		fp = fopen(path, "r");
2501 	}
2502 	if (!fp) {
2503 		snprintf(path, sizeof(path), "./%s", filename);
2504 		fp = fopen(path, "r");
2505 	}
2506 
2507 	if (!fp)
2508 		igt_critical("Could not open data file \"%s\": %s", filename,
2509 			     strerror(errno));
2510 
2511 	return fp;
2512 }
2513 
log_output(int * fd,enum igt_log_level level)2514 static void log_output(int *fd, enum igt_log_level level)
2515 {
2516 	ssize_t len;
2517 	char buf[PIPE_BUF];
2518 
2519 	if (*fd < 0)
2520 		return;
2521 
2522 	memset(buf, 0, sizeof(buf));
2523 	len = read(*fd, buf, sizeof(buf));
2524 	if (len <= 0) {
2525 		close(*fd);
2526 		*fd = -1;
2527 		return;
2528 	}
2529 
2530 	igt_log(IGT_LOG_DOMAIN, level, "[cmd] %s", buf);
2531 }
2532 
2533 /**
2534  * igt_system:
2535  *
2536  * An improved replacement of the system() call.
2537  *
2538  * Executes the shell command specified in @command with the added feature of
2539  * concurrently capturing its stdout and stderr to igt_log and igt_warn
2540  * respectively.
2541  *
2542  * Returns: The exit status of the executed process. -1 for failure.
2543  */
igt_system(const char * command)2544 int igt_system(const char *command)
2545 {
2546 	int outpipe[2] = { -1, -1 };
2547 	int errpipe[2] = { -1, -1 };
2548 	int status;
2549 	struct igt_helper_process process = {};
2550 
2551 	if (pipe(outpipe) < 0)
2552 		goto err;
2553 	if (pipe(errpipe) < 0)
2554 		goto err;
2555 
2556 	/*
2557 	 * The clone() system call called from a largish executable has
2558 	 * difficulty to make progress if interrupted too frequently, so
2559 	 * suspend the signal helper for the time of the syscall.
2560 	 */
2561 	igt_suspend_signal_helper();
2562 
2563 	igt_fork_helper(&process) {
2564 		close(outpipe[0]);
2565 		close(errpipe[0]);
2566 
2567 		if (dup2(outpipe[1], STDOUT_FILENO) < 0)
2568 			goto child_err;
2569 		if (dup2(errpipe[1], STDERR_FILENO) < 0)
2570 			goto child_err;
2571 
2572 		execl("/bin/sh", "sh", "-c", command,
2573 		      (char *) NULL);
2574 
2575 	child_err:
2576 		exit(EXIT_FAILURE);
2577 	}
2578 
2579 	igt_resume_signal_helper();
2580 
2581 	close(outpipe[1]);
2582 	close(errpipe[1]);
2583 
2584 	while (outpipe[0] >= 0 || errpipe[0] >= 0) {
2585 		log_output(&outpipe[0], IGT_LOG_INFO);
2586 		log_output(&errpipe[0], IGT_LOG_WARN);
2587 	}
2588 
2589 	status = igt_wait_helper(&process);
2590 
2591 	return WEXITSTATUS(status);
2592 err:
2593 	close(outpipe[0]);
2594 	close(outpipe[1]);
2595 	close(errpipe[0]);
2596 	close(errpipe[1]);
2597 	return -1;
2598 }
2599 
2600 /**
2601  * igt_system_quiet:
2602  * Similar to igt_system(), except redirect output to /dev/null
2603  *
2604  * Returns: The exit status of the executed process. -1 for failure.
2605  */
igt_system_quiet(const char * command)2606 int igt_system_quiet(const char *command)
2607 {
2608 	int stderr_fd_copy = -1, stdout_fd_copy = -1, status, nullfd = -1;
2609 
2610 	/* redirect */
2611 	if ((nullfd = open("/dev/null", O_WRONLY)) == -1)
2612 		goto err;
2613 	if ((stdout_fd_copy = dup(STDOUT_FILENO)) == -1)
2614 		goto err;
2615 	if ((stderr_fd_copy = dup(STDERR_FILENO)) == -1)
2616 		goto err;
2617 
2618 	if (dup2(nullfd, STDOUT_FILENO) == -1)
2619 		goto err;
2620 	if (dup2(nullfd, STDERR_FILENO) == -1)
2621 		goto err;
2622 
2623 	/* See igt_system() for the reason for suspending the signal helper. */
2624 	igt_suspend_signal_helper();
2625 
2626 	if ((status = system(command)) == -1)
2627 		goto err;
2628 
2629 	igt_resume_signal_helper();
2630 
2631 	/* restore */
2632 	if (dup2(stdout_fd_copy, STDOUT_FILENO) == -1)
2633 		goto err;
2634 	if (dup2(stderr_fd_copy, STDERR_FILENO) == -1)
2635 		goto err;
2636 
2637 	close(stdout_fd_copy);
2638 	close(stderr_fd_copy);
2639 	close(nullfd);
2640 
2641 	return WEXITSTATUS(status);
2642 err:
2643 	igt_resume_signal_helper();
2644 
2645 	close(stderr_fd_copy);
2646 	close(stdout_fd_copy);
2647 	close(nullfd);
2648 
2649 	return -1;
2650 }
2651