Debian Codegraph @

fuzzers/midx_fuzzer.c

raw
1 /*
2 * libgit2 multi-pack-index 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 "futils.h"
16 #include "hash.h"
17 #include "midx.h"
18
19 #include "standalone_driver.h"
20
21 int LLVMFuzzerInitialize(int *argc, char ***argv)
22 {
23 GIT_UNUSED(argc);
24 GIT_UNUSED(argv);
25
26 if (git_libgit2_init() < 0) {
27 fprintf(stderr, "Failed to initialize libgit2\n");
28 abort();
29 }
30 return 0;
31 }
32
33 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
34 {
35 git_midx_file idx = {{0}};
36 git_midx_entry e;
37 git_str midx_buf = GIT_STR_INIT;
38 unsigned char hash[GIT_HASH_SHA1_SIZE];
39 git_oid oid = GIT_OID_NONE;
40 bool append_hash = false;
41
42 if (size < 4)
43 return 0;
44
45 /*
46 * If the first byte in the stream has the high bit set, append the
47 * SHA1 hash so that the packfile is somewhat valid.
48 */
49 append_hash = *data & 0x80;
50 /* Keep a 4-byte alignment to avoid unaligned accesses. */
51 data += 4;
52 size -= 4;
53
54 if (append_hash) {
55 if (git_str_init(&midx_buf, size + GIT_HASH_SHA1_SIZE) < 0)
56 goto cleanup;
57 if (git_hash_buf(hash, data, size, GIT_HASH_ALGORITHM_SHA1) < 0) {
58 fprintf(stderr, "Failed to compute the SHA1 hash\n");
59 abort();
60 }
61 memcpy(midx_buf.ptr, data, size);
62 memcpy(midx_buf.ptr + size, hash, GIT_HASH_SHA1_SIZE);
63
64 memcpy(oid.id, hash, GIT_OID_SHA1_SIZE);
65 } else {
66 git_str_attach_notowned(&midx_buf, (char *)data, size);
67 }
68
69 if (git_midx_parse(&idx, (const unsigned char *)git_str_cstr(&midx_buf), git_str_len(&midx_buf)) < 0)
70 goto cleanup;
71
72 /* Search for any oid, just to exercise that codepath. */
73 if (git_midx_entry_find(&e, &idx, &oid, GIT_OID_SHA1_HEXSIZE) < 0)
74 goto cleanup;
75
76 cleanup:
77 git_midx_close(&idx);
78 git_str_dispose(&midx_buf);
79 return 0;
80 }