Skip to content

Commit

Permalink
Fix offline instrumentation: provide class loader for correct frame c…
Browse files Browse the repository at this point in the history
…omputation

The frame computation requires other classes to be loaded, but in offline instrumentation we process one class after another, so the order of files could affect the result.
  • Loading branch information
zuevmaxim committed Nov 28, 2024
1 parent 88e7fe7 commit 972d64d
Showing 1 changed file with 21 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

/**
Expand All @@ -35,12 +38,28 @@ public class Instrumentator {
private final List<File> myRoots;
private final List<File> myOutputRoots;
private final Filters myFilters;

/**
* This loader is provided to the instrumenter for correct frames computation in ClassWriterImpl.
*/
private final ClassLoader myLoader;

public Instrumentator(List<File> roots, List<File> outputRoots, Filters filters) {
myRoots = roots;
myOutputRoots = outputRoots;
myFilters = filters;
myLoader = createClassLoader(roots);
}

private ClassLoader createClassLoader(List<File> roots) {
URL[] urls = new URL[roots.size()];
for (int i = 0; i < roots.size(); i++) {
try {
urls[i] = myRoots.get(i).toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
return new URLClassLoader(urls);
}

public void instrument(final boolean countHits) {
Expand Down Expand Up @@ -84,9 +103,7 @@ protected void visitFile(String packageName, File file) {
final String className = packageName.isEmpty()
? classSimpleName
: ClassNameUtil.convertToInternalName(packageName) + "/" + classSimpleName;
// This loader is not user actually, just need some not null loader
final ClassLoader loader = ClassLoader.getSystemClassLoader();
final byte[] transformed = myTransformer.transform(loader, className, null, null, bytes);
final byte[] transformed = myTransformer.transform(myLoader, className, null, null, bytes);
if (transformed != null) {
bytes = transformed;
}
Expand Down

0 comments on commit 972d64d

Please sign in to comment.