Search in sources :

Example 1 with RewriteResult

use of org.springsource.loaded.SystemClassReflectionRewriter.RewriteResult in project spring-loaded by spring-projects.

the class SpringLoadedPreProcessor method preProcess.

/**
	 * Main entry point to Spring Loaded when it is running as an agent. This method will use the classLoader and the
	 * class name in order to determine whether the type should be made reloadable. Non-reloadable types will at least
	 * get their call sites rewritten.
	 *
	 * @param classLoader the classloader loading this type
	 * @param slashedClassName the slashed class name (e.g. java/lang/String) being loaded
	 * @param protectionDomain the protection domain for the loaded class
	 * @param bytes the class bytes for the class being loaded
	 * @return potentially modified bytes
	 */
public byte[] preProcess(ClassLoader classLoader, String slashedClassName, ProtectionDomain protectionDomain, byte[] bytes) {
    if (disabled) {
        return bytes;
    }
    // TODO need configurable debug here, ability to dump any code before/after
    for (Plugin plugin : getGlobalPlugins()) {
        if (plugin instanceof LoadtimeInstrumentationPlugin) {
            LoadtimeInstrumentationPlugin loadtimeInstrumentationPlugin = (LoadtimeInstrumentationPlugin) plugin;
            if (loadtimeInstrumentationPlugin.accept(slashedClassName, classLoader, protectionDomain, bytes)) {
                bytes = loadtimeInstrumentationPlugin.modify(slashedClassName, classLoader, bytes);
            }
        }
    }
    tryToEnsureSystemClassesInitialized(slashedClassName);
    TypeRegistry typeRegistry = TypeRegistry.getTypeRegistryFor(classLoader);
    if (GlobalConfiguration.verboseMode && log.isLoggable(Level.INFO)) {
        logPreProcess(classLoader, slashedClassName, typeRegistry);
    }
    if (typeRegistry == null) {
        // A null type registry indicates nothing is being made reloadable for the classloader
        if (classLoader == null && slashedClassName != null) {
            // Indicates loading of a system class
            if (systemClassesContainingReflection.contains(slashedClassName)) {
                try {
                    // TODO [perf] why are we not using the cache here, is it because the list is so short?
                    RewriteResult rr = SystemClassReflectionRewriter.rewrite(slashedClassName, bytes);
                    if (GlobalConfiguration.verboseMode && log.isLoggable(Level.INFO)) {
                        log.info("System class rewritten: name=" + slashedClassName + " rewrite summary=" + rr.summarize());
                    }
                    systemClassesRequiringInitialization.put(slashedClassName, rr.bits);
                    return rr.bytes;
                } catch (Exception re) {
                    re.printStackTrace();
                }
            } else if (slashedClassName.equals("java/lang/invoke/InnerClassLambdaMetafactory")) {
                bytes = Java8.enhanceInnerClassLambdaMetaFactory(bytes);
                return bytes;
            } else if ((GlobalConfiguration.investigateSystemClassReflection || GlobalConfiguration.rewriteAllSystemClasses) && SystemClassReflectionInvestigator.investigate(slashedClassName, bytes, GlobalConfiguration.investigateSystemClassReflection) > 0) {
                // This block can help when you suspect there is a system class using reflection and that
                // class isn't on the 'shortlist' (in systemClassesContainingReflection). Basically turn on the
                // options to trigger this investigation then add them to the shortlist if it looks like they need rewriting.
                RewriteResult rr = SystemClassReflectionRewriter.rewrite(slashedClassName, bytes);
                if (GlobalConfiguration.rewriteAllSystemClasses) {
                    systemClassesRequiringInitialization.put(slashedClassName, rr.bits);
                    return rr.bytes;
                } else {
                    System.err.println("Type " + slashedClassName + " rewrite summary: " + rr.summarize());
                    return bytes;
                }
            }
        }
        return bytes;
    }
    // What happens here? The aim is to determine if the type should be made reloadable.
    // 1. If NO, but something in this classloader might be, then rewrite the call sites.
    // 2. If NO, and nothing in this classloader might be, return the original bytes.
    // 3. If YES, make the type reloadable (including rewriting call sites)
    ReloadableTypeNameDecision isReloadableTypeName = typeRegistry.isReloadableTypeName(slashedClassName, protectionDomain, bytes);
    if (isReloadableTypeName.isReloadable && GlobalConfiguration.explainMode && log.isLoggable(Level.INFO)) {
        log.info("[explanation] Based on the name, type " + slashedClassName + " is considered to be reloadable");
    }
    //		}
    if (isReloadableTypeName.isReloadable) {
        if (!firstReloadableTypeHit) {
            firstReloadableTypeHit = true;
            // TODO move into the ctor for ReloadableType so that it can't block loading
            tryToEnsureSystemClassesInitialized(slashedClassName);
        }
        if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
            log.info("processing " + slashedClassName + " as a reloadable type");
        }
        try {
            // TODO decide one way or the other on slashed/dotted from preprocessor to infrastructure
            String dottedClassName = slashedClassName.replace('/', '.');
            String watchPath = getWatchPathFromProtectionDomain(protectionDomain, slashedClassName);
            if (watchPath == null) {
                // For a CGLIB generated type, we may still need to make the type reloadable.  For example:
                // type: com/vmware/rabbit/ApplicationContext$$EnhancerByCGLIB$$512eb60c
                // codesource determined to be: file:/Users/aclement/springsource/tc-server-developer-2.1.1.RELEASE/spring-insight-instance/wtpwebapps/hello-rabbit-client/WEB-INF/lib/cglib-nodep-2.2.jar <no signer certificates>
                // But if the type 'com/vmware/rabbit/ApplicationContext' is reloadable, then this should be too
                boolean makeReloadableAnyway = false;
                int cglibIndex = slashedClassName.indexOf("$$EnhancerBy");
                if (cglibIndex != -1) {
                    String originalType = slashedClassName.substring(0, cglibIndex);
                    if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
                        log.info("Appears to be a CGLIB type, checking if type " + originalType + " is reloadable");
                    }
                    TypeRegistry currentRegistry = typeRegistry;
                    while (currentRegistry != null) {
                        ReloadableType originalReloadable = currentRegistry.getReloadableType(originalType);
                        if (originalReloadable != null) {
                            makeReloadableAnyway = true;
                            break;
                        }
                        currentRegistry = currentRegistry.getParentRegistry();
                    }
                //						if (typeRegistry.isReloadableTypeName(originalType)) {
                //							if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
                //								log.info("Type " + originalType + " is reloadable, so making CGLIB type " + slashedClassName
                //										+ " reloadable");
                //							}
                //							makeReloadableAnyway = true;
                //						}
                }
                int cglibIndex2 = makeReloadableAnyway ? -1 : slashedClassName.indexOf("$$FastClassByCGLIB");
                if (cglibIndex2 != -1) {
                    String originalType = slashedClassName.substring(0, cglibIndex2);
                    if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
                        log.info("Appears to be a CGLIB FastClass type, checking if type " + originalType + " is reloadable");
                    }
                    TypeRegistry currentRegistry = typeRegistry;
                    while (currentRegistry != null) {
                        ReloadableType originalReloadable = currentRegistry.getReloadableType(originalType);
                        if (originalReloadable != null) {
                            makeReloadableAnyway = true;
                            break;
                        }
                        currentRegistry = currentRegistry.getParentRegistry();
                    }
                //						if (typeRegistry.isReloadableTypeName(originalType)) {
                //							if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
                //								log.info("Type " + originalType + " is reloadable, so making CGLIB type " + slashedClassName
                //										+ " reloadable");
                //							}
                //							makeReloadableAnyway = true;
                //						}
                }
                int proxyIndex = makeReloadableAnyway ? -1 : slashedClassName.indexOf("$Proxy");
                if (proxyIndex == 0 || (proxyIndex > 0 && slashedClassName.charAt(proxyIndex - 1) == '/')) {
                    // Determine if the interfaces being implemented are reloadable
                    String[] interfacesImplemented = Utils.discoverInterfaces(bytes);
                    if (interfacesImplemented != null) {
                        for (int i = 0; i < interfacesImplemented.length; i++) {
                            TypeRegistry currentRegistry = typeRegistry;
                            while (currentRegistry != null) {
                                ReloadableType originalReloadable = currentRegistry.getReloadableType(interfacesImplemented[i]);
                                if (originalReloadable != null) {
                                    makeReloadableAnyway = true;
                                    break;
                                }
                                currentRegistry = currentRegistry.getParentRegistry();
                            }
                        //								if (typeRegistry.isReloadableTypeName(interfacesImplemented[i])) {
                        //									makeReloadableAnyway = true;
                        //								}
                        }
                    }
                }
                // all classloaders below one loading reloadable stuff should also load reloadable stuff.
                if (!makeReloadableAnyway && classLoader.getClass().getName().endsWith("GroovyClassLoader$InnerLoader")) {
                    makeReloadableAnyway = true;
                }
                if (!makeReloadableAnyway) {
                    //						else {
                    if (GlobalConfiguration.verboseMode) {
                        Log.log("Cannot watch " + slashedClassName + ": not making it reloadable");
                    }
                    if (needsClientSideRewriting(slashedClassName)) {
                        bytes = typeRegistry.methodCallRewriteUseCacheIfAvailable(slashedClassName, bytes);
                    }
                    return bytes;
                //						}
                }
            }
            ReloadableType rtype = typeRegistry.addType(dottedClassName, bytes);
            if (rtype == null && GlobalConfiguration.callsideRewritingOn) {
                // it is not a candidate for being made reloadable (maybe it is an annotation type)
                // but we still need to rewrite call sites.
                bytes = typeRegistry.methodCallRewrite(bytes);
            } else {
                if (GlobalConfiguration.fileSystemMonitoring && watchPath != null) {
                    typeRegistry.monitorForUpdates(rtype, watchPath);
                }
                return rtype.bytesLoaded;
            }
        } catch (RuntimeException re) {
            log.throwing("SpringLoadedPreProcessor", "preProcess", re);
            throw re;
        }
    } else {
        try {
            // with due to GroovyPlugin class that intercepts define in that infrastructure
            if (needsClientSideRewriting(slashedClassName) && (classLoader == null || !classLoader.getClass().getName().equals("org.codehaus.groovy.runtime.callsite.CallSiteClassLoader"))) {
                bytes = typeRegistry.methodCallRewriteUseCacheIfAvailable(slashedClassName, bytes);
            }
        } catch (Throwable t) {
            log.log(Level.SEVERE, "Unexpected problem transforming call sites", t);
        }
    }
    return bytes;
}
Also used : LoadtimeInstrumentationPlugin(org.springsource.loaded.LoadtimeInstrumentationPlugin) TypeRegistry(org.springsource.loaded.TypeRegistry) ReloadableTypeNameDecision(org.springsource.loaded.TypeRegistry.ReloadableTypeNameDecision) ReloadableType(org.springsource.loaded.ReloadableType) RewriteResult(org.springsource.loaded.SystemClassReflectionRewriter.RewriteResult) LoadtimeInstrumentationPlugin(org.springsource.loaded.LoadtimeInstrumentationPlugin) IsReloadableTypePlugin(org.springsource.loaded.IsReloadableTypePlugin) Plugin(org.springsource.loaded.Plugin)

