litest.c 90.4 KB
Newer Older
Peter Hutterer's avatar
Peter Hutterer committed
1 2
/*
 * Copyright © 2013 Red Hat, Inc.
3
 * Copyright © 2013 Marcin Slusarz <marcin.slusarz@gmail.com>
Peter Hutterer's avatar
Peter Hutterer committed
4
 *
5 6 7 8 9 10
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
Peter Hutterer's avatar
Peter Hutterer committed
11
 *
12 13 14 15 16 17 18 19 20 21 22
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
Peter Hutterer's avatar
Peter Hutterer committed
23 24 25 26 27
 */

#include "config.h"

#include <check.h>
28
#include <dirent.h>
Peter Hutterer's avatar
Peter Hutterer committed
29
#include <errno.h>
30
#include <libgen.h>
Peter Hutterer's avatar
Peter Hutterer committed
31
#include <fcntl.h>
32
#include <fnmatch.h>
Peter Hutterer's avatar
Peter Hutterer committed
33 34
#include <getopt.h>
#include <poll.h>
35
#include <signal.h>
Peter Hutterer's avatar
Peter Hutterer committed
36 37 38
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
39
#include <stdarg.h>
Peter Hutterer's avatar
Peter Hutterer committed
40 41
#include <time.h>
#include <unistd.h>
42
#include "linux/input.h"
Peter Hutterer's avatar
Peter Hutterer committed
43
#include <sys/ptrace.h>
44
#include <sys/resource.h>
Peter Hutterer's avatar
Peter Hutterer committed
45 46
#include <sys/timerfd.h>
#include <sys/wait.h>
47 48
#include <sys/stat.h>
#include <sys/types.h>
49
#include <libudev.h>
50 51 52
#if HAVE_LIBSYSTEMD
#include <systemd/sd-bus.h>
#endif
53 54 55
#ifdef __FreeBSD__
#include <termios.h>
#endif
Peter Hutterer's avatar
Peter Hutterer committed
56 57 58 59

#include "litest.h"
#include "litest-int.h"
#include "libinput-util.h"
60
#include "quirks.h"
Peter Hutterer's avatar
Peter Hutterer committed
61

62 63
#include <linux/kd.h>

64 65
#define UDEV_RULES_D "/run/udev/rules.d"
#define UDEV_RULE_PREFIX "99-litest-"
66
#define UDEV_HWDB_D "/etc/udev/hwdb.d"
67
#define UDEV_MODEL_QUIRKS_RULE_FILE UDEV_RULES_D \
68
	"/91-litest-model-quirks-REMOVEME-XXXXXX.rules"
69
#define UDEV_MODEL_QUIRKS_HWDB_FILE UDEV_HWDB_D \
70
	"/91-litest-model-quirks-REMOVEME-XXXXXX.hwdb"
71
#define UDEV_TEST_DEVICE_RULE_FILE UDEV_RULES_D \
72
	"/91-litest-test-device-REMOVEME-XXXXXXX.rules"
73
#define UDEV_DEVICE_GROUPS_FILE UDEV_RULES_D \
74
	"/80-libinput-device-groups-litest-XXXXXX.rules"
75

76
static int jobs = 8;
77 78
static bool in_debugger = false;
static bool verbose = false;
79
static bool run_deviceless = false;
80
const char *filter_test = NULL;
81
const char *filter_device = NULL;
82
const char *filter_group = NULL;
83
static struct quirks_context *quirks_context;
Peter Hutterer's avatar
Peter Hutterer committed
84

85 86 87 88 89
struct created_file {
	struct list link;
	char *path;
};

90 91 92
struct list created_files_list; /* list of all files to remove at the end of
				   the test run */

93 94
static void litest_init_udev_rules(struct list *created_files_list);
static void litest_remove_udev_rules(struct list *created_files_list);
95
static inline char *litest_install_quirks(struct list *created_files_list);
96

97 98 99 100 101
/* defined for the litest selftest */
#ifndef LITEST_DISABLE_BACKTRACE_LOGGING
#define litest_log(...) fprintf(stderr, __VA_ARGS__)
#define litest_vlog(format_, args_) vfprintf(stderr, format_, args_)
#else
102 103
#define litest_log(...) { /* __VA_ARGS__ */ }
#define litest_vlog(...) { /* __VA_ARGS__ */ }
104 105 106 107 108
#endif

static void
litest_backtrace(void)
{
109 110 111
#if HAVE_GSTACK
	pid_t parent, child;
	int pipefd[2];
112

113
	if (pipe(pipefd) == -1)
114 115
		return;

116 117
	parent = getpid();
	child = fork();
118

119 120
	if (child == 0) {
		char pid[8];
121

122 123
		close(pipefd[0]);
		dup2(pipefd[1], STDOUT_FILENO);
124

125
		sprintf(pid, "%d", parent);
126

127 128 129
		execlp("gstack", "gstack", pid, NULL);
		exit(errno);
	}
130

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
	/* parent */
	char buf[1024];
	int status, nread;

	close(pipefd[1]);
	waitpid(child, &status, 0);

	status = WEXITSTATUS(status);
	if (status != 0) {
		litest_log("ERROR: gstack failed, no backtrace available: %s\n",
			   strerror(status));
	} else {
		litest_log("\nBacktrace:\n");
		while ((nread = read(pipefd[0], buf, sizeof(buf) - 1)) > 0) {
			buf[nread] = '\0';
			litest_log("%s", buf);
147
		}
148
		litest_log("\n");
149
	}
150
	close(pipefd[0]);
151
#endif
152
}
153

154
LIBINPUT_ATTRIBUTE_PRINTF(5, 6)
155
__attribute__((noreturn))
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
void
litest_fail_condition(const char *file,
		      int line,
		      const char *func,
		      const char *condition,
		      const char *message,
		      ...)
{
	litest_log("FAILED: %s\n", condition);

	if (message) {
		va_list args;
		va_start(args, message);
		litest_vlog(message, args);
		va_end(args);
	}

	litest_log("in %s() (%s:%d)\n", func, file, line);
	litest_backtrace();
	abort();
}

