[llvm] [CAS] Add llvm-cas-fuzzer for ObjectStore::validate() (PR #190635)
Paul Kirth via llvm-commits
llvm-commits at lists.llvm.org
Mon Apr 6 11:31:57 PDT 2026
================
@@ -0,0 +1,388 @@
+//===-- cas-fuzzer.cpp - Fuzzer for CAS ObjectStore::validate() -----------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Fuzzer for on-disk CAS validation. Creates a valid CAS database, stores
+// objects, corrupts the on-disk files using fuzzer-provided bytes, then calls
+// validate(). The invariant: validate() must either succeed or return an error,
+// never crash.
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/ADT/ScopeExit.h"
+#include "llvm/CAS/ActionCache.h"
+#include "llvm/CAS/BuiltinUnifiedCASDatabases.h"
+#include "llvm/CAS/ObjectStore.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/ScopedPrinter.h"
+#include "llvm/Support/raw_ostream.h"
+#include <cstdint>
+#include <cstring>
+
+using namespace llvm;
+using namespace llvm::cas;
+
+namespace {
+
+/// Read a little-endian uint32 from Data, or 0 if not enough bytes.
+static uint32_t readU32(const uint8_t *Data, size_t Size, size_t Offset) {
+ if (Offset + 4 > Size)
+ return 0;
+ return support::endian::read32le(Data + Offset);
+}
+
+/// Read a little-endian uint16 from Data, or 0 if not enough bytes.
+static uint16_t readU16(const uint8_t *Data, size_t Size, size_t Offset) {
+ if (Offset + 2 > Size)
+ return 0;
+ return support::endian::read16le(Data + Offset);
+}
+
+/// Find the versioned subdirectory (v1.N) inside the CAS root.
+static std::string findVersionedSubdir(StringRef CASDir) {
+ std::error_code EC;
+ std::string Best;
+ uint64_t BestOrder = 0;
+ for (sys::fs::directory_iterator DirI(CASDir, EC), DirE; !EC && DirI != DirE;
+ DirI.increment(EC)) {
+ if (DirI->type() != sys::fs::file_type::directory_file)
+ continue;
+ StringRef Name = sys::path::filename(DirI->path());
+ if (!Name.starts_with("v1."))
+ continue;
+ uint64_t Order;
+ if (Name.substr(3).getAsInteger(10, Order))
+ continue;
+ if (Best.empty() || Order > BestOrder) {
+ Best = DirI->path();
+ BestOrder = Order;
+ }
+ }
+ return Best;
+}
+
+/// Collect paths of files matching a prefix in a directory.
+static void collectFilesWithPrefix(StringRef Dir, StringRef Prefix,
+ SmallVectorImpl<std::string> &Results) {
+ std::error_code EC;
+ for (sys::fs::directory_iterator DirI(Dir, EC), DirE; !EC && DirI != DirE;
+ DirI.increment(EC)) {
+ StringRef Name = sys::path::filename(DirI->path());
+ if (Name.starts_with(Prefix))
+ Results.push_back(DirI->path());
+ }
+}
+
+/// Read an entire file into a buffer.
+static bool readFileBytes(StringRef Path, SmallVectorImpl<char> &Buf) {
+ auto MBOrErr = MemoryBuffer::getFile(Path, /*IsText=*/false,
+ /*RequiresNullTerminator=*/false);
+ if (!MBOrErr)
+ return false;
+ Buf.assign((*MBOrErr)->getBufferStart(), (*MBOrErr)->getBufferEnd());
+ return true;
+}
+
+/// Write buffer contents to a file, replacing it entirely.
+static bool writeFileBytes(StringRef Path, ArrayRef<char> Buf) {
+ std::error_code EC;
+ raw_fd_ostream OS(Path, EC, sys::fs::OF_None);
+ if (EC)
+ return false;
+ OS.write(Buf.data(), Buf.size());
+ return !OS.has_error();
+}
+
+/// Create a CAS database and store some baseline objects.
+/// Returns the ObjectRefs for stored objects via LeafRef.
+static bool createAndPopulateCAS(StringRef TmpDir,
+ std::unique_ptr<ObjectStore> &CAS,
+ std::unique_ptr<ActionCache> &AC) {
+ auto Result = createOnDiskUnifiedCASDatabases(TmpDir);
+ if (!Result) {
+ consumeError(Result.takeError());
+ return false;
+ }
+ CAS = std::move(Result->first);
+ AC = std::move(Result->second);
+
+ // Store a leaf node (no refs, small data).
+ const char LeafData[] = "hello-cas-fuzzer-leaf-data";
+ auto Leaf = CAS->store({}, arrayRefFromStringRef<char>(LeafData));
+ if (!Leaf) {
+ consumeError(Leaf.takeError());
+ return false;
+ }
+
+ // Store a node with a ref to the leaf.
+ const char NodeData[] = "node-with-one-ref";
+ auto Node1 = CAS->store({*Leaf}, arrayRefFromStringRef<char>(NodeData));
+ if (!Node1) {
+ consumeError(Node1.takeError());
+ return false;
+ }
+
+ // Store a node referencing both previous nodes.
+ const char Node2Data[] = "node-with-two-refs";
+ auto Node2 =
+ CAS->store({*Leaf, *Node1}, arrayRefFromStringRef<char>(Node2Data));
+ if (!Node2) {
+ consumeError(Node2.takeError());
+ return false;
+ }
+
+ // Store a larger data node to potentially exercise different size encodings.
+ std::string LargeData(4096, 'X');
+ auto LargeNode =
+ CAS->store({}, arrayRefFromStringRef<char>(StringRef(LargeData)));
+ if (!LargeNode) {
+ consumeError(LargeNode.takeError());
+ return false;
+ }
+
+ return true;
+}
+
+/// Apply byte-level mutations to a file.
+static void applyByteMutations(StringRef Path, const uint8_t *Data,
+ size_t Size) {
+ SmallVector<char> Buf;
+ if (!readFileBytes(Path, Buf) || Buf.empty())
+ return;
+
+ // Parse as 7-byte chunks: [offset(4)][op(1)][value(1)][unused(1)]
+ for (size_t I = 0; I + 6 <= Size; I += 7) {
+ uint32_t Offset = readU32(Data, Size, I) % Buf.size();
+ uint8_t Op = Data[I + 4] % 3;
+ uint8_t Value = Data[I + 5];
+ switch (Op) {
+ case 0: // XOR
+ Buf[Offset] ^= Value;
+ break;
+ case 1: // SET
+ Buf[Offset] = Value;
+ break;
+ case 2: // Zero
+ Buf[Offset] = 0;
+ break;
+ }
+ }
+ writeFileBytes(Path, Buf);
+}
+
+/// Truncate a file to a given fraction of its size.
+static void truncateFile(StringRef Path, uint8_t Fraction) {
+ SmallVector<char> Buf;
+ if (!readFileBytes(Path, Buf) || Buf.empty())
+ return;
+ // Fraction is 0-255, map to 0-100% of file size.
+ size_t NewSize = (size_t)((uint64_t)Buf.size() * Fraction / 255);
+ // Don't zero out the size.
+ if (NewSize == 0)
+ NewSize = 1;
+ Buf.resize(NewSize);
+ writeFileBytes(Path, Buf);
+}
+
+/// Append garbage bytes to a file.
+static void appendGarbage(StringRef Path, const uint8_t *Data, size_t Size) {
+ SmallVector<char> Buf;
+ if (!readFileBytes(Path, Buf))
+ return;
+ Buf.append(reinterpret_cast<const char *>(Data),
+ reinterpret_cast<const char *>(Data + Size));
+ writeFileBytes(Path, Buf);
+}
+
+/// Zero out a range in a file.
+static void zeroRange(StringRef Path, uint32_t Offset, uint16_t Length) {
+ SmallVector<char> Buf;
+ if (!readFileBytes(Path, Buf) || Buf.empty())
+ return;
+ size_t Start = Offset % Buf.size();
+ size_t End = std::min(Start + (size_t)Length, Buf.size());
+ std::memset(Buf.data() + Start, 0, End - Start);
+ writeFileBytes(Path, Buf);
+}
+
+/// Corrupt standalone files (obj.*, leaf.*, leaf+0.*).
+static void corruptStandaloneFiles(StringRef SubDir, const uint8_t *Data,
----------------
ilovepi wrote:
Would this be easier if you used an `ArrayRef<uint8_t>` over explicit ptr and size? the API may be a little nicer, and you'd have access to the ADT helpers.
https://github.com/llvm/llvm-project/pull/190635
More information about the llvm-commits
mailing list