Example 2 with RewriteResult

use of org.springsource.loaded.SystemClassReflectionRewriter.RewriteResult in project spring-loaded by spring-projects.

the class SystemClassReflectionRewriterTests method jlrField_get.

@Test
public void jlrField_get() throws Exception {
    byte[] classbytes = loadBytesForClass("system.Twelve");
    RewriteResult rr = SystemClassReflectionRewriter.rewrite("system.Twelve", classbytes);
    byte[] newbytes = rr.bytes;
    Class<?> clazz = loadit("system.Twelve", newbytes);
    // Check the new field and method are in the type:
    //@formatter:off
    assertEquals("CLASS: system/Twelve v50 0x0021(public synchronized) super java/lang/Object\n" + "SOURCE: Twelve.java null\n" + "FIELD 0x0001(public) foo Ljava/lang/String;\n" + "FIELD 0x0009(public static) __sljlcgf Ljava/lang/reflect/Method;\n" + "FIELD 0x0009(public static) __sljlrfg Ljava/lang/reflect/Method;\n" + "METHOD: 0x0001(public) <init>()V\n" + "METHOD: 0x0001(public) runIt()Ljava/lang/String; java/lang/Exception\n" + "METHOD: 0x0001(public) gf()Ljava/lang/Object; java/lang/Exception\n" + "METHOD: 0x000a(private static) __sljlcgf(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/reflect/Field; java/lang/NoSuchFieldException\n" + "METHOD: 0x000a(private static) __sljlrfg(Ljava/lang/reflect/Field;Ljava/lang/Object;)Ljava/lang/Object; java/lang/IllegalAccessException java/lang/IllegalArgumentException\n" + "\n", toStringClass(newbytes));
    //@formatter:on
    Object value = run(clazz, "runIt");
    // Check that without the field initialized, things behave as expected
    assertEquals("complete:value=abc", value);
    assertEquals(0, callcount);
    // Set the field
    Method m = SystemClassReflectionRewriterTests.class.getDeclaredMethod("helperJLRFG_0", Class.class, String.class);
    assertNotNull(m);
    clazz.getDeclaredField(jlcgf).set(null, m);
    m = SystemClassReflectionRewriterTests.class.getDeclaredMethod("helperJLRFG", Field.class, Object.class);
    assertNotNull(m);
    clazz.getDeclaredField(jlrfGetMember).set(null, m);
    // Now re-run, should be intercepted to call our helper
    value = run(clazz, "runIt");
    assertEquals("complete:value=null", value);
    // Check the correct amount of rewriting went on
    assertTrue((rr.bits & (JLRF_GET | JLC_GETFIELD)) != 0);
    assertTrue((rr.bits & ~(JLRF_GET | JLC_GETFIELD)) == 0);
    assertEquals(1, callcount);
    assertEquals("Class.getField() Field.get()", rr.summarize());
}
Also used : Field(java.lang.reflect.Field) RewriteResult(org.springsource.loaded.SystemClassReflectionRewriter.RewriteResult) Method(java.lang.reflect.Method) Test(org.junit.Test)