178
__attribute__((noreturn))
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
void
litest_fail_comparison_int(const char *file,
			   int line,
			   const char *func,
			   const char *operator,
			   int a,
			   int b,
			   const char *astr,
			   const char *bstr)
{
	litest_log("FAILED COMPARISON: %s %s %s\n", astr, operator, bstr);
	litest_log("Resolved to: %d %s %d\n", a, operator, b);
	litest_log("in %s() (%s:%d)\n", func, file, line);
	litest_backtrace();
	abort();
}

196
__attribute__((noreturn))
197 198 199 200 201 202 203 204 205 206 207
void
litest_fail_comparison_ptr(const char *file,
			   int line,
			   const char *func,
			   const char *comparison)
{
	litest_log("FAILED COMPARISON: %s\n", comparison);
	litest_log("in %s() (%s:%d)\n", func, file, line);
	litest_backtrace();
	abort();
}
Peter Hutterer's avatar
Peter Hutterer committed
208 209 210 211

struct test {
	struct list node;
	char *name;
212 213 214 215 216 217
	char *devname;
	void *func;
	void *setup;
	void *teardown;

	struct range range;
218
	bool deviceless;
Peter Hutterer's avatar
Peter Hutterer committed
219 220 221 222 223 224 225 226 227 228
};

struct suite {
	struct list node;
	struct list tests;
	char *name;
};

static struct litest_device *current_device;

229 230
struct litest_device *litest_current_device(void)
{
Peter Hutterer's avatar
Peter Hutterer committed
231 232 233
	return current_device;
}

234 235
void litest_set_current_device(struct litest_device *device)
{
Peter Hutterer's avatar
Peter Hutterer committed
236 237 238 239 240 241 242 243 244
	current_device = device;
}

void litest_generic_device_teardown(void)
{
	litest_delete_device(current_device);
	current_device = NULL;
}

245
struct list devices;
Peter Hutterer's avatar
Peter Hutterer committed
246 247 248

static struct list all_tests;

249 250
static inline void
litest_system(const char *command)
251
{
252 253 254 255
	int ret;

	ret = system(command);

256
	if (ret == -1) {
257
		litest_abort_msg("Failed to execute: %s", command);
258 259
	} else if (WIFEXITED(ret)) {
		if (WEXITSTATUS(ret))
260 261
			litest_abort_msg("'%s' failed with %d",
					 command,
262 263
					 WEXITSTATUS(ret));
	} else if (WIFSIGNALED(ret)) {
264 265
		litest_abort_msg("'%s' terminated with signal %d",
				 command,
266 267
				 WTERMSIG(ret));
	}
268 269
}

270 271 272 273 274 275 276
static void
litest_reload_udev_rules(void)
{
	litest_system("udevadm control --reload-rules");
	litest_system("udevadm hwdb --update");
}

Peter Hutterer's avatar
Peter Hutterer committed
277 278
static void
litest_add_tcase_for_device(struct suite *suite,
279
			    const char *funcname,
Peter Hutterer's avatar
Peter Hutterer committed
280
			    void *func,
281 282
			    const struct litest_test_device *dev,
			    const struct range *range)
Peter Hutterer's avatar
Peter Hutterer committed
283 284 285 286
{
	struct test *t;

	t = zalloc(sizeof(*t));
Peter Hutterer's avatar
Peter Hutterer committed
287 288
	t->name = safe_strdup(funcname);
	t->devname = safe_strdup(dev->shortname);
289 290 291 292
	t->func = func;
	t->setup = dev->setup;
	t->teardown = dev->teardown ?
			dev->teardown : litest_generic_device_teardown;
293
	if (range)
294 295 296
		t->range = *range;

	list_insert(&suite->tests, &t->node);
Peter Hutterer's avatar
Peter Hutterer committed
297 298 299
}

static void
300 301
litest_add_tcase_no_device(struct suite *suite,
			   void *func,
302
			   const char *funcname,
303
			   const struct range *range)
Peter Hutterer's avatar
Peter Hutterer committed
304 305
{
	struct test *t;
306
	const char *test_name = funcname;
Peter Hutterer's avatar
Peter Hutterer committed
307

308 309 310 311
	if (filter_device &&
	    fnmatch(filter_device, test_name, 0) != 0)
		return;

Peter Hutterer's avatar
Peter Hutterer committed
312
	t = zalloc(sizeof(*t));
Peter Hutterer's avatar
Peter Hutterer committed
313 314
	t->name = safe_strdup(test_name);
	t->devname = safe_strdup("no device");
315
	t->func = func;
316
	if (range)
317 318 319 320 321
		t->range = *range;
	t->setup = NULL;
	t->teardown = NULL;

	list_insert(&suite->tests, &t->node);
Peter Hutterer's avatar
Peter Hutterer committed
322 323
}

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
static void
litest_add_tcase_deviceless(struct suite *suite,
			    void *func,
			    const char *funcname,
			    const struct range *range)
{
	struct test *t;
	const char *test_name = funcname;

	if (filter_device &&
	    fnmatch(filter_device, test_name, 0) != 0)
		return;

	t = zalloc(sizeof(*t));
	t->deviceless = true;
	t->name = safe_strdup(test_name);
	t->devname = safe_strdup("deviceless");
	t->func = func;
	if (range)
		t->range = *range;
	t->setup = NULL;
	t->teardown = NULL;

	list_insert(&suite->tests, &t->node);
}

