Debian Codegraph @

fuzzers/commit_graph_fuzzer.c

raw
1 /*
2 * libgit2 commit-graph fuzzer target.
3 *
4 * Copyright (C) the libgit2 contributors. All rights reserved.
5 *
6 * This file is part of libgit2, distributed under the GNU GPL v2 with
7 * a Linking Exception. For full terms see the included COPYING file.
8 */
9
10 #include <stdio.h>
11
12 #include "git2.h"
13
14 #include "common.h"
15 #include "str.h"
16 #include "futils.h"
17 #include "hash.h"
18 #include "commit_graph.h"
19
20 #include "standalone_driver.h"
21
22 int LLVMFuzzerInitialize(int *argc, char ***argv)
23 {
24 GIT_UNUSED(argc);
25 GIT_UNUSED(argv);
26
27 if (git_libgit2_init() < 0) {
28 fprintf(stderr, "Failed to initialize libgit2\n");
29 abort();
30 }
31 return 0;
32 }
33
34 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
35 {
36 git_commit_graph_file file = {{0}};
37 git_commit_graph_entry e;
38 git_str commit_graph_buf = GIT_STR_INIT;
39 unsigned char hash[GIT_HASH_SHA1_SIZE];
40 git_oid oid = GIT_OID_NONE;
41 bool append_hash = false;
42
43 if (size < 4)
44 return 0;
45
46 /*
47 * If the first byte in the stream has the high bit set, append the
48 * SHA1 hash so that the file is somewhat valid.
49 */
50 append_hash = *data & 0x80;
51 /* Keep a 4-byte alignment to avoid unaligned accesses. */
52 data += 4;
53 size -= 4;
54
55 if (append_hash) {
56 if (git_str_init(&commit_graph_buf, size + GIT_HASH_SHA1_SIZE) < 0)
57 goto cleanup;
58 if (git_hash_buf(hash, data, size, GIT_HASH_ALGORITHM_SHA1) < 0) {
59 fprintf(stderr, "Failed to compute the SHA1 hash\n");
60 abort();
61 }
62 memcpy(commit_graph_buf.ptr, data, size);
63 memcpy(commit_graph_buf.ptr + size, hash, GIT_HASH_SHA1_SIZE);
64
65 memcpy(oid.id, hash, GIT_OID_SHA1_SIZE);
66 } else {
67 git_str_attach_notowned(&commit_graph_buf, (char *)data, size);
68 }
69
70 if (git_commit_graph_file_parse(
71 &file,
72 (const unsigned char *)git_str_cstr(&commit_graph_buf),
73 git_str_len(&commit_graph_buf))
74 < 0)
75 goto cleanup;
76
77 /* Search for any oid, just to exercise that codepath. */
78 if (git_commit_graph_entry_find(&e, &file, &oid, GIT_OID_SHA1_HEXSIZE) < 0)
79 goto cleanup;
80
81 cleanup:
82 git_commit_graph_file_close(&file);
83 git_str_dispose(&commit_graph_buf);
84 return 0;
85 }