This repository was archived by the owner on Mar 16, 2026. It is now read-only.
forked from microsoft/java-debug
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJavaHotCodeReplaceProvider.java
More file actions
785 lines (713 loc) · 32 KB
/
Copy pathJavaHotCodeReplaceProvider.java
File metadata and controls
785 lines (713 loc) · 32 KB
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 (c) 2000, 2016 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Yevgen Kogan - Bug 403475 - Hot Code Replace drops too much frames in some cases
*******************************************************************************/
/*******************************************************************************
* Copyright (c) 2017-2019 Microsoft Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Microsoft Corporation - Adapter the code for VSCode Java Debugger
*******************************************************************************/
package com.microsoft.java.debug.plugin.internal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.core.resources.IBuildConfiguration;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelMarker;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.core.util.ISourceAttribute;
import org.eclipse.jdt.internal.core.util.Util;
import org.eclipse.jdt.ls.core.internal.JobHelpers;
import org.eclipse.jdt.ls.core.internal.ProjectUtils;
import com.microsoft.java.debug.core.Configuration;
import com.microsoft.java.debug.core.DebugException;
import com.microsoft.java.debug.core.DebugSettings;
import com.microsoft.java.debug.core.DebugUtility;
import com.microsoft.java.debug.core.IDebugSession;
import com.microsoft.java.debug.core.StackFrameUtility;
import com.microsoft.java.debug.core.adapter.AdapterUtils;
import com.microsoft.java.debug.core.adapter.Constants;
import com.microsoft.java.debug.core.adapter.ErrorCode;
import com.microsoft.java.debug.core.adapter.HotCodeReplaceEvent;
import com.microsoft.java.debug.core.adapter.IDebugAdapterContext;
import com.microsoft.java.debug.core.adapter.IHotCodeReplaceProvider;
import com.microsoft.java.debug.core.protocol.Events;
import com.sun.jdi.IncompatibleThreadStateException;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.StackFrame;
import com.sun.jdi.ThreadReference;
import com.sun.jdi.VMDisconnectedException;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.request.StepRequest;
import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;
/**
* The hot code replace provider listens for changes to class files and notifies
* the running debug session of the changes.
*/
public class JavaHotCodeReplaceProvider implements IHotCodeReplaceProvider, IResourceChangeListener {
private static final Logger logger = Logger.getLogger(Configuration.LOGGER_NAME);
private static final String CLASS_FILE_EXTENSION = "class"; //$NON-NLS-1$
private IDebugSession currentDebugSession;
private IDebugAdapterContext context;
private Map<ThreadReference, List<StackFrame>> threadFrameMap = new HashMap<>();
private List<Consumer<List<String>>> consumers = new ArrayList<Consumer<List<String>>>();
private PublishSubject<HotCodeReplaceEvent> eventSubject = PublishSubject.<HotCodeReplaceEvent>create();
private List<IResource> deltaResources = new ArrayList<>();
private List<String> deltaClassNames = new ArrayList<>();
private String mainProjectName = "";
/**
* Visitor for resource deltas.
*/
private ChangedClassFilesVisitor classFilesVisitor = new ChangedClassFilesVisitor();
/**
* A visitor which collects changed class files.
*/
class ChangedClassFilesVisitor implements IResourceDeltaVisitor {
/**
* The collection of changed class files.
*/
private List<IResource> changedFiles = null;
/**
* Collection of qualified type names, corresponding to class files.
*/
private List<String> fullyQualifiedNames = null;
/**
* Answers whether children should be visited.
* <p>
* If the associated resource is a class file which has been changed, record it.
* </p>
*/
@Override
public boolean visit(IResourceDelta delta) {
if (delta == null || 0 == (delta.getKind() & IResourceDelta.CHANGED)) {
return false;
}
IResource resource = delta.getResource();
if (resource != null) {
switch (resource.getType()) {
case IResource.FILE:
if (0 == (delta.getFlags() & IResourceDelta.CONTENT)) {
return false;
}
if (CLASS_FILE_EXTENSION.equals(resource.getFullPath().getFileExtension())) {
IPath localLocation = resource.getLocation();
if (localLocation != null) {
String path = localLocation.toOSString();
IClassFileReader reader = ToolFactory.createDefaultClassFileReader(path,
IClassFileReader.CLASSFILE_ATTRIBUTES);
if (reader != null) {
// this name is slash-delimited
String qualifiedName = new String(reader.getClassName());
boolean hasBlockingErrors = false;
try {
// If the user doesn't want to replace
// classfiles containing
// compilation errors, get the source
// file associated with
// the class file and query it for
// compilation errors
IJavaProject pro = JavaCore.create(resource.getProject());
ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();
String sourceName = null;
if (sourceAttribute != null) {
sourceName = new String(sourceAttribute.getSourceFileName());
}
IResource sourceFile = getSourceFile(pro, qualifiedName, sourceName);
if (sourceFile != null) {
IMarker[] problemMarkers = null;
problemMarkers = sourceFile.findMarkers(
IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true,
IResource.DEPTH_INFINITE);
for (IMarker problemMarker : problemMarkers) {
if (problemMarker.getAttribute(IMarker.SEVERITY,
-1) == IMarker.SEVERITY_ERROR) {
hasBlockingErrors = true;
break;
}
}
}
} catch (CoreException e) {
logger.log(Level.SEVERE, "Failed to visit classes: " + e.getMessage(), e);
}
if (!hasBlockingErrors) {
changedFiles.add(resource);
// dot-delimit the name
fullyQualifiedNames.add(qualifiedName.replace('/', '.'));
}
}
}
}
return false;
default:
return true;
}
}
return true;
}
/**
* Resets the file collection to empty.
*/
public void reset() {
changedFiles = new ArrayList<>();
fullyQualifiedNames = new ArrayList<>();
}
/**
* Answers a collection of changed class files or <code>null</code>.
*/
public List<IResource> getChangedClassFiles() {
return changedFiles;
}
/**
* Returns a collection of qualified type names corresponding to the changed
* class files.
*
* @return List
*/
public List<String> getQualifiedNamesList() {
return fullyQualifiedNames;
}
/**
* Returns the source file associated with the given type, or <code>null</code>
* if no source file could be found.
*
* @param project
* the java project containing the classfile
* @param qualifiedName
* fully qualified name of the type, slash delimited
* @param sourceAttribute
* debug source attribute, or <code>null</code> if none
*/
private IResource getSourceFile(IJavaProject project, String qualifiedName, String sourceAttribute) {
String name = null;
IJavaElement element = null;
try {
if (sourceAttribute == null) {
element = findElement(qualifiedName, project);
} else {
int i = qualifiedName.lastIndexOf('/');
if (i > 0) {
name = qualifiedName.substring(0, i + 1);
name = name + sourceAttribute;
} else {
name = sourceAttribute;
}
element = project.findElement(new Path(name));
}
if (element instanceof ICompilationUnit) {
ICompilationUnit cu = (ICompilationUnit) element;
return cu.getCorrespondingResource();
}
} catch (CoreException e) {
logger.log(Level.INFO, "Failed to get source file with exception" + e.getMessage(), e);
}
return null;
}
}
@Override
public void initialize(IDebugAdapterContext context, Map<String, Object> options) {
if (DebugSettings.getCurrent().hotCodeReplace != DebugSettings.HotCodeReplace.NEVER) {
// Listen to the built file events.
ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_BUILD);
}
this.context = context;
currentDebugSession = context.getDebugSession();
this.mainProjectName = ((String) options.get(Constants.PROJECT_NAME));
}
@Override
public void close() {
if (DebugSettings.getCurrent().hotCodeReplace != DebugSettings.HotCodeReplace.NEVER) {
// Remove the listener.
ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
}
eventSubject.onComplete();
}
@Override
public void resourceChanged(IResourceChangeEvent event) {
if (event.getType() == IResourceChangeEvent.POST_BUILD) {
ChangedClassFilesVisitor visitor = getChangedClassFiles(event);
if (visitor != null) {
List<IResource> resources = visitor.getChangedClassFiles();
List<String> classNames = visitor.getQualifiedNamesList();
synchronized (this) {
for (int i = 0; i < classNames.size(); i++) {
String className = classNames.get(i);
IResource resource = resources.get(i);
boolean duplicate = false;
for (int j = 0; j < deltaClassNames.size(); j++) {
if (Objects.equals(deltaClassNames.get(j), className)
&& JdtUtils.isSameFile(deltaResources.get(j), resource)) {
duplicate = true;
break;
}
}
if (!duplicate) {
deltaClassNames.add(className);
deltaResources.add(resource);
}
}
}
publishEvent(HotCodeReplaceEvent.EventType.BUILD_COMPLETE, "Build completed.");
}
}
}
@Override
public void onClassRedefined(Consumer<List<String>> consumer) {
this.consumers.add(consumer);
}
@Override
public CompletableFuture<List<String>> redefineClasses() {
triggerBuildForBspProject();
JobHelpers.waitForBuildJobs(10 * 1000);
return CompletableFuture.supplyAsync(() -> {
List<String> classNames = new ArrayList<>();
String errorMessage = null;
synchronized (this) {
classNames.addAll(deltaClassNames);
errorMessage = doHotCodeReplace(deltaResources, deltaClassNames);
deltaResources.clear();
deltaClassNames.clear();
}
if (!classNames.isEmpty() && errorMessage != null) {
throw AdapterUtils.createCompletionException(errorMessage, ErrorCode.HCR_FAILURE);
}
return classNames;
});
}
@Override
public Observable<HotCodeReplaceEvent> getEventHub() {
return eventSubject;
}
private void publishEvent(HotCodeReplaceEvent.EventType type, String message) {
eventSubject.onNext(new HotCodeReplaceEvent(type, message));
}
private void publishEvent(HotCodeReplaceEvent.EventType type, String message, Object data) {
eventSubject.onNext(new HotCodeReplaceEvent(type, message, data));
}
private String doHotCodeReplace(List<IResource> resourcesToReplace, List<String> qualifiedNamesToReplace) {
if (context == null || currentDebugSession == null) {
return null;
}
if (resourcesToReplace == null || qualifiedNamesToReplace == null || qualifiedNamesToReplace.isEmpty()
|| resourcesToReplace.isEmpty()) {
return null;
}
filterNotLoadedTypes(resourcesToReplace, qualifiedNamesToReplace);
if (qualifiedNamesToReplace.isEmpty()) {
return null;
// If none of the changed types are loaded, do nothing.
}
// Not supported scenario:
if (!currentDebugSession.getVM().canRedefineClasses()) {
publishEvent(HotCodeReplaceEvent.EventType.ERROR, "JVM doesn't support hot reload classes");
return "JVM doesn't support hot reload classes";
}
String errorMessage = null;
publishEvent(HotCodeReplaceEvent.EventType.STARTING, "Start hot code replacement procedure...");
try {
List<ThreadReference> poppedThreads = new ArrayList<>();
boolean framesPopped = false;
if (this.currentDebugSession.getVM().canPopFrames()) {
try {
attemptPopFrames(resourcesToReplace, qualifiedNamesToReplace, poppedThreads);
framesPopped = true; // No exception occurred
} catch (DebugException e) {
logger.log(Level.WARNING, "Failed to pop frames " + e.getMessage(), e);
}
}
redefineTypesJDK(resourcesToReplace, qualifiedNamesToReplace);
for (Consumer<List<String>> consumer : consumers) {
consumer.accept(qualifiedNamesToReplace);
}
if (containsObsoleteMethods()) {
publishEvent(HotCodeReplaceEvent.EventType.ERROR, "JVM contains obsolete methods");
errorMessage = "JVM contains obsolete methods";
}
if (currentDebugSession.getVM().canPopFrames() && framesPopped) {
attemptStepIn(poppedThreads);
} else {
attemptDropToFrame(resourcesToReplace, qualifiedNamesToReplace);
}
} catch (DebugException e) {
logger.log(Level.SEVERE, "Failed to complete hot code replace: " + e.getMessage(), e);
errorMessage = e.getMessage();
} finally {
publishEvent(HotCodeReplaceEvent.EventType.END, "Completed hot code replace", qualifiedNamesToReplace);
threadFrameMap.clear();
}
return errorMessage;
}
private void filterNotLoadedTypes(List<IResource> resources, List<String> qualifiedNames) {
for (int i = 0, numElements = qualifiedNames.size(); i < numElements; i++) {
String name = qualifiedNames.get(i);
List<ReferenceType> list = getJdiClassesByName(name);
if (list.isEmpty()) {
// If no classes with the given name are loaded in the VM, don't
// waste
// cycles trying to replace.
qualifiedNames.remove(i);
resources.remove(i);
// Decrement the index and number of elements to compensate for
// item removal
i--;
numElements--;
}
}
}
/**
* Returns VirtualMachine.classesByName(String), logging any JDI exceptions.
*
* @see com.sun.jdi.VirtualMachine
*/
private List<ReferenceType> getJdiClassesByName(String className) {
try {
VirtualMachine vm = this.currentDebugSession.getVM();
if (vm != null) {
return vm.classesByName(className);
}
} catch (VMDisconnectedException ex) {
// Ignore this exception since it will happen when the VM is still running.
}
return Collections.emptyList();
}
/**
* Looks for the deepest affected stack frames in the stack and forces pop
* affected frames. Does this for all of the active stack frames in the session.
*/
private void attemptPopFrames(List<IResource> resources, List<String> replacedClassNames,
List<ThreadReference> poppedThreads) throws DebugException {
List<StackFrame> popFrames = getAffectedFrames(currentDebugSession.getAllThreads(), replacedClassNames);
for (StackFrame popFrame : popFrames) {
try {
popStackFrame(popFrame);
poppedThreads.add(popFrame.thread());
} catch (DebugException de) {
poppedThreads.remove(popFrame.thread());
}
}
}
/**
* Performs a "step into" operation on the given threads.
*/
private void attemptStepIn(List<ThreadReference> threads) {
for (ThreadReference thread : threads) {
stepIntoThread(thread);
}
}
/**
* Looks for the deepest affected stack frame in the stack and forces a drop to
* frame. Does this for all of the active stack frames in the target.
*/
private void attemptDropToFrame(List<IResource> resources, List<String> replacedClassNames)
throws DebugException {
List<StackFrame> dropFrames = getAffectedFrames(currentDebugSession.getAllThreads(), replacedClassNames);
// All threads that want to drop to frame are able. Proceed with the
// drop
for (StackFrame dropFrame : dropFrames) {
dropToStackFrame(dropFrame);
}
}
/**
* Returns a list of frames which should be popped in the given threads.
*/
private List<StackFrame> getAffectedFrames(List<ThreadReference> threads, List<String> replacedClassNames)
throws DebugException {
List<StackFrame> popFrames = new ArrayList<>();
for (ThreadReference thread : threads) {
if (thread.isSuspended()) {
StackFrame affectedFrame = getAffectedFrame(thread, replacedClassNames);
if (affectedFrame == null) {
// No frame to drop to in this thread
continue;
}
if (supportsDropToFrame(thread, affectedFrame)) {
popFrames.add(affectedFrame);
}
}
}
return popFrames;
}
/**
* Returns the stack frame that should be dropped to in the given thread after a
* hot code replace. This is calculated by determining if the threads contain
* stack frames that reside in one of the given replaced class names. If
* possible, only stack frames whose methods were directly affected (and not
* simply all frames in affected types) will be returned.
*/
private StackFrame getAffectedFrame(ThreadReference thread, List<String> replacedClassNames)
throws DebugException {
List<StackFrame> frames = getStackFrames(thread, false);
StackFrame affectedFrame = null;
for (int i = 0; i < frames.size(); i++) {
StackFrame frame = frames.get(i);
if (containsChangedType(frame, replacedClassNames)) {
if (supportsDropToFrame(thread, frame)) {
affectedFrame = frame;
break;
}
// The frame we wanted to drop to cannot be popped.
// Set the affected frame to the next lowest pop-able
// frame on the stack.
int j = i;
while (j > 0) {
j--;
frame = frames.get(j);
if (supportsDropToFrame(thread, frame)) {
affectedFrame = frame;
break;
}
}
break;
}
}
return affectedFrame;
}
private boolean containsChangedType(StackFrame frame, List<String> replacedClassNames) throws DebugException {
String declaringTypeName = JdtUtils.getDeclaringTypeName(frame);
// Check if the frame's declaring type was changed
if (replacedClassNames.contains(declaringTypeName)) {
return true;
}
// Check if one of the frame's declaring type's inner classes have
// changed
for (String className : replacedClassNames) {
int index = className.indexOf('$');
if (index > -1 && declaringTypeName.equals(className.substring(0, index))) {
return true;
}
}
return false;
}
private boolean supportsDropToFrame(ThreadReference thread, StackFrame frame) {
List<StackFrame> frames = getStackFrames(thread, false);
for (int i = 0; i < frames.size(); i++) {
if (StackFrameUtility.isNative(frames.get(i))) {
return false;
}
if (frames.get(i) == frame) {
return true;
}
}
return false;
}
protected void popStackFrame(StackFrame frame) throws DebugException {
if (frame != null) {
ThreadReference thread = frame.thread();
List<StackFrame> frames = getStackFrames(thread, false);
int desiredSize = frames.indexOf(frame);
while (desiredSize >= 0) {
StackFrameUtility.pop(frames.get(0));
frames = getStackFrames(thread, true);
desiredSize--;
}
}
}
protected void dropToStackFrame(StackFrame frame) throws DebugException {
// Pop the drop frame and all frames above it
popStackFrame(frame);
stepIntoThread(frame.thread());
}
private void redefineTypesJDK(List<IResource> resources, List<String> qualifiedNames) throws DebugException {
Map<ReferenceType, byte[]> typesToBytes = getTypesToBytes(resources, qualifiedNames);
try {
currentDebugSession.getVM().redefineClasses(typesToBytes);
} catch (UnsupportedOperationException | NoClassDefFoundError | VerifyError | ClassFormatError
| ClassCircularityError e) {
publishEvent(HotCodeReplaceEvent.EventType.ERROR, e.getMessage());
throw new DebugException("Failed to redefine classes: " + e.getMessage());
}
}
private void stepIntoThread(ThreadReference thread) {
StepRequest request = DebugUtility.createStepIntoRequest(thread,
this.context.getStepFilters().classNameFilters);
currentDebugSession.getEventHub().stepEvents().filter(debugEvent -> request.equals(debugEvent.event.request()))
.take(1).subscribe(debugEvent -> {
debugEvent.shouldResume = false;
// Have to send to events to keep the UI sync with the step in operations:
context.getProtocolServer().sendEvent(new Events.StoppedEvent("step", thread.uniqueID()));
context.getProtocolServer().sendEvent(new Events.ContinuedEvent(thread.uniqueID()));
});
request.enable();
thread.resume();
}
/**
* Returns a mapping of class files to the bytes that make up those class files.
*
* @param resources
* the classfiles
* @param qualifiedNames
* the fully qualified type names corresponding to the classfiles.
* The typeNames correspond to the resources on a one-to-one basis.
* @return a mapping of class files to bytes key: class file value: the bytes
* which make up that classfile
*/
private Map<ReferenceType, byte[]> getTypesToBytes(List<IResource> resources, List<String> qualifiedNames) {
Map<ReferenceType, byte[]> typesToBytes = new HashMap<>(resources.size());
Iterator<IResource> resourceIter = resources.iterator();
Iterator<String> nameIter = qualifiedNames.iterator();
IResource resource;
String name;
while (resourceIter.hasNext()) {
resource = resourceIter.next();
name = nameIter.next();
List<ReferenceType> classes = getJdiClassesByName(name);
byte[] bytes = null;
try {
bytes = Util.getResourceContentsAsByteArray((IFile) resource);
} catch (CoreException e) {
continue;
}
for (ReferenceType type : classes) {
typesToBytes.put(type, bytes);
}
}
return typesToBytes;
}
/**
* Returns the class file visitor after visiting the resource change. The
* visitor contains the changed class files and qualified type names. Returns
* <code>null</code> if the visitor encounters an exception, or the delta is not
* a POST_BUILD.
*/
private ChangedClassFilesVisitor getChangedClassFiles(IResourceChangeEvent event) {
IResourceDelta delta = event.getDelta();
if (event.getType() != IResourceChangeEvent.POST_BUILD || delta == null) {
return null;
}
classFilesVisitor.reset();
try {
delta.accept(classFilesVisitor);
} catch (CoreException e) {
return null; // quiet failure
}
return classFilesVisitor;
}
/**
* Returns the class file or compilation unit containing the given fully
* qualified name in the specified project. All registered java like file
* extensions are considered.
*
* @param qualifiedTypeName
* fully qualified type name
* @param project
* project to search in
* @return class file or compilation unit or <code>null</code>
* @throws CoreException
* if an exception occurs
*/
public static IJavaElement findElement(String qualifiedTypeName, IJavaProject project) throws CoreException {
String path = qualifiedTypeName;
final String[] javaLikeExtensions = JavaCore.getJavaLikeExtensions();
int pos = path.indexOf('$');
if (pos != -1) {
path = path.substring(0, pos);
}
path = path.replace('.', IPath.SEPARATOR);
path += "."; //$NON-NLS-1$
for (String ext : javaLikeExtensions) {
IJavaElement element = project.findElement(new Path(path + ext));
if (element != null) {
return element;
}
}
return null;
}
private boolean containsObsoleteMethods() throws DebugException {
List<ThreadReference> threads = currentDebugSession.getAllThreads();
for (ThreadReference thread : threads) {
if (!thread.isSuspended()) {
continue;
}
List<StackFrame> frames = getStackFrames(thread, true);
if (frames == null || frames.isEmpty()) {
continue;
}
for (StackFrame frame : frames) {
if (StackFrameUtility.isObsolete(frame)) {
return true;
}
}
}
return false;
}
private List<StackFrame> getStackFrames(ThreadReference thread, boolean refresh) {
return threadFrameMap.compute(thread, (key, oldValue) -> {
try {
return oldValue == null || refresh ? key.frames() : oldValue;
} catch (IncompatibleThreadStateException e) {
logger.log(Level.SEVERE, "Failed to get stack frames: " + e.getMessage(), e);
return oldValue;
}
});
}
/**
* Trigger build separately if the main project is a BSP project.
* This is because auto build for BSP project will not update the class files to disk.
*/
private void triggerBuildForBspProject() {
// check if the workspace contains BSP project first. This is for performance consideration.
// Due to that getJavaProjectFromType() is a heavy operation.
if (!containsBspProjects()) {
return;
}
IProject mainProject = JdtUtils.getMainProject(this.mainProjectName, context.getMainClass());
if (mainProject != null && JdtUtils.isBspProject(mainProject)) {
try {
ResourcesPlugin.getWorkspace().build(
new IBuildConfiguration[]{mainProject.getActiveBuildConfig()},
IncrementalProjectBuilder.INCREMENTAL_BUILD,
false /*buildReference*/,
new NullProgressMonitor()
);
} catch (CoreException e) {
// ignore compilation errors
}
}
}
private boolean containsBspProjects() {
for (IJavaProject javaProject : ProjectUtils.getJavaProjects()) {
if (JdtUtils.isBspProject(javaProject.getProject())) {
return true;
}
}
return false;
}
}