blob: cf3ee8c6fddcde8030e9419ba6147ac77de1dd0d [file] [log] [blame]
Ben Murdoch097c5b22016-05-18 11:27:45 +01001// Copyright 2016 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "test/fuzzer/fuzzer-support.h"
6
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10
11#include "include/libplatform/libplatform.h"
12
13namespace v8_fuzzer {
14
15namespace {
16
17FuzzerSupport* g_fuzzer_support = nullptr;
18
19void DeleteFuzzerSupport() {
20 if (g_fuzzer_support) {
21 delete g_fuzzer_support;
22 g_fuzzer_support = nullptr;
23 }
24}
25
26} // namespace
27
28class FuzzerSupport::ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
29 public:
30 virtual void* Allocate(size_t length) {
31 void* data = AllocateUninitialized(length);
32 return data == NULL ? data : memset(data, 0, length);
33 }
34 virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
35 virtual void Free(void* data, size_t) { free(data); }
36};
37
38FuzzerSupport::FuzzerSupport(int* argc, char*** argv) {
39 v8::V8::SetFlagsFromCommandLine(argc, *argv, true);
40 v8::V8::InitializeICU();
41 v8::V8::InitializeExternalStartupData((*argv)[0]);
42 platform_ = v8::platform::CreateDefaultPlatform();
43 v8::V8::InitializePlatform(platform_);
44 v8::V8::Initialize();
45
46 allocator_ = new ArrayBufferAllocator;
47 v8::Isolate::CreateParams create_params;
48 create_params.array_buffer_allocator = allocator_;
49 isolate_ = v8::Isolate::New(create_params);
50
51 {
52 v8::Isolate::Scope isolate_scope(isolate_);
53 v8::HandleScope handle_scope(isolate_);
54 context_.Reset(isolate_, v8::Context::New(isolate_));
55 }
56}
57
58FuzzerSupport::~FuzzerSupport() {
59 {
60 v8::Isolate::Scope isolate_scope(isolate_);
61 while (v8::platform::PumpMessageLoop(platform_, isolate_)) /* empty */
62 ;
63
64 v8::HandleScope handle_scope(isolate_);
65 context_.Reset();
66 }
67
68 isolate_->Dispose();
69 isolate_ = nullptr;
70
71 delete allocator_;
72 allocator_ = nullptr;
73
74 v8::V8::Dispose();
75 v8::V8::ShutdownPlatform();
76
77 delete platform_;
78 platform_ = nullptr;
79}
80
81// static
82FuzzerSupport* FuzzerSupport::Get() { return g_fuzzer_support; }
83
84v8::Isolate* FuzzerSupport::GetIsolate() { return isolate_; }
85
86v8::Local<v8::Context> FuzzerSupport::GetContext() {
87 v8::Isolate::Scope isolate_scope(isolate_);
88 v8::EscapableHandleScope handle_scope(isolate_);
89 v8::Local<v8::Context> context =
90 v8::Local<v8::Context>::New(isolate_, context_);
91 return handle_scope.Escape(context);
92}
93
94} // namespace v8_fuzzer
95
96extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) {
97 v8_fuzzer::g_fuzzer_support = new v8_fuzzer::FuzzerSupport(argc, argv);
98 atexit(&v8_fuzzer::DeleteFuzzerSupport);
99 return 0;
100}