350 351 352 353 354 355
static struct suite *
get_suite(const char *name)
{
	struct suite *s;

	list_for_each(s, &all_tests, node) {
356
		if (streq(s->name, name))
357 358 359 360
			return s;
	}

	s = zalloc(sizeof(*s));
Peter Hutterer's avatar
Peter Hutterer committed
361
	s->name = safe_strdup(name);
362 363 364 365 366 367 368

	list_init(&s->tests);
	list_insert(&all_tests, &s->node);

	return s;
}

Peter Hutterer's avatar
Peter Hutterer committed
369
static void
370 371 372
litest_add_tcase(const char *suite_name,
		 const char *funcname,
		 void *func,
Peter Hutterer's avatar
Peter Hutterer committed
373
		 enum litest_device_feature required,
374 375
		 enum litest_device_feature excluded,
		 const struct range *range)
Peter Hutterer's avatar
Peter Hutterer committed
376
{
377
	struct suite *suite;
378
	bool added = false;
Peter Hutterer's avatar
Peter Hutterer committed
379

380 381
	litest_assert(required >= LITEST_DEVICELESS);
	litest_assert(excluded >= LITEST_DEVICELESS);
382

383 384 385 386
	if (filter_test &&
	    fnmatch(filter_test, funcname, 0) != 0)
		return;

387 388 389 390
	if (filter_group &&
	    fnmatch(filter_group, suite_name, 0) != 0)
		return;

391 392
	suite = get_suite(suite_name);

393 394 395 396 397
	if (required == LITEST_DEVICELESS &&
	    excluded == LITEST_DEVICELESS) {
		litest_add_tcase_deviceless(suite, func, funcname, range);
		added = true;
	} else if (required == LITEST_DISABLE_DEVICE &&
Peter Hutterer's avatar
Peter Hutterer committed
398
	    excluded == LITEST_DISABLE_DEVICE) {
399
		litest_add_tcase_no_device(suite, func, funcname, range);
400
		added = true;
Peter Hutterer's avatar
Peter Hutterer committed
401
	} else if (required != LITEST_ANY || excluded != LITEST_ANY) {
402 403 404 405
		struct litest_test_device *dev;

		list_for_each(dev, &devices, node) {
			if (dev->features & LITEST_IGNORED)
406 407
				continue;

408
			if (filter_device &&
409
			    fnmatch(filter_device, dev->shortname, 0) != 0)
410
				continue;
411 412
			if ((dev->features & required) != required ||
			    (dev->features & excluded) != 0)
413 414 415 416 417
				continue;

			litest_add_tcase_for_device(suite,
						    funcname,
						    func,
418
						    dev,
419
						    range);
420
			added = true;
Peter Hutterer's avatar
Peter Hutterer committed
421 422
		}
	} else {
423 424 425 426
		struct litest_test_device *dev;

		list_for_each(dev, &devices, node) {
			if (dev->features & LITEST_IGNORED)
427 428
				continue;

429
			if (filter_device &&
430
			    fnmatch(filter_device, dev->shortname, 0) != 0)
431 432
				continue;

433 434 435
			litest_add_tcase_for_device(suite,
						    funcname,
						    func,
436
						    dev,
437
						    range);
438
			added = true;
Peter Hutterer's avatar
Peter Hutterer committed
439 440
		}
	}
441

442 443 444 445
	if (!added &&
	    filter_test == NULL &&
	    filter_device == NULL &&
	    filter_group == NULL) {
446 447 448
		fprintf(stderr, "Test '%s' does not match any devices. Aborting.\n", funcname);
		abort();
	}
Peter Hutterer's avatar
Peter Hutterer committed
449 450 451
}

void
452
_litest_add_no_device(const char *name, const char *funcname, void *func)
Peter Hutterer's avatar
Peter Hutterer committed
453
{
454
	_litest_add(name, funcname, func, LITEST_DISABLE_DEVICE, LITEST_DISABLE_DEVICE);
Peter Hutterer's avatar
Peter Hutterer committed
455 456
}

457
void
458 459 460 461
_litest_add_ranged_no_device(const char *name,
			     const char *funcname,
			     void *func,
			     const struct range *range)
Peter Hutterer's avatar
Peter Hutterer committed
462
{
463 464 465 466 467 468
	_litest_add_ranged(name,
			   funcname,
			   func,
			   LITEST_DISABLE_DEVICE,
			   LITEST_DISABLE_DEVICE,
			   range);
469
}
Peter Hutterer's avatar
Peter Hutterer committed
470

471 472 473 474 475 476 477 478 479 480 481 482 483
void
_litest_add_deviceless(const char *name,
		       const char *funcname,
		       void *func)
{
	_litest_add_ranged(name,
			   funcname,
			   func,
			   LITEST_DEVICELESS,
			   LITEST_DEVICELESS,
			   NULL);
}

484
void
485 486 487 488 489
_litest_add(const char *name,
	    const char *funcname,
	    void *func,
	    enum litest_device_feature required,
	    enum litest_device_feature excluded)
490
{
491 492 493 494 495 496
	_litest_add_ranged(name,
			   funcname,
			   func,
			   required,
			   excluded,
			   NULL);
497
}
498

499
void
500 501 502 503 504 505
_litest_add_ranged(const char *name,
		   const char *funcname,
		   void *func,
		   enum litest_device_feature required,
		   enum litest_device_feature excluded,
		   const struct range *range)
506
{
507
	litest_add_tcase(name, funcname, func, required, excluded, range);
508 509 510
}

void
511 512 513 514
_litest_add_for_device(const char *name,
		       const char *funcname,
		       void *func,
		       enum litest_device_type type)
515
{
516
	_litest_add_ranged_for_device(name, funcname, func, type, NULL);
517 518 519
}

void
520 521 522 523 524
_litest_add_ranged_for_device(const char *name,
			      const char *funcname,
			      void *func,
			      enum litest_device_type type,
			      const struct range *range)
