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