[libc-commits] [libc] [libc] add hashtable fuzzing (PR #87949)

Schrodinger ZHU Yifan via libc-commits libc-commits at lists.llvm.org
Fri Apr 19 14:51:29 PDT 2024


================
@@ -0,0 +1,159 @@
+#include "src/__support/CPP/new.h"
+#include "src/__support/CPP/optional.h"
+#include "src/__support/HashTable/table.h"
+#include "src/string/memcpy.h"
+#include <search.h>
+#include <stdint.h>
+namespace LIBC_NAMESPACE {
+
+enum class Action { Find, Insert, CrossCheck };
+static uint8_t *global_buffer = nullptr;
+static size_t remaining = 0;
+
+static cpp::optional<uint8_t> next_u8() {
+  if (remaining == 0)
+    return cpp::nullopt;
+  uint8_t result = *global_buffer;
+  global_buffer++;
+  remaining--;
+  return result;
+}
+
+static cpp::optional<uint64_t> next_uint64() {
+  uint64_t result;
+  if (remaining < sizeof(result))
+    return cpp::nullopt;
+  memcpy(&result, global_buffer, sizeof(result));
+  global_buffer += sizeof(result);
+  remaining -= sizeof(result);
+  return result;
+}
+
+static cpp::optional<Action> next_action() {
+  if (cpp::optional<uint8_t> action = next_u8()) {
+    switch (*action % 3) {
+    case 0:
+      return Action::Find;
+    case 1:
+      return Action::Insert;
+    case 2:
+      return Action::CrossCheck;
+    }
+  }
+  return cpp::nullopt;
+}
+
+static cpp::optional<char *> next_cstr() {
+  char *result = reinterpret_cast<char *>(global_buffer);
+  if (cpp::optional<uint8_t> len = next_u8()) {
+    uint64_t length;
+    for (length = 0; length < *len; length++) {
+      if (length >= remaining)
+        return cpp::nullopt;
+      if (*global_buffer == '\0')
+        break;
+    }
+    if (length >= remaining)
+      return cpp::nullopt;
+    global_buffer[length] = '\0';
+    global_buffer += length + 1;
+    remaining -= length + 1;
+    return result;
+  }
+  return cpp::nullopt;
+}
+
+#define get_value(op)                                                          \
----------------
SchrodingerZhu wrote:

If there is not enough data for next action, we will attempt a early return. The macro is designed to be of the same effect of the [`question mark operator` in Rust](https://doc.rust-lang.org/rust-by-example/std/result/question_mark.html).

https://github.com/llvm/llvm-project/pull/87949


More information about the libc-commits mailing list