525 526
{
	struct suite *s;
527
	struct litest_test_device *dev;
528
	bool device_filtered = false;
529

530
	litest_assert(type < LITEST_NO_DEVICE);
531

532 533 534 535
	if (filter_test &&
	    fnmatch(filter_test, funcname, 0) != 0)
		return;

536 537 538 539
	if (filter_group &&
	    fnmatch(filter_group, name, 0) != 0)
		return;

540
	s = get_suite(name);
541
	list_for_each(dev, &devices, node) {
542
		if (filter_device &&
543
		    fnmatch(filter_device, dev->shortname, 0) != 0) {
544
			device_filtered = true;
545
			continue;
546
		}
547

548
		if (dev->type == type) {
549 550 551
			litest_add_tcase_for_device(s,
						    funcname,
						    func,
552
						    dev,
553
						    range);
554 555 556 557
			return;
		}
	}

558 559
	/* only abort if no filter was set, that's a bug */
	if (!device_filtered)
560
		litest_abort_msg("Invalid test device type\n");
Peter Hutterer's avatar
Peter Hutterer committed
561 562
}

563
LIBINPUT_ATTRIBUTE_PRINTF(3, 0)
564
static void
565 566
litest_log_handler(struct libinput *libinput,
		   enum libinput_log_priority pri,
567 568 569
		   const char *format,
		   va_list args)
{
570
	static int is_tty = -1;
571
	const char *priority = NULL;
572 573 574 575
	const char *color;

	if (is_tty == -1)
		is_tty = isatty(STDERR_FILENO);
576 577

	switch(pri) {
578 579 580 581 582 583
	case LIBINPUT_LOG_PRIORITY_INFO:
		priority =  "info ";
		color = ANSI_HIGHLIGHT;
		break;
	case LIBINPUT_LOG_PRIORITY_ERROR:
		priority = "error";
584
		color = ANSI_BRIGHT_RED;
585 586 587 588 589
		break;
	case LIBINPUT_LOG_PRIORITY_DEBUG:
		priority = "debug";
		color = ANSI_NORMAL;
		break;
590 591
	default:
		  abort();
592 593
	}

594 595
	if (!is_tty)
		color = "";
596
	else if (strstr(format, "tap:"))
597 598 599 600 601 602 603 604 605 606 607
		color = ANSI_BLUE;
	else if (strstr(format, "thumb state:"))
		color = ANSI_YELLOW;
	else if (strstr(format, "button state:"))
		color = ANSI_MAGENTA;
	else if (strstr(format, "touch-size:") ||
		 strstr(format, "pressure:"))
		color = ANSI_GREEN;
	else if (strstr(format, "palm:") ||
		 strstr(format, "thumb:"))
		color = ANSI_CYAN;
608
	else if (strstr(format, "edge-scroll:"))
609 610
		color = ANSI_BRIGHT_GREEN;

611
	fprintf(stderr, "%slitest %s ", color, priority);
612
	vfprintf(stderr, format, args);
613
	if (is_tty)
614 615
		fprintf(stderr, ANSI_NORMAL);

616
	if (strstr(format, "client bug: ") ||
617 618 619 620 621 622
	    strstr(format, "libinput bug: ")) {
		/* valgrind is too slow and some of our offsets are too
		 * short, don't abort if during a valgrind run we get a
		 * negative offset */
		if (!getenv("USING_VALGRIND") ||
		    !strstr(format, "offset negative"))
623
		litest_abort_msg("libinput bug triggered, aborting.\n");
624
	}
625 626
}

627 628 629 630 631 632
static char *
litest_init_device_udev_rules(struct litest_test_device *dev);

static void
litest_init_all_device_udev_rules(struct list *created_files)
{
633
	struct litest_test_device *dev;
634

635
	list_for_each(dev, &devices, node) {
636 637
		char *udev_file;

638
		udev_file = litest_init_device_udev_rules(dev);
639 640 641 642 643 644 645 646
		if (udev_file) {
			struct created_file *file = zalloc(sizeof(*file));
			file->path = udev_file;
			list_insert(created_files, &file->link);
		}
	}
}

647 648 649
static int
open_restricted(const char *path, int flags, void *userdata)
{
650 651
	int fd = open(path, flags);
	return fd < 0 ? -errno : fd;
652 653 654 655 656 657 658 659 660 661 662 663 664
}

static void
close_restricted(int fd, void *userdata)
{
	close(fd);
}

struct libinput_interface interface = {
	.open_restricted = open_restricted,
	.close_restricted = close_restricted,
};

665 666 667 668 669 670 671 672
static void
litest_signal(int sig)
{
	struct created_file *f, *tmp;

	list_for_each_safe(f, tmp, &created_files_list, link) {
		list_remove(&f->link);
		unlink(f->path);
673
		rmdir(f->path);
674 675 676
		/* in the sighandler, we can't free */
	}

677 678 679 680 681 682
	if (fork() == 0) {
		/* child, we can run system() */
		litest_reload_udev_rules();
		exit(0);
	}

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
	exit(1);
}

static inline void
litest_setup_sighandler(int sig)
{
	struct sigaction act, oact;
	int rc;

	sigemptyset(&act.sa_mask);
	sigaddset(&act.sa_mask, sig);
	act.sa_flags = 0;
	act.sa_handler = litest_signal;
	rc = sigaction(sig, &act, &oact);
	litest_assert_int_ne(rc, -1);
}

700 701
static void
litest_free_test_list(struct list *tests)
702
{
Peter Hutterer's avatar
Peter Hutterer committed
703
	struct suite *s, *snext;
704 705 706 707 708 709

	list_for_each_safe(s, snext, tests, node) {
		struct test *t, *tnext;

		list_for_each_safe(t, tnext, &s->tests, node) {
			free(t->name);
710
			free(t->devname);
711 712 713 714 715 716 717 718 719 720
			list_remove(&t->node);
			free(t);
		}

		list_remove(&s->node);
		free(s->name);
		free(s);
	}
}

