summaryrefslogtreecommitdiff
path: root/plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFunctionBreakpoint.java
blob: 03a9ce5ab3141ab945b06bf4e99cffe9f68fae69 (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
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package org.jetbrains.kotlin.idea.debugger.breakpoints;

import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.JavaDebuggerBundle;
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.*;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.engine.requests.RequestManagerImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.impl.PositionUtil;
import com.intellij.debugger.jdi.ClassesByNameProvider;
import com.intellij.debugger.jdi.MethodBytecodeUtil;
import com.intellij.debugger.requests.Requestor;
import com.intellij.debugger.ui.breakpoints.BreakpointWithHighlighter;
import com.intellij.debugger.ui.breakpoints.FilteredRequestor;
import com.intellij.debugger.ui.breakpoints.MethodBreakpoint;
import com.intellij.debugger.ui.breakpoints.MethodBreakpointBase;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.progress.*;
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator;
import com.intellij.openapi.progress.util.ProgressWindow;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizerUtil;
import com.intellij.openapi.util.Key;
import com.intellij.psi.*;
import com.intellij.ui.LayeredIcon;
import com.intellij.util.DocumentUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.xdebugger.breakpoints.XBreakpoint;
import com.intellij.xdebugger.breakpoints.XBreakpointListener;
import com.intellij.xdebugger.impl.XDebugSessionImpl;
import com.sun.jdi.*;
import com.sun.jdi.event.LocatableEvent;
import com.sun.jdi.event.MethodEntryEvent;
import com.sun.jdi.event.MethodExitEvent;
import com.sun.jdi.request.*;
import one.util.streamex.StreamEx;
import org.jdom.Element;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.java.debugger.breakpoints.properties.JavaMethodBreakpointProperties;
import org.jetbrains.kotlin.analysis.decompiler.psi.file.KtClsFile;
import org.jetbrains.kotlin.asJava.LightClassUtilsKt;
import org.jetbrains.kotlin.asJava.builder.LightMemberOrigin;
import org.jetbrains.kotlin.asJava.elements.KtLightMethod;
import org.jetbrains.kotlin.idea.debugger.KotlinDebuggerCoreBundle;
import org.jetbrains.kotlin.idea.decompiler.navigation.SourceNavigationHelper;
import org.jetbrains.kotlin.psi.KtClass;
import org.jetbrains.kotlin.psi.KtClassOrObject;
import org.jetbrains.kotlin.psi.KtDeclaration;
import org.jetbrains.kotlin.psi.KtPrimaryConstructor;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Opcodes;

import javax.swing.*;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.stream.Stream;

import static org.jetbrains.kotlin.idea.util.application.ApplicationUtilsKt.isDispatchThread;
import static org.jetbrains.kotlin.idea.util.application.ApplicationUtilsKt.isUnitTestMode;

// This class is copied from com.intellij.debugger.ui.breakpoints.MethodBreakpoint.
// Changed parts are marked with '// MODIFICATION: ' comments.
// This should be deleted when IDEA opens the method breakpoint API (presumably in 193).
public class KotlinFunctionBreakpoint extends BreakpointWithHighlighter<JavaMethodBreakpointProperties> implements MethodBreakpointBase {
    private static final Logger LOG = Logger.getInstance(KotlinFunctionBreakpoint.class);
    @Nullable private JVMName mySignature;
    private boolean myIsStatic;

    protected KotlinFunctionBreakpoint(@NotNull Project project, XBreakpoint breakpoint) {
        super(project, breakpoint);
    }

    public boolean isStatic() {
        return myIsStatic;
    }

    @Override
    @NotNull
    public Key<MethodBreakpoint> getCategory() {
        return MethodBreakpoint.CATEGORY;
    }

    @Override
    public boolean isValid() {
         return super.isValid() && getMethodName() != null;
    }

    // MODIFICATION: Start Kotlin implementation
    @Override
    public void reload() {
        super.reload();

        setMethodName(null);
        mySignature = null;

        Project project = myProject;
        Task.Backgroundable task = new Task.Backgroundable(project, KotlinDebuggerCoreBundle.message("function.breakpoint.initialize")) {
            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                SourcePosition sourcePosition = KotlinFunctionBreakpoint.this.getSourcePosition();
                MethodDescriptor descriptor =
                        sourcePosition == null
                        ? null
                        : DumbService.getInstance(project).runReadActionInSmartMode(() -> getMethodDescriptor(project, sourcePosition));

                ProgressIndicatorProvider.checkCanceled();

                String methodName = descriptor == null ? null : descriptor.methodName;
                JVMName methodSignature = descriptor == null ? null : descriptor.methodSignature;
                boolean methodIsStatic = descriptor != null && descriptor.isStatic;

                PsiClass psiClass = KotlinFunctionBreakpoint.this.getPsiClass();

                ProgressIndicatorProvider.checkCanceled();

                KotlinFunctionBreakpoint.this.setMethodName(methodName);
                KotlinFunctionBreakpoint.this.mySignature = methodSignature;
                KotlinFunctionBreakpoint.this.myIsStatic = methodIsStatic;

                if (psiClass != null) {
                    KotlinFunctionBreakpoint.this.getProperties().myClassPattern =
                            ReadAction.compute(() -> psiClass.getQualifiedName());
                }
                if (methodIsStatic) {
                    KotlinFunctionBreakpoint.this.setInstanceFiltersEnabled(false);
                }
            }
        };

        ProgressManager progressManager = ProgressManager.getInstance();
        if (isDispatchThread() && !isUnitTestMode()) {
            progressManager.runProcessWithProgressAsynchronously(task, new BackgroundableProcessIndicator(task));
        } else {
            EmptyProgressIndicator progressIndicator = new EmptyProgressIndicator();
            progressManager.runProcess(() -> task.run(progressIndicator), progressIndicator);
        }
    }

    @Override
    public PsiClass getPsiClass() {
        SourcePosition sourcePosition = getSourcePosition();
        KtClassOrObject declaration = PositionUtil.getPsiElementAt(myProject, KtClassOrObject.class, sourcePosition);

        if (declaration == null) {
            return null;
        }

        return DumbService.getInstance(myProject).runReadActionInSmartMode(() -> LightClassUtilsKt.toLightClass(declaration));
    }

    // MODIFICATION: End Kotlin implementation

    private static void createRequestForSubClasses(
            @NotNull MethodBreakpointBase breakpoint,
            @NotNull DebugProcessImpl debugProcess,
            @NotNull ReferenceType baseType
    ) {
        DebuggerManagerThreadImpl.assertIsManagerThread();
        RequestManagerImpl requestsManager = debugProcess.getRequestsManager();
        ClassPrepareRequest request = requestsManager.createClassPrepareRequest((debuggerProcess, referenceType) -> {
            if (instanceOf(referenceType, baseType)) {
                createRequestForPreparedClassEmulated(breakpoint, debugProcess, referenceType, false);
            }
        }, null);
        if (request != null) {
            requestsManager.registerRequest(breakpoint, request);
            request.enable();
        }

        AtomicReference<ProgressWindow> indicatorRef = new AtomicReference<>();
        ApplicationManager.getApplication().invokeAndWait(
                () -> {
                    ProgressWindow progress =
                            new ProgressWindow(
                                    true, false, debugProcess.getProject(),
                                    KotlinDebuggerCoreBundle.message("function.breakpoint.cancel.emulation")
                            );
                    progress.setDelayInMillis(2000);
                    indicatorRef.set(progress);
                });
        ProgressWindow indicator = indicatorRef.get();

        AtomicBoolean changed = new AtomicBoolean();
        XBreakpointListener<XBreakpoint<?>> listener = new XBreakpointListener<XBreakpoint<?>>() {
            void changed(@NotNull XBreakpoint b) {
                if (b == breakpoint.getXBreakpoint()) {
                    changed.set(true);
                    indicator.cancel();
                }
            }

            @Override
            public void breakpointRemoved(@NotNull XBreakpoint b) {
                changed(b);
            }

            @Override
            public void breakpointChanged(@NotNull XBreakpoint b) {
                changed(b);
            }
        };

        BreakpointListenerConnector.subscribe(debugProcess, indicator, listener);
        ProgressManager.getInstance().executeProcessUnderProgress(
                () -> processPreparedSubTypes(
                        baseType,
                        (subType, classesByName) ->
                                createRequestForPreparedClassEmulated(breakpoint, debugProcess, subType, classesByName, false),
                        indicator),
                indicator);
        if (indicator.isCanceled() && !changed.get()) {
            breakpoint.disableEmulation();
        }
    }

    @Override
    public void disableEmulation() {
        MethodBreakpointBase.disableEmulation(this);
    }

    private static void createRequestForPreparedClassEmulated(
            @NotNull MethodBreakpointBase breakpoint,
            @NotNull DebugProcessImpl debugProcess,
            @NotNull ReferenceType classType,
            boolean base
    ) {
        createRequestForPreparedClassEmulated(
                breakpoint, debugProcess, classType,
                debugProcess.getVirtualMachineProxy().getClassesByNameProvider(), base);
    }

    private static boolean shouldCreateRequest(XBreakpoint xBreakpoint, DebugProcessImpl debugProcess) {
        return DumbService.getInstance(debugProcess.getProject()).runReadActionInSmartMode(() -> {
            JavaDebugProcess process = debugProcess.getXdebugProcess();
            return process != null
                   && debugProcess.isAttached()
                   && (xBreakpoint == null || ((XDebugSessionImpl) process.getSession()).isBreakpointActive(xBreakpoint));
        });
    }

    private static void createRequestForPreparedClassEmulated(
            @NotNull MethodBreakpointBase breakpoint,
            @NotNull DebugProcessImpl debugProcess,
            @NotNull ReferenceType classType,
            @NotNull ClassesByNameProvider classesByName,
            boolean base
    ) {
        if (!MethodBreakpointBase.canBeEmulated(debugProcess)) {
            breakpoint.disableEmulation();
            return;
        }
        if (!base && !shouldCreateRequest(breakpoint.getXBreakpoint(), debugProcess)) {
            return;
        }
        Method lambdaMethod = MethodBytecodeUtil.getLambdaMethod(classType, classesByName);
        if (lambdaMethod != null &&
            breakpoint
                    .matchingMethods(StreamEx.of(((ClassType) classType).interfaces()).flatCollection(ReferenceType::allMethods),
                                     debugProcess)
                    .findFirst().isEmpty()) {
            return;
        }
        StreamEx<Method> methods = lambdaMethod != null
                                   ? StreamEx.of(lambdaMethod)
                                   : breakpoint.matchingMethods(StreamEx.of(classType.methods()).filter(m -> base || !m.isAbstract()),
                                                                debugProcess);
        boolean found = false;
        for (Method method : methods) {
            found = true;
            if (method.isNative()) {
                breakpoint.disableEmulation();
                return;
            }
            Method target = MethodBytecodeUtil.getBridgeTargetMethod(method, classesByName);
            if (target != null && !ContainerUtil.isEmpty(DebuggerUtilsEx.allLineLocations(target))) {
                method = target;
            }

            List<Location> allLineLocations = DebuggerUtilsEx.allLineLocations(method);
            if (allLineLocations == null && !method.isBridge()) { // no line numbers
                breakpoint.disableEmulation();
                return;
            }
            if (!ContainerUtil.isEmpty(allLineLocations)) {
                if (breakpoint.isWatchEntry()) {
                    createLocationBreakpointRequest(breakpoint, ContainerUtil.getFirstItem(allLineLocations), debugProcess, true);
                }
                if (breakpoint.isWatchExit()) {
                    MethodBytecodeUtil.visit(method, new MethodVisitor(Opcodes.API_VERSION) {
                        int myLastLine = 0;

                        @Override
                        public void visitLineNumber(int line, Label start) {
                            myLastLine = line;
                        }

                        @Override
                        public void visitInsn(int opcode) {
                            switch (opcode) {
                                case Opcodes.RETURN:
                                case Opcodes.IRETURN:
                                case Opcodes.FRETURN:
                                case Opcodes.ARETURN:
                                case Opcodes.LRETURN:
                                case Opcodes.DRETURN:
                                    //case Opcodes.ATHROW:
                                    allLineLocations.stream()
                                            .filter(l -> l.lineNumber() == myLastLine)
                                            .findFirst().ifPresent(
                                            location -> createLocationBreakpointRequest(breakpoint, location, debugProcess, false));
                            }
                        }
                    }, true);
                }
            }
        }
        if (base && found) {
            // desired class found - now also track all new classes
            createRequestForSubClasses(breakpoint, debugProcess, classType);
        }
    }

    private static void createLocationBreakpointRequest(
            @NotNull FilteredRequestor requestor,
            @Nullable Location location,
            @NotNull DebugProcessImpl debugProcess,
            boolean methodEntry
    ) {
        BreakpointRequest request = createLocationBreakpointRequest(requestor, location, debugProcess);
        if (request != null) {
            request.putProperty(METHOD_ENTRY_KEY, methodEntry);
        }
    }

    @Nullable
    private static BreakpointRequest createLocationBreakpointRequest(
            @NotNull FilteredRequestor requestor,
            @Nullable Location location,
            @NotNull DebugProcessImpl debugProcess
    ) {
        if (location != null) {
            RequestManagerImpl requestsManager = debugProcess.getRequestsManager();
            BreakpointRequest request = requestsManager.createBreakpointRequest(requestor, location);
            requestsManager.enableRequest(request);
            return request;
        }
        return null;
    }

    @Override
    protected void createRequestForPreparedClass(@NotNull DebugProcessImpl debugProcess, @NotNull ReferenceType classType) {
        if (isEmulated()) {
            createRequestForPreparedClassEmulated(this, debugProcess, classType, true);
        } else {
            createRequestForPreparedClassOriginal(debugProcess, classType);
        }
    }

    private void createRequestForPreparedClassOriginal(@NotNull DebugProcessImpl debugProcess, @NotNull ReferenceType classType) {
        try {
            boolean hasMethod = false;
            for (Method method : classType.allMethods()) {
                String signature = method.signature();
                String name = method.name();

                String nameFromProperties = getMethodName();
                if (nameFromProperties != null && mySignature != null) {
                    if (nameFromProperties.equals(name) && mySignature.getName(debugProcess).equals(signature)) {
                        hasMethod = true;
                        break;
                    }
                }
            }

            if (!hasMethod) {
                debugProcess.getRequestsManager().setInvalid(
                        this, JavaDebuggerBundle.message("error.invalid.breakpoint.method.not.found", classType.name())
                );
                return;
            }

            RequestManagerImpl requestManager = debugProcess.getRequestsManager();
            if (isWatchEntry()) {
                MethodEntryRequest entryRequest = findRequest(debugProcess, MethodEntryRequest.class, this);
                if (entryRequest == null) {
                    entryRequest = requestManager.createMethodEntryRequest(this);
                } else {
                    entryRequest.disable();
                }
                //entryRequest.addClassFilter(myClassQualifiedName);
                // use addClassFilter(ReferenceType) in order to stop on subclasses also!
                entryRequest.addClassFilter(classType);
                debugProcess.getRequestsManager().enableRequest(entryRequest);
            }
            if (isWatchExit()) {
                MethodExitRequest exitRequest = findRequest(debugProcess, MethodExitRequest.class, this);
                if (exitRequest == null) {
                    exitRequest = requestManager.createMethodExitRequest(this);
                } else {
                    exitRequest.disable();
                }
                //exitRequest.addClassFilter(myClassQualifiedName);
                exitRequest.addClassFilter(classType);
                debugProcess.getRequestsManager().enableRequest(exitRequest);
            }
        } catch (Exception e) {
            LOG.debug(e);
        }
    }

    @Override
    public String getEventMessage(@NotNull LocatableEvent event) {
        return getEventMessage(event, getFileName());
    }

    @Nls
    private static String getEventMessage(@NotNull LocatableEvent event, @NotNull String defaultFileName) {
        Location location = event.location();
        if (event instanceof MethodEntryEvent) {
            return getEventMessage(true, ((MethodEntryEvent) event).method(), location, defaultFileName);
        }
        if (event instanceof MethodExitEvent) {
            return getEventMessage(false, ((MethodExitEvent) event).method(), location, defaultFileName);
        }
        Object entryProperty = event.request().getProperty(METHOD_ENTRY_KEY);
        if (entryProperty instanceof Boolean) {
            return getEventMessage((Boolean) entryProperty, location.method(), location, defaultFileName);
        }
        return "";
    }

    @Nls
    private static String getEventMessage(boolean entry, Method method, Location location, String defaultFileName) {
        String locationQName = DebuggerUtilsEx.getLocationMethodQName(location);
        String locationFileName = DebuggerUtilsEx.getSourceName(location, e -> defaultFileName);
        int locationLine = location.lineNumber();
        return JavaDebuggerBundle.message(entry ? "status.method.entry.breakpoint.reached" : "status.method.exit.breakpoint.reached",
                                      method.declaringType().name() + "." + method.name() + "()",
                                      locationQName,
                                      locationFileName,
                                      locationLine
        );
    }

    @Override
    public PsiElement getEvaluationElement() {
        return getPsiClass();
    }

    @Override
    protected Icon getDisabledIcon(boolean isMuted) {
        if (DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().findMasterBreakpoint(this) != null && isMuted) {
            return AllIcons.Debugger.Db_muted_dep_method_breakpoint;
        }
        return null;
    }

    @Override
    protected Icon getVerifiedIcon(boolean isMuted) {
        return isSuspend() ? AllIcons.Debugger.Db_verified_method_breakpoint : AllIcons.Debugger.Db_verified_no_suspend_method_breakpoint;
    }

    @Override
    @NotNull
    protected Icon getVerifiedWarningsIcon(boolean isMuted) {
        return new LayeredIcon(isMuted ? AllIcons.Debugger.Db_muted_method_breakpoint : AllIcons.Debugger.Db_method_breakpoint,
                               AllIcons.General.WarningDecorator);
    }

    @Override
    public String getDisplayName() {
        StringBuilder buffer = new StringBuilder();
        if (isValid()) {
            String className = getClassName();
            boolean classNameExists = className != null && className.length() > 0;
            if (classNameExists) {
                buffer.append(className);
            }
            if (getMethodName() != null) {
                if (classNameExists) {
                    buffer.append(".");
                }
                buffer.append(getMethodName());
            }
        } else {
            buffer.append(JavaDebuggerBundle.message("status.breakpoint.invalid"));
        }
        @SuppressWarnings("HardCodedStringLiteral")
        String s = buffer.toString();
        return s;
    }

    @Override
    public boolean evaluateCondition(@NotNull EvaluationContextImpl context, @NotNull LocatableEvent event) throws EvaluateException {
        if (!matchesEvent(event, context.getDebugProcess())) {
            return false;
        }
        return super.evaluateCondition(context, event);
    }

    private boolean matchesEvent(@NotNull LocatableEvent event, DebugProcessImpl process) throws EvaluateException {
        if (isEmulated()) {
            return true;
        }
        if (getMethodName() == null || mySignature == null) {
            return false;
        }
        Method method = event.location().method();
        return method != null && method.name().equals(getMethodName()) && method.signature().equals(mySignature.getName(process));
    }

    @Nullable
    public static KotlinFunctionBreakpoint create(@NotNull Project project, XBreakpoint xBreakpoint) {
        KotlinFunctionBreakpoint breakpoint = new KotlinFunctionBreakpoint(project, xBreakpoint);
        return (KotlinFunctionBreakpoint) breakpoint.init();
    }

    //public boolean canMoveTo(final SourcePosition position) {
    //  return super.canMoveTo(position) && PositionUtil.getPsiElementAt(getProject(), PsiMethod.class, position) != null;
    //}

    /**
     * finds FQ method's class name and method's signature
     */
    @Nullable
    private static MethodDescriptor getMethodDescriptor(@NotNull Project project, @NotNull SourcePosition sourcePosition) {
        Document document = PsiDocumentManager.getInstance(project).getDocument(sourcePosition.getFile());
        if (document == null) {
            return null;
        }
        //final int endOffset = document.getLineEndOffset(sourcePosition);
        //final MethodDescriptor descriptor = docManager.commitAndRunReadAction(new Computable<MethodDescriptor>() {
        // conflicts with readAction on initial breakpoints creation
        MethodDescriptor descriptor = DumbService.getInstance(project).runReadActionInSmartMode(() -> {
            // MODIFICATION: Start Kotlin implementation
            PsiMethod method = resolveJvmMethodFromKotlinDeclaration(project, sourcePosition);
            if (method == null) {
                return null;
            }

            KtDeclaration kotlinOrigin = getSourceOrigin(method);

            if (kotlinOrigin != null) {
                int offset = kotlinOrigin.getTextOffset();
                if (!DocumentUtil.isValidOffset(offset, document) || document.getLineNumber(offset) < sourcePosition.getLine()) {
                    return null;
                }
            }

            MethodDescriptor res = new MethodDescriptor();
            res.methodName = JVMNameUtil.getJVMMethodName(method);

            try {
                res.methodSignature = JVMNameUtil.getJVMSignature(method);
                res.isStatic = method.hasModifierProperty(PsiModifier.STATIC);
            } catch (IndexNotReadyException ignored) {
                return null;
            }

            return res;
            // MODIFICATION: End Kotlin implementation
        });
        if (descriptor == null || descriptor.methodName == null || descriptor.methodSignature == null) {
            return null;
        }
        return descriptor;
    }

    // MODIFICATION: Start Kotlin implementation
    @Nullable
    private static KtDeclaration getSourceOrigin(PsiMethod method) {
        if (method instanceof KtLightMethod) {
            KtLightMethod lightMethod = (KtLightMethod) method;
            LightMemberOrigin lightMemberOrigin = lightMethod.getLightMemberOrigin();
            if (lightMemberOrigin != null) {
                KtDeclaration originalElement = lightMemberOrigin.getAuxiliaryOriginalElement();
                if (originalElement == null) {
                    originalElement = lightMemberOrigin.getOriginalElement();
                }

                if (originalElement != null) {
                    KtDeclaration sourceOrigin = SourceNavigationHelper.INSTANCE.getNavigationElement(originalElement);
                    if (sourceOrigin.getContainingFile() instanceof KtClsFile) {
                        return null;
                    }
                    return sourceOrigin;
                }
            }
        }

        return null;
    }

    @Nullable
    private static PsiMethod resolveJvmMethodFromKotlinDeclaration(@NotNull Project project, @NotNull SourcePosition sourcePosition) {
        KtDeclaration declaration = PositionUtil.getPsiElementAt(project, KtDeclaration.class, sourcePosition);

        if (declaration instanceof KtClass) {
            KtPrimaryConstructor constructor = ((KtClass) declaration).getPrimaryConstructor();
            if (constructor != null) {
                declaration = constructor;
            } else {
                PsiClass lightClass = LightClassUtilsKt.toLightClass((KtClassOrObject) declaration);
                if (lightClass != null) {
                    PsiMethod[] constructors = lightClass.getConstructors();
                    if (constructors.length > 0) {
                        return constructors[0];
                    }
                }

                return null;
            }
        }

        if (declaration == null) {
            return null;
        }

        KtDeclaration originalDeclaration = SourceNavigationHelper.INSTANCE.getOriginalElement(declaration);
        for (PsiElement element : LightClassUtilsKt.toLightElements(originalDeclaration)) {
            if (element instanceof PsiMethod) {
                // TODO handle all light methods
                return (PsiMethod) element;
            }
        }

        return null;
    }
    // MODIFICATION: End Kotlin implementation

    @Nullable
    private static <T extends EventRequest> T findRequest(
            @NotNull DebugProcessImpl debugProcess,
            Class<T> requestClass,
            Requestor requestor
    ) {
        return StreamEx.of(debugProcess.getRequestsManager().findRequests(requestor)).select(requestClass).findFirst().orElse(null);
    }

    @Override
    public void readExternal(@NotNull Element breakpointNode) throws InvalidDataException {
        super.readExternal(breakpointNode);
        try {
            getProperties().WATCH_ENTRY = Boolean.valueOf(JDOMExternalizerUtil.readField(breakpointNode, "WATCH_ENTRY"));
        } catch (Exception ignored) {
        }
        try {
            getProperties().WATCH_EXIT = Boolean.valueOf(JDOMExternalizerUtil.readField(breakpointNode, "WATCH_EXIT"));
        } catch (Exception ignored) {
        }
    }

    private boolean isEmulated() {
        return getProperties().EMULATED;
    }

    @Override
    public boolean isWatchEntry() {
        return getProperties().WATCH_ENTRY;
    }

    @Override
    public boolean isWatchExit() {
        return getProperties().WATCH_EXIT;
    }

    @Override
    public StreamEx<Method> matchingMethods(StreamEx<Method> methods, DebugProcessImpl debugProcess) {
        try {
            String methodName = getMethodName();
            String signature = mySignature != null ? mySignature.getName(debugProcess) : null;
            return methods.filter(m -> Objects.equals(methodName, m.name()) && Objects.equals(signature, m.signature())).limit(1);
        } catch (EvaluateException e) {
            LOG.warn(e);
        }
        return StreamEx.empty();
    }

    @Nullable
    private String getMethodName() {
        return getProperties().myMethodName;
    }

    private void setMethodName(@Nullable String methodName) {
        getProperties().myMethodName = methodName;
    }

    private static final class MethodDescriptor {
        String methodName;
        JVMName methodSignature;
        boolean isStatic;
    }

    private static void processPreparedSubTypes(
            ReferenceType classType,
            BiConsumer<ReferenceType, ClassesByNameProvider> consumer,
            ProgressIndicator progressIndicator
    ) {
        long start = 0;
        if (LOG.isDebugEnabled()) {
            start = System.currentTimeMillis();
        }
        progressIndicator.setIndeterminate(false);
        progressIndicator.start();
        progressIndicator.setText(JavaDebuggerBundle.message("label.method.breakpoints.processing.classes"));
        try {
            MultiMap<ReferenceType, ReferenceType> inheritance = new MultiMap<>();
            List<ReferenceType> allTypes = classType.virtualMachine().allClasses();
            for (int i = 0; i < allTypes.size(); i++) {
                if (progressIndicator.isCanceled()) {
                    return;
                }
                ReferenceType type = allTypes.get(i);
                if (type.isPrepared()) {
                    try {
                        supertypes(type).forEach(st -> inheritance.putValue(st, type));
                    } catch (ObjectCollectedException ignored) {
                    }
                }
                progressIndicator.setText2(i + "/" + allTypes.size());
                progressIndicator.setFraction((double) i / allTypes.size());
            }
            List<ReferenceType> types = StreamEx.ofTree(classType, t -> StreamEx.of(inheritance.get(t))).skip(1).toList();

            progressIndicator.setText(JavaDebuggerBundle.message("label.method.breakpoints.setting.breakpoints"));

            ClassesByNameProvider classesByName = ClassesByNameProvider.createCache(allTypes);

            for (int i = 0; i < types.size(); i++) {
                if (progressIndicator.isCanceled()) {
                    return;
                }
                consumer.accept(types.get(i), classesByName);

                progressIndicator.setText2(i + "/" + types.size());
                progressIndicator.setFraction((double) i / types.size());
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Processed " + types.size() + " classes in " + (System.currentTimeMillis() - start) + "ms");
            }
        } finally {
            progressIndicator.stop();
        }
    }

    // MODIFICATION: Add utilities absent in older platform versions
    private static boolean instanceOf(@Nullable ReferenceType type, @NotNull ReferenceType superType) {
        if (type == null) {
            return false;
        }
        if (superType.equals(type)) {
            return true;
        }
        return supertypes(type).anyMatch(t -> instanceOf(t, superType));
    }

    private static Stream<? extends ReferenceType> supertypes(ReferenceType type) {
        if (type instanceof InterfaceType) {
            return ((InterfaceType) type).superinterfaces().stream();
        } else if (type instanceof ClassType) {
            return StreamEx.<ReferenceType>ofNullable(((ClassType) type).superclass()).prepend(((ClassType) type).interfaces());
        }
        return StreamEx.empty();
    }
    // MODIFICATION: End
}