Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / bindings / core / v8 / WorkerScriptController.cpp
1 /*
2  * Copyright (C) 2009, 2012 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32
33 #include "bindings/core/v8/WorkerScriptController.h"
34
35 #include "bindings/core/v8/ScriptSourceCode.h"
36 #include "bindings/core/v8/ScriptValue.h"
37 #include "bindings/core/v8/V8DedicatedWorkerGlobalScope.h"
38 #include "bindings/core/v8/V8ErrorHandler.h"
39 #include "bindings/core/v8/V8GCController.h"
40 #include "bindings/core/v8/V8Initializer.h"
41 #include "bindings/core/v8/V8ObjectConstructor.h"
42 #include "bindings/core/v8/V8ScriptRunner.h"
43 #include "bindings/core/v8/V8SharedWorkerGlobalScope.h"
44 #include "bindings/core/v8/V8WorkerGlobalScope.h"
45 #include "bindings/core/v8/WrapperTypeInfo.h"
46 #include "bindings/modules/v8/V8ServiceWorkerGlobalScope.h"
47 #include "core/events/ErrorEvent.h"
48 #include "core/frame/DOMTimer.h"
49 #include "core/inspector/ScriptCallStack.h"
50 #include "core/workers/SharedWorkerGlobalScope.h"
51 #include "core/workers/WorkerGlobalScope.h"
52 #include "core/workers/WorkerObjectProxy.h"
53 #include "core/workers/WorkerThread.h"
54 #include "platform/heap/ThreadState.h"
55 #include "public/platform/Platform.h"
56 #include "public/platform/WebWorkerRunLoop.h"
57 #include <v8.h>
58
59 namespace blink {
60
61 class WorkerScriptController::WorkerGlobalScopeExecutionState FINAL {
62     STACK_ALLOCATED();
63 public:
64     explicit WorkerGlobalScopeExecutionState(WorkerScriptController* controller)
65         : hadException(false)
66         , lineNumber(0)
67         , columnNumber(0)
68         , m_controller(controller)
69         , m_outerState(controller->m_globalScopeExecutionState)
70     {
71         m_controller->m_globalScopeExecutionState = this;
72     }
73
74     ~WorkerGlobalScopeExecutionState()
75     {
76         m_controller->m_globalScopeExecutionState = m_outerState;
77     }
78
79     void trace(Visitor* visitor)
80     {
81         visitor->trace(m_errorEventFromImportedScript);
82     }
83
84     bool hadException;
85     String errorMessage;
86     int lineNumber;
87     int columnNumber;
88     String sourceURL;
89     ScriptValue exception;
90     RefPtrWillBeMember<ErrorEvent> m_errorEventFromImportedScript;
91
92     // A WorkerGlobalScopeExecutionState context is stack allocated by
93     // WorkerScriptController::evaluate(), with the contoller using it
94     // during script evaluation. To handle nested evaluate() uses,
95     // WorkerGlobalScopeExecutionStates are chained together;
96     // |m_outerState| keeps a pointer to the context object one level out
97     // (or 0, if outermost.) Upon return from evaluate(), the
98     // WorkerScriptController's WorkerGlobalScopeExecutionState is popped
99     // and the previous one restored (see above dtor.)
100     //
101     // With Oilpan, |m_outerState| isn't traced. It'll be "up the stack"
102     // and its fields will be traced when scanning the stack.
103     WorkerScriptController* m_controller;
104     WorkerGlobalScopeExecutionState* m_outerState;
105 };
106
107 WorkerScriptController::WorkerScriptController(WorkerGlobalScope& workerGlobalScope)
108     : m_isolate(v8::Isolate::New())
109     , m_workerGlobalScope(workerGlobalScope)
110     , m_executionForbidden(false)
111     , m_executionScheduledToTerminate(false)
112     , m_globalScopeExecutionState(0)
113 {
114     m_isolate->Enter();
115     V8Initializer::initializeWorker(m_isolate);
116     v8::V8::Initialize();
117     V8PerIsolateData::ensureInitialized(m_isolate);
118     m_world = DOMWrapperWorld::create(WorkerWorldId);
119     m_interruptor = adoptPtr(new V8IsolateInterruptor(m_isolate));
120     ThreadState::current()->addInterruptor(m_interruptor.get());
121 }
122
123 // We need to postpone V8 Isolate destruction until the very end of
124 // worker thread finalization when all objects on the worker heap
125 // are destroyed.
126 class IsolateCleanupTask : public ThreadState::CleanupTask {
127 public:
128     static PassOwnPtr<IsolateCleanupTask> create(v8::Isolate* isolate)
129     {
130         return adoptPtr(new IsolateCleanupTask(isolate));
131     }
132
133     virtual void postCleanup()
134     {
135         V8PerIsolateData::dispose(m_isolate);
136         m_isolate->Exit();
137         m_isolate->Dispose();
138     }
139
140 private:
141     explicit IsolateCleanupTask(v8::Isolate* isolate) : m_isolate(isolate)  { }
142
143     v8::Isolate* m_isolate;
144 };
145
146 WorkerScriptController::~WorkerScriptController()
147 {
148     ThreadState::current()->removeInterruptor(m_interruptor.get());
149
150     m_world->dispose();
151
152     // The corresponding call to didStartWorkerRunLoop is in
153     // WorkerThread::initialize().
154     // See http://webkit.org/b/83104#c14 for why this is here.
155     blink::Platform::current()->didStopWorkerRunLoop(blink::WebWorkerRunLoop(m_workerGlobalScope.thread()));
156
157     if (isContextInitialized())
158         m_scriptState->disposePerContextData();
159
160     ThreadState::current()->addCleanupTask(IsolateCleanupTask::create(m_isolate));
161 }
162
163 bool WorkerScriptController::initializeContextIfNeeded()
164 {
165     v8::HandleScope handleScope(m_isolate);
166
167     if (isContextInitialized())
168         return true;
169
170     v8::Handle<v8::Context> context = v8::Context::New(m_isolate);
171     if (context.IsEmpty())
172         return false;
173
174     m_scriptState = ScriptState::create(context, m_world);
175
176     ScriptState::Scope scope(m_scriptState.get());
177
178     // Set DebugId for the new context.
179     context->SetEmbedderData(0, v8AtomicString(m_isolate, "worker"));
180
181     // Create a new JS object and use it as the prototype for the shadow global object.
182     const WrapperTypeInfo* contextType = &V8DedicatedWorkerGlobalScope::wrapperTypeInfo;
183     if (m_workerGlobalScope.isServiceWorkerGlobalScope())
184         contextType = &V8ServiceWorkerGlobalScope::wrapperTypeInfo;
185     else if (!m_workerGlobalScope.isDedicatedWorkerGlobalScope())
186         contextType = &V8SharedWorkerGlobalScope::wrapperTypeInfo;
187     v8::Handle<v8::Function> workerGlobalScopeConstructor = m_scriptState->perContextData()->constructorForType(contextType);
188     v8::Local<v8::Object> jsWorkerGlobalScope = V8ObjectConstructor::newInstance(m_isolate, workerGlobalScopeConstructor);
189     if (jsWorkerGlobalScope.IsEmpty()) {
190         m_scriptState->disposePerContextData();
191         return false;
192     }
193
194     V8DOMWrapper::associateObjectWithWrapper<V8WorkerGlobalScope>(PassRefPtrWillBeRawPtr<WorkerGlobalScope>(&m_workerGlobalScope), contextType, jsWorkerGlobalScope, m_isolate, WrapperConfiguration::Dependent);
195
196     // Insert the object instance as the prototype of the shadow object.
197     v8::Handle<v8::Object> globalObject = v8::Handle<v8::Object>::Cast(m_scriptState->context()->Global()->GetPrototype());
198     globalObject->SetPrototype(jsWorkerGlobalScope);
199
200     return true;
201 }
202
203 ScriptValue WorkerScriptController::evaluate(const String& script, const String& fileName, const TextPosition& scriptStartPosition)
204 {
205     if (!initializeContextIfNeeded())
206         return ScriptValue();
207
208     ScriptState::Scope scope(m_scriptState.get());
209
210     if (!m_disableEvalPending.isEmpty()) {
211         m_scriptState->context()->AllowCodeGenerationFromStrings(false);
212         m_scriptState->context()->SetErrorMessageForCodeGenerationFromStrings(v8String(m_isolate, m_disableEvalPending));
213         m_disableEvalPending = String();
214     }
215
216     v8::TryCatch block;
217
218     v8::Handle<v8::String> scriptString = v8String(m_isolate, script);
219     v8::Handle<v8::Script> compiledScript = V8ScriptRunner::compileScript(scriptString, fileName, scriptStartPosition, 0, m_isolate);
220     v8::Local<v8::Value> result = V8ScriptRunner::runCompiledScript(compiledScript, &m_workerGlobalScope, m_isolate);
221
222     if (!block.CanContinue()) {
223         m_workerGlobalScope.script()->forbidExecution();
224         return ScriptValue();
225     }
226
227     if (block.HasCaught()) {
228         v8::Local<v8::Message> message = block.Message();
229         m_globalScopeExecutionState->hadException = true;
230         m_globalScopeExecutionState->errorMessage = toCoreString(message->Get());
231         m_globalScopeExecutionState->lineNumber = message->GetLineNumber();
232         m_globalScopeExecutionState->columnNumber = message->GetStartColumn() + 1;
233         TOSTRING_DEFAULT(V8StringResource<>, sourceURL, message->GetScriptOrigin().ResourceName(), ScriptValue());
234         m_globalScopeExecutionState->sourceURL = sourceURL;
235         m_globalScopeExecutionState->exception = ScriptValue(m_scriptState.get(), block.Exception());
236         block.Reset();
237     } else {
238         m_globalScopeExecutionState->hadException = false;
239     }
240
241     if (result.IsEmpty() || result->IsUndefined())
242         return ScriptValue();
243
244     return ScriptValue(m_scriptState.get(), result);
245 }
246
247 void WorkerScriptController::evaluate(const ScriptSourceCode& sourceCode, RefPtrWillBeRawPtr<ErrorEvent>* errorEvent)
248 {
249     if (isExecutionForbidden())
250         return;
251
252     WorkerGlobalScopeExecutionState state(this);
253     evaluate(sourceCode.source(), sourceCode.url().string(), sourceCode.startPosition());
254     if (state.hadException) {
255         if (errorEvent) {
256             if (state.m_errorEventFromImportedScript) {
257                 // Propagate inner error event outwards.
258                 *errorEvent = state.m_errorEventFromImportedScript.release();
259                 return;
260             }
261             if (m_workerGlobalScope.shouldSanitizeScriptError(state.sourceURL, NotSharableCrossOrigin))
262                 *errorEvent = ErrorEvent::createSanitizedError(m_world.get());
263             else
264                 *errorEvent = ErrorEvent::create(state.errorMessage, state.sourceURL, state.lineNumber, state.columnNumber, m_world.get());
265             V8ErrorHandler::storeExceptionOnErrorEventWrapper(errorEvent->get(), state.exception.v8Value(), m_scriptState->context()->Global(), m_isolate);
266         } else {
267             ASSERT(!m_workerGlobalScope.shouldSanitizeScriptError(state.sourceURL, NotSharableCrossOrigin));
268             RefPtrWillBeRawPtr<ErrorEvent> event = nullptr;
269             if (state.m_errorEventFromImportedScript)
270                 event = state.m_errorEventFromImportedScript.release();
271             else
272                 event = ErrorEvent::create(state.errorMessage, state.sourceURL, state.lineNumber, state.columnNumber, m_world.get());
273             m_workerGlobalScope.reportException(event, nullptr, NotSharableCrossOrigin);
274         }
275     }
276 }
277
278 void WorkerScriptController::scheduleExecutionTermination()
279 {
280     // The mutex provides a memory barrier to ensure that once
281     // termination is scheduled, isExecutionTerminating will
282     // accurately reflect that state when called from another thread.
283     {
284         MutexLocker locker(m_scheduledTerminationMutex);
285         m_executionScheduledToTerminate = true;
286     }
287     v8::V8::TerminateExecution(m_isolate);
288 }
289
290 bool WorkerScriptController::isExecutionTerminating() const
291 {
292     // See comments in scheduleExecutionTermination regarding mutex usage.
293     MutexLocker locker(m_scheduledTerminationMutex);
294     return m_executionScheduledToTerminate;
295 }
296
297 void WorkerScriptController::forbidExecution()
298 {
299     ASSERT(m_workerGlobalScope.isContextThread());
300     m_executionForbidden = true;
301 }
302
303 bool WorkerScriptController::isExecutionForbidden() const
304 {
305     ASSERT(m_workerGlobalScope.isContextThread());
306     return m_executionForbidden;
307 }
308
309 void WorkerScriptController::disableEval(const String& errorMessage)
310 {
311     m_disableEvalPending = errorMessage;
312 }
313
314 void WorkerScriptController::rethrowExceptionFromImportedScript(PassRefPtrWillBeRawPtr<ErrorEvent> errorEvent, ExceptionState& exceptionState)
315 {
316     const String& errorMessage = errorEvent->message();
317     if (m_globalScopeExecutionState)
318         m_globalScopeExecutionState->m_errorEventFromImportedScript = errorEvent;
319     exceptionState.rethrowV8Exception(V8ThrowException::createGeneralError(errorMessage, m_isolate));
320 }
321
322 } // namespace blink