memcmp.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <malloc.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include "utils.h"
  6. #define SIZE 256
  7. #define ITERATIONS 10000
  8. int test_memcmp(const void *s1, const void *s2, size_t n);
  9. /* test all offsets and lengths */
  10. static void test_one(char *s1, char *s2)
  11. {
  12. unsigned long offset, size;
  13. for (offset = 0; offset < SIZE; offset++) {
  14. for (size = 0; size < (SIZE-offset); size++) {
  15. int x, y;
  16. unsigned long i;
  17. y = memcmp(s1+offset, s2+offset, size);
  18. x = test_memcmp(s1+offset, s2+offset, size);
  19. if (((x ^ y) < 0) && /* Trick to compare sign */
  20. ((x | y) != 0)) { /* check for zero */
  21. printf("memcmp returned %d, should have returned %d (offset %ld size %ld)\n", x, y, offset, size);
  22. for (i = offset; i < offset+size; i++)
  23. printf("%02x ", s1[i]);
  24. printf("\n");
  25. for (i = offset; i < offset+size; i++)
  26. printf("%02x ", s2[i]);
  27. printf("\n");
  28. abort();
  29. }
  30. }
  31. }
  32. }
  33. static int testcase(void)
  34. {
  35. char *s1;
  36. char *s2;
  37. unsigned long i;
  38. s1 = memalign(128, SIZE);
  39. if (!s1) {
  40. perror("memalign");
  41. exit(1);
  42. }
  43. s2 = memalign(128, SIZE);
  44. if (!s2) {
  45. perror("memalign");
  46. exit(1);
  47. }
  48. srandom(1);
  49. for (i = 0; i < ITERATIONS; i++) {
  50. unsigned long j;
  51. unsigned long change;
  52. for (j = 0; j < SIZE; j++)
  53. s1[j] = random();
  54. memcpy(s2, s1, SIZE);
  55. /* change one byte */
  56. change = random() % SIZE;
  57. s2[change] = random() & 0xff;
  58. test_one(s1, s2);
  59. }
  60. srandom(1);
  61. for (i = 0; i < ITERATIONS; i++) {
  62. unsigned long j;
  63. unsigned long change;
  64. for (j = 0; j < SIZE; j++)
  65. s1[j] = random();
  66. memcpy(s2, s1, SIZE);
  67. /* change multiple bytes, 1/8 of total */
  68. for (j = 0; j < SIZE / 8; j++) {
  69. change = random() % SIZE;
  70. s2[change] = random() & 0xff;
  71. }
  72. test_one(s1, s2);
  73. }
  74. return 0;
  75. }
  76. int main(void)
  77. {
  78. return test_harness(testcase, "memcmp");
  79. }