721 722 723 724 725 726 727 728 729 730 731 732 733
LIBINPUT_ATTRIBUTE_PRINTF(3, 0)
static inline void
quirk_log_handler(struct libinput *unused,
		  enum libinput_log_priority priority,
		  const char *format,
		  va_list args)
{
	if (priority < LIBINPUT_LOG_PRIORITY_ERROR)
		return;

	vfprintf(stderr, format, args);
}

734
static int
735
litest_run_suite(struct list *tests, int which, int max, int error_fd)
736 737 738 739
{
	int failed = 0;
	SRunner *sr = NULL;
	struct suite *s;
740
	struct test *t;
741
	int count = -1;
742 743 744 745 746 747
	struct name {
		struct list node;
		char *name;
	};
	struct name *n, *tmp;
	struct list testnames;
748

Peter Hutterer's avatar
Peter Hutterer committed
749
	quirks_context = quirks_init_subsystem(getenv("LIBINPUT_QUIRKS_DIR"),
750 751 752 753 754
					       NULL,
					       quirk_log_handler,
					       NULL,
					       QLOG_LIBINPUT_LOGGING);

755 756 757 758
	/* Check just takes the suite/test name pointers but doesn't strdup
	 * them - we have to keep them around */
	list_init(&testnames);

759 760 761 762
	/* For each test, create one test suite with one test case, then
	   add it to the test runner. The only benefit suites give us in
	   check is that we can filter them, but our test runner has a
	   --filter-group anyway. */
763
	list_for_each(s, tests, node) {
764 765 766
		list_for_each(t, &s->tests, node) {
			Suite *suite;
			TCase *tc;
767
			char *sname, *tname;
768

769 770 771 772 773
			/* We run deviceless tests as part of the normal
			 * test suite runner, just in case. Filtering
			 * all the other ones out just for the case where
			 * we can't run the full runner.
			 */
774
			if (run_deviceless && !t->deviceless)
775 776
				continue;

777 778 779
			count = (count + 1) % max;
			if (max != 1 && (count % max) != which)
				continue;
780

781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
			xasprintf(&sname,
				  "%s:%s:%s",
				  s->name,
				  t->name,
				  t->devname);
			litest_assert(sname != NULL);
			n = zalloc(sizeof(*n));
			n->name = sname;
			list_insert(&testnames, &n->node);

			xasprintf(&tname,
				  "%s:%s",
				  t->name,
				  t->devname);
			litest_assert(tname != NULL);
			n = zalloc(sizeof(*n));
			n->name = tname;
			list_insert(&testnames, &n->node);

			tc = tcase_create(tname);
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
			tcase_add_checked_fixture(tc,
						  t->setup,
						  t->teardown);
			if (t->range.upper != t->range.lower)
				tcase_add_loop_test(tc,
						    t->func,
						    t->range.lower,
						    t->range.upper);
			else
				tcase_add_test(tc, t->func);

			suite = suite_create(sname);
			suite_add_tcase(suite, tc);

			if (!sr)
				sr = srunner_create(suite);
			else
				srunner_add_suite(sr, suite);
		}
820 821 822
	}

	if (!sr)
823
		goto out;
824 825 826

	srunner_run_all(sr, CK_ENV);
	failed = srunner_ntests_failed(sr);
827 828 829 830 831 832 833 834 835 836 837 838 839
	if (failed) {
		TestResult **trs;

		trs = srunner_failures(sr);
		for (int i = 0; i < failed; i++) {
			dprintf(error_fd,
				":: Failure: %s:%d:%s\n",
				tr_lfile(trs[i]),
				tr_lno(trs[i]),
				tr_tcname(trs[i]));
		}
		free(trs);
	}
840
	srunner_free(sr);
841 842 843 844 845 846
out:
	list_for_each_safe(n, tmp, &testnames, node) {
		free(n->name);
		free(n);
	}

847 848
	quirks_context_unref(quirks_context);

849 850 851 852
	return failed;
}

static int
853
litest_fork_subtests(struct list *tests, int max_forks)
854 855 856 857 858
{
	int failed = 0;
	int status;
	pid_t pid;
	int f;
859
	int pipes[max_forks];
860 861

	for (f = 0; f < max_forks; f++) {
862 863 864 865 866 867
		int rc;
		int pipefd[2];

		rc = pipe2(pipefd, O_NONBLOCK|O_NONBLOCK);
		assert(rc != -1);

868 869
		pid = fork();
		if (pid == 0) {
870 871 872 873 874 875
			close(pipefd[0]);
			failed = litest_run_suite(tests,
						  f,
						  max_forks,
						  pipefd[1]);

876 877 878
			litest_free_test_list(&all_tests);
			exit(failed);
			/* child always exits here */
879 880 881
		} else {
			pipes[f] = pipefd[0];
			close(pipefd[1]);
882 883 884 885 886 887 888 889 890
		}
	}

	/* parent process only */
	while (wait(&status) != -1 && errno != ECHILD) {
		if (WEXITSTATUS(status) != 0)
			failed = 1;
	}

891 892 893 894 895 896 897 898 899 900 901 902
	for (f = 0; f < max_forks; f++) {
		char buf[1024] = {0};
		int rc;

		while ((rc = read(pipes[f], buf, sizeof(buf) - 1)) > 0) {
			buf[rc] = '\0';
			fprintf(stderr, "%s", buf);
		}

		close(pipes[f]);
	}

903 904 905
	return failed;
}

