Home | History | Annotate | Download | only in fuzzing
      1 /* Copyright 2016 Google Inc. All Rights Reserved.
      2 
      3 Licensed under the Apache License, Version 2.0 (the "License");
      4 you may not use this file except in compliance with the License.
      5 You may obtain a copy of the License at
      6 
      7     http://www.apache.org/licenses/LICENSE-2.0
      8 
      9 Unless required by applicable law or agreed to in writing, software
     10 distributed under the License is distributed on an "AS IS" BASIS,
     11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 See the License for the specific language governing permissions and
     13 limitations under the License.
     14 ==============================================================================*/
     15 
     16 #include "tensorflow/cc/ops/standard_ops.h"
     17 #include "tensorflow/core/kernels/fuzzing/fuzz_session.h"
     18 
     19 namespace tensorflow {
     20 namespace fuzzing {
     21 
     22 class FuzzEncodeJpeg : public FuzzSession {
     23   SINGLE_INPUT_OP_BUILDER(DT_UINT8, EncodeJpeg);
     24 
     25   void FuzzImpl(const uint8_t* data, size_t size) final {
     26     if (size < 6) return;
     27 
     28     // Pick random channels and aspect ratio, and then set the
     29     // input based upon the aspect ratio and size.
     30     int64 channels = (data[0] % 2) * 2 + 1;  // 1, 3
     31     int64 height = data[1] + (data[2] << 8);
     32     int64 width = data[2] + (data[3] << 8);
     33     if (width == 0) return;
     34 
     35     // TODO(dga): kcc@ notes: better to use actual supplied h, w and then
     36     // trim them if needed to ensure w*h <= size-4.
     37     double hw_ratio = height / width;
     38     int64 remaining_bytes = size - 5;
     39     int64 pixels = remaining_bytes / channels;
     40     height = static_cast<int64>(floor(sqrt(hw_ratio * pixels)));
     41     if (height == 0) return;
     42     width = static_cast<int64>(floor(pixels / height));
     43     if (width == 0) return;
     44     size_t actual_pixels = height * width * channels;
     45     if (actual_pixels == 0) return;
     46 
     47     // TODO(dga):  Generalize this by borrowing the AsTensor logic
     48     // from tf testing, once we have a few more fuzzers written.
     49     Tensor input_tensor(tensorflow::DT_UINT8,
     50                         TensorShape({height, width, channels}));
     51     auto flat_tensor = input_tensor.flat<uint8>();
     52     for (size_t i = 0; i < actual_pixels; i++) {
     53       flat_tensor(i) = data[i];
     54     }
     55     // TODO(b/32704451): Don't just ignore the ::tensorflow::Status object!
     56     RunOneInput(input_tensor).IgnoreError();
     57   }
     58 };
     59 
     60 STANDARD_TF_FUZZ_FUNCTION(FuzzEncodeJpeg);
     61 
     62 }  // end namespace fuzzing
     63 }  // end namespace tensorflow
     64