Example 3 with RewriteResult

use of org.springsource.loaded.SystemClassReflectionRewriter.RewriteResult in project spring-loaded by spring-projects.

the class SystemClassReflectionRewriterTests method jlrMethod_Invoke.

@Test
public void jlrMethod_Invoke() throws Exception {
    byte[] classbytes = loadBytesForClass("system.Eleven");
    RewriteResult rr = SystemClassReflectionRewriter.rewrite("system.Eleven", classbytes);
    byte[] newbytes = rr.bytes;
    Class<?> clazz = loadit("system.Eleven", newbytes);
    // Check the new field and method are in the type:
    //@formatter:off
    assertEquals("CLASS: system/Eleven v50 0x0021(public synchronized) super java/lang/Object\n" + "SOURCE: Eleven.java null\n" + "FIELD 0x0009(public static) __sljlcgdm Ljava/lang/reflect/Method;\n" + "FIELD 0x0009(public static) __sljlrmi Ljava/lang/reflect/Method;\n" + "METHOD: 0x0001(public) <init>()V\n" + "METHOD: 0x0001(public) runIt()Ljava/lang/String; java/lang/Exception\n" + "METHOD: 0x0089(public static) invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object; java/lang/Exception\n" + "METHOD: 0x0001(public) foo(ILjava/lang/String;)Ljava/lang/String;\n" + "METHOD: 0x008a(private static) __sljlcgdm(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method; java/lang/NoSuchMethodException\n" + "METHOD: 0x000a(private static) __sljlrmi(Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object; java/lang/IllegalAccessException java/lang/reflect/InvocationTargetException\n" + "\n", toStringClass(newbytes));
    //@formatter:on
    Object value = run(clazz, "runIt");
    // Check that without the field initialized, things behave as expected
    assertEquals("complete:obj=i=12:s=abc", value);
    assertEquals(0, callcount);
    // Set the field
    Method m = SystemClassReflectionRewriterTests.class.getDeclaredMethod("helperJLRMI_0", Class.class, String.class, Class[].class);
    assertNotNull(m);
    clazz.getDeclaredField(jlcgdm).set(null, m);
    m = SystemClassReflectionRewriterTests.class.getDeclaredMethod("helperJLRMI", Method.class, Object.class, Object[].class);
    assertNotNull(m);
    clazz.getDeclaredField(jlrmInvokeMember).set(null, m);
    // Now re-run, should be intercepted to call our helper
    value = run(clazz, "runIt");
    assertEquals("complete:obj=null", value);
    // Check the correct amount of rewriting went on
    assertTrue((rr.bits & (JLC_GETDECLAREDMETHOD | JLRM_INVOKE)) != 0);
    assertTrue((rr.bits & ~(JLC_GETDECLAREDMETHOD | JLRM_INVOKE)) == 0);
    assertEquals(1, callcount);
    assertEquals("Class.getDeclaredMethod() Method.invoke()", rr.summarize());
}
Also used : RewriteResult(org.springsource.loaded.SystemClassReflectionRewriter.RewriteResult) Method(java.lang.reflect.Method) Test(org.junit.Test)

