1 /*
2  * arch/arm/kernel/kprobes-test.c
3  *
4  * Copyright (C) 2011 Jon Medhurst <tixy@yxit.co.uk>.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  */
10 
11 /*
12  * This file contains test code for ARM kprobes.
13  *
14  * The top level function run_all_tests() executes tests for all of the
15  * supported instruction sets: ARM, 16-bit Thumb, and 32-bit Thumb. These tests
16  * fall into two categories; run_api_tests() checks basic functionality of the
17  * kprobes API, and run_test_cases() is a comprehensive test for kprobes
18  * instruction decoding and simulation.
19  *
20  * run_test_cases() first checks the kprobes decoding table for self consistency
21  * (using table_test()) then executes a series of test cases for each of the CPU
22  * instruction forms. coverage_start() and coverage_end() are used to verify
23  * that these test cases cover all of the possible combinations of instructions
24  * described by the kprobes decoding tables.
25  *
26  * The individual test cases are in kprobes-test-arm.c and kprobes-test-thumb.c
27  * which use the macros defined in kprobes-test.h. The rest of this
28  * documentation will describe the operation of the framework used by these
29  * test cases.
30  */
31 
32 /*
33  * TESTING METHODOLOGY
34  * -------------------
35  *
36  * The methodology used to test an ARM instruction 'test_insn' is to use
37  * inline assembler like:
38  *
39  * test_before: nop
40  * test_case:	test_insn
41  * test_after:	nop
42  *
43  * When the test case is run a kprobe is placed of each nop. The
44  * post-handler of the test_before probe is used to modify the saved CPU
45  * register context to that which we require for the test case. The
46  * pre-handler of the of the test_after probe saves a copy of the CPU
47  * register context. In this way we can execute test_insn with a specific
48  * register context and see the results afterwards.
49  *
50  * To actually test the kprobes instruction emulation we perform the above
51  * step a second time but with an additional kprobe on the test_case
52  * instruction itself. If the emulation is accurate then the results seen
53  * by the test_after probe will be identical to the first run which didn't
54  * have a probe on test_case.
55  *
56  * Each test case is run several times with a variety of variations in the
57  * flags value of stored in CPSR, and for Thumb code, different ITState.
58  *
59  * For instructions which can modify PC, a second test_after probe is used
60  * like this:
61  *
62  * test_before: nop
63  * test_case:	test_insn
64  * test_after:	nop
65  *		b test_done
66  * test_after2: nop
67  * test_done:
68  *
69  * The test case is constructed such that test_insn branches to
70  * test_after2, or, if testing a conditional instruction, it may just
71  * continue to test_after. The probes inserted at both locations let us
72  * determine which happened. A similar approach is used for testing
73  * backwards branches...
74  *
75  *		b test_before
76  *		b test_done  @ helps to cope with off by 1 branches
77  * test_after2: nop
78  *		b test_done
79  * test_before: nop
80  * test_case:	test_insn
81  * test_after:	nop
82  * test_done:
83  *
84  * The macros used to generate the assembler instructions describe above
85  * are TEST_INSTRUCTION, TEST_BRANCH_F (branch forwards) and TEST_BRANCH_B
86  * (branch backwards). In these, the local variables numbered 1, 50, 2 and
87  * 99 represent: test_before, test_case, test_after2 and test_done.
88  *
89  * FRAMEWORK
90  * ---------
91  *
92  * Each test case is wrapped between the pair of macros TESTCASE_START and
93  * TESTCASE_END. As well as performing the inline assembler boilerplate,
94  * these call out to the kprobes_test_case_start() and
95  * kprobes_test_case_end() functions which drive the execution of the test
96  * case. The specific arguments to use for each test case are stored as
97  * inline data constructed using the various TEST_ARG_* macros. Putting
98  * this all together, a simple test case may look like:
99  *
100  *	TESTCASE_START("Testing mov r0, r7")
101  *	TEST_ARG_REG(7, 0x12345678) // Set r7=0x12345678
102  *	TEST_ARG_END("")
103  *	TEST_INSTRUCTION("mov r0, r7")
104  *	TESTCASE_END
105  *
106  * Note, in practice the single convenience macro TEST_R would be used for this
107  * instead.
108  *
109  * The above would expand to assembler looking something like:
110  *
111  *	@ TESTCASE_START
112  *	bl	__kprobes_test_case_start
113  *	.pushsection .rodata
114  *	"10:
115  *	.ascii "mov r0, r7"	@ text title for test case
116  *	.byte	0
117  *	.popsection
118  *	@ start of inline data...
119  *	.word	10b		@ pointer to title in .rodata section
120  *
121  *	@ TEST_ARG_REG
122  *	.byte	ARG_TYPE_REG
123  *	.byte	7
124  *	.short	0
125  *	.word	0x1234567
126  *
127  *	@ TEST_ARG_END
128  *	.byte	ARG_TYPE_END
129  *	.byte	TEST_ISA	@ flags, including ISA being tested
130  *	.short	50f-0f		@ offset of 'test_before'
131  *	.short	2f-0f		@ offset of 'test_after2' (if relevent)
132  *	.short	99f-0f		@ offset of 'test_done'
133  *	@ start of test case code...
134  *	0:
135  *	.code	TEST_ISA	@ switch to ISA being tested
136  *
137  *	@ TEST_INSTRUCTION
138  *	50:	nop		@ location for 'test_before' probe
139  *	1:	mov r0, r7	@ the test case instruction 'test_insn'
140  *		nop		@ location for 'test_after' probe
141  *
142  *	// TESTCASE_END
143  *	2:
144  *	99:	bl __kprobes_test_case_end_##TEST_ISA
145  *	.code	NONMAL_ISA
146  *
147  * When the above is execute the following happens...
148  *
149  * __kprobes_test_case_start() is an assembler wrapper which sets up space
150  * for a stack buffer and calls the C function kprobes_test_case_start().
151  * This C function will do some initial processing of the inline data and
152  * setup some global state. It then inserts the test_before and test_after
153  * kprobes and returns a value which causes the assembler wrapper to jump
154  * to the start of the test case code, (local label '0').
155  *
156  * When the test case code executes, the test_before probe will be hit and
157  * test_before_post_handler will call setup_test_context(). This fills the
158  * stack buffer and CPU registers with a test pattern and then processes
159  * the test case arguments. In our example there is one TEST_ARG_REG which
160  * indicates that R7 should be loaded with the value 0x12345678.
161  *
162  * When the test_before probe ends, the test case continues and executes
163  * the "mov r0, r7" instruction. It then hits the test_after probe and the
164  * pre-handler for this (test_after_pre_handler) will save a copy of the
165  * CPU register context. This should now have R0 holding the same value as
166  * R7.
167  *
168  * Finally we get to the call to __kprobes_test_case_end_{32,16}. This is
169  * an assembler wrapper which switches back to the ISA used by the test
170  * code and calls the C function kprobes_test_case_end().
171  *
172  * For each run through the test case, test_case_run_count is incremented
173  * by one. For even runs, kprobes_test_case_end() saves a copy of the
174  * register and stack buffer contents from the test case just run. It then
175  * inserts a kprobe on the test case instruction 'test_insn' and returns a
176  * value to cause the test case code to be re-run.
177  *
178  * For odd numbered runs, kprobes_test_case_end() compares the register and
179  * stack buffer contents to those that were saved on the previous even
180  * numbered run (the one without the kprobe on test_insn). These should be
181  * the same if the kprobe instruction simulation routine is correct.
182  *
183  * The pair of test case runs is repeated with different combinations of
184  * flag values in CPSR and, for Thumb, different ITState. This is
185  * controlled by test_context_cpsr().
186  *
187  * BUILDING TEST CASES
188  * -------------------
189  *
190  *
191  * As an aid to building test cases, the stack buffer is initialised with
192  * some special values:
193  *
194  *   [SP+13*4]	Contains SP+120. This can be used to test instructions
195  *		which load a value into SP.
196  *
197  *   [SP+15*4]	When testing branching instructions using TEST_BRANCH_{F,B},
198  *		this holds the target address of the branch, 'test_after2'.
199  *		This can be used to test instructions which load a PC value
200  *		from memory.
201  */
202 
203 #include <linux/kernel.h>
204 #include <linux/module.h>
205 #include <linux/slab.h>
206 #include <linux/kprobes.h>
207 #include <linux/errno.h>
208 #include <linux/stddef.h>
209 #include <linux/bug.h>
210 #include <asm/opcodes.h>
211 
212 #include "core.h"
213 #include "test-core.h"
214 #include "../decode-arm.h"
215 #include "../decode-thumb.h"
216 
217 
218 #define BENCHMARKING	1
219 
220 
221 /*
222  * Test basic API
223  */
224 
225 static bool test_regs_ok;
226 static int test_func_instance;
227 static int pre_handler_called;
228 static int post_handler_called;
229 static int jprobe_func_called;
230 static int kretprobe_handler_called;
231 static int tests_failed;
232 
233 #define FUNC_ARG1 0x12345678
234 #define FUNC_ARG2 0xabcdef
235 
236 
237 #ifndef CONFIG_THUMB2_KERNEL
238 
239 #define RET(reg)	"mov	pc, "#reg
240 
241 long arm_func(long r0, long r1);
242 
243 static void __used __naked __arm_kprobes_test_func(void)
244 {
245 	__asm__ __volatile__ (
246 		".arm					\n\t"
247 		".type arm_func, %%function		\n\t"
248 		"arm_func:				\n\t"
249 		"adds	r0, r0, r1			\n\t"
250 		"mov	pc, lr				\n\t"
251 		".code "NORMAL_ISA	 /* Back to Thumb if necessary */
252 		: : : "r0", "r1", "cc"
253 	);
254 }
255 
256 #else /* CONFIG_THUMB2_KERNEL */
257 
258 #define RET(reg)	"bx	"#reg
259 
260 long thumb16_func(long r0, long r1);
261 long thumb32even_func(long r0, long r1);
262 long thumb32odd_func(long r0, long r1);
263 
264 static void __used __naked __thumb_kprobes_test_funcs(void)
265 {
266 	__asm__ __volatile__ (
267 		".type thumb16_func, %%function		\n\t"
268 		"thumb16_func:				\n\t"
269 		"adds.n	r0, r0, r1			\n\t"
270 		"bx	lr				\n\t"
271 
272 		".align					\n\t"
273 		".type thumb32even_func, %%function	\n\t"
274 		"thumb32even_func:			\n\t"
275 		"adds.w	r0, r0, r1			\n\t"
276 		"bx	lr				\n\t"
277 
278 		".align					\n\t"
279 		"nop.n					\n\t"
280 		".type thumb32odd_func, %%function	\n\t"
281 		"thumb32odd_func:			\n\t"
282 		"adds.w	r0, r0, r1			\n\t"
283 		"bx	lr				\n\t"
284 
285 		: : : "r0", "r1", "cc"
286 	);
287 }
288 
289 #endif /* CONFIG_THUMB2_KERNEL */
290 
291 
292 static int call_test_func(long (*func)(long, long), bool check_test_regs)
293 {
294 	long ret;
295 
296 	++test_func_instance;
297 	test_regs_ok = false;
298 
299 	ret = (*func)(FUNC_ARG1, FUNC_ARG2);
300 	if (ret != FUNC_ARG1 + FUNC_ARG2) {
301 		pr_err("FAIL: call_test_func: func returned %lx\n", ret);
302 		return false;
303 	}
304 
305 	if (check_test_regs && !test_regs_ok) {
306 		pr_err("FAIL: test regs not OK\n");
307 		return false;
308 	}
309 
310 	return true;
311 }
312 
313 static int __kprobes pre_handler(struct kprobe *p, struct pt_regs *regs)
314 {
315 	pre_handler_called = test_func_instance;
316 	if (regs->ARM_r0 == FUNC_ARG1 && regs->ARM_r1 == FUNC_ARG2)
317 		test_regs_ok = true;
318 	return 0;
319 }
320 
321 static void __kprobes post_handler(struct kprobe *p, struct pt_regs *regs,
322 				unsigned long flags)
323 {
324 	post_handler_called = test_func_instance;
325 	if (regs->ARM_r0 != FUNC_ARG1 + FUNC_ARG2 || regs->ARM_r1 != FUNC_ARG2)
326 		test_regs_ok = false;
327 }
328 
329 static struct kprobe the_kprobe = {
330 	.addr		= 0,
331 	.pre_handler	= pre_handler,
332 	.post_handler	= post_handler
333 };
334 
335 static int test_kprobe(long (*func)(long, long))
336 {
337 	int ret;
338 
339 	the_kprobe.addr = (kprobe_opcode_t *)func;
340 	ret = register_kprobe(&the_kprobe);
341 	if (ret < 0) {
342 		pr_err("FAIL: register_kprobe failed with %d\n", ret);
343 		return ret;
344 	}
345 
346 	ret = call_test_func(func, true);
347 
348 	unregister_kprobe(&the_kprobe);
349 	the_kprobe.flags = 0; /* Clear disable flag to allow reuse */
350 
351 	if (!ret)
352 		return -EINVAL;
353 	if (pre_handler_called != test_func_instance) {
354 		pr_err("FAIL: kprobe pre_handler not called\n");
355 		return -EINVAL;
356 	}
357 	if (post_handler_called != test_func_instance) {
358 		pr_err("FAIL: kprobe post_handler not called\n");
359 		return -EINVAL;
360 	}
361 	if (!call_test_func(func, false))
362 		return -EINVAL;
363 	if (pre_handler_called == test_func_instance ||
364 				post_handler_called == test_func_instance) {
365 		pr_err("FAIL: probe called after unregistering\n");
366 		return -EINVAL;
367 	}
368 
369 	return 0;
370 }
371 
372 static void __kprobes jprobe_func(long r0, long r1)
373 {
374 	jprobe_func_called = test_func_instance;
375 	if (r0 == FUNC_ARG1 && r1 == FUNC_ARG2)
376 		test_regs_ok = true;
377 	jprobe_return();
378 }
379 
380 static struct jprobe the_jprobe = {
381 	.entry		= jprobe_func,
382 };
383 
384 static int test_jprobe(long (*func)(long, long))
385 {
386 	int ret;
387 
388 	the_jprobe.kp.addr = (kprobe_opcode_t *)func;
389 	ret = register_jprobe(&the_jprobe);
390 	if (ret < 0) {
391 		pr_err("FAIL: register_jprobe failed with %d\n", ret);
392 		return ret;
393 	}
394 
395 	ret = call_test_func(func, true);
396 
397 	unregister_jprobe(&the_jprobe);
398 	the_jprobe.kp.flags = 0; /* Clear disable flag to allow reuse */
399 
400 	if (!ret)
401 		return -EINVAL;
402 	if (jprobe_func_called != test_func_instance) {
403 		pr_err("FAIL: jprobe handler function not called\n");
404 		return -EINVAL;
405 	}
406 	if (!call_test_func(func, false))
407 		return -EINVAL;
408 	if (jprobe_func_called == test_func_instance) {
409 		pr_err("FAIL: probe called after unregistering\n");
410 		return -EINVAL;
411 	}
412 
413 	return 0;
414 }
415 
416 static int __kprobes
417 kretprobe_handler(struct kretprobe_instance *ri, struct pt_regs *regs)
418 {
419 	kretprobe_handler_called = test_func_instance;
420 	if (regs_return_value(regs) == FUNC_ARG1 + FUNC_ARG2)
421 		test_regs_ok = true;
422 	return 0;
423 }
424 
425 static struct kretprobe the_kretprobe = {
426 	.handler	= kretprobe_handler,
427 };
428 
429 static int test_kretprobe(long (*func)(long, long))
430 {
431 	int ret;
432 
433 	the_kretprobe.kp.addr = (kprobe_opcode_t *)func;
434 	ret = register_kretprobe(&the_kretprobe);
435 	if (ret < 0) {
436 		pr_err("FAIL: register_kretprobe failed with %d\n", ret);
437 		return ret;
438 	}
439 
440 	ret = call_test_func(func, true);
441 
442 	unregister_kretprobe(&the_kretprobe);
443 	the_kretprobe.kp.flags = 0; /* Clear disable flag to allow reuse */
444 
445 	if (!ret)
446 		return -EINVAL;
447 	if (kretprobe_handler_called != test_func_instance) {
448 		pr_err("FAIL: kretprobe handler not called\n");
449 		return -EINVAL;
450 	}
451 	if (!call_test_func(func, false))
452 		return -EINVAL;
453 	if (jprobe_func_called == test_func_instance) {
454 		pr_err("FAIL: kretprobe called after unregistering\n");
455 		return -EINVAL;
456 	}
457 
458 	return 0;
459 }
460 
461 static int run_api_tests(long (*func)(long, long))
462 {
463 	int ret;
464 
465 	pr_info("    kprobe\n");
466 	ret = test_kprobe(func);
467 	if (ret < 0)
468 		return ret;
469 
470 	pr_info("    jprobe\n");
471 	ret = test_jprobe(func);
472 #if defined(CONFIG_THUMB2_KERNEL) && !defined(MODULE)
473 	if (ret == -EINVAL) {
474 		pr_err("FAIL: Known longtime bug with jprobe on Thumb kernels\n");
475 		tests_failed = ret;
476 		ret = 0;
477 	}
478 #endif
479 	if (ret < 0)
480 		return ret;
481 
482 	pr_info("    kretprobe\n");
483 	ret = test_kretprobe(func);
484 	if (ret < 0)
485 		return ret;
486 
487 	return 0;
488 }
489 
490 
491 /*
492  * Benchmarking
493  */
494 
495 #if BENCHMARKING
496 
497 static void __naked benchmark_nop(void)
498 {
499 	__asm__ __volatile__ (
500 		"nop		\n\t"
501 		RET(lr)"	\n\t"
502 	);
503 }
504 
505 #ifdef CONFIG_THUMB2_KERNEL
506 #define wide ".w"
507 #else
508 #define wide
509 #endif
510 
511 static void __naked benchmark_pushpop1(void)
512 {
513 	__asm__ __volatile__ (
514 		"stmdb"wide"	sp!, {r3-r11,lr}  \n\t"
515 		"ldmia"wide"	sp!, {r3-r11,pc}"
516 	);
517 }
518 
519 static void __naked benchmark_pushpop2(void)
520 {
521 	__asm__ __volatile__ (
522 		"stmdb"wide"	sp!, {r0-r8,lr}  \n\t"
523 		"ldmia"wide"	sp!, {r0-r8,pc}"
524 	);
525 }
526 
527 static void __naked benchmark_pushpop3(void)
528 {
529 	__asm__ __volatile__ (
530 		"stmdb"wide"	sp!, {r4,lr}  \n\t"
531 		"ldmia"wide"	sp!, {r4,pc}"
532 	);
533 }
534 
535 static void __naked benchmark_pushpop4(void)
536 {
537 	__asm__ __volatile__ (
538 		"stmdb"wide"	sp!, {r0,lr}  \n\t"
539 		"ldmia"wide"	sp!, {r0,pc}"
540 	);
541 }
542 
543 
544 #ifdef CONFIG_THUMB2_KERNEL
545 
546 static void __naked benchmark_pushpop_thumb(void)
547 {
548 	__asm__ __volatile__ (
549 		"push.n	{r0-r7,lr}  \n\t"
550 		"pop.n	{r0-r7,pc}"
551 	);
552 }
553 
554 #endif
555 
556 static int __kprobes
557 benchmark_pre_handler(struct kprobe *p, struct pt_regs *regs)
558 {
559 	return 0;
560 }
561 
562 static int benchmark(void(*fn)(void))
563 {
564 	unsigned n, i, t, t0;
565 
566 	for (n = 1000; ; n *= 2) {
567 		t0 = sched_clock();
568 		for (i = n; i > 0; --i)
569 			fn();
570 		t = sched_clock() - t0;
571 		if (t >= 250000000)
572 			break; /* Stop once we took more than 0.25 seconds */
573 	}
574 	return t / n; /* Time for one iteration in nanoseconds */
575 };
576 
577 static int kprobe_benchmark(void(*fn)(void), unsigned offset)
578 {
579 	struct kprobe k = {
580 		.addr		= (kprobe_opcode_t *)((uintptr_t)fn + offset),
581 		.pre_handler	= benchmark_pre_handler,
582 	};
583 
584 	int ret = register_kprobe(&k);
585 	if (ret < 0) {
586 		pr_err("FAIL: register_kprobe failed with %d\n", ret);
587 		return ret;
588 	}
589 
590 	ret = benchmark(fn);
591 
592 	unregister_kprobe(&k);
593 	return ret;
594 };
595 
596 struct benchmarks {
597 	void		(*fn)(void);
598 	unsigned	offset;
599 	const char	*title;
600 };
601 
602 static int run_benchmarks(void)
603 {
604 	int ret;
605 	struct benchmarks list[] = {
606 		{&benchmark_nop, 0, "nop"},
607 		/*
608 		 * benchmark_pushpop{1,3} will have the optimised
609 		 * instruction emulation, whilst benchmark_pushpop{2,4} will
610 		 * be the equivalent unoptimised instructions.
611 		 */
612 		{&benchmark_pushpop1, 0, "stmdb	sp!, {r3-r11,lr}"},
613 		{&benchmark_pushpop1, 4, "ldmia	sp!, {r3-r11,pc}"},
614 		{&benchmark_pushpop2, 0, "stmdb	sp!, {r0-r8,lr}"},
615 		{&benchmark_pushpop2, 4, "ldmia	sp!, {r0-r8,pc}"},
616 		{&benchmark_pushpop3, 0, "stmdb	sp!, {r4,lr}"},
617 		{&benchmark_pushpop3, 4, "ldmia	sp!, {r4,pc}"},
618 		{&benchmark_pushpop4, 0, "stmdb	sp!, {r0,lr}"},
619 		{&benchmark_pushpop4, 4, "ldmia	sp!, {r0,pc}"},
620 #ifdef CONFIG_THUMB2_KERNEL
621 		{&benchmark_pushpop_thumb, 0, "push.n	{r0-r7,lr}"},
622 		{&benchmark_pushpop_thumb, 2, "pop.n	{r0-r7,pc}"},
623 #endif
624 		{0}
625 	};
626 
627 	struct benchmarks *b;
628 	for (b = list; b->fn; ++b) {
629 		ret = kprobe_benchmark(b->fn, b->offset);
630 		if (ret < 0)
631 			return ret;
632 		pr_info("    %dns for kprobe %s\n", ret, b->title);
633 	}
634 
635 	pr_info("\n");
636 	return 0;
637 }
638 
639 #endif /* BENCHMARKING */
640 
641 
642 /*
643  * Decoding table self-consistency tests
644  */
645 
646 static const int decode_struct_sizes[NUM_DECODE_TYPES] = {
647 	[DECODE_TYPE_TABLE]	= sizeof(struct decode_table),
648 	[DECODE_TYPE_CUSTOM]	= sizeof(struct decode_custom),
649 	[DECODE_TYPE_SIMULATE]	= sizeof(struct decode_simulate),
650 	[DECODE_TYPE_EMULATE]	= sizeof(struct decode_emulate),
651 	[DECODE_TYPE_OR]	= sizeof(struct decode_or),
652 	[DECODE_TYPE_REJECT]	= sizeof(struct decode_reject)
653 };
654 
655 static int table_iter(const union decode_item *table,
656 			int (*fn)(const struct decode_header *, void *),
657 			void *args)
658 {
659 	const struct decode_header *h = (struct decode_header *)table;
660 	int result;
661 
662 	for (;;) {
663 		enum decode_type type = h->type_regs.bits & DECODE_TYPE_MASK;
664 
665 		if (type == DECODE_TYPE_END)
666 			return 0;
667 
668 		result = fn(h, args);
669 		if (result)
670 			return result;
671 
672 		h = (struct decode_header *)
673 			((uintptr_t)h + decode_struct_sizes[type]);
674 
675 	}
676 }
677 
678 static int table_test_fail(const struct decode_header *h, const char* message)
679 {
680 
681 	pr_err("FAIL: kprobes test failure \"%s\" (mask %08x, value %08x)\n",
682 					message, h->mask.bits, h->value.bits);
683 	return -EINVAL;
684 }
685 
686 struct table_test_args {
687 	const union decode_item *root_table;
688 	u32			parent_mask;
689 	u32			parent_value;
690 };
691 
692 static int table_test_fn(const struct decode_header *h, void *args)
693 {
694 	struct table_test_args *a = (struct table_test_args *)args;
695 	enum decode_type type = h->type_regs.bits & DECODE_TYPE_MASK;
696 
697 	if (h->value.bits & ~h->mask.bits)
698 		return table_test_fail(h, "Match value has bits not in mask");
699 
700 	if ((h->mask.bits & a->parent_mask) != a->parent_mask)
701 		return table_test_fail(h, "Mask has bits not in parent mask");
702 
703 	if ((h->value.bits ^ a->parent_value) & a->parent_mask)
704 		return table_test_fail(h, "Value is inconsistent with parent");
705 
706 	if (type == DECODE_TYPE_TABLE) {
707 		struct decode_table *d = (struct decode_table *)h;
708 		struct table_test_args args2 = *a;
709 		args2.parent_mask = h->mask.bits;
710 		args2.parent_value = h->value.bits;
711 		return table_iter(d->table.table, table_test_fn, &args2);
712 	}
713 
714 	return 0;
715 }
716 
717 static int table_test(const union decode_item *table)
718 {
719 	struct table_test_args args = {
720 		.root_table	= table,
721 		.parent_mask	= 0,
722 		.parent_value	= 0
723 	};
724 	return table_iter(args.root_table, table_test_fn, &args);
725 }
726 
727 
728 /*
729  * Decoding table test coverage analysis
730  *
731  * coverage_start() builds a coverage_table which contains a list of
732  * coverage_entry's to match each entry in the specified kprobes instruction
733  * decoding table.
734  *
735  * When test cases are run, coverage_add() is called to process each case.
736  * This looks up the corresponding entry in the coverage_table and sets it as
737  * being matched, as well as clearing the regs flag appropriate for the test.
738  *
739  * After all test cases have been run, coverage_end() is called to check that
740  * all entries in coverage_table have been matched and that all regs flags are
741  * cleared. I.e. that all possible combinations of instructions described by
742  * the kprobes decoding tables have had a test case executed for them.
743  */
744 
745 bool coverage_fail;
746 
747 #define MAX_COVERAGE_ENTRIES 256
748 
749 struct coverage_entry {
750 	const struct decode_header	*header;
751 	unsigned			regs;
752 	unsigned			nesting;
753 	char				matched;
754 };
755 
756 struct coverage_table {
757 	struct coverage_entry	*base;
758 	unsigned		num_entries;
759 	unsigned		nesting;
760 };
761 
762 struct coverage_table coverage;
763 
764 #define COVERAGE_ANY_REG	(1<<0)
765 #define COVERAGE_SP		(1<<1)
766 #define COVERAGE_PC		(1<<2)
767 #define COVERAGE_PCWB		(1<<3)
768 
769 static const char coverage_register_lookup[16] = {
770 	[REG_TYPE_ANY]		= COVERAGE_ANY_REG | COVERAGE_SP | COVERAGE_PC,
771 	[REG_TYPE_SAMEAS16]	= COVERAGE_ANY_REG,
772 	[REG_TYPE_SP]		= COVERAGE_SP,
773 	[REG_TYPE_PC]		= COVERAGE_PC,
774 	[REG_TYPE_NOSP]		= COVERAGE_ANY_REG | COVERAGE_SP,
775 	[REG_TYPE_NOSPPC]	= COVERAGE_ANY_REG | COVERAGE_SP | COVERAGE_PC,
776 	[REG_TYPE_NOPC]		= COVERAGE_ANY_REG | COVERAGE_PC,
777 	[REG_TYPE_NOPCWB]	= COVERAGE_ANY_REG | COVERAGE_PC | COVERAGE_PCWB,
778 	[REG_TYPE_NOPCX]	= COVERAGE_ANY_REG,
779 	[REG_TYPE_NOSPPCX]	= COVERAGE_ANY_REG | COVERAGE_SP,
780 };
781 
782 unsigned coverage_start_registers(const struct decode_header *h)
783 {
784 	unsigned regs = 0;
785 	int i;
786 	for (i = 0; i < 20; i += 4) {
787 		int r = (h->type_regs.bits >> (DECODE_TYPE_BITS + i)) & 0xf;
788 		regs |= coverage_register_lookup[r] << i;
789 	}
790 	return regs;
791 }
792 
793 static int coverage_start_fn(const struct decode_header *h, void *args)
794 {
795 	struct coverage_table *coverage = (struct coverage_table *)args;
796 	enum decode_type type = h->type_regs.bits & DECODE_TYPE_MASK;
797 	struct coverage_entry *entry = coverage->base + coverage->num_entries;
798 
799 	if (coverage->num_entries == MAX_COVERAGE_ENTRIES - 1) {
800 		pr_err("FAIL: Out of space for test coverage data");
801 		return -ENOMEM;
802 	}
803 
804 	++coverage->num_entries;
805 
806 	entry->header = h;
807 	entry->regs = coverage_start_registers(h);
808 	entry->nesting = coverage->nesting;
809 	entry->matched = false;
810 
811 	if (type == DECODE_TYPE_TABLE) {
812 		struct decode_table *d = (struct decode_table *)h;
813 		int ret;
814 		++coverage->nesting;
815 		ret = table_iter(d->table.table, coverage_start_fn, coverage);
816 		--coverage->nesting;
817 		return ret;
818 	}
819 
820 	return 0;
821 }
822 
823 static int coverage_start(const union decode_item *table)
824 {
825 	coverage.base = kmalloc(MAX_COVERAGE_ENTRIES *
826 				sizeof(struct coverage_entry), GFP_KERNEL);
827 	coverage.num_entries = 0;
828 	coverage.nesting = 0;
829 	return table_iter(table, coverage_start_fn, &coverage);
830 }
831 
832 static void
833 coverage_add_registers(struct coverage_entry *entry, kprobe_opcode_t insn)
834 {
835 	int regs = entry->header->type_regs.bits >> DECODE_TYPE_BITS;
836 	int i;
837 	for (i = 0; i < 20; i += 4) {
838 		enum decode_reg_type reg_type = (regs >> i) & 0xf;
839 		int reg = (insn >> i) & 0xf;
840 		int flag;
841 
842 		if (!reg_type)
843 			continue;
844 
845 		if (reg == 13)
846 			flag = COVERAGE_SP;
847 		else if (reg == 15)
848 			flag = COVERAGE_PC;
849 		else
850 			flag = COVERAGE_ANY_REG;
851 		entry->regs &= ~(flag << i);
852 
853 		switch (reg_type) {
854 
855 		case REG_TYPE_NONE:
856 		case REG_TYPE_ANY:
857 		case REG_TYPE_SAMEAS16:
858 			break;
859 
860 		case REG_TYPE_SP:
861 			if (reg != 13)
862 				return;
863 			break;
864 
865 		case REG_TYPE_PC:
866 			if (reg != 15)
867 				return;
868 			break;
869 
870 		case REG_TYPE_NOSP:
871 			if (reg == 13)
872 				return;
873 			break;
874 
875 		case REG_TYPE_NOSPPC:
876 		case REG_TYPE_NOSPPCX:
877 			if (reg == 13 || reg == 15)
878 				return;
879 			break;
880 
881 		case REG_TYPE_NOPCWB:
882 			if (!is_writeback(insn))
883 				break;
884 			if (reg == 15) {
885 				entry->regs &= ~(COVERAGE_PCWB << i);
886 				return;
887 			}
888 			break;
889 
890 		case REG_TYPE_NOPC:
891 		case REG_TYPE_NOPCX:
892 			if (reg == 15)
893 				return;
894 			break;
895 		}
896 
897 	}
898 }
899 
900 static void coverage_add(kprobe_opcode_t insn)
901 {
902 	struct coverage_entry *entry = coverage.base;
903 	struct coverage_entry *end = coverage.base + coverage.num_entries;
904 	bool matched = false;
905 	unsigned nesting = 0;
906 
907 	for (; entry < end; ++entry) {
908 		const struct decode_header *h = entry->header;
909 		enum decode_type type = h->type_regs.bits & DECODE_TYPE_MASK;
910 
911 		if (entry->nesting > nesting)
912 			continue; /* Skip sub-table we didn't match */
913 
914 		if (entry->nesting < nesting)
915 			break; /* End of sub-table we were scanning */
916 
917 		if (!matched) {
918 			if ((insn & h->mask.bits) != h->value.bits)
919 				continue;
920 			entry->matched = true;
921 		}
922 
923 		switch (type) {
924 
925 		case DECODE_TYPE_TABLE:
926 			++nesting;
927 			break;
928 
929 		case DECODE_TYPE_CUSTOM:
930 		case DECODE_TYPE_SIMULATE:
931 		case DECODE_TYPE_EMULATE:
932 			coverage_add_registers(entry, insn);
933 			return;
934 
935 		case DECODE_TYPE_OR:
936 			matched = true;
937 			break;
938 
939 		case DECODE_TYPE_REJECT:
940 		default:
941 			return;
942 		}
943 
944 	}
945 }
946 
947 static void coverage_end(void)
948 {
949 	struct coverage_entry *entry = coverage.base;
950 	struct coverage_entry *end = coverage.base + coverage.num_entries;
951 
952 	for (; entry < end; ++entry) {
953 		u32 mask = entry->header->mask.bits;
954 		u32 value = entry->header->value.bits;
955 
956 		if (entry->regs) {
957 			pr_err("FAIL: Register test coverage missing for %08x %08x (%05x)\n",
958 				mask, value, entry->regs);
959 			coverage_fail = true;
960 		}
961 		if (!entry->matched) {
962 			pr_err("FAIL: Test coverage entry missing for %08x %08x\n",
963 				mask, value);
964 			coverage_fail = true;
965 		}
966 	}
967 
968 	kfree(coverage.base);
969 }
970 
971 
972 /*
973  * Framework for instruction set test cases
974  */
975 
976 void __naked __kprobes_test_case_start(void)
977 {
978 	__asm__ __volatile__ (
979 		"stmdb	sp!, {r4-r11}				\n\t"
980 		"sub	sp, sp, #"__stringify(TEST_MEMORY_SIZE)"\n\t"
981 		"bic	r0, lr, #1  @ r0 = inline data		\n\t"
982 		"mov	r1, sp					\n\t"
983 		"bl	kprobes_test_case_start			\n\t"
984 		RET(r0)"					\n\t"
985 	);
986 }
987 
988 #ifndef CONFIG_THUMB2_KERNEL
989 
990 void __naked __kprobes_test_case_end_32(void)
991 {
992 	__asm__ __volatile__ (
993 		"mov	r4, lr					\n\t"
994 		"bl	kprobes_test_case_end			\n\t"
995 		"cmp	r0, #0					\n\t"
996 		"movne	pc, r0					\n\t"
997 		"mov	r0, r4					\n\t"
998 		"add	sp, sp, #"__stringify(TEST_MEMORY_SIZE)"\n\t"
999 		"ldmia	sp!, {r4-r11}				\n\t"
1000 		"mov	pc, r0					\n\t"
1001 	);
1002 }
1003 
1004 #else /* CONFIG_THUMB2_KERNEL */
1005 
1006 void __naked __kprobes_test_case_end_16(void)
1007 {
1008 	__asm__ __volatile__ (
1009 		"mov	r4, lr					\n\t"
1010 		"bl	kprobes_test_case_end			\n\t"
1011 		"cmp	r0, #0					\n\t"
1012 		"bxne	r0					\n\t"
1013 		"mov	r0, r4					\n\t"
1014 		"add	sp, sp, #"__stringify(TEST_MEMORY_SIZE)"\n\t"
1015 		"ldmia	sp!, {r4-r11}				\n\t"
1016 		"bx	r0					\n\t"
1017 	);
1018 }
1019 
1020 void __naked __kprobes_test_case_end_32(void)
1021 {
1022 	__asm__ __volatile__ (
1023 		".arm						\n\t"
1024 		"orr	lr, lr, #1  @ will return to Thumb code	\n\t"
1025 		"ldr	pc, 1f					\n\t"
1026 		"1:						\n\t"
1027 		".word	__kprobes_test_case_end_16		\n\t"
1028 	);
1029 }
1030 
1031 #endif
1032 
1033 
1034 int kprobe_test_flags;
1035 int kprobe_test_cc_position;
1036 
1037 static int test_try_count;
1038 static int test_pass_count;
1039 static int test_fail_count;
1040 
1041 static struct pt_regs initial_regs;
1042 static struct pt_regs expected_regs;
1043 static struct pt_regs result_regs;
1044 
1045 static u32 expected_memory[TEST_MEMORY_SIZE/sizeof(u32)];
1046 
1047 static const char *current_title;
1048 static struct test_arg *current_args;
1049 static u32 *current_stack;
1050 static uintptr_t current_branch_target;
1051 
1052 static uintptr_t current_code_start;
1053 static kprobe_opcode_t current_instruction;
1054 
1055 
1056 #define TEST_CASE_PASSED -1
1057 #define TEST_CASE_FAILED -2
1058 
1059 static int test_case_run_count;
1060 static bool test_case_is_thumb;
1061 static int test_instance;
1062 
1063 static unsigned long test_check_cc(int cc, unsigned long cpsr)
1064 {
1065 	int ret = arm_check_condition(cc << 28, cpsr);
1066 
1067 	return (ret != ARM_OPCODE_CONDTEST_FAIL);
1068 }
1069 
1070 static int is_last_scenario;
1071 static int probe_should_run; /* 0 = no, 1 = yes, -1 = unknown */
1072 static int memory_needs_checking;
1073 
1074 static unsigned long test_context_cpsr(int scenario)
1075 {
1076 	unsigned long cpsr;
1077 
1078 	probe_should_run = 1;
1079 
1080 	/* Default case is that we cycle through 16 combinations of flags */
1081 	cpsr  = (scenario & 0xf) << 28; /* N,Z,C,V flags */
1082 	cpsr |= (scenario & 0xf) << 16; /* GE flags */
1083 	cpsr |= (scenario & 0x1) << 27; /* Toggle Q flag */
1084 
1085 	if (!test_case_is_thumb) {
1086 		/* Testing ARM code */
1087 		int cc = current_instruction >> 28;
1088 
1089 		probe_should_run = test_check_cc(cc, cpsr) != 0;
1090 		if (scenario == 15)
1091 			is_last_scenario = true;
1092 
1093 	} else if (kprobe_test_flags & TEST_FLAG_NO_ITBLOCK) {
1094 		/* Testing Thumb code without setting ITSTATE */
1095 		if (kprobe_test_cc_position) {
1096 			int cc = (current_instruction >> kprobe_test_cc_position) & 0xf;
1097 			probe_should_run = test_check_cc(cc, cpsr) != 0;
1098 		}
1099 
1100 		if (scenario == 15)
1101 			is_last_scenario = true;
1102 
1103 	} else if (kprobe_test_flags & TEST_FLAG_FULL_ITBLOCK) {
1104 		/* Testing Thumb code with all combinations of ITSTATE */
1105 		unsigned x = (scenario >> 4);
1106 		unsigned cond_base = x % 7; /* ITSTATE<7:5> */
1107 		unsigned mask = x / 7 + 2;  /* ITSTATE<4:0>, bits reversed */
1108 
1109 		if (mask > 0x1f) {
1110 			/* Finish by testing state from instruction 'itt al' */
1111 			cond_base = 7;
1112 			mask = 0x4;
1113 			if ((scenario & 0xf) == 0xf)
1114 				is_last_scenario = true;
1115 		}
1116 
1117 		cpsr |= cond_base << 13;	/* ITSTATE<7:5> */
1118 		cpsr |= (mask & 0x1) << 12;	/* ITSTATE<4> */
1119 		cpsr |= (mask & 0x2) << 10;	/* ITSTATE<3> */
1120 		cpsr |= (mask & 0x4) << 8;	/* ITSTATE<2> */
1121 		cpsr |= (mask & 0x8) << 23;	/* ITSTATE<1> */
1122 		cpsr |= (mask & 0x10) << 21;	/* ITSTATE<0> */
1123 
1124 		probe_should_run = test_check_cc((cpsr >> 12) & 0xf, cpsr) != 0;
1125 
1126 	} else {
1127 		/* Testing Thumb code with several combinations of ITSTATE */
1128 		switch (scenario) {
1129 		case 16: /* Clear NZCV flags and 'it eq' state (false as Z=0) */
1130 			cpsr = 0x00000800;
1131 			probe_should_run = 0;
1132 			break;
1133 		case 17: /* Set NZCV flags and 'it vc' state (false as V=1) */
1134 			cpsr = 0xf0007800;
1135 			probe_should_run = 0;
1136 			break;
1137 		case 18: /* Clear NZCV flags and 'it ls' state (true as C=0) */
1138 			cpsr = 0x00009800;
1139 			break;
1140 		case 19: /* Set NZCV flags and 'it cs' state (true as C=1) */
1141 			cpsr = 0xf0002800;
1142 			is_last_scenario = true;
1143 			break;
1144 		}
1145 	}
1146 
1147 	return cpsr;
1148 }
1149 
1150 static void setup_test_context(struct pt_regs *regs)
1151 {
1152 	int scenario = test_case_run_count>>1;
1153 	unsigned long val;
1154 	struct test_arg *args;
1155 	int i;
1156 
1157 	is_last_scenario = false;
1158 	memory_needs_checking = false;
1159 
1160 	/* Initialise test memory on stack */
1161 	val = (scenario & 1) ? VALM : ~VALM;
1162 	for (i = 0; i < TEST_MEMORY_SIZE / sizeof(current_stack[0]); ++i)
1163 		current_stack[i] = val + (i << 8);
1164 	/* Put target of branch on stack for tests which load PC from memory */
1165 	if (current_branch_target)
1166 		current_stack[15] = current_branch_target;
1167 	/* Put a value for SP on stack for tests which load SP from memory */
1168 	current_stack[13] = (u32)current_stack + 120;
1169 
1170 	/* Initialise register values to their default state */
1171 	val = (scenario & 2) ? VALR : ~VALR;
1172 	for (i = 0; i < 13; ++i)
1173 		regs->uregs[i] = val ^ (i << 8);
1174 	regs->ARM_lr = val ^ (14 << 8);
1175 	regs->ARM_cpsr &= ~(APSR_MASK | PSR_IT_MASK);
1176 	regs->ARM_cpsr |= test_context_cpsr(scenario);
1177 
1178 	/* Perform testcase specific register setup  */
1179 	args = current_args;
1180 	for (; args[0].type != ARG_TYPE_END; ++args)
1181 		switch (args[0].type) {
1182 		case ARG_TYPE_REG: {
1183 			struct test_arg_regptr *arg =
1184 				(struct test_arg_regptr *)args;
1185 			regs->uregs[arg->reg] = arg->val;
1186 			break;
1187 		}
1188 		case ARG_TYPE_PTR: {
1189 			struct test_arg_regptr *arg =
1190 				(struct test_arg_regptr *)args;
1191 			regs->uregs[arg->reg] =
1192 				(unsigned long)current_stack + arg->val;
1193 			memory_needs_checking = true;
1194 			/*
1195 			 * Test memory at an address below SP is in danger of
1196 			 * being altered by an interrupt occurring and pushing
1197 			 * data onto the stack. Disable interrupts to stop this.
1198 			 */
1199 			if (arg->reg == 13)
1200 				regs->ARM_cpsr |= PSR_I_BIT;
1201 			break;
1202 		}
1203 		case ARG_TYPE_MEM: {
1204 			struct test_arg_mem *arg = (struct test_arg_mem *)args;
1205 			current_stack[arg->index] = arg->val;
1206 			break;
1207 		}
1208 		default:
1209 			break;
1210 		}
1211 }
1212 
1213 struct test_probe {
1214 	struct kprobe	kprobe;
1215 	bool		registered;
1216 	int		hit;
1217 };
1218 
1219 static void unregister_test_probe(struct test_probe *probe)
1220 {
1221 	if (probe->registered) {
1222 		unregister_kprobe(&probe->kprobe);
1223 		probe->kprobe.flags = 0; /* Clear disable flag to allow reuse */
1224 	}
1225 	probe->registered = false;
1226 }
1227 
1228 static int register_test_probe(struct test_probe *probe)
1229 {
1230 	int ret;
1231 
1232 	if (probe->registered)
1233 		BUG();
1234 
1235 	ret = register_kprobe(&probe->kprobe);
1236 	if (ret >= 0) {
1237 		probe->registered = true;
1238 		probe->hit = -1;
1239 	}
1240 	return ret;
1241 }
1242 
1243 static int __kprobes
1244 test_before_pre_handler(struct kprobe *p, struct pt_regs *regs)
1245 {
1246 	container_of(p, struct test_probe, kprobe)->hit = test_instance;
1247 	return 0;
1248 }
1249 
1250 static void __kprobes
1251 test_before_post_handler(struct kprobe *p, struct pt_regs *regs,
1252 							unsigned long flags)
1253 {
1254 	setup_test_context(regs);
1255 	initial_regs = *regs;
1256 	initial_regs.ARM_cpsr &= ~PSR_IGNORE_BITS;
1257 }
1258 
1259 static int __kprobes
1260 test_case_pre_handler(struct kprobe *p, struct pt_regs *regs)
1261 {
1262 	container_of(p, struct test_probe, kprobe)->hit = test_instance;
1263 	return 0;
1264 }
1265 
1266 static int __kprobes
1267 test_after_pre_handler(struct kprobe *p, struct pt_regs *regs)
1268 {
1269 	struct test_arg *args;
1270 
1271 	if (container_of(p, struct test_probe, kprobe)->hit == test_instance)
1272 		return 0; /* Already run for this test instance */
1273 
1274 	result_regs = *regs;
1275 
1276 	/* Mask out results which are indeterminate */
1277 	result_regs.ARM_cpsr &= ~PSR_IGNORE_BITS;
1278 	for (args = current_args; args[0].type != ARG_TYPE_END; ++args)
1279 		if (args[0].type == ARG_TYPE_REG_MASKED) {
1280 			struct test_arg_regptr *arg =
1281 				(struct test_arg_regptr *)args;
1282 			result_regs.uregs[arg->reg] &= arg->val;
1283 		}
1284 
1285 	/* Undo any changes done to SP by the test case */
1286 	regs->ARM_sp = (unsigned long)current_stack;
1287 	/* Enable interrupts in case setup_test_context disabled them */
1288 	regs->ARM_cpsr &= ~PSR_I_BIT;
1289 
1290 	container_of(p, struct test_probe, kprobe)->hit = test_instance;
1291 	return 0;
1292 }
1293 
1294 static struct test_probe test_before_probe = {
1295 	.kprobe.pre_handler	= test_before_pre_handler,
1296 	.kprobe.post_handler	= test_before_post_handler,
1297 };
1298 
1299 static struct test_probe test_case_probe = {
1300 	.kprobe.pre_handler	= test_case_pre_handler,
1301 };
1302 
1303 static struct test_probe test_after_probe = {
1304 	.kprobe.pre_handler	= test_after_pre_handler,
1305 };
1306 
1307 static struct test_probe test_after2_probe = {
1308 	.kprobe.pre_handler	= test_after_pre_handler,
1309 };
1310 
1311 static void test_case_cleanup(void)
1312 {
1313 	unregister_test_probe(&test_before_probe);
1314 	unregister_test_probe(&test_case_probe);
1315 	unregister_test_probe(&test_after_probe);
1316 	unregister_test_probe(&test_after2_probe);
1317 }
1318 
1319 static void print_registers(struct pt_regs *regs)
1320 {
1321 	pr_err("r0  %08lx | r1  %08lx | r2  %08lx | r3  %08lx\n",
1322 		regs->ARM_r0, regs->ARM_r1, regs->ARM_r2, regs->ARM_r3);
1323 	pr_err("r4  %08lx | r5  %08lx | r6  %08lx | r7  %08lx\n",
1324 		regs->ARM_r4, regs->ARM_r5, regs->ARM_r6, regs->ARM_r7);
1325 	pr_err("r8  %08lx | r9  %08lx | r10 %08lx | r11 %08lx\n",
1326 		regs->ARM_r8, regs->ARM_r9, regs->ARM_r10, regs->ARM_fp);
1327 	pr_err("r12 %08lx | sp  %08lx | lr  %08lx | pc  %08lx\n",
1328 		regs->ARM_ip, regs->ARM_sp, regs->ARM_lr, regs->ARM_pc);
1329 	pr_err("cpsr %08lx\n", regs->ARM_cpsr);
1330 }
1331 
1332 static void print_memory(u32 *mem, size_t size)
1333 {
1334 	int i;
1335 	for (i = 0; i < size / sizeof(u32); i += 4)
1336 		pr_err("%08x %08x %08x %08x\n", mem[i], mem[i+1],
1337 						mem[i+2], mem[i+3]);
1338 }
1339 
1340 static size_t expected_memory_size(u32 *sp)
1341 {
1342 	size_t size = sizeof(expected_memory);
1343 	int offset = (uintptr_t)sp - (uintptr_t)current_stack;
1344 	if (offset > 0)
1345 		size -= offset;
1346 	return size;
1347 }
1348 
1349 static void test_case_failed(const char *message)
1350 {
1351 	test_case_cleanup();
1352 
1353 	pr_err("FAIL: %s\n", message);
1354 	pr_err("FAIL: Test %s\n", current_title);
1355 	pr_err("FAIL: Scenario %d\n", test_case_run_count >> 1);
1356 }
1357 
1358 static unsigned long next_instruction(unsigned long pc)
1359 {
1360 #ifdef CONFIG_THUMB2_KERNEL
1361 	if ((pc & 1) &&
1362 	    !is_wide_instruction(__mem_to_opcode_thumb16(*(u16 *)(pc - 1))))
1363 		return pc + 2;
1364 	else
1365 #endif
1366 	return pc + 4;
1367 }
1368 
1369 static uintptr_t __used kprobes_test_case_start(const char **title, void *stack)
1370 {
1371 	struct test_arg *args;
1372 	struct test_arg_end *end_arg;
1373 	unsigned long test_code;
1374 
1375 	current_title = *title++;
1376 	args = (struct test_arg *)title;
1377 	current_args = args;
1378 	current_stack = stack;
1379 
1380 	++test_try_count;
1381 
1382 	while (args->type != ARG_TYPE_END)
1383 		++args;
1384 	end_arg = (struct test_arg_end *)args;
1385 
1386 	test_code = (unsigned long)(args + 1); /* Code starts after args */
1387 
1388 	test_case_is_thumb = end_arg->flags & ARG_FLAG_THUMB;
1389 	if (test_case_is_thumb)
1390 		test_code |= 1;
1391 
1392 	current_code_start = test_code;
1393 
1394 	current_branch_target = 0;
1395 	if (end_arg->branch_offset != end_arg->end_offset)
1396 		current_branch_target = test_code + end_arg->branch_offset;
1397 
1398 	test_code += end_arg->code_offset;
1399 	test_before_probe.kprobe.addr = (kprobe_opcode_t *)test_code;
1400 
1401 	test_code = next_instruction(test_code);
1402 	test_case_probe.kprobe.addr = (kprobe_opcode_t *)test_code;
1403 
1404 	if (test_case_is_thumb) {
1405 		u16 *p = (u16 *)(test_code & ~1);
1406 		current_instruction = __mem_to_opcode_thumb16(p[0]);
1407 		if (is_wide_instruction(current_instruction)) {
1408 			u16 instr2 = __mem_to_opcode_thumb16(p[1]);
1409 			current_instruction = __opcode_thumb32_compose(current_instruction, instr2);
1410 		}
1411 	} else {
1412 		current_instruction = __mem_to_opcode_arm(*(u32 *)test_code);
1413 	}
1414 
1415 	if (current_title[0] == '.')
1416 		verbose("%s\n", current_title);
1417 	else
1418 		verbose("%s\t@ %0*x\n", current_title,
1419 					test_case_is_thumb ? 4 : 8,
1420 					current_instruction);
1421 
1422 	test_code = next_instruction(test_code);
1423 	test_after_probe.kprobe.addr = (kprobe_opcode_t *)test_code;
1424 
1425 	if (kprobe_test_flags & TEST_FLAG_NARROW_INSTR) {
1426 		if (!test_case_is_thumb ||
1427 			is_wide_instruction(current_instruction)) {
1428 				test_case_failed("expected 16-bit instruction");
1429 				goto fail;
1430 		}
1431 	} else {
1432 		if (test_case_is_thumb &&
1433 			!is_wide_instruction(current_instruction)) {
1434 				test_case_failed("expected 32-bit instruction");
1435 				goto fail;
1436 		}
1437 	}
1438 
1439 	coverage_add(current_instruction);
1440 
1441 	if (end_arg->flags & ARG_FLAG_UNSUPPORTED) {
1442 		if (register_test_probe(&test_case_probe) < 0)
1443 			goto pass;
1444 		test_case_failed("registered probe for unsupported instruction");
1445 		goto fail;
1446 	}
1447 
1448 	if (end_arg->flags & ARG_FLAG_SUPPORTED) {
1449 		if (register_test_probe(&test_case_probe) >= 0)
1450 			goto pass;
1451 		test_case_failed("couldn't register probe for supported instruction");
1452 		goto fail;
1453 	}
1454 
1455 	if (register_test_probe(&test_before_probe) < 0) {
1456 		test_case_failed("register test_before_probe failed");
1457 		goto fail;
1458 	}
1459 	if (register_test_probe(&test_after_probe) < 0) {
1460 		test_case_failed("register test_after_probe failed");
1461 		goto fail;
1462 	}
1463 	if (current_branch_target) {
1464 		test_after2_probe.kprobe.addr =
1465 				(kprobe_opcode_t *)current_branch_target;
1466 		if (register_test_probe(&test_after2_probe) < 0) {
1467 			test_case_failed("register test_after2_probe failed");
1468 			goto fail;
1469 		}
1470 	}
1471 
1472 	/* Start first run of test case */
1473 	test_case_run_count = 0;
1474 	++test_instance;
1475 	return current_code_start;
1476 pass:
1477 	test_case_run_count = TEST_CASE_PASSED;
1478 	return (uintptr_t)test_after_probe.kprobe.addr;
1479 fail:
1480 	test_case_run_count = TEST_CASE_FAILED;
1481 	return (uintptr_t)test_after_probe.kprobe.addr;
1482 }
1483 
1484 static bool check_test_results(void)
1485 {
1486 	size_t mem_size = 0;
1487 	u32 *mem = 0;
1488 
1489 	if (memcmp(&expected_regs, &result_regs, sizeof(expected_regs))) {
1490 		test_case_failed("registers differ");
1491 		goto fail;
1492 	}
1493 
1494 	if (memory_needs_checking) {
1495 		mem = (u32 *)result_regs.ARM_sp;
1496 		mem_size = expected_memory_size(mem);
1497 		if (memcmp(expected_memory, mem, mem_size)) {
1498 			test_case_failed("test memory differs");
1499 			goto fail;
1500 		}
1501 	}
1502 
1503 	return true;
1504 
1505 fail:
1506 	pr_err("initial_regs:\n");
1507 	print_registers(&initial_regs);
1508 	pr_err("expected_regs:\n");
1509 	print_registers(&expected_regs);
1510 	pr_err("result_regs:\n");
1511 	print_registers(&result_regs);
1512 
1513 	if (mem) {
1514 		pr_err("current_stack=%p\n", current_stack);
1515 		pr_err("expected_memory:\n");
1516 		print_memory(expected_memory, mem_size);
1517 		pr_err("result_memory:\n");
1518 		print_memory(mem, mem_size);
1519 	}
1520 
1521 	return false;
1522 }
1523 
1524 static uintptr_t __used kprobes_test_case_end(void)
1525 {
1526 	if (test_case_run_count < 0) {
1527 		if (test_case_run_count == TEST_CASE_PASSED)
1528 			/* kprobes_test_case_start did all the needed testing */
1529 			goto pass;
1530 		else
1531 			/* kprobes_test_case_start failed */
1532 			goto fail;
1533 	}
1534 
1535 	if (test_before_probe.hit != test_instance) {
1536 		test_case_failed("test_before_handler not run");
1537 		goto fail;
1538 	}
1539 
1540 	if (test_after_probe.hit != test_instance &&
1541 				test_after2_probe.hit != test_instance) {
1542 		test_case_failed("test_after_handler not run");
1543 		goto fail;
1544 	}
1545 
1546 	/*
1547 	 * Even numbered test runs ran without a probe on the test case so
1548 	 * we can gather reference results. The subsequent odd numbered run
1549 	 * will have the probe inserted.
1550 	*/
1551 	if ((test_case_run_count & 1) == 0) {
1552 		/* Save results from run without probe */
1553 		u32 *mem = (u32 *)result_regs.ARM_sp;
1554 		expected_regs = result_regs;
1555 		memcpy(expected_memory, mem, expected_memory_size(mem));
1556 
1557 		/* Insert probe onto test case instruction */
1558 		if (register_test_probe(&test_case_probe) < 0) {
1559 			test_case_failed("register test_case_probe failed");
1560 			goto fail;
1561 		}
1562 	} else {
1563 		/* Check probe ran as expected */
1564 		if (probe_should_run == 1) {
1565 			if (test_case_probe.hit != test_instance) {
1566 				test_case_failed("test_case_handler not run");
1567 				goto fail;
1568 			}
1569 		} else if (probe_should_run == 0) {
1570 			if (test_case_probe.hit == test_instance) {
1571 				test_case_failed("test_case_handler ran");
1572 				goto fail;
1573 			}
1574 		}
1575 
1576 		/* Remove probe for any subsequent reference run */
1577 		unregister_test_probe(&test_case_probe);
1578 
1579 		if (!check_test_results())
1580 			goto fail;
1581 
1582 		if (is_last_scenario)
1583 			goto pass;
1584 	}
1585 
1586 	/* Do next test run */
1587 	++test_case_run_count;
1588 	++test_instance;
1589 	return current_code_start;
1590 fail:
1591 	++test_fail_count;
1592 	goto end;
1593 pass:
1594 	++test_pass_count;
1595 end:
1596 	test_case_cleanup();
1597 	return 0;
1598 }
1599 
1600 
1601 /*
1602  * Top level test functions
1603  */
1604 
1605 static int run_test_cases(void (*tests)(void), const union decode_item *table)
1606 {
1607 	int ret;
1608 
1609 	pr_info("    Check decoding tables\n");
1610 	ret = table_test(table);
1611 	if (ret)
1612 		return ret;
1613 
1614 	pr_info("    Run test cases\n");
1615 	ret = coverage_start(table);
1616 	if (ret)
1617 		return ret;
1618 
1619 	tests();
1620 
1621 	coverage_end();
1622 	return 0;
1623 }
1624 
1625 
1626 static int __init run_all_tests(void)
1627 {
1628 	int ret = 0;
1629 
1630 	pr_info("Beginning kprobe tests...\n");
1631 
1632 #ifndef CONFIG_THUMB2_KERNEL
1633 
1634 	pr_info("Probe ARM code\n");
1635 	ret = run_api_tests(arm_func);
1636 	if (ret)
1637 		goto out;
1638 
1639 	pr_info("ARM instruction simulation\n");
1640 	ret = run_test_cases(kprobe_arm_test_cases, probes_decode_arm_table);
1641 	if (ret)
1642 		goto out;
1643 
1644 #else /* CONFIG_THUMB2_KERNEL */
1645 
1646 	pr_info("Probe 16-bit Thumb code\n");
1647 	ret = run_api_tests(thumb16_func);
1648 	if (ret)
1649 		goto out;
1650 
1651 	pr_info("Probe 32-bit Thumb code, even halfword\n");
1652 	ret = run_api_tests(thumb32even_func);
1653 	if (ret)
1654 		goto out;
1655 
1656 	pr_info("Probe 32-bit Thumb code, odd halfword\n");
1657 	ret = run_api_tests(thumb32odd_func);
1658 	if (ret)
1659 		goto out;
1660 
1661 	pr_info("16-bit Thumb instruction simulation\n");
1662 	ret = run_test_cases(kprobe_thumb16_test_cases,
1663 				probes_decode_thumb16_table);
1664 	if (ret)
1665 		goto out;
1666 
1667 	pr_info("32-bit Thumb instruction simulation\n");
1668 	ret = run_test_cases(kprobe_thumb32_test_cases,
1669 				probes_decode_thumb32_table);
1670 	if (ret)
1671 		goto out;
1672 #endif
1673 
1674 	pr_info("Total instruction simulation tests=%d, pass=%d fail=%d\n",
1675 		test_try_count, test_pass_count, test_fail_count);
1676 	if (test_fail_count) {
1677 		ret = -EINVAL;
1678 		goto out;
1679 	}
1680 
1681 #if BENCHMARKING
1682 	pr_info("Benchmarks\n");
1683 	ret = run_benchmarks();
1684 	if (ret)
1685 		goto out;
1686 #endif
1687 
1688 #if __LINUX_ARM_ARCH__ >= 7
1689 	/* We are able to run all test cases so coverage should be complete */
1690 	if (coverage_fail) {
1691 		pr_err("FAIL: Test coverage checks failed\n");
1692 		ret = -EINVAL;
1693 		goto out;
1694 	}
1695 #endif
1696 
1697 out:
1698 	if (ret == 0)
1699 		ret = tests_failed;
1700 	if (ret == 0)
1701 		pr_info("Finished kprobe tests OK\n");
1702 	else
1703 		pr_err("kprobe tests failed\n");
1704 
1705 	return ret;
1706 }
1707 
1708 
1709 /*
1710  * Module setup
1711  */
1712 
1713 #ifdef MODULE
1714 
1715 static void __exit kprobe_test_exit(void)
1716 {
1717 }
1718 
1719 module_init(run_all_tests)
1720 module_exit(kprobe_test_exit)
1721 MODULE_LICENSE("GPL");
1722 
1723 #else /* !MODULE */
1724 
1725 late_initcall(run_all_tests);
1726 
1727 #endif
1728