OLD | NEW |
| (Empty) |
1 // Copyright (c) 2012 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 "chrome/renderer/native_handler.h" | |
6 | |
7 #include "base/memory/linked_ptr.h" | |
8 #include "base/logging.h" | |
9 #include "chrome/renderer/module_system.h" | |
10 #include "v8/include/v8.h" | |
11 | |
12 NativeHandler::NativeHandler() | |
13 : object_template_( | |
14 v8::Persistent<v8::ObjectTemplate>::New(v8::ObjectTemplate::New())) { | |
15 } | |
16 | |
17 NativeHandler::~NativeHandler() { | |
18 object_template_.Dispose(); | |
19 } | |
20 | |
21 v8::Handle<v8::Object> NativeHandler::NewInstance() { | |
22 return object_template_->NewInstance(); | |
23 } | |
24 | |
25 // static | |
26 v8::Handle<v8::Value> NativeHandler::Router(const v8::Arguments& args) { | |
27 // It is possible for JS code to execute after ModuleSystem has been deleted | |
28 // in which case the native handlers will also have been deleted, making | |
29 // HandlerFunction below point to freed memory. | |
30 if (!ModuleSystem::IsPresentInCurrentContext()) { | |
31 return v8::ThrowException(v8::Exception::Error( | |
32 v8::String::New("ModuleSystem has been deleted"))); | |
33 } | |
34 HandlerFunction* handler_function = static_cast<HandlerFunction*>( | |
35 args.Data().As<v8::External>()->Value()); | |
36 return handler_function->Run(args); | |
37 } | |
38 | |
39 void NativeHandler::RouteFunction(const std::string& name, | |
40 const HandlerFunction& handler_function) { | |
41 linked_ptr<HandlerFunction> function(new HandlerFunction(handler_function)); | |
42 // TODO(koz): Investigate using v8's MakeWeak() function instead of holding | |
43 // on to these pointers here. | |
44 handler_functions_.push_back(function); | |
45 v8::Handle<v8::FunctionTemplate> function_template = | |
46 v8::FunctionTemplate::New(Router, | |
47 v8::External::New(function.get())); | |
48 object_template_->Set(name.c_str(), function_template); | |
49 } | |
50 | |
51 void NativeHandler::RouteStaticFunction(const std::string& name, | |
52 const HandlerFunc handler_func) { | |
53 v8::Handle<v8::FunctionTemplate> function_template = | |
54 v8::FunctionTemplate::New(handler_func, v8::External::New(this)); | |
55 object_template_->Set(name.c_str(), function_template); | |
56 } | |
OLD | NEW |