[
https://issues.apache.org/jira/browse/GROOVY-11916?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18144114#comment-18144114
]
ASF GitHub Bot commented on GROOVY-11916:
-----------------------------------------
daniellansun commented on code in PR #3227:
URL: https://github.com/apache/groovy/pull/3227#discussion_r4558312540
##########
src/main/java/org/codehaus/groovy/control/ResolveVisitor.java:
##########
@@ -1195,6 +1289,72 @@ protected Expression transformPropertyExpression(final
PropertyExpression pe) {
return isTopLevelProperty ? correctClassClassChain(xe) : xe;
}
+ /**
+ * Whether a type found through a star import, a module import, or a
default
+ * import is accessible from {@link #currentClass}.
+ * <p>
+ * Public types are visible. A package-private type stays visible in its
own
+ * package, a protected member type stays visible to subclasses of its
enclosing
+ * type, and a private member type stays visible inside the enclosing
nest. A
+ * public member of an inaccessible enclosing type is not visible, so a
star
+ * import cannot bind it.
+ * <p>
+ * Single-type imports are not filtered. An explicit {@code import
p.Hidden}
+ * or a fully-qualified name still resolves, matching long-standing Groovy
+ * behaviour, and {@code Class.forName} is unaffected. Static field imports
+ * already apply an access check ({@link StaticImportVisitor}, since
Groovy 5).
+ *
+ * @param type a resolved candidate
+ * @param knownOuter the type named by {@code import some.Type.*} when
+ * {@code type} is a binary member type that does not
expose
+ * {@link ClassNode#getOuterClass()}
+ * @return {@code true} if the star import may bind {@code type}
+ */
+ private boolean isStarImportAccessible(final ClassNode type, final
ClassNode knownOuter) {
+ ClassNode outer = type.getOuterClass();
+ if (outer == null) {
+ outer = knownOuter;
Review Comment:
Thanks for the question. I looked at this carefully, and I think
`knownOuter` still has to stay. Overriding
`ConstructedNestedClass.getOuterClass()` does not look like a safe replacement.
`isStarImportAccessible` runs after `resolve()`, which has already
redirected the temporary node onto the loaded class.
`ClassNode.getOuterClass()` follows that redirect. A binary member type is not
an `InnerClassNode`, so the loaded node's `getOuterClass()` is null. An
override that follows the redirect would still not name the enclosing type from
`import Type.*`.
Returning `knownEnclosingType` and ignoring the redirect also looks unsafe.
`transformPropertyExpression` keeps that node as the type of the
`ClassExpression` for `Outer.Inner`. `getModifiers()` follows the redirect, so
a non-static binary member would then look like a non-static inner class with a
known outer. `NewifyASTTransformation` would prepend an enclosing instance for
`Outer.Inner.new(...)`. `StaticTypeCheckingVisitor.hasAccessToClass` would stop
treating a null outer as an unknown enclosing type, and a protected precompiled
member would pick up the subclass check. `GenericsType.appendName` and
`StaticTypeCheckingSupport.applyGenericsContext` read the same method.
I've added comments on `ConstructedNestedClass` and on the `knownOuter`
parameter to record this. I'd be glad to adjust if I've missed a safer way to
do it.
##########
src/test/groovy/bugs/Groovy11916.groovy:
##########
@@ -0,0 +1,727 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package bugs
+
+import groovy.lang.GroovyClassLoader
+import org.codehaus.groovy.control.CompilationUnit
+import org.codehaus.groovy.control.CompilerConfiguration
+import org.codehaus.groovy.control.Phases
+import org.codehaus.groovy.control.customizers.ImportCustomizer
+import org.junit.jupiter.api.BeforeAll
+import org.junit.jupiter.api.Test
+
+import java.lang.reflect.Modifier
+
+import static groovy.test.GroovyAssert.assertScript
+import static groovy.test.GroovyAssert.shouldFail
+
+/**
+ * Star imports, module imports, and default imports resolve only accessible
+ * types. A source import shadows those defaults, including {@code java.lang}.
+ * Two source star imports bind the first accessible type in source order.
+ * An explicit single-type import, a fully qualified name, and
+ * {@code Class.forName} still name a type that is not public.
+ */
+final class Groovy11916 {
+
+ private static GroovyClassLoader types
+
+ @BeforeAll
+ static void compilePackagePrivateTypes() {
+ types = compile(Groovy11916.classLoader, [
+ 'p/Types': '''
+ package p
+
+ @groovy.transform.PackageScope
+ class Hidden {}
+
+ class Visible {}
+
+ @groovy.transform.PackageScope
+ class Outer {
+ public static class Inner {}
+ }
+
+ class Protector {
+ protected static class Secret {}
+ }
+
+ class Priv {
+ private static class Secret {}
+ public static class Shown {}
+ }
+
+ @groovy.transform.PackageScope
+ class Collision {}
+ '''
+ ])
+ assert !Modifier.isPublic(types.loadClass('p.Hidden').modifiers)
+ assert !Modifier.isPublic(types.loadClass('p.Collision').modifiers)
+ assert Modifier.isPublic(types.loadClass('p.Visible').modifiers)
+ assert !Modifier.isPublic(types.loadClass('p.Outer').modifiers)
+ assert Modifier.isPublic(types.loadClass('p.Outer$Inner').modifiers)
+ assert
Modifier.isProtected(types.loadClass('p.Protector$Secret').modifiers)
+ assert Modifier.isPrivate(types.loadClass('p.Priv$Secret').modifiers)
Review Comment:
Thanks. Those asserts are not themselves the accessibility check.
`isStarImportAccessible` is, and its javadoc is the rule: public, same package,
a protected member from a subclass, a private member inside the nest, and no
public member of an inaccessible outer. The test methods below are what
exercise that.
The modifier asserts only lock the bytecode flags of the fixture compiled
just above, which those methods then load. Resolve reads the flags from the
class file. If `@PackageScope` had not cleared public, or a member type did not
have the flag named there, a later test could pass or fail for the wrong type.
I have added a short comment there. I would rather not copy that block into
other test classes, but I am happy to expand the comment if that would help.
##########
src/test/groovy/bugs/Groovy11916.groovy:
##########
@@ -0,0 +1,727 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package bugs
+
+import groovy.lang.GroovyClassLoader
+import org.codehaus.groovy.control.CompilationUnit
+import org.codehaus.groovy.control.CompilerConfiguration
+import org.codehaus.groovy.control.Phases
+import org.codehaus.groovy.control.customizers.ImportCustomizer
+import org.junit.jupiter.api.BeforeAll
+import org.junit.jupiter.api.Test
+
+import java.lang.reflect.Modifier
+
+import static groovy.test.GroovyAssert.assertScript
+import static groovy.test.GroovyAssert.shouldFail
+
+/**
+ * Star imports, module imports, and default imports resolve only accessible
+ * types. A source import shadows those defaults, including {@code java.lang}.
+ * Two source star imports bind the first accessible type in source order.
+ * An explicit single-type import, a fully qualified name, and
+ * {@code Class.forName} still name a type that is not public.
+ */
+final class Groovy11916 {
+
+ private static GroovyClassLoader types
+
+ @BeforeAll
+ static void compilePackagePrivateTypes() {
+ types = compile(Groovy11916.classLoader, [
+ 'p/Types': '''
+ package p
+
+ @groovy.transform.PackageScope
+ class Hidden {}
+
+ class Visible {}
+
+ @groovy.transform.PackageScope
+ class Outer {
+ public static class Inner {}
+ }
+
+ class Protector {
+ protected static class Secret {}
+ }
+
+ class Priv {
+ private static class Secret {}
+ public static class Shown {}
+ }
+
+ @groovy.transform.PackageScope
+ class Collision {}
+ '''
+ ])
+ assert !Modifier.isPublic(types.loadClass('p.Hidden').modifiers)
+ assert !Modifier.isPublic(types.loadClass('p.Collision').modifiers)
+ assert Modifier.isPublic(types.loadClass('p.Visible').modifiers)
+ assert !Modifier.isPublic(types.loadClass('p.Outer').modifiers)
+ assert Modifier.isPublic(types.loadClass('p.Outer$Inner').modifiers)
+ assert
Modifier.isProtected(types.loadClass('p.Protector$Secret').modifiers)
+ assert Modifier.isPrivate(types.loadClass('p.Priv$Secret').modifiers)
+ }
+
+ private static GroovyClassLoader compile(ClassLoader parent, Map<String,
String> sources, CompilerConfiguration config = null) {
+ def loader = new GroovyClassLoader(parent, config)
+ def unit = new CompilationUnit(config, null, loader)
+ sources.each { name, text -> unit.addSource(name + '.groovy', text) }
+ unit.compile(Phases.CLASS_GENERATION)
+ unit.classes.sort { it.name }.each { groovyClass ->
+ loader.defineClass(groovyClass.name, groovyClass.bytes)
+ }
+ loader
+ }
+
+ private static void putType(Map<String, String> sources, String pkg,
String simpleName, String state) {
+ sources[pkg + '/Marker'] = "package ${pkg}\nclass Marker {}"
+ if (state == 'p') {
+ sources[pkg + '/' + simpleName] = "package ${pkg}\nclass
${simpleName} {}"
+ } else if (state == 'k') {
+ sources[pkg + '/' + simpleName] = "package
${pkg}\[email protected]\nclass ${simpleName} {}"
+ }
+ }
+
+ private static String useSource(String pkg, String imports, String
simpleName) {
+ """\
+package ${pkg}
+${imports}
+class Use {
+ ${simpleName} field
+ static Class which() { ${simpleName} }
+}
+"""
+ }
+
+ /** First public type in source order. {@code p} public, {@code k}
package-private, {@code m} missing. */
+ private static String firstStar(String a, String b, String c) {
+ if (a == 'p') return 'pa.X'
+ if (b == 'p') return 'pb.X'
+ if (c == 'p') return 'pc.X'
+ return 'unresolved'
+ }
+
+ private static String classifyUse(Map<String, String> sources, String
className, CompilerConfiguration config = null) {
+ // Dependency types are compiled first so package-private modifiers are
+ // already on the bytecode when the importing compilation unit is
resolved.
+ def deps = sources.findAll { name, text -> !name.endsWith('/Use') }
+ def use = sources.findAll { name, text -> name.endsWith('/Use') }
+ try {
+ def parent = deps ? compile(Groovy11916.classLoader, deps) :
Groovy11916.classLoader
+ def loader = compile(parent, use, config)
+ return
loader.loadClass(className).getDeclaredMethod('which').invoke(null).name
+ } catch (Exception e) {
+ String text = ''
+ for (Throwable t = e; t != null; t = t.cause) {
+ if (t.message != null) text += t.message + '\n'
+ }
+ if (text.contains('ambiguous')) return 'ambiguous'
+ if (text.contains('unable to resolve')) return 'unresolved'
+ if (text.contains('not public')) return 'not-public'
+ def snippet = text.readLines().collect { it.trim() }.findAll { it
}.take(4).join(' | ')
+ return 'other:' + (snippet ?: e.getClass().simpleName)
+ }
+ }
+
+ @Test
+ void testStarImportDoesNotResolvePackagePrivateJdkType() {
+ assert !Modifier.isPublic(Class.forName('java.util.TimSort').modifiers)
+
+ def err = shouldFail '''
+ import java.util.*
+ def seen = null instanceof TimSort
+ '''
+ assert err.message.contains('unable to resolve class TimSort')
+
+ // A bare name in a script is a dynamic property when it is not a type.
+ // It must not bind the inaccessible class (that binding is what throws
+ // IllegalAccessError for a later instanceof / checkcast).
+ err = shouldFail '''
+ import java.util.*
+ assert TimSort.name == 'java.util.TimSort'
+ '''
+ assert err instanceof MissingPropertyException
+ }
+
+ @Test
+ void testDefaultImportDoesNotResolvePackagePrivateJdkType() {
+ def err = shouldFail '''
+ def seen = null instanceof TimSort
+ '''
+ assert err.message.contains('unable to resolve class TimSort')
+ }
+
+ @Test
+ void testModuleImportDoesNotResolvePackagePrivateJdkType() {
+ def err = shouldFail '''
+ import module java.base
+ def seen = null instanceof TimSort
+ '''
+ assert err.message.contains('unable to resolve class TimSort')
+ }
+
+ @Test
+ void testStarImportStillResolvesPublicTypes() {
+ assertScript '''
+ import java.util.*
+ assert ArrayList.name == 'java.util.ArrayList'
+ assert List.name == 'java.util.List'
+ assert new ArrayList() instanceof List
+ '''
+ assertScript '''
+ import java.util.Map.*
+ Entry e = [a:1].entrySet().first()
+ assert e.key == 'a'
+ '''
+ assertScript '''
+ import static java.util.Map.*
+ Entry e = [a:1].entrySet().first()
+ assert e instanceof Entry
+ '''
+ assertScript '''
+ import module java.base
+ assert ArrayList.name == 'java.util.ArrayList'
+ assert LocalDate.name == 'java.time.LocalDate'
+ '''
+ }
+
+ @Test
+ void testExplicitReferenceToPackagePrivateTypeStillResolves() {
+ assertScript '''
+ import java.util.TimSort
+ assert TimSort.name == 'java.util.TimSort'
Review Comment:
Thanks for raising this. The explicit import still compiles because
`visitClass` resolves `module.getImports()` with `resolve(type, false, false,
true)` and fails only when the name does not exist. `isStarImportAccessible` is
not called on that path. A fully qualified name takes the same path.
The program-structure chapter describes a simple import as naming the class.
It does not make an inaccessible explicit import a compile error, and this is
not a generics rule, so javac's JLS 7.5.1 / 6.6.1 failure is not what this
change implements.
Star, module, and default imports are filtered because they bind a simple
name the source did not write. Putting the same check inside `resolve()` would
also reject the explicit import and the qualified name, and it would stop the
star loop from distinguishing "no such class" from "present, but not importable
on demand". Same-package, protected, and nest access would still have to
succeed. That feels like a separate diagnostic, rather than a fix to the
star-import rule in this PR.
`TimSort.name` runs for a different reason. The type is not public, so the
class expression is not an `ldc` (`BytecodeHelper.isClassLiteralPossible`). It
is loaded with `Class.forName`. That does not decide whether `ResolveVisitor`
accepts the import.
##########
src/main/java/org/codehaus/groovy/control/ResolveVisitor.java:
##########
@@ -1195,6 +1289,72 @@ protected Expression transformPropertyExpression(final
PropertyExpression pe) {
return isTopLevelProperty ? correctClassClassChain(xe) : xe;
}
+ /**
+ * Whether a type found through a star import, a module import, or a
default
+ * import is accessible from {@link #currentClass}.
+ * <p>
+ * Public types are visible. A package-private type stays visible in its
own
+ * package, a protected member type stays visible to subclasses of its
enclosing
+ * type, and a private member type stays visible inside the enclosing
nest. A
+ * public member of an inaccessible enclosing type is not visible, so a
star
+ * import cannot bind it.
+ * <p>
+ * Single-type imports are not filtered. An explicit {@code import
p.Hidden}
+ * or a fully-qualified name still resolves, matching long-standing Groovy
+ * behaviour, and {@code Class.forName} is unaffected. Static field imports
+ * already apply an access check ({@link StaticImportVisitor}, since
Groovy 5).
+ *
+ * @param type a resolved candidate
+ * @param knownOuter the type named by {@code import some.Type.*} when
+ * {@code type} is a binary member type that does not
expose
+ * {@link ClassNode#getOuterClass()}
+ * @return {@code true} if the star import may bind {@code type}
+ */
+ private boolean isStarImportAccessible(final ClassNode type, final
ClassNode knownOuter) {
+ ClassNode outer = type.getOuterClass();
+ if (outer == null) {
+ outer = knownOuter;
+ }
+ if (outer == null) {
+ outer = binaryEnclosing(type);
+ }
+ if (outer != null && outer != type && !isStarImportAccessible(outer,
null)) {
+ return false;
Review Comment:
Thanks, I agree. Those issues in `ResolveVisitor` are worth fixing, but I
would keep them out of this PR.
> Star imports should not resolve package-private types
> -----------------------------------------------------
>
> Key: GROOVY-11916
> URL: https://issues.apache.org/jira/browse/GROOVY-11916
> Project: Groovy
> Issue Type: Bug
> Reporter: Paul King
> Priority: Major
>
> Groovy's star import resolution (e.g., import java.util.*) currently includes
> package-private classes in name resolution. On modern JDKs (9+) with the
> module system, these classes cannot actually be used — attempts result in
> IllegalAccessError at runtime. This can lead to confusing errors and
> inconsistency with Java's behaviour where star imports only resolve public
> types.
> For example, import java.util.* allows def cls = TimSort to compile
> (resolving the package-private java.util.TimSort), but any actual usage
> (instanceof, construction, method calls) fails at runtime with
> IllegalAccessError.
> {code:groovy}
> import java.util.*
> assert String.modifiers == 17
> def cls = TimSort // fine
> assert cls.modifiers == 0
> println cls // => class java.util.TimSort
> println Class.forName('java.util.TimSort') // => class java.util.TimSort
> println new Object() instanceof TimSort // IllegalAccessError
> {code}
> Having said that, as a counter example, is it really any different than being
> able to get the class via Class.forName?
> If the Java behavior is deemed correct, the fix would be to filter non-public
> classes during star import resolution in ResolveVisitor, producing a clean
> compile-time error instead of a runtime error. This is technically a breaking
> change but only affects code that was already failing at runtime on modular
> JDKs.
> This also benefits the import module feature (GROOVY-11896), which expands to
> star imports — filtering at the resolution level means module imports
> correctly include only public types, matching Java's import module semantics.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)