From 6b5c2ad2d3cdfa24935e60ba5c4d166eb1ca94f4 Mon Sep 17 00:00:00 2001
From: Zihao Yu <yuzihao@ict.ac.cn>
Date: Sat, 1 Jul 2023 00:56:02 +0800
Subject: [PATCH] tests,cpu-test: add more tests from movfuscator

---
 tests/cpu-tests/tests/crc32.c    | 47 ++++++++++++++++++++++++++++++++
 tests/cpu-tests/tests/mersenne.c | 34 +++++++++++++++++++++++
 2 files changed, 81 insertions(+)
 create mode 100644 tests/cpu-tests/tests/crc32.c
 create mode 100644 tests/cpu-tests/tests/mersenne.c

diff --git a/tests/cpu-tests/tests/crc32.c b/tests/cpu-tests/tests/crc32.c
new file mode 100644
index 0000000..3f694c5
--- /dev/null
+++ b/tests/cpu-tests/tests/crc32.c
@@ -0,0 +1,47 @@
+/* from http://rosettacode.org/wiki/CRC-32#C */
+
+#include <klib-macros.h>
+#include "trap.h"
+
+#define STR "The quick brown fox jumps over the lazy dog"
+#define STRLEN (sizeof(STR) - 1)
+ 
+uint32_t rc_crc32(uint32_t crc, const char *buf, size_t len) {
+	static uint32_t table[256];
+	static int have_table = 0;
+	uint32_t rem;
+	uint8_t octet;
+	int i, j;
+	const char *p, *q;
+ 
+	/* This check is not thread safe; there is no mutex. */
+	if (have_table == 0) {
+		/* Calculate CRC table. */
+		for (i = 0; i < 256; i++) {
+			rem = i;  /* remainder from polynomial division */
+			for (j = 0; j < 8; j++) {
+				if (rem & 1) {
+					rem >>= 1;
+					rem ^= 0xedb88320;
+				} else
+					rem >>= 1;
+			}
+			table[i] = rem;
+		}
+		have_table = 1;
+	}
+ 
+	crc = ~crc;
+	q = buf + len;
+	for (p = buf; p < q; p++) {
+		octet = *p;  /* Cast to unsigned octet. */
+		crc = (crc >> 8) ^ table[(crc & 0xff) ^ octet];
+	}
+	return ~crc;
+}
+ 
+int main() {
+  uint32_t res = rc_crc32(0, STR, STRLEN);
+  check(res == 0x414FA339);
+	return 0;
+}
diff --git a/tests/cpu-tests/tests/mersenne.c b/tests/cpu-tests/tests/mersenne.c
new file mode 100644
index 0000000..8eab567
--- /dev/null
+++ b/tests/cpu-tests/tests/mersenne.c
@@ -0,0 +1,34 @@
+/* adapted from http://rosettacode.org/wiki/Factors_of_a_Mersenne_number#C */
+#include "trap.h"
+
+int isPrime(int n) {
+  int d = 5;
+  if (n % 2 == 0) return n==2;
+  if (n % 3 == 0) return n==3;
+  while (d * d <= n) {
+    if (n % d == 0) return 0;
+    d += 2;
+    if (n % d == 0) return 0;
+    d += 4;
+  }
+  return 1;
+}
+
+int main() {
+  int i, d, p, r, q = 929;
+  if (!isPrime(q)) return 1; 
+  r = q;
+  while (r > 0) r <<= 1;
+  d = 2 * q + 1;
+  do {
+    for (p = r, i = 1; p; p <<= 1) {
+      i = ((long long)i * i) % d;
+      if (p < 0) i *= 2;
+      if (i > d) i -= d;
+    }
+    if (i != 1) d += 2 * q;
+    else break;
+  } while(1);
+  check(d == 13007);
+  return 0;
+}