fuzzer-support.cc 2.36 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "test/fuzzer/fuzzer-support.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "include/libplatform/libplatform.h"

13 14
#include "src/flags.h"

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
namespace v8_fuzzer {

namespace {

FuzzerSupport* g_fuzzer_support = nullptr;

void DeleteFuzzerSupport() {
  if (g_fuzzer_support) {
    delete g_fuzzer_support;
    g_fuzzer_support = nullptr;
  }
}

}  // namespace

FuzzerSupport::FuzzerSupport(int* argc, char*** argv) {
31
  v8::internal::FLAG_expose_gc = true;
32
  v8::V8::SetFlagsFromCommandLine(argc, *argv, true);
33
  v8::V8::InitializeICUDefaultLocation((*argv)[0]);
34 35 36 37 38
  v8::V8::InitializeExternalStartupData((*argv)[0]);
  platform_ = v8::platform::CreateDefaultPlatform();
  v8::V8::InitializePlatform(platform_);
  v8::V8::Initialize();

39
  allocator_ = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
  v8::Isolate::CreateParams create_params;
  create_params.array_buffer_allocator = allocator_;
  isolate_ = v8::Isolate::New(create_params);

  {
    v8::Isolate::Scope isolate_scope(isolate_);
    v8::HandleScope handle_scope(isolate_);
    context_.Reset(isolate_, v8::Context::New(isolate_));
  }
}

FuzzerSupport::~FuzzerSupport() {
  {
    v8::Isolate::Scope isolate_scope(isolate_);
    while (v8::platform::PumpMessageLoop(platform_, isolate_)) /* empty */
      ;

    v8::HandleScope handle_scope(isolate_);
    context_.Reset();
  }

61
  isolate_->LowMemoryNotification();
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
  isolate_->Dispose();
  isolate_ = nullptr;

  delete allocator_;
  allocator_ = nullptr;

  v8::V8::Dispose();
  v8::V8::ShutdownPlatform();

  delete platform_;
  platform_ = nullptr;
}

// static
FuzzerSupport* FuzzerSupport::Get() { return g_fuzzer_support; }

78
v8::Isolate* FuzzerSupport::GetIsolate() const { return isolate_; }
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

v8::Local<v8::Context> FuzzerSupport::GetContext() {
  v8::Isolate::Scope isolate_scope(isolate_);
  v8::EscapableHandleScope handle_scope(isolate_);
  v8::Local<v8::Context> context =
      v8::Local<v8::Context>::New(isolate_, context_);
  return handle_scope.Escape(context);
}

}  // namespace v8_fuzzer

extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) {
  v8_fuzzer::g_fuzzer_support = new v8_fuzzer::FuzzerSupport(argc, argv);
  atexit(&v8_fuzzer::DeleteFuzzerSupport);
  return 0;
}