oss-fuzz/projects/file/magic_fuzzer.cc

55 lines
1.5 KiB
C++
Raw Normal View History

2016-11-03 17:20:34 +00:00
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2016-11-07 20:41:32 +00:00
#include <libgen.h>
2016-11-03 17:20:34 +00:00
#include <stddef.h>
#include <stdint.h>
2016-11-05 00:04:01 +00:00
#include <stdio.h>
#include <stdlib.h>
2016-11-07 20:41:32 +00:00
#include <string>
2016-11-03 17:20:34 +00:00
#include <magic.h>
2016-11-05 00:04:01 +00:00
struct Environment {
2016-11-07 20:41:32 +00:00
Environment(std::string data_dir) {
2016-11-05 00:04:01 +00:00
magic = magic_open(MAGIC_NONE);
2016-11-07 20:41:32 +00:00
std::string magic_path = data_dir + "/magic";
if (magic_load(magic, magic_path.c_str())) {
2016-11-05 00:04:01 +00:00
fprintf(stderr, "error loading magic file: %s\n", magic_error(magic));
exit(1);
}
}
magic_t magic;
};
2016-11-07 20:41:32 +00:00
static Environment* env;
extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) {
char* exe_path = (*argv)[0];
// dirname() can modify its argument.
char* exe_path_copy = strdup(exe_path);
char* dir = dirname(exe_path_copy);
2016-11-07 20:41:32 +00:00
env = new Environment(dir);
free(exe_path_copy);
2016-11-07 20:41:32 +00:00
return 0;
}
2016-11-05 00:04:01 +00:00
2016-11-03 17:20:34 +00:00
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (size < 1)
return 0;
2016-11-07 20:41:32 +00:00
magic_buffer(env->magic, data, size);
2016-11-03 17:20:34 +00:00
return 0;
}