GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [java] Fix memory-leak in type resolution by oowekyala · Pull Request #2920 · pmd/pmd

[java] Fix memory-leak in type resolution #2920

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
adangel merged 10 commits into pmd:master from oowekyala:issue-2911-class-leak
Nov 23, 2020

Uh oh!

There was an error while loading. Please reload this page.

Merged

[java] Fix memory-leak in type resolution #2920

Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
10 commits
Select commit Hold shift + click to select a range
4fe3874
Simplify constructor of JavaTypeDefinitionSimple
oowekyala Nov 14, 2020
00d76b0
Restrict caching to classes loaded by the bootstrap loader
oowekyala Nov 14, 2020
307eacd
Fix errors
oowekyala Nov 14, 2020
4ee7b7a
Load fewer class names
oowekyala Nov 14, 2020
30124fe
Don't cache enclosing class (pretty rare to hit it)
oowekyala Nov 14, 2020
3ccdb55
Make overload without varargs
oowekyala Nov 14, 2020
51c0df8
Remove cache entirely
oowekyala Nov 14, 2020
b70462b
Update release notes, refs #2920
oowekyala Nov 14, 2020
a5bcdb3
Merge branch 'master' into issue-2911-class-leak
oowekyala Nov 23, 2020
9aaae81
Handle TNPE and LinkageE when loading type params
oowekyala Nov 23, 2020
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

2 changes: 2 additions & 0 deletions 2 docs/pages/release_notes.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ This is a {{ site.pmd.release_type }} release.

