summaryrefslogtreecommitdiffstats
path: root/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerImpl.cpp
blob: 750f6c2505f1a7d4db77d8cad847fc329cc60aa5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
/*
 * Copyright (c) 2010-2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "platform/v8_inspector/V8DebuggerImpl.h"

#include "platform/inspector_protocol/Values.h"
#include "platform/v8_inspector/Atomics.h"
#include "platform/v8_inspector/DebuggerScript.h"
#include "platform/v8_inspector/ScriptBreakpoint.h"
#include "platform/v8_inspector/V8DebuggerAgentImpl.h"
#include "platform/v8_inspector/V8RuntimeAgentImpl.h"
#include "platform/v8_inspector/V8StackTraceImpl.h"
#include "platform/v8_inspector/V8StringUtil.h"
#include "platform/v8_inspector/public/V8DebuggerClient.h"

namespace blink {

namespace {
const char stepIntoV8MethodName[] = "stepIntoStatement";
const char stepOutV8MethodName[] = "stepOutOfFunction";
volatile int s_lastContextId = 0;

inline v8::Local<v8::Boolean> v8Boolean(bool value, v8::Isolate* isolate)
{
    return value ? v8::True(isolate) : v8::False(isolate);
}

}

static bool inLiveEditScope = false;

v8::MaybeLocal<v8::Value> V8DebuggerImpl::callDebuggerMethod(const char* functionName, int argc, v8::Local<v8::Value> argv[])
{
    v8::MicrotasksScope microtasks(m_isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);
    v8::Local<v8::Object> debuggerScript = m_debuggerScript.Get(m_isolate);
    v8::Local<v8::Function> function = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8InternalizedString(functionName)));
    ASSERT(m_isolate->InContext());
    return function->Call(m_isolate->GetCurrentContext(), debuggerScript, argc, argv);
}

PassOwnPtr<V8Debugger> V8Debugger::create(v8::Isolate* isolate, V8DebuggerClient* client)
{
    return adoptPtr(new V8DebuggerImpl(isolate, client));
}

V8DebuggerImpl::V8DebuggerImpl(v8::Isolate* isolate, V8DebuggerClient* client)
    : m_isolate(isolate)
    , m_client(client)
    , m_breakpointsActivated(true)
    , m_runningNestedMessageLoop(false)
{
}

V8DebuggerImpl::~V8DebuggerImpl()
{
}

void V8DebuggerImpl::enable()
{
    ASSERT(!enabled());
    v8::HandleScope scope(m_isolate);
    v8::Debug::SetDebugEventListener(m_isolate, &V8DebuggerImpl::v8DebugEventCallback, v8::External::New(m_isolate, this));
    m_debuggerContext.Reset(m_isolate, v8::Debug::GetDebugContext(m_isolate));
    compileDebuggerScript();
}

void V8DebuggerImpl::disable()
{
    ASSERT(enabled());
    clearBreakpoints();
    m_debuggerScript.Reset();
    m_debuggerContext.Reset();
    v8::Debug::SetDebugEventListener(m_isolate, nullptr);
}

bool V8DebuggerImpl::enabled() const
{
    return !m_debuggerScript.IsEmpty();
}

void V8Debugger::setContextDebugData(v8::Local<v8::Context> context, const String16& type, int contextGroupId)
{
    int contextId = atomicIncrement(&s_lastContextId);
    String16 debugData = String16::number(contextGroupId) + "," + String16::number(contextId) + "," + type;
    v8::HandleScope scope(context->GetIsolate());
    v8::Context::Scope contextScope(context);
    context->SetEmbedderData(static_cast<int>(v8::Context::kDebugIdIndex), toV8String(context->GetIsolate(), debugData));
}

int V8Debugger::contextId(v8::Local<v8::Context> context)
{
    v8::Local<v8::Value> data = context->GetEmbedderData(static_cast<int>(v8::Context::kDebugIdIndex));
    if (data.IsEmpty() || !data->IsString())
        return 0;
    String16 dataString = toProtocolString(data.As<v8::String>());
    if (dataString.isEmpty())
        return 0;
    size_t commaPos = dataString.find(",");
    if (commaPos == kNotFound)
        return 0;
    size_t commaPos2 = dataString.find(",", commaPos + 1);
    if (commaPos2 == kNotFound)
        return 0;
    return dataString.substring(commaPos + 1, commaPos2 - commaPos - 1).toInt();
}

static int getGroupId(v8::Local<v8::Context> context)
{
    v8::Local<v8::Value> data = context->GetEmbedderData(static_cast<int>(v8::Context::kDebugIdIndex));
    if (data.IsEmpty() || !data->IsString())
        return 0;
    String16 dataString = toProtocolString(data.As<v8::String>());
    if (dataString.isEmpty())
        return 0;
    size_t commaPos = dataString.find(",");
    if (commaPos == kNotFound)
        return 0;
    return dataString.substring(0, commaPos).toInt();
}

void V8DebuggerImpl::addDebuggerAgent(int contextGroupId, V8DebuggerAgentImpl* agent)
{
    ASSERT(contextGroupId);
    ASSERT(!m_debuggerAgentsMap.contains(contextGroupId));
    if (m_debuggerAgentsMap.isEmpty())
        enable();
    m_debuggerAgentsMap.set(contextGroupId, agent);

    protocol::Vector<V8DebuggerParsedScript> compiledScripts;
    getCompiledScripts(contextGroupId, compiledScripts);
    for (size_t i = 0; i < compiledScripts.size(); i++)
        agent->didParseSource(compiledScripts[i]);
}

void V8DebuggerImpl::removeDebuggerAgent(int contextGroupId)
{
    ASSERT(contextGroupId);
    if (!m_debuggerAgentsMap.contains(contextGroupId))
        return;

    if (!m_pausedContext.IsEmpty() && getGroupId(m_pausedContext) == contextGroupId)
        continueProgram();

    m_debuggerAgentsMap.remove(contextGroupId);

    if (m_debuggerAgentsMap.isEmpty())
        disable();
}

V8DebuggerAgentImpl* V8DebuggerImpl::getDebuggerAgentForContext(v8::Local<v8::Context> context)
{
    int groupId = getGroupId(context);
    if (!groupId)
        return nullptr;
    return m_debuggerAgentsMap.get(groupId);
}

void V8DebuggerImpl::addRuntimeAgent(int contextGroupId, V8RuntimeAgentImpl* agent)
{
    ASSERT(contextGroupId);
    ASSERT(!m_runtimeAgentsMap.contains(contextGroupId));
    m_runtimeAgentsMap.set(contextGroupId, agent);
}

void V8DebuggerImpl::removeRuntimeAgent(int contextGroupId)
{
    ASSERT(contextGroupId);
    if (m_runtimeAgentsMap.contains(contextGroupId))
        m_runtimeAgentsMap.remove(contextGroupId);
}

V8RuntimeAgentImpl* V8DebuggerImpl::getRuntimeAgentForContext(v8::Local<v8::Context> context)
{
    int groupId = getGroupId(context);
    if (!groupId)
        return nullptr;
    return m_runtimeAgentsMap.get(groupId);
}

void V8DebuggerImpl::getCompiledScripts(int contextGroupId, protocol::Vector<V8DebuggerParsedScript>& result)
{
    v8::HandleScope scope(m_isolate);
    v8::MicrotasksScope microtasks(m_isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);
    v8::Local<v8::Object> debuggerScript = m_debuggerScript.Get(m_isolate);
    ASSERT(!debuggerScript->IsUndefined());
    v8::Local<v8::Function> getScriptsFunction = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8InternalizedString("getScripts")));
    v8::Local<v8::Value> argv[] = { v8::Integer::New(m_isolate, contextGroupId) };
    v8::Local<v8::Value> value;
    if (!getScriptsFunction->Call(debuggerContext(), debuggerScript, WTF_ARRAY_LENGTH(argv), argv).ToLocal(&value))
        return;
    ASSERT(value->IsArray());
    v8::Local<v8::Array> scriptsArray = v8::Local<v8::Array>::Cast(value);
    result.resize(scriptsArray->Length());
    for (unsigned i = 0; i < scriptsArray->Length(); ++i)
        result[i] = createParsedScript(v8::Local<v8::Object>::Cast(scriptsArray->Get(v8::Integer::New(m_isolate, i))), true);
}

String16 V8DebuggerImpl::setBreakpoint(const String16& sourceID, const ScriptBreakpoint& scriptBreakpoint, int* actualLineNumber, int* actualColumnNumber, bool interstatementLocation)
{
    v8::HandleScope scope(m_isolate);
    v8::Context::Scope contextScope(debuggerContext());

    v8::Local<v8::Object> info = v8::Object::New(m_isolate);
    info->Set(v8InternalizedString("sourceID"), toV8String(m_isolate, sourceID));
    info->Set(v8InternalizedString("lineNumber"), v8::Integer::New(m_isolate, scriptBreakpoint.lineNumber));
    info->Set(v8InternalizedString("columnNumber"), v8::Integer::New(m_isolate, scriptBreakpoint.columnNumber));
    info->Set(v8InternalizedString("interstatementLocation"), v8Boolean(interstatementLocation, m_isolate));
    info->Set(v8InternalizedString("condition"), toV8String(m_isolate, scriptBreakpoint.condition));

    v8::Local<v8::Function> setBreakpointFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.Get(m_isolate)->Get(v8InternalizedString("setBreakpoint")));
    v8::Local<v8::Value> breakpointId = v8::Debug::Call(debuggerContext(), setBreakpointFunction, info).ToLocalChecked();
    if (!breakpointId->IsString())
        return "";
    *actualLineNumber = info->Get(v8InternalizedString("lineNumber"))->Int32Value();
    *actualColumnNumber = info->Get(v8InternalizedString("columnNumber"))->Int32Value();
    return toProtocolString(breakpointId.As<v8::String>());
}

void V8DebuggerImpl::removeBreakpoint(const String16& breakpointId)
{
    v8::HandleScope scope(m_isolate);
    v8::Context::Scope contextScope(debuggerContext());

    v8::Local<v8::Object> info = v8::Object::New(m_isolate);
    info->Set(v8InternalizedString("breakpointId"), toV8String(m_isolate, breakpointId));

    v8::Local<v8::Function> removeBreakpointFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.Get(m_isolate)->Get(v8InternalizedString("removeBreakpoint")));
    v8::Debug::Call(debuggerContext(), removeBreakpointFunction, info).ToLocalChecked();
}

void V8DebuggerImpl::clearBreakpoints()
{
    v8::HandleScope scope(m_isolate);
    v8::Context::Scope contextScope(debuggerContext());

    v8::Local<v8::Function> clearBreakpoints = v8::Local<v8::Function>::Cast(m_debuggerScript.Get(m_isolate)->Get(v8InternalizedString("clearBreakpoints")));
    v8::Debug::Call(debuggerContext(), clearBreakpoints).ToLocalChecked();
}

void V8DebuggerImpl::setBreakpointsActivated(bool activated)
{
    if (!enabled()) {
        ASSERT_NOT_REACHED();
        return;
    }
    v8::HandleScope scope(m_isolate);
    v8::Context::Scope contextScope(debuggerContext());

    v8::Local<v8::Object> info = v8::Object::New(m_isolate);
    info->Set(v8InternalizedString("enabled"), v8::Boolean::New(m_isolate, activated));
    v8::Local<v8::Function> setBreakpointsActivated = v8::Local<v8::Function>::Cast(m_debuggerScript.Get(m_isolate)->Get(v8InternalizedString("setBreakpointsActivated")));
    v8::Debug::Call(debuggerContext(), setBreakpointsActivated, info).ToLocalChecked();

    m_breakpointsActivated = activated;
}

V8DebuggerImpl::PauseOnExceptionsState V8DebuggerImpl::getPauseOnExceptionsState()
{
    ASSERT(enabled());
    v8::HandleScope scope(m_isolate);
    v8::Context::Scope contextScope(debuggerContext());

    v8::Local<v8::Value> argv[] = { v8::Undefined(m_isolate) };
    v8::Local<v8::Value> result = callDebuggerMethod("pauseOnExceptionsState", 0, argv).ToLocalChecked();
    return static_cast<V8DebuggerImpl::PauseOnExceptionsState>(result->Int32Value());
}

void V8DebuggerImpl::setPauseOnExceptionsState(PauseOnExceptionsState pauseOnExceptionsState)
{
    ASSERT(enabled());
    v8::HandleScope scope(m_isolate);
    v8::Context::Scope contextScope(debuggerContext());

    v8::Local<v8::Value> argv[] = { v8::Int32::New(m_isolate, pauseOnExceptionsState) };
    callDebuggerMethod("setPauseOnExceptionsState", 1, argv);
}

void V8DebuggerImpl::setPauseOnNextStatement(bool pause)
{
    ASSERT(!m_runningNestedMessageLoop);
    if (pause)
        v8::Debug::DebugBreak(m_isolate);
    else
        v8::Debug::CancelDebugBreak(m_isolate);
}

bool V8DebuggerImpl::pausingOnNextStatement()
{
    return v8::Debug::CheckDebugBreak(m_isolate);
}

bool V8DebuggerImpl::canBreakProgram()
{
    if (!m_breakpointsActivated)
        return false;
    return m_isolate->InContext();
}

void V8DebuggerImpl::breakProgram()
{
    if (isPaused()) {
        ASSERT(!m_runningNestedMessageLoop);
        v8::Local<v8::Value> exception;
        v8::Local<v8::Array> hitBreakpoints;
        handleProgramBreak(m_pausedContext, m_executionState, exception, hitBreakpoints);
        return;
    }

    if (!canBreakProgram())
        return;

    v8::HandleScope scope(m_isolate);
    if (m_breakProgramCallbackTemplate.IsEmpty()) {
        v8::Local<v8::FunctionTemplate> templ = v8::FunctionTemplate::New(m_isolate);
        templ->SetCallHandler(&V8DebuggerImpl::breakProgramCallback, v8::External::New(m_isolate, this));
        m_breakProgramCallbackTemplate.Reset(m_isolate, templ);
    }

    v8::Local<v8::Function> breakProgramFunction = v8::Local<v8::FunctionTemplate>::New(m_isolate, m_breakProgramCallbackTemplate)->GetFunction();
    v8::Debug::Call(debuggerContext(), breakProgramFunction).ToLocalChecked();
}

void V8DebuggerImpl::continueProgram()
{
    if (isPaused())
        m_client->quitMessageLoopOnPause();
    m_pausedContext.Clear();
    m_executionState.Clear();
}

void V8DebuggerImpl::stepIntoStatement()
{
    ASSERT(isPaused());
    ASSERT(!m_executionState.IsEmpty());
    v8::HandleScope handleScope(m_isolate);
    v8::Local<v8::Value> argv[] = { m_executionState };
    callDebuggerMethod(stepIntoV8MethodName, 1, argv);
    continueProgram();
}

void V8DebuggerImpl::stepOverStatement()
{
    ASSERT(isPaused());
    ASSERT(!m_executionState.IsEmpty());
    v8::HandleScope handleScope(m_isolate);
    v8::Local<v8::Value> argv[] = { m_executionState };
    callDebuggerMethod("stepOverStatement", 1, argv);
    continueProgram();
}

void V8DebuggerImpl::stepOutOfFunction()
{
    ASSERT(isPaused());
    ASSERT(!m_executionState.IsEmpty());
    v8::HandleScope handleScope(m_isolate);
    v8::Local<v8::Value> argv[] = { m_executionState };
    callDebuggerMethod(stepOutV8MethodName, 1, argv);
    continueProgram();
}

void V8DebuggerImpl::clearStepping()
{
    ASSERT(enabled());
    v8::HandleScope scope(m_isolate);
    v8::Context::Scope contextScope(debuggerContext());

    v8::Local<v8::Value> argv[] = { v8::Undefined(m_isolate) };
    callDebuggerMethod("clearStepping", 0, argv);
}

bool V8DebuggerImpl::setScriptSource(const String16& sourceID, const String16& newContent, bool preview, ErrorString* error, Maybe<protocol::Debugger::SetScriptSourceError>* errorData, JavaScriptCallFrames* newCallFrames, Maybe<bool>* stackChanged)
{
    class EnableLiveEditScope {
    public:
        explicit EnableLiveEditScope(v8::Isolate* isolate) : m_isolate(isolate)
        {
            v8::Debug::SetLiveEditEnabled(m_isolate, true);
            inLiveEditScope = true;
        }
        ~EnableLiveEditScope()
        {
            v8::Debug::SetLiveEditEnabled(m_isolate, false);
            inLiveEditScope = false;
        }
    private:
        v8::Isolate* m_isolate;
    };

    ASSERT(enabled());
    v8::HandleScope scope(m_isolate);

    OwnPtr<v8::Context::Scope> contextScope;
    if (!isPaused())
        contextScope = adoptPtr(new v8::Context::Scope(debuggerContext()));

    v8::Local<v8::Value> argv[] = { toV8String(m_isolate, sourceID), toV8String(m_isolate, newContent), v8Boolean(preview, m_isolate) };

    v8::Local<v8::Value> v8result;
    {
        EnableLiveEditScope enableLiveEditScope(m_isolate);
        v8::TryCatch tryCatch(m_isolate);
        tryCatch.SetVerbose(false);
        v8::MaybeLocal<v8::Value> maybeResult = callDebuggerMethod("liveEditScriptSource", 3, argv);
        if (tryCatch.HasCaught()) {
            v8::Local<v8::Message> message = tryCatch.Message();
            if (!message.IsEmpty())
                *error = toProtocolStringWithTypeCheck(message->Get());
            else
                *error = "Unknown error.";
            return false;
        }
        v8result = maybeResult.ToLocalChecked();
    }
    ASSERT(!v8result.IsEmpty());
    v8::Local<v8::Object> resultTuple = v8result->ToObject(m_isolate);
    int code = static_cast<int>(resultTuple->Get(0)->ToInteger(m_isolate)->Value());
    switch (code) {
    case 0:
        {
            *stackChanged = resultTuple->Get(1)->BooleanValue();
            // Call stack may have changed after if the edited function was on the stack.
            if (!preview && isPaused())
                *newCallFrames = currentCallFrames();
            return true;
        }
    // Compile error.
    case 1:
        {
            *errorData = protocol::Debugger::SetScriptSourceError::create()
                .setMessage(toProtocolStringWithTypeCheck(resultTuple->Get(2)))
                .setLineNumber(resultTuple->Get(3)->ToInteger(m_isolate)->Value())
                .setColumnNumber(resultTuple->Get(4)->ToInteger(m_isolate)->Value()).build();
            return false;
        }
    }
    *error = "Unknown error.";
    return false;
}

JavaScriptCallFrames V8DebuggerImpl::currentCallFrames(int limit)
{
    if (!m_isolate->InContext())
        return JavaScriptCallFrames();
    v8::Local<v8::Value> currentCallFramesV8;
    if (m_executionState.IsEmpty()) {
        v8::Local<v8::Function> currentCallFramesFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.Get(m_isolate)->Get(v8InternalizedString("currentCallFrames")));
        currentCallFramesV8 = v8::Debug::Call(debuggerContext(), currentCallFramesFunction, v8::Integer::New(m_isolate, limit)).ToLocalChecked();
    } else {
        v8::Local<v8::Value> argv[] = { m_executionState, v8::Integer::New(m_isolate, limit) };
        currentCallFramesV8 = callDebuggerMethod("currentCallFrames", WTF_ARRAY_LENGTH(argv), argv).ToLocalChecked();
    }
    ASSERT(!currentCallFramesV8.IsEmpty());
    if (!currentCallFramesV8->IsArray())
        return JavaScriptCallFrames();
    v8::Local<v8::Array> callFramesArray = currentCallFramesV8.As<v8::Array>();
    JavaScriptCallFrames callFrames;
    for (size_t i = 0; i < callFramesArray->Length(); ++i) {
        v8::Local<v8::Value> callFrameValue;
        if (!callFramesArray->Get(debuggerContext(), i).ToLocal(&callFrameValue))
            return JavaScriptCallFrames();
        if (!callFrameValue->IsObject())
            return JavaScriptCallFrames();
        v8::Local<v8::Object> callFrameObject = callFrameValue.As<v8::Object>();
        callFrames.append(JavaScriptCallFrame::create(debuggerContext(), v8::Local<v8::Object>::Cast(callFrameObject)));
    }
    return callFrames;
}

static V8DebuggerImpl* toV8DebuggerImpl(v8::Local<v8::Value> data)
{
    void* p = v8::Local<v8::External>::Cast(data)->Value();
    return static_cast<V8DebuggerImpl*>(p);
}

void V8DebuggerImpl::breakProgramCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ASSERT(2 == info.Length());
    V8DebuggerImpl* thisPtr = toV8DebuggerImpl(info.Data());
    v8::Local<v8::Context> pausedContext = thisPtr->m_isolate->GetCurrentContext();
    v8::Local<v8::Value> exception;
    v8::Local<v8::Array> hitBreakpoints;
    thisPtr->handleProgramBreak(pausedContext, v8::Local<v8::Object>::Cast(info[0]), exception, hitBreakpoints);
}

void V8DebuggerImpl::handleProgramBreak(v8::Local<v8::Context> pausedContext, v8::Local<v8::Object> executionState, v8::Local<v8::Value> exception, v8::Local<v8::Array> hitBreakpointNumbers, bool isPromiseRejection)
{
    // Don't allow nested breaks.
    if (m_runningNestedMessageLoop)
        return;

    V8DebuggerAgentImpl* agent = getDebuggerAgentForContext(pausedContext);
    if (!agent)
        return;

    protocol::Vector<String16> breakpointIds;
    if (!hitBreakpointNumbers.IsEmpty()) {
        breakpointIds.resize(hitBreakpointNumbers->Length());
        for (size_t i = 0; i < hitBreakpointNumbers->Length(); i++) {
            v8::Local<v8::Value> hitBreakpointNumber = hitBreakpointNumbers->Get(i);
            ASSERT(!hitBreakpointNumber.IsEmpty() && hitBreakpointNumber->IsInt32());
            breakpointIds[i] = String16::number(hitBreakpointNumber->Int32Value());
        }
    }

    m_pausedContext = pausedContext;
    m_executionState = executionState;
    V8DebuggerAgentImpl::SkipPauseRequest result = agent->didPause(pausedContext, exception, breakpointIds, isPromiseRejection);
    if (result == V8DebuggerAgentImpl::RequestNoSkip) {
        m_runningNestedMessageLoop = true;
        int groupId = getGroupId(pausedContext);
        ASSERT(groupId);
        m_client->runMessageLoopOnPause(groupId);
        // The agent may have been removed in the nested loop.
        agent = getDebuggerAgentForContext(pausedContext);
        if (agent)
            agent->didContinue();
        m_runningNestedMessageLoop = false;
    }
    m_pausedContext.Clear();
    m_executionState.Clear();

    if (result == V8DebuggerAgentImpl::RequestStepFrame) {
        v8::Local<v8::Value> argv[] = { executionState };
        callDebuggerMethod("stepFrameStatement", 1, argv);
    } else if (result == V8DebuggerAgentImpl::RequestStepInto) {
        v8::Local<v8::Value> argv[] = { executionState };
        callDebuggerMethod(stepIntoV8MethodName, 1, argv);
    } else if (result == V8DebuggerAgentImpl::RequestStepOut) {
        v8::Local<v8::Value> argv[] = { executionState };
        callDebuggerMethod(stepOutV8MethodName, 1, argv);
    }
}

void V8DebuggerImpl::v8DebugEventCallback(const v8::Debug::EventDetails& eventDetails)
{
    V8DebuggerImpl* thisPtr = toV8DebuggerImpl(eventDetails.GetCallbackData());
    thisPtr->handleV8DebugEvent(eventDetails);
}

v8::Local<v8::Value> V8DebuggerImpl::callInternalGetterFunction(v8::Local<v8::Object> object, const char* functionName)
{
    v8::MicrotasksScope microtasks(m_isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);
    v8::Local<v8::Value> getterValue = object->Get(v8InternalizedString(functionName));
    ASSERT(!getterValue.IsEmpty() && getterValue->IsFunction());
    return v8::Local<v8::Function>::Cast(getterValue)->Call(m_isolate->GetCurrentContext(), object, 0, 0).ToLocalChecked();
}

void V8DebuggerImpl::handleV8DebugEvent(const v8::Debug::EventDetails& eventDetails)
{
    if (!enabled())
        return;
    v8::DebugEvent event = eventDetails.GetEvent();
    if (event != v8::AsyncTaskEvent && event != v8::Break && event != v8::Exception && event != v8::AfterCompile && event != v8::BeforeCompile && event != v8::CompileError)
        return;

    v8::Local<v8::Context> eventContext = eventDetails.GetEventContext();
    ASSERT(!eventContext.IsEmpty());

    V8DebuggerAgentImpl* agent = getDebuggerAgentForContext(eventContext);
    if (agent) {
        v8::HandleScope scope(m_isolate);
        if (event == v8::AfterCompile || event == v8::CompileError) {
            v8::Context::Scope contextScope(debuggerContext());
            v8::Local<v8::Value> argv[] = { eventDetails.GetEventData() };
            v8::Local<v8::Value> value = callDebuggerMethod("getAfterCompileScript", 1, argv).ToLocalChecked();
            ASSERT(value->IsObject());
            v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(value);
            agent->didParseSource(createParsedScript(object, event == v8::AfterCompile));
        } else if (event == v8::Exception) {
            v8::Local<v8::Object> eventData = eventDetails.GetEventData();
            v8::Local<v8::Value> exception = callInternalGetterFunction(eventData, "exception");
            v8::Local<v8::Value> promise = callInternalGetterFunction(eventData, "promise");
            bool isPromiseRejection = !promise.IsEmpty() && promise->IsObject();
            handleProgramBreak(eventContext, eventDetails.GetExecutionState(), exception, v8::Local<v8::Array>(), isPromiseRejection);
        } else if (event == v8::Break) {
            v8::Local<v8::Value> argv[] = { eventDetails.GetEventData() };
            v8::Local<v8::Value> hitBreakpoints = callDebuggerMethod("getBreakpointNumbers", 1, argv).ToLocalChecked();
            ASSERT(hitBreakpoints->IsArray());
            handleProgramBreak(eventContext, eventDetails.GetExecutionState(), v8::Local<v8::Value>(), hitBreakpoints.As<v8::Array>());
        } else if (event == v8::AsyncTaskEvent) {
            if (agent->v8AsyncTaskEventsEnabled())
                handleV8AsyncTaskEvent(agent, eventContext, eventDetails.GetExecutionState(), eventDetails.GetEventData());
        }
    }
}

void V8DebuggerImpl::handleV8AsyncTaskEvent(V8DebuggerAgentImpl* agent, v8::Local<v8::Context> context, v8::Local<v8::Object> executionState, v8::Local<v8::Object> eventData)
{
    String16 type = toProtocolStringWithTypeCheck(callInternalGetterFunction(eventData, "type"));
    String16 name = toProtocolStringWithTypeCheck(callInternalGetterFunction(eventData, "name"));
    int id = callInternalGetterFunction(eventData, "id")->ToInteger(m_isolate)->Value();

    m_pausedContext = context;
    m_executionState = executionState;
    agent->didReceiveV8AsyncTaskEvent(context, type, name, id);
    m_pausedContext.Clear();
    m_executionState.Clear();
}

V8DebuggerParsedScript V8DebuggerImpl::createParsedScript(v8::Local<v8::Object> object, bool success)
{
    v8::Local<v8::Value> id = object->Get(v8InternalizedString("id"));
    ASSERT(!id.IsEmpty() && id->IsInt32());

    V8DebuggerParsedScript parsedScript;
    parsedScript.scriptId = String16::number(id->Int32Value());
    parsedScript.script.setURL(toProtocolStringWithTypeCheck(object->Get(v8InternalizedString("name"))))
        .setSourceURL(toProtocolStringWithTypeCheck(object->Get(v8InternalizedString("sourceURL"))))
        .setSourceMappingURL(toProtocolStringWithTypeCheck(object->Get(v8InternalizedString("sourceMappingURL"))))
        .setSource(toProtocolStringWithTypeCheck(object->Get(v8InternalizedString("source"))))
        .setStartLine(object->Get(v8InternalizedString("startLine"))->ToInteger(m_isolate)->Value())
        .setStartColumn(object->Get(v8InternalizedString("startColumn"))->ToInteger(m_isolate)->Value())
        .setEndLine(object->Get(v8InternalizedString("endLine"))->ToInteger(m_isolate)->Value())
        .setEndColumn(object->Get(v8InternalizedString("endColumn"))->ToInteger(m_isolate)->Value())
        .setIsContentScript(object->Get(v8InternalizedString("isContentScript"))->ToBoolean(m_isolate)->Value())
        .setIsInternalScript(object->Get(v8InternalizedString("isInternalScript"))->ToBoolean(m_isolate)->Value())
        .setExecutionContextId(object->Get(v8InternalizedString("executionContextId"))->ToInteger(m_isolate)->Value())
        .setIsLiveEdit(inLiveEditScope);
    parsedScript.success = success;
    return parsedScript;
}

void V8DebuggerImpl::compileDebuggerScript()
{
    if (!m_debuggerScript.IsEmpty()) {
        ASSERT_NOT_REACHED();
        return;
    }

    v8::HandleScope scope(m_isolate);
    v8::Context::Scope contextScope(debuggerContext());

    v8::Local<v8::String> scriptValue = v8::String::NewFromUtf8(m_isolate, DebuggerScript_js, v8::NewStringType::kInternalized, sizeof(DebuggerScript_js)).ToLocalChecked();
    v8::Local<v8::Value> value;
    if (!compileAndRunInternalScript(debuggerContext(), scriptValue).ToLocal(&value))
        return;
    ASSERT(value->IsObject());
    m_debuggerScript.Reset(m_isolate, value.As<v8::Object>());
}

v8::Local<v8::Context> V8DebuggerImpl::debuggerContext() const
{
    ASSERT(!m_debuggerContext.IsEmpty());
    return m_debuggerContext.Get(m_isolate);
}

v8::Local<v8::String> V8DebuggerImpl::v8InternalizedString(const char* str) const
{
    return v8::String::NewFromUtf8(m_isolate, str, v8::NewStringType::kInternalized).ToLocalChecked();
}

v8::MaybeLocal<v8::Value> V8DebuggerImpl::functionScopes(v8::Local<v8::Function> function)
{
    if (!enabled()) {
        ASSERT_NOT_REACHED();
        return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
    }
    v8::Local<v8::Value> argv[] = { function };
    return callDebuggerMethod("getFunctionScopes", 1, argv);
}

v8::Local<v8::Value> V8DebuggerImpl::generatorObjectDetails(v8::Local<v8::Object>& object)
{
    if (!enabled()) {
        ASSERT_NOT_REACHED();
        return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
    }
    v8::Local<v8::Value> argv[] = { object };
    return callDebuggerMethod("getGeneratorObjectDetails", 1, argv).ToLocalChecked();
}

v8::Local<v8::Value> V8DebuggerImpl::collectionEntries(v8::Local<v8::Object>& object)
{
    if (!enabled()) {
        ASSERT_NOT_REACHED();
        return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
    }
    v8::Local<v8::Value> argv[] = { object };
    return callDebuggerMethod("getCollectionEntries", 1, argv).ToLocalChecked();
}

bool V8DebuggerImpl::isPaused()
{
    return !m_pausedContext.IsEmpty();
}

v8::MaybeLocal<v8::Value> V8DebuggerImpl::runCompiledScript(v8::Local<v8::Context> context, v8::Local<v8::Script> script)
{
    // TODO(dgozman): get rid of this check.
    if (!m_client->isExecutionAllowed())
        return v8::MaybeLocal<v8::Value>();

    v8::MicrotasksScope microtasksScope(m_isolate, v8::MicrotasksScope::kRunMicrotasks);
    int groupId = getGroupId(context);
    V8DebuggerAgentImpl* agent = groupId ? m_debuggerAgentsMap.get(groupId) : nullptr;
    if (agent)
        agent->willExecuteScript(script->GetUnboundScript()->GetId());
    v8::MaybeLocal<v8::Value> result = script->Run(context);
    // Get agent from the map again, since it could have detached during script execution.
    agent = groupId ? m_debuggerAgentsMap.get(groupId) : nullptr;
    if (agent)
        agent->didExecuteScript();
    return result;
}

v8::MaybeLocal<v8::Value> V8DebuggerImpl::callFunction(v8::Local<v8::Function> function, v8::Local<v8::Context> context, v8::Local<v8::Value> receiver, int argc, v8::Local<v8::Value> info[])
{
    // TODO(dgozman): get rid of this check.
    if (!m_client->isExecutionAllowed())
        return v8::MaybeLocal<v8::Value>();

    v8::MicrotasksScope microtasksScope(m_isolate, v8::MicrotasksScope::kRunMicrotasks);
    int groupId = getGroupId(context);
    V8DebuggerAgentImpl* agent = groupId ? m_debuggerAgentsMap.get(groupId) : nullptr;
    if (agent)
        agent->willExecuteScript(function->ScriptId());
    v8::MaybeLocal<v8::Value> result = function->Call(context, receiver, argc, info);
    // Get agent from the map again, since it could have detached during script execution.
    agent = groupId ? m_debuggerAgentsMap.get(groupId) : nullptr;
    if (agent)
        agent->didExecuteScript();
    return result;
}

v8::MaybeLocal<v8::Value> V8DebuggerImpl::compileAndRunInternalScript(v8::Local<v8::Context> context, v8::Local<v8::String> source)
{
    v8::Local<v8::Script> script = compileInternalScript(context, source, String());
    if (script.IsEmpty())
        return v8::MaybeLocal<v8::Value>();
    v8::MicrotasksScope microtasksScope(m_isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);
    return script->Run(context);
}

v8::Local<v8::Script> V8DebuggerImpl::compileInternalScript(v8::Local<v8::Context> context, v8::Local<v8::String> code, const String16& fileName)
{
    // NOTE: For compatibility with WebCore, ScriptSourceCode's line starts at
    // 1, whereas v8 starts at 0.
    v8::ScriptOrigin origin(
        toV8String(m_isolate, fileName),
        v8::Integer::New(m_isolate, 0),
        v8::Integer::New(m_isolate, 0),
        v8::False(m_isolate), // sharable
        v8::Local<v8::Integer>(),
        v8::True(m_isolate), // internal
        toV8String(m_isolate, String16()), // sourceMap
        v8::True(m_isolate)); // opaqueresource
    v8::ScriptCompiler::Source source(code, origin);
    v8::Local<v8::Script> script;
    if (!v8::ScriptCompiler::Compile(context, &source, v8::ScriptCompiler::kNoCompileOptions).ToLocal(&script))
        return v8::Local<v8::Script>();
    return script;
}

PassOwnPtr<V8StackTrace> V8DebuggerImpl::createStackTrace(v8::Local<v8::StackTrace> stackTrace, size_t maxStackSize)
{
    V8DebuggerAgentImpl* agent = getDebuggerAgentForContext(m_isolate->GetCurrentContext());
    return V8StackTraceImpl::create(agent, stackTrace, maxStackSize);
}

void V8DebuggerImpl::contextCreated(const V8ContextInfo& info)
{
    V8RuntimeAgentImpl* agent = getRuntimeAgentForContext(info.context);
    if (agent)
        agent->reportExecutionContextCreated(info);
}

void V8DebuggerImpl::contextDestroyed(v8::Local<v8::Context> context)
{
    V8RuntimeAgentImpl* agent = getRuntimeAgentForContext(context);
    if (agent)
        agent->reportExecutionContextDestroyed(context);
}

void V8DebuggerImpl::resetContextGroup(int contextGroupId)
{
    V8DebuggerAgentImpl* debuggerAgent = m_debuggerAgentsMap.get(contextGroupId);
    if (debuggerAgent)
        debuggerAgent->reset();
    V8RuntimeAgentImpl* runtimeAgent = m_runtimeAgentsMap.get(contextGroupId);
    if (runtimeAgent)
        runtimeAgent->reset();
}

PassOwnPtr<V8StackTrace> V8DebuggerImpl::captureStackTrace(size_t maxStackSize)
{
    V8DebuggerAgentImpl* agent = getDebuggerAgentForContext(m_isolate->GetCurrentContext());
    return V8StackTraceImpl::capture(agent, maxStackSize);
}

v8::Local<v8::Context> V8DebuggerImpl::regexContext()
{
    if (m_regexContext.IsEmpty())
        m_regexContext.Reset(m_isolate, v8::Context::New(m_isolate));
    return m_regexContext.Get(m_isolate);
}

} // namespace blink