Example 4 with RewriteResult

use of org.springsource.loaded.SystemClassReflectionRewriter.RewriteResult in project spring-loaded by spring-projects.

the class SystemClassReflectionRewriterTests method jlClass_getDeclaredFields.

/**
	 * First test. Here we are simulating a System class that is making a call to Class.getDeclaredFields. The
	 * invocation is rewritten to go via a helper method generated into the target which uses a field settable from
	 * outside. The aim is that when SpringLoaded is initialized far enough it can set the fields in these types,
	 * effectively plugging in the reflective interceptor system.
	 */
@Test
public void jlClass_getDeclaredFields() throws Exception {
    byte[] classbytes = loadBytesForClass("system.One");
    RewriteResult rr = SystemClassReflectionRewriter.rewrite("system.One", classbytes);
    byte[] newbytes = rr.bytes;
    Class<?> clazz = loadit("system.One", newbytes);
    // Check the new field and method are in the type:
    //@formatter:off
    assertEquals("CLASS: system/One v50 0x0021(public synchronized) super java/lang/Object\n" + "SOURCE: One.java null\n" + "FIELD 0x0009(public static) __sljlcgdfs Ljava/lang/reflect/Method;\n" + "METHOD: 0x0001(public) <init>()V\n" + "METHOD: 0x0001(public) runIt()Ljava/lang/String;\n" + "METHOD: 0x0001(public) fs()[Ljava/lang/reflect/Field;\n" + "METHOD: 0x000a(private static) __sljlcgdfs(Ljava/lang/Class;)[Ljava/lang/reflect/Field;\n" + "\n", toStringClass(newbytes));
    //@formatter:on
    Object value = run(clazz, "runIt");
    // Check that without the field initialized, things behave as expected
    assertEquals("complete:fields:null?false fields:size=1", value);
    assertEquals(0, callcount);
    // Set the field
    Method m = SystemClassReflectionRewriterTests.class.getDeclaredMethod("helper", Class.class);
    assertNotNull(m);
    clazz.getDeclaredField(jlcgdfs).set(null, m);
    // Now re-run, should be intercepted to call our helper
    value = run(clazz, "runIt");
    assertEquals("complete:fields:null?true", value);
    // Check the correct amount of rewriting went on
    assertTrue((rr.bits & JLC_GETDECLAREDFIELDS) != 0);
    assertTrue((rr.bits & ~JLC_GETDECLAREDFIELDS) == 0);
    assertEquals(1, callcount);
    assertEquals("Class.getDeclaredFields()", rr.summarize());
}
Also used : RewriteResult(org.springsource.loaded.SystemClassReflectionRewriter.RewriteResult) Method(java.lang.reflect.Method) Test(org.junit.Test)

