1 /*
2  * memset test.
3  *
4  * Copyright (c) 2019-2020, Arm Limited.
5  * SPDX-License-Identifier: MIT
6  */
7 
8 #include <stdint.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include "mte.h"
13 #include "stringlib.h"
14 #include "stringtest.h"
15 
16 #define F(x, mte) {#x, x, mte},
17 
18 static const struct fun
19 {
20   const char *name;
21   void *(*fun) (void *s, int c, size_t n);
22   int test_mte;
23 } funtab[] = {
24   // clang-format off
25   F(memset, 0)
26 #if __aarch64__
27   F(__memset_aarch64, 1)
28 #elif __arm__
29   F(__memset_arm, 0)
30 #endif
31   {0, 0, 0}
32   // clang-format on
33 };
34 #undef F
35 
36 #define A 32
37 #define LEN 250000
38 static unsigned char *sbuf;
39 
40 static void *
41 alignup (void *p)
42 {
43   return (void *) (((uintptr_t) p + A - 1) & -A);
44 }
45 
46 static void
47 test (const struct fun *fun, int salign, int c, int len)
48 {
49   unsigned char *src = alignup (sbuf);
50   unsigned char *s = src + salign;
51   void *p;
52   int i;
53 
54   if (err_count >= ERR_LIMIT)
55     return;
56   if (len > LEN || salign >= A)
57     abort ();
58   for (i = 0; i < len + A; i++)
59     src[i] = '?';
60   for (i = 0; i < len; i++)
61     s[i] = 'a' + i % 23;
62 
63   s = tag_buffer (s, len, fun->test_mte);
64   p = fun->fun (s, c, len);
65   untag_buffer (s, len, fun->test_mte);
66 
67   if (p != s)
68     ERR ("%s(%p,..) returned %p\n", fun->name, s, p);
69 
70   for (i = 0; i < salign; i++)
71     {
72       if (src[i] != '?')
73 	{
74 	  ERR ("%s(align %d, %d, %d) failed\n", fun->name, salign, c, len);
75 	  quoteat ("got", src, len + A, i);
76 	  return;
77 	}
78     }
79   for (; i < salign + len; i++)
80     {
81       if (src[i] != (unsigned char) c)
82 	{
83 	  ERR ("%s(align %d, %d, %d) failed\n", fun->name, salign, c, len);
84 	  quoteat ("got", src, len + A, i);
85 	  return;
86 	}
87     }
88   for (; i < len + A; i++)
89     {
90       if (src[i] != '?')
91 	{
92 	  ERR ("%s(align %d, %d, %d) failed\n", fun->name, salign, c, len);
93 	  quoteat ("got", src, len + A, i);
94 	  return;
95 	}
96     }
97 }
98 
99 int
100 main ()
101 {
102   sbuf = mte_mmap (LEN + 2 * A);
103   int r = 0;
104   for (int i = 0; funtab[i].name; i++)
105     {
106       err_count = 0;
107       for (int s = 0; s < A; s++)
108 	{
109 	  int n;
110 	  for (n = 0; n < 100; n++)
111 	    {
112 	      test (funtab + i, s, 0, n);
113 	      test (funtab + i, s, 0x25, n);
114 	      test (funtab + i, s, 0xaa25, n);
115 	    }
116 	  for (; n < LEN; n *= 2)
117 	    {
118 	      test (funtab + i, s, 0, n);
119 	      test (funtab + i, s, 0x25, n);
120 	      test (funtab + i, s, 0xaa25, n);
121 	    }
122 	}
123       char *pass = funtab[i].test_mte && mte_enabled () ? "MTE PASS" : "PASS";
124       printf ("%s %s\n", err_count ? "FAIL" : pass, funtab[i].name);
125       if (err_count)
126 	r = -1;
127     }
128   return r;
129 }
130