1/*
2 * strcpy 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
18static const struct fun
19{
20  const char *name;
21  char *(*fun) (char *dest, const char *src);
22  int test_mte;
23} funtab[] = {
24  // clang-format off
25  F(strcpy, 0)
26#if __aarch64__
27  F(__strcpy_aarch64, 0)
28  F(__strcpy_aarch64_mte, 1)
29# if __ARM_FEATURE_SVE
30  F(__strcpy_aarch64_sve, 1)
31# endif
32#elif __arm__ && defined (__thumb2__) && !defined (__thumb__)
33  F(__strcpy_arm, 0)
34#endif
35  {0, 0, 0}
36  // clang-format on
37};
38#undef F
39
40#define ALIGN 32
41#define LEN 512
42static char *dbuf;
43static char *sbuf;
44static char wbuf[LEN + 3 * ALIGN];
45
46static void *
47alignup (void *p)
48{
49  return (void *) (((uintptr_t) p + ALIGN - 1) & -ALIGN);
50}
51
52static void
53test (const struct fun *fun, int dalign, int salign, int len)
54{
55  char *src = alignup (sbuf);
56  char *dst = alignup (dbuf);
57  char *want = wbuf;
58  char *s = src + salign;
59  char *d = dst + dalign;
60  char *w = want + dalign;
61  void *p;
62  int i;
63
64  if (err_count >= ERR_LIMIT)
65    return;
66  if (len > LEN || dalign >= ALIGN || salign >= ALIGN)
67    abort ();
68  for (i = 0; i < len + ALIGN; i++)
69    {
70      src[i] = '?';
71      want[i] = dst[i] = '*';
72    }
73  for (int i = 0; src + i < s; i++)
74    src[i] = 0;
75  for (int i = 1; i <= ALIGN; i++)
76    s[len + i] = (len + salign) & 1 ? 1 : 0;
77  for (i = 0; i < len; i++)
78    s[i] = w[i] = 'a' + (i & 31);
79  s[len] = w[len] = '\0';
80
81  s = tag_buffer (s, len + 1, fun->test_mte);
82  d = tag_buffer (d, len + 1, fun->test_mte);
83  p = fun->fun (d, s);
84  untag_buffer (s, len + 1, fun->test_mte);
85  untag_buffer (d, len + 1, fun->test_mte);
86
87  if (p != d)
88    ERR ("%s (%p,..) returned %p\n", fun->name, d, p);
89
90  for (i = 0; i < len + ALIGN; i++)
91    {
92      if (dst[i] != want[i])
93	{
94	  ERR ("%s (align %d, align %d, %d) failed\n",
95	       fun->name, dalign, salign, len);
96	  quoteat ("got", dst, len + ALIGN, i);
97	  quoteat ("want", want, len + ALIGN, i);
98	  break;
99	}
100    }
101}
102
103int
104main (void)
105{
106  sbuf = mte_mmap (LEN + 3 * ALIGN);
107  dbuf = mte_mmap (LEN + 3 * ALIGN);
108  int r = 0;
109  for (int i = 0; funtab[i].name; i++)
110    {
111      err_count = 0;
112      for (int d = 0; d < ALIGN; d++)
113	for (int s = 0; s < ALIGN; s++)
114	  for (int n = 0; n < LEN; n++)
115	    test (funtab + i, d, s, n);
116
117      char *pass = funtab[i].test_mte && mte_enabled () ? "MTE PASS" : "PASS";
118      printf ("%s %s\n", err_count ? "FAIL" : pass, funtab[i].name);
119      if (err_count)
120	r = -1;
121    }
122  return r;
123}
124