Example 5 with RewriteResult

use of org.springsource.loaded.SystemClassReflectionRewriter.RewriteResult in project spring-loaded by spring-projects.

the class SystemClassReflectionRewriterTests method jlClass_getDeclaredConstructors.

@Test
public void jlClass_getDeclaredConstructors() throws Exception {
    byte[] classbytes = loadBytesForClass("system.Ten");
    RewriteResult rr = SystemClassReflectionRewriter.rewrite("system.Ten", classbytes);
    byte[] newbytes = rr.bytes;
    Class<?> clazz = loadit("system.Ten", newbytes);
    // Check the new field and method are in the type:
    //@formatter:off
    assertEquals("CLASS: system/Ten v50 0x0021(public synchronized) super java/lang/Object\n" + "SOURCE: Ten.java null\n" + "FIELD 0x0009(public static) __sljlcgdcs Ljava/lang/reflect/Method;\n" + "METHOD: 0x0001(public) <init>()V\n" + "METHOD: 0x0001(public) runIt()Ljava/lang/String;\n" + "METHOD: 0x0001(public) cs()[Ljava/lang/reflect/Constructor;\n" + "METHOD: 0x000a(private static) __sljlcgdcs(Ljava/lang/Class;)[Ljava/lang/reflect/Constructor;\n" + "\n", toStringClass(newbytes));
    //@formatter:on
    Object value = run(clazz, "runIt");
    // Check that without the field initialized, things behave as expected
    assertEquals("complete:constructors:null?false constructors:size=1", value);
    assertEquals(0, callcount);
    // Set the field
    Method m = SystemClassReflectionRewriterTests.class.getDeclaredMethod("helper4", Class.class);
    assertNotNull(m);
    clazz.getDeclaredField(jlcGetDeclaredConstructorsMember).set(null, m);
    // Now re-run, should be intercepted to call our helper
    value = run(clazz, "runIt");
    assertEquals("complete:constructors:null?true", value);
    // Check the correct amount of rewriting went on
    assertTrue((rr.bits & JLC_GETDECLAREDCONSTRUCTORS) != 0);
    assertTrue((rr.bits & ~JLC_GETDECLAREDCONSTRUCTORS) == 0);
    assertEquals(1, callcount);
    assertEquals("Class.getDeclaredConstructors()", rr.summarize());
}
Also used : RewriteResult(org.springsource.loaded.SystemClassReflectionRewriter.RewriteResult) Method(java.lang.reflect.Method) Test(org.junit.Test)

Aggregations

RewriteResult (org.springsource.loaded.SystemClassReflectionRewriter.RewriteResult)14 Method (java.lang.reflect.Method)13 Test (org.junit.Test)13 Field (java.lang.reflect.Field)2 IsReloadableTypePlugin (org.springsource.loaded.IsReloadableTypePlugin)1 LoadtimeInstrumentationPlugin (org.springsource.loaded.LoadtimeInstrumentationPlugin)1 Plugin (org.springsource.loaded.Plugin)1 ReloadableType (org.springsource.loaded.ReloadableType)1 TypeRegistry (org.springsource.loaded.TypeRegistry)1 ReloadableTypeNameDecision (org.springsource.loaded.TypeRegistry.ReloadableTypeNameDecision)1