aboutsummaryrefslogtreecommitdiffhomepage
path: root/projects/unrar/unrar_fuzzer.cc
blob: 29cfaf4f37a3fb59714ca1b91577ca6b0236bfce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <stddef.h>
#include <stdint.h>

#include <filesystem>
#include <fstream>
#include <memory>
#include <string>
#include <system_error>
#include <unistd.h>

#include "rar.hpp"

namespace fs = std::__fs::filesystem;

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  // unrar likes to create files in the current directory.
  // So, the following few lines created and 'cd' to a directory named 'o'
  // in the current working directory.
  std::error_code code, ok;
  fs::path original_path = fs::current_path(code);
  if (code != ok) return 0;

  fs::path out_path = original_path / "o";
  bool created = fs::create_directory(out_path, code);
  if (code != ok) return 0;

  fs::current_path(out_path, code);
  if (code != ok) return 0;

  static const std::string filename = "temp.rar";
  std::ofstream file(filename,
                     std::ios::binary | std::ios::out | std::ios::trunc);
  if (!file.is_open()) {
    return 0;
  }
  file.write(reinterpret_cast<const char *>(data), size);
  file.close();

  std::unique_ptr<CommandData> cmd_data(new CommandData);
  cmd_data->ParseArg(const_cast<wchar_t *>(L"-p"));
  cmd_data->ParseArg(const_cast<wchar_t *>(L"x"));
  cmd_data->ParseDone();
  std::wstring wide_filename(filename.begin(), filename.end());
  cmd_data->AddArcName(wide_filename.c_str());

  try {
    CmdExtract extractor(cmd_data.get());
    extractor.DoExtract();
  } catch (...) {
  }

  unlink(filename.c_str());

  // 'cd' back to the original directory and delete 'o' along with
  // all its contents.
  fs::current_path(original_path, code);
  if (code != ok) return 0;
  fs::remove_all(out_path, code);
  if (code != ok) return 0;
  return 0;
}