906 907 908 909 910 911 912 913 914 915
static inline int
inhibit(void)
{
	int lock_fd = -1;
#if HAVE_LIBSYSTEMD
	sd_bus_error error = SD_BUS_ERROR_NULL;
	sd_bus_message *m = NULL;
	sd_bus *bus = NULL;
	int rc;

916 917 918
	if (run_deviceless)
		return -1;

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
	rc = sd_bus_open_system(&bus);
	if (rc != 0) {
		fprintf(stderr, "Warning: inhibit failed: %s\n", strerror(-rc));
		goto out;
	}

	rc = sd_bus_call_method(bus,
				"org.freedesktop.login1",
				"/org/freedesktop/login1",
				"org.freedesktop.login1.Manager",
				"Inhibit",
				&error,
				&m,
				"ssss",
				"handle-lid-switch:handle-power-key:handle-suspend-key:handle-hibernate-key",
				"libinput test-suite runner",
				"testing in progress",
				"block");
	if (rc < 0) {
		fprintf(stderr, "Warning: inhibit failed: %s\n", error.message);
		goto out;
	}

	rc = sd_bus_message_read(m, "h", &lock_fd);
	if (rc < 0) {
		fprintf(stderr, "Warning: inhibit failed: %s\n", strerror(-rc));
		goto out;
	}

	lock_fd = dup(lock_fd);
out:
	sd_bus_error_free(&error);
	sd_bus_message_unref(m);
	sd_bus_close(bus);
	sd_bus_unref(bus);
#endif
	return lock_fd;
}

958 959 960 961
static inline int
litest_run(int argc, char **argv)
{
	int failed = 0;
962
	int inhibit_lock_fd;
963
	char *quirks_dir;
964

965
	list_init(&created_files_list);
Peter Hutterer's avatar
Peter Hutterer committed
966

967 968 969 970 971 972
	if (list_empty(&all_tests)) {
		fprintf(stderr,
			"Error: filters are too strict, no tests to run.\n");
		return 1;
	}

973
	if (getenv("LITEST_VERBOSE"))
974
		verbose = true;
Peter Hutterer's avatar
Peter Hutterer committed
975

976 977 978 979 980 981
	if (run_deviceless) {
		quirks_dir = safe_strdup(LIBINPUT_QUIRKS_SRCDIR);
	} else {
		litest_init_udev_rules(&created_files_list);
		quirks_dir = litest_install_quirks(&created_files_list);
	}
Peter Hutterer's avatar
Peter Hutterer committed
982
	setenv("LIBINPUT_QUIRKS_DIR", quirks_dir, 1);
983
	free(quirks_dir);
984

985 986
	litest_setup_sighandler(SIGINT);

987 988
	inhibit_lock_fd = inhibit();

989
	if (jobs == 1)
990
		failed = litest_run_suite(&all_tests, 1, 1, STDERR_FILENO);
991
	else
992
		failed = litest_fork_subtests(&all_tests, jobs);
Peter Hutterer's avatar
Peter Hutterer committed
993

994 995
	close(inhibit_lock_fd);

996
	litest_free_test_list(&all_tests);
Peter Hutterer's avatar
Peter Hutterer committed
997

998
	litest_remove_udev_rules(&created_files_list);
999

Peter Hutterer's avatar
Peter Hutterer committed
1000 1001 1002
	return failed;
}

1003 1004 1005
static struct input_absinfo *
merge_absinfo(const struct input_absinfo *orig,
	      const struct input_absinfo *override)
Peter Hutterer's avatar
Peter Hutterer committed
1006
{
1007
	struct input_absinfo *abs;
1008
	unsigned int nelem, i;
1009
	size_t sz = ABS_MAX + 1;
Peter Hutterer's avatar
Peter Hutterer committed
1010

1011 1012 1013
	if (!orig)
		return NULL;

1014
	abs = zalloc(sz * sizeof(*abs));
1015
	litest_assert(abs != NULL);
1016 1017 1018 1019 1020

	nelem = 0;
	while (orig[nelem].value != -1) {
		abs[nelem] = orig[nelem];
		nelem++;
1021
		litest_assert_int_lt(nelem, sz);
1022 1023 1024 1025 1026 1027 1028
	}

	/* just append, if the same axis is present twice, libevdev will
	   only use the last value anyway */
	i = 0;
	while (override && override[i].value != -1) {
		abs[nelem++] = override[i++];
1029
		litest_assert_int_lt(nelem, sz);
1030 1031
	}

1032
	litest_assert_int_lt(nelem, sz);
1033 1034 1035 1036 1037 1038 1039 1040 1041
	abs[nelem].value = -1;

	return abs;
}

static int*
merge_events(const int *orig, const int *override)
{
	int *events;
1042
	unsigned int nelem, i;
1043 1044 1045 1046 1047
	size_t sz = KEY_MAX * 3;

	if (!orig)
		return NULL;

1048
	events = zalloc(sz * sizeof(int));
1049
	litest_assert(events != NULL);
1050 1051 1052 1053 1054

	nelem = 0;
	while (orig[nelem] != -1) {
		events[nelem] = orig[nelem];
		nelem++;
1055
		litest_assert_int_lt(nelem, sz);
1056 1057 1058 1059 1060 1061 1062
	}

	/* just append, if the same axis is present twice, libevdev will
	 * ignore the double definition anyway */
	i = 0;
	while (override && override[i] != -1) {
		events[nelem++] = override[i++];
1063
		litest_assert_int_le(nelem, sz);
1064 1065
	}

1066
	litest_assert_int_lt(nelem, sz);
1067 1068 1069 1070 1071
	events[nelem] = -1;

	return events;
}

