Introduction: In JVM, what information does permspace mainly store? How can we understand its overflow?
What is permspace?
Permspace stores static class information and method information, static methods and variables, and constant information marked by final.
Case 1 of permspace overflow:
JDK version 1.6.0 _ 45 (JDK 7/JDK 8 does not have a similar problem)
Opertion system: Ubuntu 14.04
JVM parameter:-xmx128m-xms64m-XX: permsize = 5 m-XX: maxpermsize = 10 m
Principle of exploits: in Java, string-type constant string information is stored in the permspace area to form a constant pool, which is not recycled by GC, therefore, permspace overflow is achieved by creating constant information in a loop.
import java.util.ArrayList;import java.util.List;public class PermSpaceStringConstant {public static void main(String[] args) { List<String> strs = new ArrayList<String>(); int i = 0; while(true) { strs.add(String.valueOf(i++).intern()); System.out.println("We have created " + i + " constant String."); }}} Running result:
Case 2 of permspace overflow:
JVM: jdk1.6.0 _ 45, Operation System: Ubuntu 14.04
JVM parameter:-xmx128m-xms64m-XX: permsize = 5 m-XX: maxpermsize = 5 m
Third-party Class Library: cglib-nodep-3.1.jar
Principle of exploits: permspace stores class information. Therefore, cglib is used to dynamically create a new class, and a sufficient amount of class information is created in a loop to fill the permspace area, so as to overflow the permspace.
The source code is as follows:
import java.lang.reflect.Method;import net.sf.cglib.proxy.Enhancer;import net.sf.cglib.proxy.MethodInterceptor;import net.sf.cglib.proxy.MethodProxy;public class CGLibTest {public static void main(String[] args) { new CGLibTest().testCGLIB();}public void testCGLIB() { int i = 0; while(true) {Enhancer enhancer = new Enhancer();enhancer.setSuperclass(EnhancerTest.class);enhancer.setCallback(new MethodInterceptorImpl());EnhancerTest demo = (EnhancerTest) enhancer.create();//demo.test();//System.out.println(demo);System.out.println("Create " + (i++) +" instance:" + demo.getClass().getSimpleName()); }}static class EnhancerTest { }private static class MethodInterceptorImpl implements MethodInterceptor {@Overridepublic Object intercept(Object obj, Method method, Object[] args,MethodProxy proxy) throws Throwable {//System.err.println("Before invoke " + method);Object result = proxy.invokeSuper(obj, args);//System.err.println("After invoke" + method);return result;}}}
Running result:
Summary:
Through the analysis of the above two cases, you can have a deeper understanding of the information stored in permspace: class information and constant static information.
JVM optimization: permspace Overflow