1 // Copyright 2019 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <algorithm>
6 #include <array>
7 #include <cassert>
8 #include <cstring>
9
10 #include "third_party/pffft/src/pffft.h"
11
12 namespace {
13
14 #if defined(TRANSFORM_REAL)
15 // Real FFT.
16 constexpr pffft_transform_t kTransform = PFFFT_REAL;
17 constexpr size_t kSizeOfOneSample = sizeof(float);
18 #elif defined(TRANSFORM_COMPLEX)
19 // Complex FFT.
20 constexpr pffft_transform_t kTransform = PFFFT_COMPLEX;
21 constexpr size_t kSizeOfOneSample = 2 * sizeof(float); // Real plus imaginary.
22 #else
23 #error FFT transform type not defined.
24 #endif
25
IsValidSize(size_t n)26 bool IsValidSize(size_t n) {
27 if (n == 0) {
28 return false;
29 }
30 // PFFFT only supports transforms for inputs of length N of the form
31 // N = (2^a)*(3^b)*(5^c) where a >= 5, b >=0, c >= 0.
32 constexpr std::array<int, 3> kFactors = {2, 3, 5};
33 std::array<int, kFactors.size()> factorization{};
34 for (size_t i = 0; i < kFactors.size(); ++i) {
35 const int factor = kFactors[i];
36 while (n % factor == 0) {
37 n /= factor;
38 factorization[i]++;
39 }
40 }
41 return factorization[0] >= 5 && n == 1;
42 }
43
AllocatePffftBuffer(size_t number_of_bytes)44 float* AllocatePffftBuffer(size_t number_of_bytes) {
45 return static_cast<float*>(pffft_aligned_malloc(number_of_bytes));
46 }
47
48 } // namespace
49
50 // Entry point for LibFuzzer.
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)51 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
52 // Set the number of FFT points to use |data| as input vector.
53 // The latter is truncated if the number of bytes is not an integer
54 // multiple of the size of one sample (which is either a real or a complex
55 // floating point number).
56 const size_t fft_size = size / kSizeOfOneSample;
57 if (!IsValidSize(fft_size)) {
58 return 0;
59 }
60
61 const size_t number_of_bytes = fft_size * kSizeOfOneSample;
62 assert(number_of_bytes <= size);
63
64 // Allocate input and output buffers.
65 float* in = AllocatePffftBuffer(number_of_bytes);
66 float* out = AllocatePffftBuffer(number_of_bytes);
67
68 // Copy input data.
69 std::memcpy(in, reinterpret_cast<const float*>(data), number_of_bytes);
70
71 // Setup FFT.
72 PFFFT_Setup* pffft_setup = pffft_new_setup(fft_size, kTransform);
73
74 // Call different PFFFT functions to maximize the coverage.
75 pffft_transform(pffft_setup, in, out, nullptr, PFFFT_FORWARD);
76 pffft_zconvolve_accumulate(pffft_setup, out, out, out, 1.f);
77 pffft_transform_ordered(pffft_setup, in, out, nullptr, PFFFT_BACKWARD);
78
79 // Release memory.
80 pffft_aligned_free(in);
81 pffft_aligned_free(out);
82 pffft_destroy_setup(pffft_setup);
83
84 return 0;
85 }
86