1072
static inline struct created_file *
1073 1074
litest_copy_file(const char *dest, const char *src, const char *header)
{
1075
	int in, out, length;
1076 1077 1078
	struct created_file *file;

	file = zalloc(sizeof(*file));
Peter Hutterer's avatar
Peter Hutterer committed
1079
	file->path = safe_strdup(dest);
1080

1081 1082 1083 1084 1085 1086 1087 1088
	if (strstr(dest, "XXXXXX")) {
		int suffixlen;

		suffixlen = file->path +
				strlen(file->path) -
				rindex(file->path, '.');
		out = mkstemps(file->path, suffixlen);
	} else {
1089
		out = open(file->path, O_CREAT|O_WRONLY, 0644);
1090
	}
1091 1092
	if (out == -1)
		litest_abort_msg("Failed to write to file %s (%s)\n",
1093
				 file->path,
1094
				 strerror(errno));
1095
	litest_assert_int_ne(chmod(file->path, 0644), -1);
1096

1097 1098 1099 1100
	if (header) {
		length = strlen(header);
		litest_assert_int_eq(write(out, header, length), length);
	}
1101 1102

	in = open(src, O_RDONLY);
1103 1104 1105 1106
	if (in == -1)
		litest_abort_msg("Failed to open file %s (%s)\n",
				 src,
				 strerror(errno));
1107
	/* lazy, just check for error and empty file copy */
1108
	litest_assert_int_gt(litest_send_file(out, in), 0);
1109 1110
	close(out);
	close(in);
1111 1112

	return file;
1113 1114 1115
}

static inline void
1116
litest_install_model_quirks(struct list *created_files_list)
1117
{
1118
	const char *warning =
1119 1120
			 "#################################################################\n"
			 "# WARNING: REMOVE THIS FILE\n"
1121
			 "# This is a run-time file for the libinput test suite and\n"
1122 1123 1124
			 "# should be removed on exit. If the test-suite is not currently \n"
			 "# running, remove this file and update your hwdb: \n"
			 "#       sudo udevadm hwdb --update\n"
1125
			 "#################################################################\n\n";
1126 1127 1128 1129 1130 1131
	struct created_file *file;

	file = litest_copy_file(UDEV_TEST_DEVICE_RULE_FILE,
				LIBINPUT_TEST_DEVICE_RULES_FILE,
				warning);
	list_insert(created_files_list, &file->link);
1132 1133 1134 1135 1136

	file = litest_copy_file(UDEV_DEVICE_GROUPS_FILE,
				LIBINPUT_DEVICE_GROUPS_RULES_FILE,
				warning);
	list_insert(created_files_list, &file->link);
1137 1138
}

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
static char *
litest_init_device_quirk_file(const char *data_dir,
			      struct litest_test_device *dev)
{
	int fd;
	FILE *f;
	char path[PATH_MAX];
	static int count;

	if (!dev->quirk_file)
		return NULL;

	snprintf(path, sizeof(path),
		 "%s/99-%03d-%s.quirks",
		 data_dir,
		 ++count,
		 dev->shortname);
	fd = open(path, O_CREAT|O_WRONLY, 0644);
	litest_assert_int_ne(fd, -1);
	f = fdopen(fd, "w");
	litest_assert_notnull(f);
	litest_assert_int_ge(fputs(dev->quirk_file, f), 0);
	fclose(f);

	return safe_strdup(path);
}


static char *
litest_install_quirks(struct list *created_files_list)
{
1170
	struct litest_test_device *dev;
1171
	struct created_file *file;
1172
	char dirname[] = "/run/litest-XXXXXX";
1173 1174 1175 1176 1177
	char **quirks, **q;

	litest_assert_notnull(mkdtemp(dirname));
	litest_assert_int_ne(chmod(dirname, 0755), -1);

Peter Hutterer's avatar
Peter Hutterer committed
1178
	quirks = strv_from_string(LIBINPUT_QUIRKS_FILES, ":");
1179 1180 1181 1182
	litest_assert(quirks);

	q = quirks;
	while (*q) {
Peter Hutterer's avatar
Peter Hutterer committed
1183
		const char *quirksdir = "quirks/";
1184 1185 1186 1187
		char *filename;
		char dest[PATH_MAX];
		char src[PATH_MAX];

Peter Hutterer's avatar
Peter Hutterer committed
1188 1189
		litest_assert(strneq(*q, quirksdir, strlen(quirksdir)));
		filename = &(*q)[strlen(quirksdir)];
1190

Peter Hutterer's avatar
Peter Hutterer committed
1191 1192
		snprintf(src, sizeof(src), "%s/%s",
			 LIBINPUT_QUIRKS_SRCDIR, filename);
1193 1194 1195 1196 1197 1198 1199 1200 1201
		snprintf(dest, sizeof(dest), "%s/%s", dirname, filename);
		file = litest_copy_file(dest, src, NULL);
		list_append(created_files_list, &file->link);
		q++;
	}
	strv_free(quirks);

	/* Now add the per-device special config files */

1202
	list_for_each(dev, &devices, node) {
1203 1204
		char *path;

1205
		path = litest_init_device_quirk_file(dirname, dev);
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
		if (path) {
			struct created_file *file = zalloc(sizeof(*file));
			file->path = path;
			list_insert(created_files_list, &file->link);
		}
	}

	file = zalloc(sizeof *file);
	file->path = safe_strdup(dirname);
	list_append(created_files_list, &file->link);

	return safe_strdup(dirname);
}

1220 1221
static inline void
mkdir_p(const char *dir)
1222
{
1223
	char *path, *parent;
1224 1225
	int rc;

1226 1227 1228 1229 1230 1231 1232 1233
	if (streq(dir, "/"))
		return;

	path = strdup(dir);
	parent = dirname(path);

	mkdir_p(parent);
	rc = mkdir(dir, 0755);
1234

1235 1236 1237
	if (rc == -1 && errno != EEXIST) {
		litest_abort_msg("Failed to create directory %s (%s)\n",
				 dir,
1238
				 strerror(errno));
1239 1240 1241 1242 1243
	}

	free(path);
}

