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