1 /*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <cstdint>
18
19 #include <fuzzer/FuzzedDataProvider.h>
20
21 extern "C" {
22 #include "libufdt_sysdeps.h"
23 #include "ufdt_overlay.h"
24 }
25
26 /* Count split value, plus 1 byte for dto and overlay each */
27 constexpr uint32_t kMinData = sizeof(uint32_t) + 2;
28
29 constexpr uint32_t kMaxData = 1024 * 512;
30
31 /* libFuzzer driver.
32 * We need two dtb's to test merging, so split the input data block, using
33 * the first 4 bytes to give the dtb length, the rest being overlay.
34 * The mkcorpus helper program can construct these files.
35 */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)36 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
37 /* Bound input size */
38 if (size < kMinData || size > kMaxData) {
39 return 0;
40 }
41
42 FuzzedDataProvider fdp(data, size);
43
44 /* Read fixed length header */
45 auto hdr = fdp.ConsumeBytes<uint8_t>(4);
46
47 /* Extract the length, network byte order */
48 const uint32_t dtb_len = hdr[0] << 24 | hdr[1] << 16 | hdr[2] << 8 | hdr[3];
49
50 /* Ensure the dtb and overlay are non-zero length */
51 if (dtb_len == 0 || dtb_len >= size - 1) {
52 return 0;
53 }
54
55 auto dtb = fdp.ConsumeBytes<uint8_t>(dtb_len);
56 auto overlay = fdp.ConsumeRemainingBytes<uint8_t>();
57
58 /* Check headers */
59 auto fdt_dtb = ufdt_install_blob(dtb.data(), dtb.size());
60 auto fdt_overlay = ufdt_install_blob(overlay.data(), overlay.size());
61
62 if (!fdt_dtb || !fdt_overlay) {
63 return 0;
64 }
65
66 struct fdt_header *res =
67 ufdt_apply_overlay(fdt_dtb, dtb.size(), fdt_overlay, overlay.size());
68
69 if (res) {
70 dto_free(res);
71 }
72
73 return 0;
74 }
75