You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2021/10/07 00:11:52 UTC

[groovy] branch GROOVY-10281 updated (2b4e21c -> 1cd6831)

This is an automated email from the ASF dual-hosted git repository.

sunlan pushed a change to branch GROOVY-10281
in repository https://gitbox.apache.org/repos/asf/groovy.git.


    omit 2b4e21c  GROOVY-10281: Add compiler option for logging class generation
     new 1cd6831  GROOVY-10281: Add compiler option for logging class generation

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (2b4e21c)
            \
             N -- N -- N   refs/heads/GROOVY-10281 (1cd6831)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../org/codehaus/groovy/reflection/SecurityTest.java    | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

[groovy] 01/01: GROOVY-10281: Add compiler option for logging class generation

Posted by su...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

sunlan pushed a commit to branch GROOVY-10281
in repository https://gitbox.apache.org/repos/asf/groovy.git

commit 1cd68311776d82e09164e9bcfbb851021ff21342
Author: Daniel Sun <su...@apache.org>
AuthorDate: Tue Oct 5 02:36:02 2021 +0800

    GROOVY-10281: Add compiler option for logging class generation
---
 .../groovy/classgen/asm/WriterController.java      | 11 ++--
 .../classgen/asm/util/LoggableClassVisitor.java    |  6 +-
 .../classgen/asm/util/LoggableTextifier.java       | 24 ++++++--
 .../groovy/control/CompilerConfiguration.java      | 70 ++++++++++++++++++++++
 src/test/groovy/bugs/Groovy10281.groovy            | 62 +++++++++++++++++++
 .../codehaus/groovy/reflection/SecurityTest.java   | 17 ++++++
 6 files changed, 176 insertions(+), 14 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/WriterController.java b/src/main/java/org/codehaus/groovy/classgen/asm/WriterController.java
