• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Chromium 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 "gin/public/isolate_holder.h"
6 
7 #include <stdlib.h>
8 #include <string.h>
9 
10 #include "base/logging.h"
11 #include "base/rand_util.h"
12 #include "base/sys_info.h"
13 #include "gin/array_buffer.h"
14 #include "gin/function_template.h"
15 #include "gin/per_isolate_data.h"
16 
17 namespace gin {
18 
19 namespace {
20 
GenerateEntropy(unsigned char * buffer,size_t amount)21 bool GenerateEntropy(unsigned char* buffer, size_t amount) {
22   base::RandBytes(buffer, amount);
23   return true;
24 }
25 
26 
EnsureV8Initialized(bool gin_managed)27 void EnsureV8Initialized(bool gin_managed) {
28   static bool v8_is_initialized = false;
29   static bool v8_is_gin_managed = false;
30   if (v8_is_initialized) {
31     CHECK_EQ(v8_is_gin_managed, gin_managed);
32     return;
33   }
34   v8_is_initialized = true;
35   v8_is_gin_managed = gin_managed;
36   if (!gin_managed)
37     return;
38 
39   v8::V8::SetArrayBufferAllocator(ArrayBufferAllocator::SharedInstance());
40   static const char v8_flags[] = "--use_strict --harmony";
41   v8::V8::SetFlagsFromString(v8_flags, sizeof(v8_flags) - 1);
42   v8::V8::SetEntropySource(&GenerateEntropy);
43   v8::V8::Initialize();
44 }
45 
46 }  // namespace
47 
IsolateHolder()48 IsolateHolder::IsolateHolder()
49   : isolate_owner_(true) {
50   EnsureV8Initialized(true);
51   isolate_ = v8::Isolate::New();
52   v8::ResourceConstraints constraints;
53   constraints.ConfigureDefaults(base::SysInfo::AmountOfPhysicalMemory(),
54                                 base::SysInfo::NumberOfProcessors());
55   v8::SetResourceConstraints(isolate_, &constraints);
56   Init();
57 }
58 
IsolateHolder(v8::Isolate * isolate)59 IsolateHolder::IsolateHolder(v8::Isolate* isolate)
60     : isolate_owner_(false),
61       isolate_(isolate) {
62   EnsureV8Initialized(false);
63   Init();
64 }
65 
~IsolateHolder()66 IsolateHolder::~IsolateHolder() {
67   isolate_data_.reset();
68   if (isolate_owner_)
69     isolate_->Dispose();
70 }
71 
Init()72 void IsolateHolder::Init() {
73   v8::Isolate::Scope isolate_scope(isolate_);
74   v8::HandleScope handle_scope(isolate_);
75   isolate_data_.reset(new PerIsolateData(isolate_));
76   InitFunctionTemplates(isolate_data_.get());
77 }
78 
79 }  // namespace gin
80