/src/cmp_tool/test/fuzz/fuzz_helpers.c
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * Copyright (c) Meta Platforms, Inc. and affiliates. |
3 | | * All rights reserved. |
4 | | * |
5 | | * This source code is licensed under both the BSD-style license (found in the |
6 | | * LICENSE.BSD-3.Zstandard file in the 3rdparty_licenses directory) and the GPLv2 |
7 | | * (found in the LICENSE.GPL-2 file in the 3rdparty_licenses directory). |
8 | | * You may select, at your option, one of the above-listed licenses. |
9 | | */ |
10 | | |
11 | | /* |
12 | | * Modifications made by |
13 | | * @author Dominik Loidolt (dominik.loidolt@univie.ac.at) |
14 | | * @date 2025 |
15 | | * |
16 | | * - add FUZZ_buf_to_file |
17 | | * - add FUZZ_delete_file |
18 | | * |
19 | | * Modifications are also licensed under the same license for consistency |
20 | | */ |
21 | | |
22 | | /** |
23 | | * Helper functions for fuzzing. |
24 | | */ |
25 | | |
26 | | #include <stddef.h> |
27 | | #include <stdlib.h> |
28 | | #include <unistd.h> |
29 | | #include <string.h> |
30 | | #include <errno.h> |
31 | | |
32 | | #include "fuzz_helpers.h" |
33 | | #include "fuzz_data_producer.h" |
34 | | |
35 | | |
36 | | void *FUZZ_malloc(size_t size) |
37 | 14.0k | { |
38 | 14.0k | if (size > 0) { |
39 | 12.4k | void *const mem = malloc(size); |
40 | | |
41 | 12.4k | FUZZ_ASSERT(mem); |
42 | 12.4k | return mem; |
43 | 12.4k | } |
44 | 1.61k | return NULL; |
45 | 14.0k | } |
46 | | |
47 | | |
48 | | int FUZZ_delete_file(const char *path_name) |
49 | 7.02k | { |
50 | 7.02k | int const ret = unlink(path_name); |
51 | | |
52 | 7.02k | FUZZ_ASSERT(ret != -1); |
53 | | |
54 | 7.02k | free((void *)path_name); |
55 | | |
56 | 7.02k | return ret; |
57 | 7.02k | } |
58 | | |
59 | | |
60 | | char *FUZZ_buf_to_file(const uint8_t *buf, size_t size) |
61 | 7.02k | { |
62 | 7.02k | int fd, ret_close; |
63 | 7.02k | size_t pos = 0; |
64 | | |
65 | 7.02k | char *path_name = strdup(FUZZ_TMP_DIR "/fuzz-XXXXXX"); |
66 | | |
67 | 7.02k | FUZZ_ASSERT(path_name != NULL); |
68 | | |
69 | 7.02k | fd = mkstemp(path_name); |
70 | 7.02k | FUZZ_ASSERT_MSG(fd != 1, path_name); |
71 | | |
72 | 10.8k | while (pos < size) { |
73 | 3.82k | ssize_t bytes_written = write(fd, &buf[pos], size - pos); |
74 | | |
75 | 3.82k | if (bytes_written == -1 && errno == EINTR) |
76 | 0 | continue; |
77 | | |
78 | 3.82k | FUZZ_ASSERT(bytes_written != -1); |
79 | | |
80 | 3.82k | pos += (size_t)bytes_written; |
81 | 3.82k | } |
82 | | |
83 | 7.02k | ret_close = close(fd); |
84 | 7.02k | FUZZ_ASSERT(ret_close != 1); |
85 | | |
86 | 7.02k | return path_name; |
87 | 7.02k | } |