1 /* 2 * memchr test. 3 * 4 * Copyright (c) 2020, Arm Limited. 5 * SPDX-License-Identifier: MIT 6 */ 7 8 #ifndef _GNU_SOURCE 9 #define _GNU_SOURCE 10 #endif 11 12 #include <stdint.h> 13 #include <stdio.h> 14 #include <stdlib.h> 15 #include <string.h> 16 #include <limits.h> 17 #include "mte.h" 18 #include "stringlib.h" 19 #include "stringtest.h" 20 21 #define F(x, mte) {#x, x, mte}, 22 23 static const struct fun 24 { 25 const char *name; 26 void *(*fun) (const void *s, int c, size_t n); 27 int test_mte; 28 } funtab[] = { 29 // clang-format off 30 F(memrchr, 0) 31 #if __aarch64__ 32 F(__memrchr_aarch64, 1) 33 #endif 34 {0, 0, 0} 35 // clang-format on 36 }; 37 #undef F 38 39 #define ALIGN 32 40 #define LEN 512 41 static char *sbuf; 42 43 static void * 44 alignup (void *p) 45 { 46 return (void *) (((uintptr_t) p + ALIGN) & -ALIGN); 47 } 48 49 static void 50 test (const struct fun *fun, int align, size_t seekpos, size_t len, 51 size_t maxlen) 52 { 53 char *src = alignup (sbuf); 54 char *s = src + align; 55 char *f = seekpos < maxlen ? s + seekpos : NULL; 56 int seekchar = 1; 57 void *p; 58 59 if (err_count >= ERR_LIMIT) 60 return; 61 if (len > LEN || seekpos > LEN || align > ALIGN) 62 abort (); 63 64 for (int i = 0; src + i < s; i++) 65 src[i] = seekchar; 66 for (int i = 0; i <= ALIGN; i++) 67 s[len + i] = seekchar; 68 for (int i = 0; i < len; i++) 69 s[i] = 'a' + (i & 31); 70 s[seekpos] = seekchar; 71 s[((len ^ align) & 1) && seekpos < maxlen ? seekpos - 1 : len] = seekchar; 72 73 s = tag_buffer (s, maxlen, fun->test_mte); 74 p = fun->fun (s, seekchar, maxlen); 75 untag_buffer (s, maxlen, fun->test_mte); 76 p = untag_pointer (p); 77 78 if (p != f) 79 { 80 ERR ("%s (%p, 0x%02x, %zu) returned %p, expected %p\n", fun->name, s, 81 seekchar, maxlen, p, f); 82 quote ("input", s, len); 83 } 84 } 85 86 int 87 main (void) 88 { 89 sbuf = mte_mmap (LEN + 3 * ALIGN); 90 int r = 0; 91 for (int i = 0; funtab[i].name; i++) 92 { 93 err_count = 0; 94 for (int a = 0; a < ALIGN; a++) 95 for (int n = 0; n < LEN; n++) 96 { 97 for (int sp = 0; sp < LEN; sp++) 98 test (funtab + i, a, sp, n, n); 99 } 100 char *pass = funtab[i].test_mte && mte_enabled () ? "MTE PASS" : "PASS"; 101 printf ("%s %s\n", err_count ? "FAIL" : pass, funtab[i].name); 102 if (err_count) 103 r = -1; 104 } 105 return r; 106 } 107