Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(93)

Side by Side Diff: src/inspector/V8Debugger.cpp

Issue 2292573002: [inspector] Initial import of v8_inspector. (Closed)
Patch Set: format the code, disable cpplint Created 4 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « src/inspector/V8Debugger.h ('k') | src/inspector/V8DebuggerAgentImpl.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // 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 "src/inspector/V8Debugger.h"
6
7 #include "src/inspector/DebuggerScript.h"
8 #include "src/inspector/ScriptBreakpoint.h"
9 #include "src/inspector/StringUtil.h"
10 #include "src/inspector/V8Compat.h"
11 #include "src/inspector/V8DebuggerAgentImpl.h"
12 #include "src/inspector/V8InspectorImpl.h"
13 #include "src/inspector/V8InternalValueType.h"
14 #include "src/inspector/V8StackTraceImpl.h"
15 #include "src/inspector/V8ValueCopier.h"
16 #include "src/inspector/protocol/Protocol.h"
17 #include "src/inspector/public/V8InspectorClient.h"
18
19 namespace v8_inspector {
20
21 namespace {
22 const char stepIntoV8MethodName[] = "stepIntoStatement";
23 const char stepOutV8MethodName[] = "stepOutOfFunction";
24 static const char v8AsyncTaskEventEnqueue[] = "enqueue";
25 static const char v8AsyncTaskEventWillHandle[] = "willHandle";
26 static const char v8AsyncTaskEventDidHandle[] = "didHandle";
27
28 inline v8::Local<v8::Boolean> v8Boolean(bool value, v8::Isolate* isolate) {
29 return value ? v8::True(isolate) : v8::False(isolate);
30 }
31
32 } // namespace
33
34 static bool inLiveEditScope = false;
35
36 v8::MaybeLocal<v8::Value> V8Debugger::callDebuggerMethod(
37 const char* functionName, int argc, v8::Local<v8::Value> argv[]) {
38 v8::MicrotasksScope microtasks(m_isolate,
39 v8::MicrotasksScope::kDoNotRunMicrotasks);
40 v8::Local<v8::Object> debuggerScript = m_debuggerScript.Get(m_isolate);
41 v8::Local<v8::Function> function = v8::Local<v8::Function>::Cast(
42 debuggerScript->Get(toV8StringInternalized(m_isolate, functionName)));
43 DCHECK(m_isolate->InContext());
44 return function->Call(m_isolate->GetCurrentContext(), debuggerScript, argc,
45 argv);
46 }
47
48 V8Debugger::V8Debugger(v8::Isolate* isolate, V8InspectorImpl* inspector)
49 : m_isolate(isolate),
50 m_inspector(inspector),
51 m_lastContextId(0),
52 m_enableCount(0),
53 m_breakpointsActivated(true),
54 m_runningNestedMessageLoop(false),
55 m_ignoreScriptParsedEventsCounter(0),
56 m_maxAsyncCallStackDepth(0) {}
57
58 V8Debugger::~V8Debugger() {}
59
60 void V8Debugger::enable() {
61 if (m_enableCount++) return;
62 DCHECK(!enabled());
63 v8::HandleScope scope(m_isolate);
64 v8::Debug::SetDebugEventListener(m_isolate, &V8Debugger::v8DebugEventCallback,
65 v8::External::New(m_isolate, this));
66 m_debuggerContext.Reset(m_isolate, v8::Debug::GetDebugContext(m_isolate));
67 compileDebuggerScript();
68 }
69
70 void V8Debugger::disable() {
71 if (--m_enableCount) return;
72 DCHECK(enabled());
73 clearBreakpoints();
74 m_debuggerScript.Reset();
75 m_debuggerContext.Reset();
76 allAsyncTasksCanceled();
77 v8::Debug::SetDebugEventListener(m_isolate, nullptr);
78 }
79
80 bool V8Debugger::enabled() const { return !m_debuggerScript.IsEmpty(); }
81
82 // static
83 int V8Debugger::contextId(v8::Local<v8::Context> context) {
84 v8::Local<v8::Value> data =
85 context->GetEmbedderData(static_cast<int>(v8::Context::kDebugIdIndex));
86 if (data.IsEmpty() || !data->IsString()) return 0;
87 String16 dataString = toProtocolString(data.As<v8::String>());
88 if (dataString.isEmpty()) return 0;
89 size_t commaPos = dataString.find(",");
90 if (commaPos == String16::kNotFound) return 0;
91 size_t commaPos2 = dataString.find(",", commaPos + 1);
92 if (commaPos2 == String16::kNotFound) return 0;
93 return dataString.substring(commaPos + 1, commaPos2 - commaPos - 1)
94 .toInteger();
95 }
96
97 // static
98 int V8Debugger::getGroupId(v8::Local<v8::Context> context) {
99 v8::Local<v8::Value> data =
100 context->GetEmbedderData(static_cast<int>(v8::Context::kDebugIdIndex));
101 if (data.IsEmpty() || !data->IsString()) return 0;
102 String16 dataString = toProtocolString(data.As<v8::String>());
103 if (dataString.isEmpty()) return 0;
104 size_t commaPos = dataString.find(",");
105 if (commaPos == String16::kNotFound) return 0;
106 return dataString.substring(0, commaPos).toInteger();
107 }
108
109 void V8Debugger::getCompiledScripts(
110 int contextGroupId,
111 std::vector<std::unique_ptr<V8DebuggerScript>>& result) {
112 v8::HandleScope scope(m_isolate);
113 v8::MicrotasksScope microtasks(m_isolate,
114 v8::MicrotasksScope::kDoNotRunMicrotasks);
115 v8::Local<v8::Object> debuggerScript = m_debuggerScript.Get(m_isolate);
116 DCHECK(!debuggerScript->IsUndefined());
117 v8::Local<v8::Function> getScriptsFunction = v8::Local<v8::Function>::Cast(
118 debuggerScript->Get(toV8StringInternalized(m_isolate, "getScripts")));
119 v8::Local<v8::Value> argv[] = {v8::Integer::New(m_isolate, contextGroupId)};
120 v8::Local<v8::Value> value;
121 if (!getScriptsFunction
122 ->Call(debuggerContext(), debuggerScript,
123 V8_INSPECTOR_ARRAY_LENGTH(argv), argv)
124 .ToLocal(&value))
125 return;
126 DCHECK(value->IsArray());
127 v8::Local<v8::Array> scriptsArray = v8::Local<v8::Array>::Cast(value);
128 result.reserve(scriptsArray->Length());
129 for (unsigned i = 0; i < scriptsArray->Length(); ++i) {
130 v8::Local<v8::Object> scriptObject = v8::Local<v8::Object>::Cast(
131 scriptsArray->Get(v8::Integer::New(m_isolate, i)));
132 result.push_back(wrapUnique(
133 new V8DebuggerScript(m_isolate, scriptObject, inLiveEditScope)));
134 }
135 }
136
137 String16 V8Debugger::setBreakpoint(const String16& sourceID,
138 const ScriptBreakpoint& scriptBreakpoint,
139 int* actualLineNumber,
140 int* actualColumnNumber) {
141 v8::HandleScope scope(m_isolate);
142 v8::Context::Scope contextScope(debuggerContext());
143
144 v8::Local<v8::Object> info = v8::Object::New(m_isolate);
145 info->Set(toV8StringInternalized(m_isolate, "sourceID"),
146 toV8String(m_isolate, sourceID));
147 info->Set(toV8StringInternalized(m_isolate, "lineNumber"),
148 v8::Integer::New(m_isolate, scriptBreakpoint.lineNumber));
149 info->Set(toV8StringInternalized(m_isolate, "columnNumber"),
150 v8::Integer::New(m_isolate, scriptBreakpoint.columnNumber));
151 info->Set(toV8StringInternalized(m_isolate, "condition"),
152 toV8String(m_isolate, scriptBreakpoint.condition));
153
154 v8::Local<v8::Function> setBreakpointFunction =
155 v8::Local<v8::Function>::Cast(m_debuggerScript.Get(m_isolate)->Get(
156 toV8StringInternalized(m_isolate, "setBreakpoint")));
157 v8::Local<v8::Value> breakpointId =
158 v8::Debug::Call(debuggerContext(), setBreakpointFunction, info)
159 .ToLocalChecked();
160 if (!breakpointId->IsString()) return "";
161 *actualLineNumber =
162 info->Get(toV8StringInternalized(m_isolate, "lineNumber"))->Int32Value();
163 *actualColumnNumber =
164 info->Get(toV8StringInternalized(m_isolate, "columnNumber"))
165 ->Int32Value();
166 return toProtocolString(breakpointId.As<v8::String>());
167 }
168
169 void V8Debugger::removeBreakpoint(const String16& breakpointId) {
170 v8::HandleScope scope(m_isolate);
171 v8::Context::Scope contextScope(debuggerContext());
172
173 v8::Local<v8::Object> info = v8::Object::New(m_isolate);
174 info->Set(toV8StringInternalized(m_isolate, "breakpointId"),
175 toV8String(m_isolate, breakpointId));
176
177 v8::Local<v8::Function> removeBreakpointFunction =
178 v8::Local<v8::Function>::Cast(m_debuggerScript.Get(m_isolate)->Get(
179 toV8StringInternalized(m_isolate, "removeBreakpoint")));
180 v8::Debug::Call(debuggerContext(), removeBreakpointFunction, info)
181 .ToLocalChecked();
182 }
183
184 void V8Debugger::clearBreakpoints() {
185 v8::HandleScope scope(m_isolate);
186 v8::Context::Scope contextScope(debuggerContext());
187
188 v8::Local<v8::Function> clearBreakpoints =
189 v8::Local<v8::Function>::Cast(m_debuggerScript.Get(m_isolate)->Get(
190 toV8StringInternalized(m_isolate, "clearBreakpoints")));
191 v8::Debug::Call(debuggerContext(), clearBreakpoints).ToLocalChecked();
192 }
193
194 void V8Debugger::setBreakpointsActivated(bool activated) {
195 if (!enabled()) {
196 NOTREACHED();
197 return;
198 }
199 v8::HandleScope scope(m_isolate);
200 v8::Context::Scope contextScope(debuggerContext());
201
202 v8::Local<v8::Object> info = v8::Object::New(m_isolate);
203 info->Set(toV8StringInternalized(m_isolate, "enabled"),
204 v8::Boolean::New(m_isolate, activated));
205 v8::Local<v8::Function> setBreakpointsActivated =
206 v8::Local<v8::Function>::Cast(m_debuggerScript.Get(m_isolate)->Get(
207 toV8StringInternalized(m_isolate, "setBreakpointsActivated")));
208 v8::Debug::Call(debuggerContext(), setBreakpointsActivated, info)
209 .ToLocalChecked();
210
211 m_breakpointsActivated = activated;
212 }
213
214 V8Debugger::PauseOnExceptionsState V8Debugger::getPauseOnExceptionsState() {
215 DCHECK(enabled());
216 v8::HandleScope scope(m_isolate);
217 v8::Context::Scope contextScope(debuggerContext());
218
219 v8::Local<v8::Value> argv[] = {v8::Undefined(m_isolate)};
220 v8::Local<v8::Value> result =
221 callDebuggerMethod("pauseOnExceptionsState", 0, argv).ToLocalChecked();
222 return static_cast<V8Debugger::PauseOnExceptionsState>(result->Int32Value());
223 }
224
225 void V8Debugger::setPauseOnExceptionsState(
226 PauseOnExceptionsState pauseOnExceptionsState) {
227 DCHECK(enabled());
228 v8::HandleScope scope(m_isolate);
229 v8::Context::Scope contextScope(debuggerContext());
230
231 v8::Local<v8::Value> argv[] = {
232 v8::Int32::New(m_isolate, pauseOnExceptionsState)};
233 callDebuggerMethod("setPauseOnExceptionsState", 1, argv);
234 }
235
236 void V8Debugger::setPauseOnNextStatement(bool pause) {
237 if (m_runningNestedMessageLoop) return;
238 if (pause)
239 v8::Debug::DebugBreak(m_isolate);
240 else
241 v8::Debug::CancelDebugBreak(m_isolate);
242 }
243
244 bool V8Debugger::canBreakProgram() {
245 if (!m_breakpointsActivated) return false;
246 return m_isolate->InContext();
247 }
248
249 void V8Debugger::breakProgram() {
250 if (isPaused()) {
251 DCHECK(!m_runningNestedMessageLoop);
252 v8::Local<v8::Value> exception;
253 v8::Local<v8::Array> hitBreakpoints;
254 handleProgramBreak(m_pausedContext, m_executionState, exception,
255 hitBreakpoints);
256 return;
257 }
258
259 if (!canBreakProgram()) return;
260
261 v8::HandleScope scope(m_isolate);
262 v8::Local<v8::Function> breakFunction;
263 if (!V8_FUNCTION_NEW_REMOVE_PROTOTYPE(m_isolate->GetCurrentContext(),
264 &V8Debugger::breakProgramCallback,
265 v8::External::New(m_isolate, this), 0)
266 .ToLocal(&breakFunction))
267 return;
268 v8::Debug::Call(debuggerContext(), breakFunction).ToLocalChecked();
269 }
270
271 void V8Debugger::continueProgram() {
272 if (isPaused()) m_inspector->client()->quitMessageLoopOnPause();
273 m_pausedContext.Clear();
274 m_executionState.Clear();
275 }
276
277 void V8Debugger::stepIntoStatement() {
278 DCHECK(isPaused());
279 DCHECK(!m_executionState.IsEmpty());
280 v8::HandleScope handleScope(m_isolate);
281 v8::Local<v8::Value> argv[] = {m_executionState};
282 callDebuggerMethod(stepIntoV8MethodName, 1, argv);
283 continueProgram();
284 }
285
286 void V8Debugger::stepOverStatement() {
287 DCHECK(isPaused());
288 DCHECK(!m_executionState.IsEmpty());
289 v8::HandleScope handleScope(m_isolate);
290 v8::Local<v8::Value> argv[] = {m_executionState};
291 callDebuggerMethod("stepOverStatement", 1, argv);
292 continueProgram();
293 }
294
295 void V8Debugger::stepOutOfFunction() {
296 DCHECK(isPaused());
297 DCHECK(!m_executionState.IsEmpty());
298 v8::HandleScope handleScope(m_isolate);
299 v8::Local<v8::Value> argv[] = {m_executionState};
300 callDebuggerMethod(stepOutV8MethodName, 1, argv);
301 continueProgram();
302 }
303
304 void V8Debugger::clearStepping() {
305 DCHECK(enabled());
306 v8::HandleScope scope(m_isolate);
307 v8::Context::Scope contextScope(debuggerContext());
308
309 v8::Local<v8::Value> argv[] = {v8::Undefined(m_isolate)};
310 callDebuggerMethod("clearStepping", 0, argv);
311 }
312
313 bool V8Debugger::setScriptSource(
314 const String16& sourceID, v8::Local<v8::String> newSource, bool dryRun,
315 ErrorString* error,
316 Maybe<protocol::Runtime::ExceptionDetails>* exceptionDetails,
317 JavaScriptCallFrames* newCallFrames, Maybe<bool>* stackChanged) {
318 class EnableLiveEditScope {
319 public:
320 explicit EnableLiveEditScope(v8::Isolate* isolate) : m_isolate(isolate) {
321 v8::Debug::SetLiveEditEnabled(m_isolate, true);
322 inLiveEditScope = true;
323 }
324 ~EnableLiveEditScope() {
325 v8::Debug::SetLiveEditEnabled(m_isolate, false);
326 inLiveEditScope = false;
327 }
328
329 private:
330 v8::Isolate* m_isolate;
331 };
332
333 DCHECK(enabled());
334 v8::HandleScope scope(m_isolate);
335
336 std::unique_ptr<v8::Context::Scope> contextScope;
337 if (!isPaused())
338 contextScope = wrapUnique(new v8::Context::Scope(debuggerContext()));
339
340 v8::Local<v8::Value> argv[] = {toV8String(m_isolate, sourceID), newSource,
341 v8Boolean(dryRun, m_isolate)};
342
343 v8::Local<v8::Value> v8result;
344 {
345 EnableLiveEditScope enableLiveEditScope(m_isolate);
346 v8::TryCatch tryCatch(m_isolate);
347 tryCatch.SetVerbose(false);
348 v8::MaybeLocal<v8::Value> maybeResult =
349 callDebuggerMethod("liveEditScriptSource", 3, argv);
350 if (tryCatch.HasCaught()) {
351 v8::Local<v8::Message> message = tryCatch.Message();
352 if (!message.IsEmpty())
353 *error = toProtocolStringWithTypeCheck(message->Get());
354 else
355 *error = "Unknown error.";
356 return false;
357 }
358 v8result = maybeResult.ToLocalChecked();
359 }
360 DCHECK(!v8result.IsEmpty());
361 v8::Local<v8::Object> resultTuple = v8result->ToObject(m_isolate);
362 int code =
363 static_cast<int>(resultTuple->Get(0)->ToInteger(m_isolate)->Value());
364 switch (code) {
365 case 0: {
366 *stackChanged = resultTuple->Get(1)->BooleanValue();
367 // Call stack may have changed after if the edited function was on the
368 // stack.
369 if (!dryRun && isPaused()) {
370 JavaScriptCallFrames frames = currentCallFrames();
371 newCallFrames->swap(frames);
372 }
373 return true;
374 }
375 // Compile error.
376 case 1: {
377 *exceptionDetails =
378 protocol::Runtime::ExceptionDetails::create()
379 .setExceptionId(m_inspector->nextExceptionId())
380 .setText(toProtocolStringWithTypeCheck(resultTuple->Get(2)))
381 .setLineNumber(
382 resultTuple->Get(3)->ToInteger(m_isolate)->Value() - 1)
383 .setColumnNumber(
384 resultTuple->Get(4)->ToInteger(m_isolate)->Value() - 1)
385 .build();
386 return false;
387 }
388 }
389 *error = "Unknown error.";
390 return false;
391 }
392
393 JavaScriptCallFrames V8Debugger::currentCallFrames(int limit) {
394 if (!m_isolate->InContext()) return JavaScriptCallFrames();
395 v8::Local<v8::Value> currentCallFramesV8;
396 if (m_executionState.IsEmpty()) {
397 v8::Local<v8::Function> currentCallFramesFunction =
398 v8::Local<v8::Function>::Cast(m_debuggerScript.Get(m_isolate)->Get(
399 toV8StringInternalized(m_isolate, "currentCallFrames")));
400 currentCallFramesV8 =
401 v8::Debug::Call(debuggerContext(), currentCallFramesFunction,
402 v8::Integer::New(m_isolate, limit))
403 .ToLocalChecked();
404 } else {
405 v8::Local<v8::Value> argv[] = {m_executionState,
406 v8::Integer::New(m_isolate, limit)};
407 currentCallFramesV8 =
408 callDebuggerMethod("currentCallFrames", V8_INSPECTOR_ARRAY_LENGTH(argv),
409 argv)
410 .ToLocalChecked();
411 }
412 DCHECK(!currentCallFramesV8.IsEmpty());
413 if (!currentCallFramesV8->IsArray()) return JavaScriptCallFrames();
414 v8::Local<v8::Array> callFramesArray = currentCallFramesV8.As<v8::Array>();
415 JavaScriptCallFrames callFrames;
416 for (size_t i = 0; i < callFramesArray->Length(); ++i) {
417 v8::Local<v8::Value> callFrameValue;
418 if (!callFramesArray->Get(debuggerContext(), i).ToLocal(&callFrameValue))
419 return JavaScriptCallFrames();
420 if (!callFrameValue->IsObject()) return JavaScriptCallFrames();
421 v8::Local<v8::Object> callFrameObject = callFrameValue.As<v8::Object>();
422 callFrames.push_back(JavaScriptCallFrame::create(
423 debuggerContext(), v8::Local<v8::Object>::Cast(callFrameObject)));
424 }
425 return callFrames;
426 }
427
428 static V8Debugger* toV8Debugger(v8::Local<v8::Value> data) {
429 void* p = v8::Local<v8::External>::Cast(data)->Value();
430 return static_cast<V8Debugger*>(p);
431 }
432
433 void V8Debugger::breakProgramCallback(
434 const v8::FunctionCallbackInfo<v8::Value>& info) {
435 DCHECK_EQ(info.Length(), 2);
436 V8Debugger* thisPtr = toV8Debugger(info.Data());
437 if (!thisPtr->enabled()) return;
438 v8::Local<v8::Context> pausedContext =
439 thisPtr->m_isolate->GetCurrentContext();
440 v8::Local<v8::Value> exception;
441 v8::Local<v8::Array> hitBreakpoints;
442 thisPtr->handleProgramBreak(pausedContext,
443 v8::Local<v8::Object>::Cast(info[0]), exception,
444 hitBreakpoints);
445 }
446
447 void V8Debugger::handleProgramBreak(v8::Local<v8::Context> pausedContext,
448 v8::Local<v8::Object> executionState,
449 v8::Local<v8::Value> exception,
450 v8::Local<v8::Array> hitBreakpointNumbers,
451 bool isPromiseRejection) {
452 // Don't allow nested breaks.
453 if (m_runningNestedMessageLoop) return;
454
455 V8DebuggerAgentImpl* agent =
456 m_inspector->enabledDebuggerAgentForGroup(getGroupId(pausedContext));
457 if (!agent) return;
458
459 std::vector<String16> breakpointIds;
460 if (!hitBreakpointNumbers.IsEmpty()) {
461 breakpointIds.reserve(hitBreakpointNumbers->Length());
462 for (size_t i = 0; i < hitBreakpointNumbers->Length(); i++) {
463 v8::Local<v8::Value> hitBreakpointNumber = hitBreakpointNumbers->Get(i);
464 DCHECK(!hitBreakpointNumber.IsEmpty() && hitBreakpointNumber->IsInt32());
465 breakpointIds.push_back(
466 String16::fromInteger(hitBreakpointNumber->Int32Value()));
467 }
468 }
469
470 m_pausedContext = pausedContext;
471 m_executionState = executionState;
472 V8DebuggerAgentImpl::SkipPauseRequest result = agent->didPause(
473 pausedContext, exception, breakpointIds, isPromiseRejection);
474 if (result == V8DebuggerAgentImpl::RequestNoSkip) {
475 m_runningNestedMessageLoop = true;
476 int groupId = getGroupId(pausedContext);
477 DCHECK(groupId);
478 m_inspector->client()->runMessageLoopOnPause(groupId);
479 // The agent may have been removed in the nested loop.
480 agent =
481 m_inspector->enabledDebuggerAgentForGroup(getGroupId(pausedContext));
482 if (agent) agent->didContinue();
483 m_runningNestedMessageLoop = false;
484 }
485 m_pausedContext.Clear();
486 m_executionState.Clear();
487
488 if (result == V8DebuggerAgentImpl::RequestStepFrame) {
489 v8::Local<v8::Value> argv[] = {executionState};
490 callDebuggerMethod("stepFrameStatement", 1, argv);
491 } else if (result == V8DebuggerAgentImpl::RequestStepInto) {
492 v8::Local<v8::Value> argv[] = {executionState};
493 callDebuggerMethod(stepIntoV8MethodName, 1, argv);
494 } else if (result == V8DebuggerAgentImpl::RequestStepOut) {
495 v8::Local<v8::Value> argv[] = {executionState};
496 callDebuggerMethod(stepOutV8MethodName, 1, argv);
497 }
498 }
499
500 void V8Debugger::v8DebugEventCallback(
501 const v8::Debug::EventDetails& eventDetails) {
502 V8Debugger* thisPtr = toV8Debugger(eventDetails.GetCallbackData());
503 thisPtr->handleV8DebugEvent(eventDetails);
504 }
505
506 v8::Local<v8::Value> V8Debugger::callInternalGetterFunction(
507 v8::Local<v8::Object> object, const char* functionName) {
508 v8::MicrotasksScope microtasks(m_isolate,
509 v8::MicrotasksScope::kDoNotRunMicrotasks);
510 v8::Local<v8::Value> getterValue =
511 object->Get(toV8StringInternalized(m_isolate, functionName));
512 DCHECK(!getterValue.IsEmpty() && getterValue->IsFunction());
513 return v8::Local<v8::Function>::Cast(getterValue)
514 ->Call(m_isolate->GetCurrentContext(), object, 0, 0)
515 .ToLocalChecked();
516 }
517
518 void V8Debugger::handleV8DebugEvent(
519 const v8::Debug::EventDetails& eventDetails) {
520 if (!enabled()) return;
521 v8::DebugEvent event = eventDetails.GetEvent();
522 if (event != v8::AsyncTaskEvent && event != v8::Break &&
523 event != v8::Exception && event != v8::AfterCompile &&
524 event != v8::BeforeCompile && event != v8::CompileError)
525 return;
526
527 v8::Local<v8::Context> eventContext = eventDetails.GetEventContext();
528 DCHECK(!eventContext.IsEmpty());
529
530 if (event == v8::AsyncTaskEvent) {
531 v8::HandleScope scope(m_isolate);
532 handleV8AsyncTaskEvent(eventContext, eventDetails.GetExecutionState(),
533 eventDetails.GetEventData());
534 return;
535 }
536
537 V8DebuggerAgentImpl* agent =
538 m_inspector->enabledDebuggerAgentForGroup(getGroupId(eventContext));
539 if (agent) {
540 v8::HandleScope scope(m_isolate);
541 if (m_ignoreScriptParsedEventsCounter == 0 &&
542 (event == v8::AfterCompile || event == v8::CompileError)) {
543 v8::Context::Scope contextScope(debuggerContext());
544 v8::Local<v8::Value> argv[] = {eventDetails.GetEventData()};
545 v8::Local<v8::Value> value =
546 callDebuggerMethod("getAfterCompileScript", 1, argv).ToLocalChecked();
547 if (value->IsNull()) return;
548 DCHECK(value->IsObject());
549 v8::Local<v8::Object> scriptObject = v8::Local<v8::Object>::Cast(value);
550 agent->didParseSource(wrapUnique(new V8DebuggerScript(
551 m_isolate, scriptObject, inLiveEditScope)),
552 event == v8::AfterCompile);
553 } else if (event == v8::Exception) {
554 v8::Local<v8::Object> eventData = eventDetails.GetEventData();
555 v8::Local<v8::Value> exception =
556 callInternalGetterFunction(eventData, "exception");
557 v8::Local<v8::Value> promise =
558 callInternalGetterFunction(eventData, "promise");
559 bool isPromiseRejection = !promise.IsEmpty() && promise->IsObject();
560 handleProgramBreak(eventContext, eventDetails.GetExecutionState(),
561 exception, v8::Local<v8::Array>(), isPromiseRejection);
562 } else if (event == v8::Break) {
563 v8::Local<v8::Value> argv[] = {eventDetails.GetEventData()};
564 v8::Local<v8::Value> hitBreakpoints =
565 callDebuggerMethod("getBreakpointNumbers", 1, argv).ToLocalChecked();
566 DCHECK(hitBreakpoints->IsArray());
567 handleProgramBreak(eventContext, eventDetails.GetExecutionState(),
568 v8::Local<v8::Value>(),
569 hitBreakpoints.As<v8::Array>());
570 }
571 }
572 }
573
574 void V8Debugger::handleV8AsyncTaskEvent(v8::Local<v8::Context> context,
575 v8::Local<v8::Object> executionState,
576 v8::Local<v8::Object> eventData) {
577 if (!m_maxAsyncCallStackDepth) return;
578
579 String16 type = toProtocolStringWithTypeCheck(
580 callInternalGetterFunction(eventData, "type"));
581 String16 name = toProtocolStringWithTypeCheck(
582 callInternalGetterFunction(eventData, "name"));
583 int id = callInternalGetterFunction(eventData, "id")
584 ->ToInteger(m_isolate)
585 ->Value();
586 // The scopes for the ids are defined by the eventData.name namespaces. There
587 // are currently two namespaces: "Object." and "Promise.".
588 void* ptr = reinterpret_cast<void*>(id * 4 + (name[0] == 'P' ? 2 : 0) + 1);
589 if (type == v8AsyncTaskEventEnqueue)
590 asyncTaskScheduled(name, ptr, false);
591 else if (type == v8AsyncTaskEventWillHandle)
592 asyncTaskStarted(ptr);
593 else if (type == v8AsyncTaskEventDidHandle)
594 asyncTaskFinished(ptr);
595 else
596 NOTREACHED();
597 }
598
599 V8StackTraceImpl* V8Debugger::currentAsyncCallChain() {
600 if (!m_currentStacks.size()) return nullptr;
601 return m_currentStacks.back().get();
602 }
603
604 void V8Debugger::compileDebuggerScript() {
605 if (!m_debuggerScript.IsEmpty()) {
606 NOTREACHED();
607 return;
608 }
609
610 v8::HandleScope scope(m_isolate);
611 v8::Context::Scope contextScope(debuggerContext());
612
613 v8::Local<v8::String> scriptValue =
614 v8::String::NewFromUtf8(m_isolate, DebuggerScript_js,
615 v8::NewStringType::kInternalized,
616 sizeof(DebuggerScript_js))
617 .ToLocalChecked();
618 v8::Local<v8::Value> value;
619 if (!m_inspector->compileAndRunInternalScript(debuggerContext(), scriptValue)
620 .ToLocal(&value)) {
621 NOTREACHED();
622 return;
623 }
624 DCHECK(value->IsObject());
625 m_debuggerScript.Reset(m_isolate, value.As<v8::Object>());
626 }
627
628 v8::Local<v8::Context> V8Debugger::debuggerContext() const {
629 DCHECK(!m_debuggerContext.IsEmpty());
630 return m_debuggerContext.Get(m_isolate);
631 }
632
633 v8::MaybeLocal<v8::Value> V8Debugger::functionScopes(
634 v8::Local<v8::Context> context, v8::Local<v8::Function> function) {
635 if (!enabled()) {
636 NOTREACHED();
637 return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
638 }
639 v8::Local<v8::Value> argv[] = {function};
640 v8::Local<v8::Value> scopesValue;
641 if (!callDebuggerMethod("getFunctionScopes", 1, argv).ToLocal(&scopesValue))
642 return v8::MaybeLocal<v8::Value>();
643 v8::Local<v8::Value> copied;
644 if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context,
645 scopesValue)
646 .ToLocal(&copied) ||
647 !copied->IsArray())
648 return v8::MaybeLocal<v8::Value>();
649 if (!markAsInternal(context, v8::Local<v8::Array>::Cast(copied),
650 V8InternalValueType::kScopeList))
651 return v8::MaybeLocal<v8::Value>();
652 if (!markArrayEntriesAsInternal(context, v8::Local<v8::Array>::Cast(copied),
653 V8InternalValueType::kScope))
654 return v8::MaybeLocal<v8::Value>();
655 return copied;
656 }
657
658 v8::MaybeLocal<v8::Array> V8Debugger::internalProperties(
659 v8::Local<v8::Context> context, v8::Local<v8::Value> value) {
660 v8::Local<v8::Array> properties;
661 if (!v8::Debug::GetInternalProperties(m_isolate, value).ToLocal(&properties))
662 return v8::MaybeLocal<v8::Array>();
663 if (value->IsFunction()) {
664 v8::Local<v8::Function> function = value.As<v8::Function>();
665 v8::Local<v8::Value> location = functionLocation(context, function);
666 if (location->IsObject()) {
667 createDataProperty(
668 context, properties, properties->Length(),
669 toV8StringInternalized(m_isolate, "[[FunctionLocation]]"));
670 createDataProperty(context, properties, properties->Length(), location);
671 }
672 if (function->IsGeneratorFunction()) {
673 createDataProperty(context, properties, properties->Length(),
674 toV8StringInternalized(m_isolate, "[[IsGenerator]]"));
675 createDataProperty(context, properties, properties->Length(),
676 v8::True(m_isolate));
677 }
678 }
679 if (!enabled()) return properties;
680 if (value->IsMap() || value->IsWeakMap() || value->IsSet() ||
681 value->IsWeakSet() || value->IsSetIterator() || value->IsMapIterator()) {
682 v8::Local<v8::Value> entries =
683 collectionEntries(context, v8::Local<v8::Object>::Cast(value));
684 if (entries->IsArray()) {
685 createDataProperty(context, properties, properties->Length(),
686 toV8StringInternalized(m_isolate, "[[Entries]]"));
687 createDataProperty(context, properties, properties->Length(), entries);
688 }
689 }
690 if (value->IsGeneratorObject()) {
691 v8::Local<v8::Value> location =
692 generatorObjectLocation(context, v8::Local<v8::Object>::Cast(value));
693 if (location->IsObject()) {
694 createDataProperty(
695 context, properties, properties->Length(),
696 toV8StringInternalized(m_isolate, "[[GeneratorLocation]]"));
697 createDataProperty(context, properties, properties->Length(), location);
698 }
699 }
700 if (value->IsFunction()) {
701 v8::Local<v8::Function> function = value.As<v8::Function>();
702 v8::Local<v8::Value> boundFunction = function->GetBoundFunction();
703 v8::Local<v8::Value> scopes;
704 if (boundFunction->IsUndefined() &&
705 functionScopes(context, function).ToLocal(&scopes)) {
706 createDataProperty(context, properties, properties->Length(),
707 toV8StringInternalized(m_isolate, "[[Scopes]]"));
708 createDataProperty(context, properties, properties->Length(), scopes);
709 }
710 }
711 return properties;
712 }
713
714 v8::Local<v8::Value> V8Debugger::collectionEntries(
715 v8::Local<v8::Context> context, v8::Local<v8::Object> object) {
716 if (!enabled()) {
717 NOTREACHED();
718 return v8::Undefined(m_isolate);
719 }
720 v8::Local<v8::Value> argv[] = {object};
721 v8::Local<v8::Value> entriesValue =
722 callDebuggerMethod("getCollectionEntries", 1, argv).ToLocalChecked();
723 v8::Local<v8::Value> copied;
724 if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context,
725 entriesValue)
726 .ToLocal(&copied) ||
727 !copied->IsArray())
728 return v8::Undefined(m_isolate);
729 if (!markArrayEntriesAsInternal(context, v8::Local<v8::Array>::Cast(copied),
730 V8InternalValueType::kEntry))
731 return v8::Undefined(m_isolate);
732 return copied;
733 }
734
735 v8::Local<v8::Value> V8Debugger::generatorObjectLocation(
736 v8::Local<v8::Context> context, v8::Local<v8::Object> object) {
737 if (!enabled()) {
738 NOTREACHED();
739 return v8::Null(m_isolate);
740 }
741 v8::Local<v8::Value> argv[] = {object};
742 v8::Local<v8::Value> location =
743 callDebuggerMethod("getGeneratorObjectLocation", 1, argv)
744 .ToLocalChecked();
745 v8::Local<v8::Value> copied;
746 if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context,
747 location)
748 .ToLocal(&copied) ||
749 !copied->IsObject())
750 return v8::Null(m_isolate);
751 if (!markAsInternal(context, v8::Local<v8::Object>::Cast(copied),
752 V8InternalValueType::kLocation))
753 return v8::Null(m_isolate);
754 return copied;
755 }
756
757 v8::Local<v8::Value> V8Debugger::functionLocation(
758 v8::Local<v8::Context> context, v8::Local<v8::Function> function) {
759 int scriptId = function->ScriptId();
760 if (scriptId == v8::UnboundScript::kNoScriptId) return v8::Null(m_isolate);
761 int lineNumber = function->GetScriptLineNumber();
762 int columnNumber = function->GetScriptColumnNumber();
763 if (lineNumber == v8::Function::kLineOffsetNotFound ||
764 columnNumber == v8::Function::kLineOffsetNotFound)
765 return v8::Null(m_isolate);
766 v8::Local<v8::Object> location = v8::Object::New(m_isolate);
767 if (!location->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false))
768 return v8::Null(m_isolate);
769 if (!createDataProperty(
770 context, location, toV8StringInternalized(m_isolate, "scriptId"),
771 toV8String(m_isolate, String16::fromInteger(scriptId)))
772 .FromMaybe(false))
773 return v8::Null(m_isolate);
774 if (!createDataProperty(context, location,
775 toV8StringInternalized(m_isolate, "lineNumber"),
776 v8::Integer::New(m_isolate, lineNumber))
777 .FromMaybe(false))
778 return v8::Null(m_isolate);
779 if (!createDataProperty(context, location,
780 toV8StringInternalized(m_isolate, "columnNumber"),
781 v8::Integer::New(m_isolate, columnNumber))
782 .FromMaybe(false))
783 return v8::Null(m_isolate);
784 if (!markAsInternal(context, location, V8InternalValueType::kLocation))
785 return v8::Null(m_isolate);
786 return location;
787 }
788
789 bool V8Debugger::isPaused() { return !m_pausedContext.IsEmpty(); }
790
791 std::unique_ptr<V8StackTraceImpl> V8Debugger::createStackTrace(
792 v8::Local<v8::StackTrace> stackTrace) {
793 int contextGroupId =
794 m_isolate->InContext() ? getGroupId(m_isolate->GetCurrentContext()) : 0;
795 return V8StackTraceImpl::create(this, contextGroupId, stackTrace,
796 V8StackTraceImpl::maxCallStackSizeToCapture);
797 }
798
799 int V8Debugger::markContext(const V8ContextInfo& info) {
800 DCHECK(info.context->GetIsolate() == m_isolate);
801 int contextId = ++m_lastContextId;
802 String16 debugData = String16::fromInteger(info.contextGroupId) + "," +
803 String16::fromInteger(contextId) + "," +
804 toString16(info.auxData);
805 v8::Context::Scope contextScope(info.context);
806 info.context->SetEmbedderData(static_cast<int>(v8::Context::kDebugIdIndex),
807 toV8String(m_isolate, debugData));
808 return contextId;
809 }
810
811 void V8Debugger::setAsyncCallStackDepth(V8DebuggerAgentImpl* agent, int depth) {
812 if (depth <= 0)
813 m_maxAsyncCallStackDepthMap.erase(agent);
814 else
815 m_maxAsyncCallStackDepthMap[agent] = depth;
816
817 int maxAsyncCallStackDepth = 0;
818 for (const auto& pair : m_maxAsyncCallStackDepthMap) {
819 if (pair.second > maxAsyncCallStackDepth)
820 maxAsyncCallStackDepth = pair.second;
821 }
822
823 if (m_maxAsyncCallStackDepth == maxAsyncCallStackDepth) return;
824 m_maxAsyncCallStackDepth = maxAsyncCallStackDepth;
825 if (!maxAsyncCallStackDepth) allAsyncTasksCanceled();
826 }
827
828 void V8Debugger::asyncTaskScheduled(const StringView& taskName, void* task,
829 bool recurring) {
830 if (!m_maxAsyncCallStackDepth) return;
831 asyncTaskScheduled(toString16(taskName), task, recurring);
832 }
833
834 void V8Debugger::asyncTaskScheduled(const String16& taskName, void* task,
835 bool recurring) {
836 if (!m_maxAsyncCallStackDepth) return;
837 v8::HandleScope scope(m_isolate);
838 int contextGroupId =
839 m_isolate->InContext() ? getGroupId(m_isolate->GetCurrentContext()) : 0;
840 std::unique_ptr<V8StackTraceImpl> chain = V8StackTraceImpl::capture(
841 this, contextGroupId, V8StackTraceImpl::maxCallStackSizeToCapture,
842 taskName);
843 if (chain) {
844 m_asyncTaskStacks[task] = std::move(chain);
845 if (recurring) m_recurringTasks.insert(task);
846 }
847 }
848
849 void V8Debugger::asyncTaskCanceled(void* task) {
850 if (!m_maxAsyncCallStackDepth) return;
851 m_asyncTaskStacks.erase(task);
852 m_recurringTasks.erase(task);
853 }
854
855 void V8Debugger::asyncTaskStarted(void* task) {
856 if (!m_maxAsyncCallStackDepth) return;
857 m_currentTasks.push_back(task);
858 AsyncTaskToStackTrace::iterator stackIt = m_asyncTaskStacks.find(task);
859 // Needs to support following order of events:
860 // - asyncTaskScheduled
861 // <-- attached here -->
862 // - asyncTaskStarted
863 // - asyncTaskCanceled <-- canceled before finished
864 // <-- async stack requested here -->
865 // - asyncTaskFinished
866 std::unique_ptr<V8StackTraceImpl> stack;
867 if (stackIt != m_asyncTaskStacks.end() && stackIt->second)
868 stack = stackIt->second->cloneImpl();
869 m_currentStacks.push_back(std::move(stack));
870 }
871
872 void V8Debugger::asyncTaskFinished(void* task) {
873 if (!m_maxAsyncCallStackDepth) return;
874 // We could start instrumenting half way and the stack is empty.
875 if (!m_currentStacks.size()) return;
876
877 DCHECK(m_currentTasks.back() == task);
878 m_currentTasks.pop_back();
879
880 m_currentStacks.pop_back();
881 if (m_recurringTasks.find(task) == m_recurringTasks.end())
882 m_asyncTaskStacks.erase(task);
883 }
884
885 void V8Debugger::allAsyncTasksCanceled() {
886 m_asyncTaskStacks.clear();
887 m_recurringTasks.clear();
888 m_currentStacks.clear();
889 m_currentTasks.clear();
890 }
891
892 void V8Debugger::muteScriptParsedEvents() {
893 ++m_ignoreScriptParsedEventsCounter;
894 }
895
896 void V8Debugger::unmuteScriptParsedEvents() {
897 --m_ignoreScriptParsedEventsCounter;
898 DCHECK_GE(m_ignoreScriptParsedEventsCounter, 0);
899 }
900
901 std::unique_ptr<V8StackTraceImpl> V8Debugger::captureStackTrace(
902 bool fullStack) {
903 if (!m_isolate->InContext()) return nullptr;
904
905 v8::HandleScope handles(m_isolate);
906 int contextGroupId = getGroupId(m_isolate->GetCurrentContext());
907 if (!contextGroupId) return nullptr;
908
909 size_t stackSize =
910 fullStack ? V8StackTraceImpl::maxCallStackSizeToCapture : 1;
911 if (m_inspector->enabledRuntimeAgentForGroup(contextGroupId))
912 stackSize = V8StackTraceImpl::maxCallStackSizeToCapture;
913
914 return V8StackTraceImpl::capture(this, contextGroupId, stackSize);
915 }
916
917 } // namespace v8_inspector
OLDNEW
« no previous file with comments | « src/inspector/V8Debugger.h ('k') | src/inspector/V8DebuggerAgentImpl.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698