1244
static inline void
1245 1246 1247 1248
litest_init_udev_rules(struct list *created_files)
{
	mkdir_p(UDEV_RULES_D);
	mkdir_p(UDEV_HWDB_D);
1249

1250
	litest_install_model_quirks(created_files);
1251
	litest_init_all_device_udev_rules(created_files);
1252 1253 1254
	litest_reload_udev_rules();
}

1255
static inline void
1256 1257 1258
litest_remove_udev_rules(struct list *created_files_list)
{
	struct created_file *f, *tmp;
1259 1260 1261
	bool reload_udev;

	reload_udev = !list_empty(created_files_list);
1262 1263 1264 1265

	list_for_each_safe(f, tmp, created_files_list, link) {
		list_remove(&f->link);
		unlink(f->path);
1266
		rmdir(f->path);
1267 1268 1269 1270
		free(f->path);
		free(f);
	}

1271 1272
	if (reload_udev)
		litest_reload_udev_rules();
1273 1274 1275 1276 1277 1278
}

static char *
litest_init_device_udev_rules(struct litest_test_device *dev)
{
	int rc;
1279
	int fd;
1280 1281
	FILE *f;
	char *path = NULL;
1282
	static int count;
1283 1284

	if (!dev->udev_rule)
1285
		return NULL;
1286

1287
	rc = xasprintf(&path,
1288
		      "%s/%s%03d-%s-XXXXXX.rules",
1289 1290
		      UDEV_RULES_D,
		      UDEV_RULE_PREFIX,
1291
		      ++count,
1292
		      dev->shortname);
1293 1294 1295 1296
	litest_assert_int_eq(rc,
			     (int)(
				   strlen(UDEV_RULES_D) +
				   strlen(UDEV_RULE_PREFIX) +
1297
				   strlen(dev->shortname) + 18));
1298 1299 1300 1301

	fd = mkstemps(path, 6);
	litest_assert_int_ne(fd, -1);
	f = fdopen(fd, "w");
1302 1303
	litest_assert_notnull(f);
	litest_assert_int_ge(fputs(dev->udev_rule, f), 0);
1304 1305 1306 1307 1308
	fclose(f);

	return path;
}

1309 1310 1311 1312
/**
 * Creates a uinput device but does not add it to a libinput context
 */
struct litest_device *
1313 1314 1315 1316 1317 1318 1319
litest_create(enum litest_device_type which,
	      const char *name_override,
	      struct input_id *id_override,
	      const struct input_absinfo *abs_override,
	      const int *events_override)
{
	struct litest_device *d = NULL;
1320
	struct litest_test_device *dev;
1321 1322 1323
	const char *name;
	const struct input_id *id;
	struct input_absinfo *abs;
1324
	int *events, *e;
1325 1326
	const char *path;
	int fd, rc;
1327
	bool found = false;
Peter Hutterer's avatar
Peter Hutterer committed
1328

1329 1330 1331
	list_for_each(dev, &devices, node) {
		if (dev->type == which) {
			found = true;
Peter Hutterer's avatar
Peter Hutterer committed
1332
			break;
1333
		}
Peter Hutterer's avatar
Peter Hutterer committed
1334 1335
	}

1336
	if (!found)
Peter Hutterer's avatar
Peter Hutterer committed
1337
		ck_abort_msg("Invalid device type %d\n", which);
1338 1339 1340 1341

	d = zalloc(sizeof(*d));

	/* device has custom create method */
1342 1343
	if (dev->create) {
		dev->create(d);
1344
		if (abs_override || events_override) {
1345
			litest_abort_msg("Custom create cannot be overridden");
1346
		}
1347
	} else {
1348 1349 1350 1351
		abs = merge_absinfo(dev->absinfo, abs_override);
		events = merge_events(dev->events, events_override);
		name = name_override ? name_override : dev->name;
		id = id_override ? id_override : dev->id;
1352 1353 1354 1355 1356

		d->uinput = litest_create_uinput_device_from_description(name,
									 id,
									 abs,
									 events);
1357
		d->interface = dev->interface;
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368

		for (e = events; *e != -1; e += 2) {
			unsigned int type = *e,
				     code = *(e + 1);

			if (type == INPUT_PROP_MAX &&
			    code == INPUT_PROP_SEMI_MT) {
				d->semi_mt.is_semi_mt = true;
				break;
			}
		}
1369

1370 1371
		free(abs);
		free(events);
Peter Hutterer's avatar
Peter Hutterer committed
1372 1373
	}

1374 1375 1376 1377
	path = libevdev_uinput_get_devnode(d->uinput);
	litest_assert(path != NULL);
	fd = open(path, O_RDWR|O_NONBLOCK);
	litest_assert_int_ne(fd, -1);
1378

1379 1380
	rc = libevdev_new_from_fd(fd, &d->evdev);
	litest_assert_int_eq(rc, 0);
1381 1382 1383 1384 1385

	return d;

}

1386 1387 1388 1389 1390
struct libinput *
litest_create_context(void)
{
	struct libinput *libinput =
		libinput_path_create_context(&interface, NULL);
1391
	litest_assert_notnull(libinput);
1392 1393 1394 1395 1396

	libinput_log_set_handler(libinput, litest_log_handler);
	if (verbose)
		libinput_log_set_priority(libinput, LIBINPUT_LOG_PRIORITY_DEBUG);

1397 1398 1399
	return libinput;
}

1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
void
litest_disable_log_handler(struct libinput *libinput)
{
	libinput_log_set_handler(libinput, NULL);
}

void
litest_restore_log_handler(struct libinput *libinput)
{
	libinput_log_set_handler(libinput, litest_log_handler);
1410 1411
	if (verbose)
		libinput_log_set_priority(libinput, LIBINPUT_LOG_PRIORITY_DEBUG);
1412 1413
}

1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
LIBINPUT_ATTRIBUTE_PRINTF(3, 0)
static void
litest_bug_log_handler(struct libinput *libinput,
		       enum libinput_log_priority pri,
		       const char *format,