index 7a08d52..d34cc3b 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/WriterController.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/WriterController.java
@@ -41,12 +41,9 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 
-import static org.apache.groovy.util.SystemUtil.getBooleanSafe;
 import static org.codehaus.groovy.ast.ClassHelper.isGeneratedFunction;
 
 public class WriterController {
-
-    private static final boolean LOG_CLASSGEN = getBooleanSafe("groovy.log.classgen");
     private static final String RECORD_CLASS_NAME = "java.lang.Record";
 
     private AsmClassGenerator acg;
@@ -136,7 +133,7 @@ public class WriterController {
         this.acg = asmClassGenerator;
         this.context = gcon;
         this.compileStack = new CompileStack(this);
-        this.cv = createClassVisitor(cv);
+        this.cv = createClassVisitor(cv, config);
         if (this.optimizeForInt) {
             this.statementWriter = new OptimizingStatementWriter(this);
         } else {
@@ -145,11 +142,11 @@ public class WriterController {
         this.typeChooser = new StatementMetaTypeChooser();
     }
 
-    private static ClassVisitor createClassVisitor(final ClassVisitor cv) {
-        if (!LOG_CLASSGEN || cv instanceof LoggableClassVisitor) {
+    private static ClassVisitor createClassVisitor(final ClassVisitor cv, CompilerConfiguration config) {
+        if (!config.isLogClassgen() || cv instanceof LoggableClassVisitor) {
             return cv;
         }
-        return new LoggableClassVisitor(cv);
+        return new LoggableClassVisitor(cv, config);
     }
 
     private static int chooseBytecodeVersion(final boolean invokedynamic, final boolean previewFeatures, final String targetBytecode) {
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/util/LoggableClassVisitor.java b/src/main/java/org/codehaus/groovy/classgen/asm/util/LoggableClassVisitor.java
index dd86cbb..5fd97a9 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/util/LoggableClassVisitor.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/util/LoggableClassVisitor.java
@@ -29,6 +29,10 @@ import org.objectweb.asm.util.TraceClassVisitor;
  */
 public class LoggableClassVisitor extends ClassVisitor {
     public LoggableClassVisitor(final ClassVisitor cv) {
-        super(CompilerConfiguration.ASM_API_VERSION, new TraceClassVisitor(cv, new LoggableTextifier(), null));
+        this(cv, CompilerConfiguration.DEFAULT);
+    }
+
+    public LoggableClassVisitor(ClassVisitor cv, CompilerConfiguration compilerConfiguration) {
+        super(CompilerConfiguration.ASM_API_VERSION, new TraceClassVisitor(cv, new LoggableTextifier(compilerConfiguration), null));
     }
 }
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/util/LoggableTextifier.java b/src/main/java/org/codehaus/groovy/classgen/asm/util/LoggableTextifier.java
index ffc2454..4d7ca98 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/util/LoggableTextifier.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/util/LoggableTextifier.java
@@ -26,6 +26,7 @@ import org.objectweb.asm.TypePath;
 import org.objectweb.asm.util.Printer;
 import org.objectweb.asm.util.Textifier;
 
+import java.io.PrintWriter;
 import java.util.LinkedList;
 import java.util.List;
 
@@ -35,19 +36,30 @@ import java.util.List;
  * @since 2.5.0
  */
 public class LoggableTextifier extends Textifier {
-    private static final String GROOVY_LOG_CLASSGEN_STACKTRACE_MAX_DEPTH = "groovy.log.classgen.stacktrace.max.depth";
     private static final String GROOVY = ".groovy.";
     private static final String LOGGABLE_TEXTIFIER = ".LoggableTextifier";
-    private static final int STACKTRACE_MAX_DEPTH = Integer.getInteger(GROOVY_LOG_CLASSGEN_STACKTRACE_MAX_DEPTH, 0);
+    private final CompilerConfiguration compilerConfiguration;
+    private final int logClassgenStackTraceMaxDepth;
+    private final PrintWriter out;
     private int loggedLineCnt = 0;
 
     public LoggableTextifier() {
+        this(CompilerConfiguration.DEFAULT);
+    }
+
+    public LoggableTextifier(CompilerConfiguration compilerConfiguration) {
         super(CompilerConfiguration.ASM_API_VERSION);
+        this.compilerConfiguration = compilerConfiguration;
+
+        this.logClassgenStackTraceMaxDepth = compilerConfiguration.getLogClassgenStackTraceMaxDepth();
+        this.out = null == compilerConfiguration.getOutput()
+                        ? new PrintWriter(System.out, true)
+                        : compilerConfiguration.getOutput();
     }
 
     @Override
     protected Textifier createTextifier() {
-        return new LoggableTextifier();
+        return new LoggableTextifier(compilerConfiguration);
     }
 
     protected void log() {
@@ -67,11 +79,11 @@ public class LoggableTextifier extends Textifier {
         if (bcList.size() > 0) {
             List<StackTraceElement> invocationPositionInfo = getInvocationPositionInfo();
             if (invocationPositionInfo.size() > 0) {
-                System.out.print(formatInvocationPositionInfo(invocationPositionInfo));
+                out.print(formatInvocationPositionInfo(invocationPositionInfo));
             }
 
             for (Object bc : bcList) {
-                System.out.print(bc);
+                out.print(bc);
             }
         }
 
@@ -85,7 +97,7 @@ public class LoggableTextifier extends Textifier {
         for (StackTraceElement stackTraceElement : stackTraceElements) {
             String className = stackTraceElement.getClassName();
             if (className.contains(GROOVY) && !className.endsWith(LOGGABLE_TEXTIFIER)) {
-                if (stackTraceElementList.size() >= STACKTRACE_MAX_DEPTH) {
+                if (stackTraceElementList.size() >= logClassgenStackTraceMaxDepth) {
                     break;
                 }
 
diff --git a/src/main/java/org/codehaus/groovy/control/CompilerConfiguration.java b/src/main/java/org/codehaus/groovy/control/CompilerConfiguration.java
index fa366a5..ae5b2c7 100644
--- a/src/main/java/org/codehaus/groovy/control/CompilerConfiguration.java
+++ b/src/main/java/org/codehaus/groovy/control/CompilerConfiguration.java
@@ -40,6 +40,7 @@ import java.util.Set;
 import java.util.StringTokenizer;
 
 import static org.apache.groovy.util.SystemUtil.getBooleanSafe;
+import static org.apache.groovy.util.SystemUtil.getIntegerSafe;
 import static org.apache.groovy.util.SystemUtil.getSystemPropertySafe;
 import static org.codehaus.groovy.runtime.StringGroovyMethods.isAtLeast;
 
@@ -401,6 +402,16 @@ public class CompilerConfiguration {
     private boolean sealedAnnotations;
 
     /**
+     * Whether logging class generation is enabled
+     */
+    private boolean logClassgen;
+
+    /**
+     * sets logging class generation stack trace max depth
+     */
+    private int logClassgenStackTraceMaxDepth;
+
+    /**
      * options for joint compilation (null by default == no joint compilation)
      */
     private Map<String, Object> jointCompilationOptions;
@@ -421,6 +432,7 @@ public class CompilerConfiguration {
 
     private BytecodeProcessor bytecodePostprocessor;
 
+
     /**
      * Sets the compiler flags/settings to default values.
      *
@@ -462,6 +474,8 @@ public class CompilerConfiguration {
         recordsNative = !getBooleanSafe("groovy.records.native.disable");
         sealedNative = !getBooleanSafe("groovy.sealed.native.disable");
         sealedAnnotations = !getBooleanSafe("groovy.sealed.annotations.disable");
+        logClassgen = getBooleanSafe("groovy.log.classgen");
+        logClassgenStackTraceMaxDepth = getIntegerSafe("groovy.log.classgen.stacktrace.max.depth", 0);
         sourceEncoding = getSystemPropertySafe("groovy.source.encoding",
                 getSystemPropertySafe("file.encoding", DEFAULT_SOURCE_ENCODING));
         setTargetDirectorySafe(getSystemPropertySafe("groovy.target.directory"));
@@ -510,6 +524,8 @@ public class CompilerConfiguration {
         setPreviewFeatures(configuration.isPreviewFeatures());
         setSealedNative(configuration.isSealedNative());
         setSealedAnnotations(configuration.isSealedAnnotations());
+        setLogClassgen(configuration.isLogClassgen());
+        setLogClassgenStackTraceMaxDepth(configuration.getLogClassgenStackTraceMaxDepth());
         setDefaultScriptExtension(configuration.getDefaultScriptExtension());
         setSourceEncoding(configuration.getSourceEncoding());
         Map<String, Object> jointCompilationOptions = configuration.getJointCompilationOptions();
@@ -677,6 +693,19 @@ public class CompilerConfiguration {
         text = configuration.getProperty("groovy.sealed.annotations.disable");
         if (text != null) setSealedAnnotations(!text.equalsIgnoreCase("false"));
 
+        text = configuration.getProperty("groovy.log.classgen");
+        if (text != null) setLogClassgen(text.equalsIgnoreCase("true"));
+
+        text = configuration.getProperty("groovy.log.classgen.stacktrace.max.depth");
+        if (text != null) {
+            int logClassgenStackTraceMaxDepth = 0;
+            try {
+                logClassgenStackTraceMaxDepth = Integer.parseInt(text);
+            } catch (Exception ignored) {
+            }
+            setLogClassgenStackTraceMaxDepth(Math.max(logClassgenStackTraceMaxDepth, 0));
+        }
+
         text = configuration.getProperty("groovy.classpath");
         if (text != null) setClasspath(text);
 
@@ -724,6 +753,7 @@ public class CompilerConfiguration {
         }
     }
 
+
     /**
      * Gets the currently configured warning level. See {@link WarningMessage}
      * for level details.
@@ -1059,6 +1089,46 @@ public class CompilerConfiguration {
     }
 
     /**
+     * Returns whether logging class generation is enabled
+     *
+     * @return whether logging class generation is enabled
+     * @since 4.0.0
+     */
+    public boolean isLogClassgen() {
+        return logClassgen;
+    }
+
+    /**
+     * Sets whether logging class generation is enabled
+     *
+     * @param logClassgen whether to enable logging class generation
+     * @since 4.0.0
+     */
+    public void setLogClassgen(boolean logClassgen) {
+        this.logClassgen = logClassgen;
+    }
+
+    /**
+     * Returns stack trace max depth of logging class generation
+     *
+     * @return stack trace max depth of logging class generation
+     * @since 4.0.0
+     */
+    public int getLogClassgenStackTraceMaxDepth() {
+        return logClassgenStackTraceMaxDepth;
+    }
+
+    /**
+     * Sets stack trace max depth of logging class generation
+     *
+     * @param logClassgenStackTraceMaxDepth stack trace max depth of logging class generation
+     * @since 4.0.0
+     */
+    public void setLogClassgenStackTraceMaxDepth(int logClassgenStackTraceMaxDepth) {
+        this.logClassgenStackTraceMaxDepth = logClassgenStackTraceMaxDepth;
+    }
+
+    /**
      * Gets the joint compilation options for this configuration.
      * @return the options
      */
diff --git a/src/test/groovy/bugs/Groovy10281.groovy b/src/test/groovy/bugs/Groovy10281.groovy
new file mode 100644
index 0000000..4468433
--- /dev/null
+++ b/src/test/groovy/bugs/Groovy10281.groovy
@@ -0,0 +1,62 @@
+/*
+ *  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.transform.CompileStatic
+import org.codehaus.groovy.control.CompilationUnit
+import org.codehaus.groovy.control.CompilerConfiguration
+import org.codehaus.groovy.control.Phases
+import org.junit.Test
+
+@CompileStatic
+final class Groovy10281 {
+    @Test
+    void testLoggingClassGenWithStacktrace() {
+        def result = logClassGen(true)
+        assert result.contains('// org.codehaus.groovy.classgen.AsmClassGenerator#visitClass:')
+        assert result.contains('public class helloWorld extends groovy/lang/Script {')
+        assert result.contains('LDC "Hello, world!"')
+    }
+
+    @Test
+    void testLoggingClassGenWithoutStacktrace() {
+        def result = logClassGen(false)
+        assert !result.contains('// org.codehaus.groovy.classgen.AsmClassGenerator#visitClass:')
+        assert result.contains('public class helloWorld extends groovy/lang/Script {')
+        assert result.contains('LDC "Hello, world!"')
+    }
+
+    private static String logClassGen(boolean stacktrace) {
+        def code = """
+                println 'Hello, world!'
+            """
+        def result = new StringWriter()
+        PrintWriter pw = new PrintWriter(result)
+        def config = stacktrace ? new CompilerConfiguration(logClassgen: true, logClassgenStackTraceMaxDepth: 50, output: pw)
+                                                    : new CompilerConfiguration(logClassgen: true, output: pw)
+
+        new CompilationUnit(config).with {
+            addSource 'helloWorld.groovy', code
+            compile Phases.CLASS_GENERATION
+        }
+
+        pw.close()
+        return result.toString()
+    }
+}
diff --git a/src/test/org/codehaus/groovy/reflection/SecurityTest.java b/src/test/org/codehaus/groovy/reflection/SecurityTest.java
index 5f24859..cdc4b7c 100644
--- a/src/test/org/codehaus/groovy/reflection/SecurityTest.java
+++ b/src/test/org/codehaus/groovy/reflection/SecurityTest.java
@@ -21,6 +21,7 @@ package org.codehaus.groovy.reflection;
 import groovy.lang.GroovyObjectSupport;
 import groovy.test.GroovyTestCase;
 import org.codehaus.groovy.runtime.InvokerInvocationException;
+import org.codehaus.groovy.vmplugin.VMPluginFactory;
 
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
@@ -82,6 +83,22 @@ public class SecurityTest extends GroovyTestCase {
     Permissions forbidden;
 
     public void setUp() {
+        // Forbidding suppressAccessChecks in the test will make the internal implementation of some JDK fail,
+        // so load vm plugin before security manager is installed:
+        /*
+         *     Caused by: java.security.AccessControlException: suppressAccessChecks
+         *         at org.codehaus.groovy.reflection.SecurityTest$1.checkPermission(SecurityTest.java:92)
+         *         at java.base/java.lang.reflect.AccessibleObject.checkPermission(AccessibleObject.java:83)
+         *         at java.base/java.lang.reflect.Constructor.setAccessible(Constructor.java:180)
+         *         at java.base/java.lang.invoke.InnerClassLambdaMetafactory$1.run(InnerClassLambdaMetafactory.java:207)
+         *         at java.base/java.lang.invoke.InnerClassLambdaMetafactory$1.run(InnerClassLambdaMetafactory.java:200)
+         *         at java.base/java.security.AccessController.doPrivileged(Native Method)
+         *         at java.base/java.lang.invoke.InnerClassLambdaMetafactory.buildCallSite(InnerClassLambdaMetafactory.java:199)
+         *         at java.base/java.lang.invoke.LambdaMetafactory.metafactory(LambdaMetafactory.java:329)
+         *         at java.base/java.lang.invoke.BootstrapMethodInvoker.invoke(BootstrapMethodInvoker.java:127)
+         */
+        VMPluginFactory.getPlugin();
+
         forbidden = new Permissions();
         forbidden.add(new ReflectPermission("suppressAccessChecks"));
         restrictiveSecurityManager = new SecurityManager() {