* pmd-core
* [#1939](https://github.com/pmd/pmd/issues/1939): \[core] XPath expressions return handling
* pmd-java
* [#2911](https://github.com/pmd/pmd/issues/2911): \[java] `ClassTypeResolver#searchNodeNameForClass` leaks memory


### API Changes
Expand Down
52 changes: 44 additions & 8 deletions 52 pmd-java/src/main/java/net/sourceforge/pmd/lang/java/typeresolution/ClassTypeResolver.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.lang3.StringUtils;

import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.QualifiableNode;
Expand Down Expand Up @@ -289,20 +292,24 @@ public Object visit(ASTClassOrInterfaceType node, Object data) {
/**
* Set's the node's type to the found Class in the node's name (if there is a class to be found).
*
* @param node
*
* @return The index in the array produced by splitting the node's name by '.', which is not part of the
* class name found. Example: com.package.SomeClass.staticField.otherField, return would be 3
* class name found. Example: com.package.SomeClass.staticField.otherField, return would be 3
*/
private int searchNodeNameForClass(TypeNode node) {
private int searchNodeNameForClass(ASTName node, String[] segments) {
// this is the index from which field/method names start in the dotSplitImage array
int startIndex = node.getImage().split("\\.").length;
int startIndex = lastIndexThatMayBeAClassNameExclusive(node, segments);
if (startIndex == 0) {
return 0;
}

String reducedImage = StringUtils.join(Arrays.asList(segments).subList(0, startIndex), '.');

// tries to find a class in the node's image by omitting the parts after each '.', example:
// First try: com.package.SomeClass.staticField.otherField
// Second try: com.package.SomeClass.staticField
// Third try: com.package.SomeClass <- found a class!
for (String reducedImage = node.getImage();;) {

while (StringUtils.isNotEmpty(reducedImage) && startIndex > 0) {
populateType(node, reducedImage);
if (node.getType() != null) {
break; // we found a class!
Expand All @@ -323,6 +330,35 @@ private int searchNodeNameForClass(TypeNode node) {
return startIndex;
}

private int lastIndexThatMayBeAClassNameExclusive(ASTName name, String[] segments) {
assert segments.length > 0;



if (name.getParent() instanceof ASTPrimarySuffix) {
// not a class name as class name in primary
// expressions are only prefixes of the expr
return 0;
}

JavaNode opa = name.getParent().getParent();
if (opa.getNumChildren() > 1 + name.getParent().getIndexInParent()) {
// there is a following sibling to the primary prefix
JavaNode nextSibling = opa.getChild(name.getParent().getIndexInParent() + 1);
if (isArguments(nextSibling)) {
return segments.length - 1;
}
}
return segments.length;
}

private boolean isArguments(JavaNode node) {
if (node instanceof ASTPrimarySuffix) {
return ((ASTPrimarySuffix) node).isArguments();
}
return false;
}

private ASTArgumentList getArgumentList(ASTArguments args) {
if (args != null) {
return args.getFirstChildOfType(ASTArgumentList.class);
Expand All @@ -344,7 +380,7 @@ public Object visit(ASTName node, Object data) {
Class<?> accessingClass = getEnclosingTypeDeclarationClass(node);
String[] dotSplitImage = node.getImage().split("\\.");

int startIndex = searchNodeNameForClass(node);
int startIndex = searchNodeNameForClass(node, dotSplitImage);

ASTArguments astArguments = getSuffixMethodArgs(node);
ASTArgumentList astArgumentList = getArgumentList(astArguments);
Expand Down Expand Up @@ -964,7 +1000,7 @@ public Object visit(ASTPrimaryExpression primaryNode, Object data) {
// restore type of the name and search again
ASTName name = previousChild.getFirstChildOfType(ASTName.class);
name.setTypeDefinition(null);
searchNodeNameForClass(name);
searchNodeNameForClass(name, name.getImage().split("\\."));
if (name.getTypeDefinition() != null) {
// rollup from Name -> PrimaryPrefix
previousChild.setTypeDefinition(name.getTypeDefinition());
Expand Down
34 changes: 11 additions & 23 deletions 34 .../java/net/sourceforge/pmd/lang/java/typeresolution/typedefinition/JavaTypeDefinition.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,15 @@
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.ArrayUtils;


public abstract class JavaTypeDefinition implements TypeDefinition {
// contains non-generic and raw EXACT types
private static final Map<Class<?>, JavaTypeDefinition> CLASS_EXACT_TYPE_DEF_CACHE = new ConcurrentHashMap<>();

private static final JavaTypeDefinition[] NO_GENERICS = {};


private final TypeDefinitionType definitionType;

Expand Down Expand Up @@ -52,33 +51,22 @@ public static JavaTypeDefinition forClass(TypeDefinitionType type, JavaTypeDefin
}
}

public static JavaTypeDefinition forClass(final Class<?> clazz) {
return clazz == Object.class ? JavaTypeDefinitionSimple.OBJECT_DEFINITION
: forClass(clazz, NO_GENERICS); // very common

}

public static JavaTypeDefinition forClass(final Class<?> clazz, JavaTypeDefinition... boundGenerics) {
if (clazz == null) {
return null;
}

// deal with generic types
if (boundGenerics.length != 0) {
// With generics there is no cache
return new JavaTypeDefinitionSimple(clazz, boundGenerics);
}

final JavaTypeDefinition typeDef = CLASS_EXACT_TYPE_DEF_CACHE.get(clazz);

if (typeDef != null) {
return typeDef;
}

final JavaTypeDefinition newDef;
try {
newDef = new JavaTypeDefinitionSimple(clazz);
} catch (final NoClassDefFoundError e) {
return new JavaTypeDefinitionSimple(clazz, boundGenerics);
} catch (final LinkageError e) {
Comment thread
oowekyala marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

return null; // Can happen if a parent class references a class not in classpath
}

CLASS_EXACT_TYPE_DEF_CACHE.put(clazz, newDef);

return newDef;
}

@Override
Expand Down
3 changes: 1 addition & 2 deletions 3 .../net/sourceforge/pmd/lang/java/typeresolution/typedefinition/JavaTypeDefinitionLower.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,13 @@
import static net.sourceforge.pmd.lang.java.typeresolution.typedefinition.TypeDefinitionType.LOWER_WILDCARD;

/* default */ class JavaTypeDefinitionLower extends JavaTypeDefinitionUpper {
private static final JavaTypeDefinition OBJECT_DEFINITION = forClass(Object.class);

protected JavaTypeDefinitionLower(JavaTypeDefinition... typeList) {
super(LOWER_WILDCARD, typeList);
}

@Override
protected JavaTypeDefinition firstJavaType() {
return OBJECT_DEFINITION;
return forClass(Object.class);
}
}
99 changes: 52 additions & 47 deletions 99 ...net/sourceforge/pmd/lang/java/typeresolution/typedefinition/JavaTypeDefinitionSimple.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,38 @@


/* default */ class JavaTypeDefinitionSimple extends JavaTypeDefinition {

static final JavaTypeDefinitionSimple OBJECT_DEFINITION = new JavaTypeDefinitionSimple(Object.class);
private final Class<?> clazz;
private final JavaTypeDefinition[] genericArgs;
private JavaTypeDefinition[] genericArgs;
// cached because calling clazz.getTypeParameters().length create a new array every time
private final int typeParameterCount;
private final boolean isGeneric;
private final boolean isRawType;
private final JavaTypeDefinition enclosingClass;
private int typeParameterCount = -1;
private final int typeArgumentCount;

private static final Logger LOG = Logger.getLogger(JavaTypeDefinitionSimple.class.getName());
private static final JavaTypeDefinition[] NO_GENERICS = {};

protected JavaTypeDefinitionSimple(Class<?> clazz, JavaTypeDefinition... boundGenerics) {
super(EXACT);
this.clazz = clazz;

typeArgumentCount = boundGenerics.length;
if (boundGenerics.length > 0) {
genericArgs = Arrays.copyOf(boundGenerics, boundGenerics.length);
} // otherwise stays null
}

private Class<?> loadEnclosing(Class<?> clazz) {
try {
return clazz.getEnclosingClass();
} catch (LinkageError e) {
if (LOG.isLoggable(Level.WARNING)) {
LOG.log(Level.WARNING, "Could not load enclosing class of " + clazz.getName() + ", due to: " + e);
}
return null;
}
}

private TypeVariable<?>[] getTypeParameters(Class<?> clazz) {
Comment thread
oowekyala marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

final TypeVariable<?>[] typeParameters;
// the anonymous class can't have generics, but we may be binding generics from super classes
if (clazz.isAnonymousClass()) {
Expand All @@ -53,27 +70,7 @@ protected JavaTypeDefinitionSimple(Class<?> clazz, JavaTypeDefinition... boundGe
} else {
typeParameters = clazz.getTypeParameters();
}

typeParameterCount = typeParameters.length;
isGeneric = typeParameters.length != 0;
isRawType = isGeneric && boundGenerics.length == 0;

if (isGeneric) {
// Generics will be lazily loaded if not already known
this.genericArgs = Arrays.copyOf(boundGenerics, typeParameterCount);
} else {
this.genericArgs = NO_GENERICS;
}

Class<?> enclosing = null;
try {
enclosing = clazz.getEnclosingClass();
} catch (LinkageError e) {
if (LOG.isLoggable(Level.WARNING)) {
LOG.log(Level.WARNING, "Could not load enclosing class of " + clazz.getName() + ", due to: " + e);
}
}
enclosingClass = forClass(enclosing);
return typeParameters;
}

@Override
Expand All @@ -83,12 +80,25 @@ public Class<?> getType() {

@Override
public JavaTypeDefinition getEnclosingClass() {
return enclosingClass;
return JavaTypeDefinition.forClass(loadEnclosing(clazz));
}

@Override
public boolean isRawType() {
return isGeneric() && typeArgumentCount == 0;
}

@Override
public boolean isGeneric() {
return isGeneric;
return getTypeParameterCount() != 0;
}

@Override
public int getTypeParameterCount() {
if (typeParameterCount == -1) {
typeParameterCount = getTypeParameters(clazz).length;
Comment thread
oowekyala marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

}
return typeParameterCount;
}

private JavaTypeDefinition getGenericType(final String parameterName, Method method,
Expand Down Expand Up @@ -131,6 +141,10 @@ public JavaTypeDefinition getGenericType(final String parameterName) {

@Override
public JavaTypeDefinition getGenericType(final int index) {
if (genericArgs == null) {
genericArgs = new JavaTypeDefinition[getTypeParameterCount()];
}

// Check if it has been lazily initialized first
final JavaTypeDefinition cachedDefinition = genericArgs[index];
if (cachedDefinition != null) {
Expand Down Expand Up @@ -265,11 +279,6 @@ public boolean hasSameErasureAs(JavaTypeDefinition def) {
return clazz == def.getType();
}

@Override
public int getTypeParameterCount() {
return typeParameterCount;
}


@Override
public String toString() {
Expand All @@ -278,27 +287,24 @@ public String toString() {
.append(", genericArgs=[");

// Forcefully resolve all generic types
for (int i = 0; i < genericArgs.length; i++) {
getGenericType(i);
}

for (final JavaTypeDefinition jtd : genericArgs) {
for (int i = 0; i < getTypeParameterCount(); i++) {
JavaTypeDefinition jtd = getGenericType(i);
sb.append(jtd.shallowString()).append(", ");
}

if (genericArgs.length != 0) {
if (getTypeParameterCount() != 0) {
sb.replace(sb.length() - 3, sb.length() - 1, ""); // remove last comma
}

return sb.append("], isGeneric=").append(isGeneric)
return sb.append("], isGeneric=").append(isGeneric())
.append("]\n").toString();
}

@Override
public String shallowString() {
return new StringBuilder("JavaTypeDefinition [clazz=").append(clazz)
.append(", definitionType=").append(getDefinitionType())
.append(", isGeneric=").append(isGeneric)
.append(", isGeneric=").append(isGeneric())
.append("]\n").toString();
}

Expand All @@ -325,6 +331,10 @@ public boolean equals(Object obj) {
return false;
}

if (isRawType() || otherTypeDef.isRawType()) {
return this.isRawType() == otherTypeDef.isRawType();
}

for (int i = 0; i < getTypeParameterCount(); ++i) {
// Note: we assume that cycles can only exist because of raw types
if (!getGenericType(i).equals(otherTypeDef.getGenericType(i))) {
Expand Down Expand Up @@ -411,11 +421,6 @@ public int getJavaTypeCount() {
return 1;
}

@Override
public boolean isRawType() {
return isRawType;
}

@Override
public boolean isIntersectionType() {
return false;
Expand Down
4 changes: 2 additions & 2 deletions 4 pmd-java/src/test/java/net/sourceforge/pmd/typeresolution/ClassTypeResolverTest.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -1703,8 +1703,8 @@ public void testJavaTypeDefinitionEquals() {
a = forClass(JavaTypeDefinitionEquals.class);
b = forClass(JavaTypeDefinitionEquals.class,
forClass(List.class, a));
assertEquals(a, b);
assertEquals(b, a);
assertNotEquals(a, b);
assertNotEquals(b, a);
}

@Test
Expand Down
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402809 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.