• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2016 Google Inc.
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 #include <libgen.h>
16 #include <stddef.h>
17 #include <stdint.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string>
21 
22 #include <magic.h>
23 
24 struct Environment {
EnvironmentEnvironment25   Environment(std::string data_dir) {
26     magic = magic_open(MAGIC_NONE);
27     std::string magic_path = data_dir + "/magic";
28     if (magic_load(magic, magic_path.c_str())) {
29       fprintf(stderr, "error loading magic file: %s\n", magic_error(magic));
30       exit(1);
31     }
32   }
33 
34   magic_t magic;
35 };
36 
37 static Environment* env;
38 
LLVMFuzzerInitialize(int * argc,char *** argv)39 extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) {
40   char* exe_path = (*argv)[0];
41   // dirname() can modify its argument.
42   char* exe_path_copy = strdup(exe_path);
43   char* dir = dirname(exe_path_copy);
44   env = new Environment(dir);
45   free(exe_path_copy);
46   return 0;
47 }
48 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)49 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
50   if (size < 1)
51     return 0;
52   magic_buffer(env->magic, data, size);
53   return 0;
54 }
55