proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/ClassPoolTail.java
ClassPoolTail
appendClassPath
class ClassPoolTail { protected ClassPathList pathList; public ClassPoolTail() { pathList = null; } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("[class path: "); ClassPathList list = pathList; while (list != null) { buf.append(list.path.toString()); buf.append(File.pathSeparatorChar); list = list.next; } buf.append(']'); return buf.toString(); } public synchronized ClassPath insertClassPath(ClassPath cp) { pathList = new ClassPathList(cp, pathList); return cp; } public synchronized ClassPath appendClassPath(ClassPath cp) {<FILL_FUNCTION_BODY>} public synchronized void removeClassPath(ClassPath cp) { ClassPathList list = pathList; if (list != null) if (list.path == cp) pathList = list.next; else { while (list.next != null) if (list.next.path == cp) list.next = list.next.next; else list = list.next; } } public ClassPath appendSystemPath() { if (org.hotswap.agent.javassist.bytecode.ClassFile.MAJOR_VERSION < org.hotswap.agent.javassist.bytecode.ClassFile.JAVA_9) return appendClassPath(new ClassClassPath()); ClassLoader cl = Thread.currentThread().getContextClassLoader(); return appendClassPath(new LoaderClassPath(cl)); } public ClassPath insertClassPath(String pathname) throws NotFoundException { return insertClassPath(makePathObject(pathname)); } public ClassPath appendClassPath(String pathname) throws NotFoundException { return appendClassPath(makePathObject(pathname)); } private static ClassPath makePathObject(String pathname) throws NotFoundException { String lower = pathname.toLowerCase(); if (lower.endsWith(".jar") || lower.endsWith(".zip")) return new JarClassPath(pathname); int len = pathname.length(); if (len > 2 && pathname.charAt(len - 1) == '*' && (pathname.charAt(len - 2) == '/' || pathname.charAt(len - 2) == File.separatorChar)) { String dir = pathname.substring(0, len - 2); return new JarDirClassPath(dir); } return new DirClassPath(pathname); } /** * This method does not close the output stream. */ void writeClassfile(String classname, OutputStream out) throws NotFoundException, IOException, CannotCompileException { InputStream fin = openClassfile(classname); if (fin == null) throw new NotFoundException(classname); try { copyStream(fin, out); } finally { fin.close(); } } /* -- faster version -- void checkClassName(String classname) throws NotFoundException { if (find(classname) == null) throw new NotFoundException(classname); } -- slower version -- void checkClassName(String classname) throws NotFoundException { InputStream fin = openClassfile(classname); try { fin.close(); } catch (IOException e) {} } */ /** * Opens the class file for the class specified by * <code>classname</code>. * * @param classname a fully-qualified class name * @return null if the file has not been found. * @throws NotFoundException if any error is reported by ClassPath. */ InputStream openClassfile(String classname) throws NotFoundException { ClassPathList list = pathList; InputStream ins = null; NotFoundException error = null; while (list != null) { try { ins = list.path.openClassfile(classname); } catch (NotFoundException e) { if (error == null) error = e; } if (ins == null) list = list.next; else return ins; } if (error != null) throw error; return null; // not found } /** * Searches the class path to obtain the URL of the class file * specified by classname. It is also used to determine whether * the class file exists. * * @param classname a fully-qualified class name. * @return null if the class file could not be found. */ public URL find(String classname) { ClassPathList list = pathList; URL url = null; while (list != null) { url = list.path.find(classname); if (url == null) list = list.next; else return url; } return null; } /** * Reads from an input stream until it reaches the end. * * @return the contents of that input stream */ public static byte[] readStream(InputStream fin) throws IOException { byte[][] bufs = new byte[8][]; int bufsize = 4096; for (int i = 0; i < 8; ++i) { bufs[i] = new byte[bufsize]; int size = 0; int len = 0; do { len = fin.read(bufs[i], size, bufsize - size); if (len >= 0) size += len; else { byte[] result = new byte[bufsize - 4096 + size]; int s = 0; for (int j = 0; j < i; ++j) { System.arraycopy(bufs[j], 0, result, s, s + 4096); s = s + s + 4096; } System.arraycopy(bufs[i], 0, result, s, size); return result; } } while (size < bufsize); bufsize *= 2; } throw new IOException("too much data"); } /** * Reads from an input stream and write to an output stream * until it reaches the end. This method does not close the * streams. */ public static void copyStream(InputStream fin, OutputStream fout) throws IOException { int bufsize = 4096; byte[] buf = null; for (int i = 0; i < 64; ++i) { if (i < 8) { bufsize *= 2; buf = new byte[bufsize]; } int size = 0; int len = 0; do { len = fin.read(buf, size, bufsize - size); if (len >= 0) size += len; else { fout.write(buf, 0, size); return; } } while (size < bufsize); fout.write(buf); } throw new IOException("too much data"); } }
ClassPathList tail = new ClassPathList(cp, null); ClassPathList list = pathList; if (list == null) pathList = tail; else { while (list.next != null) list = list.next; list.next = tail; } return cp;
1,909
85
1,994
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/CtMember.java
Cache
visibleFrom
class Cache extends CtMember { @Override protected void extendToString(StringBuffer buffer) {} @Override public boolean hasAnnotation(String clz) { return false; } @Override public Object getAnnotation(Class<?> clz) throws ClassNotFoundException { return null; } @Override public Object[] getAnnotations() throws ClassNotFoundException { return null; } @Override public byte[] getAttribute(String name) { return null; } @Override public Object[] getAvailableAnnotations() { return null; } @Override public int getModifiers() { return 0; } @Override public String getName() { return null; } @Override public String getSignature() { return null; } @Override public void setAttribute(String name, byte[] data) {} @Override public void setModifiers(int mod) {} @Override public String getGenericSignature() { return null; } @Override public void setGenericSignature(String sig) {} private CtMember methodTail; private CtMember consTail; // constructor tail private CtMember fieldTail; Cache(CtClassType decl) { super(decl); methodTail = this; consTail = this; fieldTail = this; fieldTail.next = this; } CtMember methodHead() { return this; } CtMember lastMethod() { return methodTail; } CtMember consHead() { return methodTail; } // may include a static initializer CtMember lastCons() { return consTail; } CtMember fieldHead() { return consTail; } CtMember lastField() { return fieldTail; } void addMethod(CtMember method) { method.next = methodTail.next; methodTail.next = method; if (methodTail == consTail) { consTail = method; if (methodTail == fieldTail) fieldTail = method; } methodTail = method; } /* Both constructors and a class initializer. */ void addConstructor(CtMember cons) { cons.next = consTail.next; consTail.next = cons; if (consTail == fieldTail) fieldTail = cons; consTail = cons; } void addField(CtMember field) { field.next = this; // or fieldTail.next fieldTail.next = field; fieldTail = field; } static int count(CtMember head, CtMember tail) { int n = 0; while (head != tail) { n++; head = head.next; } return n; } void remove(CtMember mem) { CtMember m = this; CtMember node; while ((node = m.next) != this) { if (node == mem) { m.next = node.next; if (node == methodTail) methodTail = m; if (node == consTail) consTail = m; if (node == fieldTail) fieldTail = m; break; } m = m.next; } } } protected CtMember(CtClass clazz) { declaringClass = clazz; next = null; } final CtMember next() { return next; } /** * This method is invoked when setName() or replaceClassName() * in CtClass is called. * * @see CtMethod#nameReplaced() */ void nameReplaced() {} @Override public String toString() { StringBuffer buffer = new StringBuffer(getClass().getName()); buffer.append("@"); buffer.append(Integer.toHexString(hashCode())); buffer.append("["); buffer.append(Modifier.toString(getModifiers())); extendToString(buffer); buffer.append("]"); return buffer.toString(); } /** * Invoked by {@link #toString()} to add to the buffer and provide the * complete value. Subclasses should invoke this method, adding a * space before each token. The modifiers for the member are * provided first; subclasses should provide additional data such * as return type, field or method name, etc. */ protected abstract void extendToString(StringBuffer buffer); /** * Returns the class that declares this member. */ public CtClass getDeclaringClass() { return declaringClass; } /** * Returns true if this member is accessible from the given class. */ public boolean visibleFrom(CtClass clazz) {<FILL_FUNCTION_BODY>
int mod = getModifiers(); if (Modifier.isPublic(mod)) return true; else if (Modifier.isPrivate(mod)) return clazz == declaringClass; else { // package or protected String declName = declaringClass.getPackageName(); String fromName = clazz.getPackageName(); boolean visible; if (declName == null) visible = fromName == null; else visible = declName.equals(fromName); if (!visible && Modifier.isProtected(mod)) return clazz.subclassOf(declaringClass); return visible; }
1,253
166
1,419
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/CtNewClass.java
CtNewClass
inheritAllConstructors
class CtNewClass extends CtClassType { /* true if the class is an interface. */ protected boolean hasConstructor; CtNewClass(String name, ClassPool cp, boolean isInterface, CtClass superclass) { super(name, cp); wasChanged = true; String superName; if (isInterface || superclass == null) superName = null; else superName = superclass.getName(); classfile = new ClassFile(isInterface, name, superName); if (isInterface && superclass != null) classfile.setInterfaces(new String[] { superclass.getName() }); setModifiers(Modifier.setPublic(getModifiers())); hasConstructor = isInterface; } @Override protected void extendToString(StringBuffer buffer) { if (hasConstructor) buffer.append("hasConstructor "); super.extendToString(buffer); } @Override public void addConstructor(CtConstructor c) throws CannotCompileException { hasConstructor = true; super.addConstructor(c); } @Override public void toBytecode(DataOutputStream out) throws CannotCompileException, IOException { if (!hasConstructor) try { inheritAllConstructors(); hasConstructor = true; } catch (NotFoundException e) { throw new CannotCompileException(e); } super.toBytecode(out); } /** * Adds constructors inhrited from the super class. * * <p>After this method is called, the class inherits all the * constructors from the super class. The added constructor * calls the super's constructor with the same signature. */ public void inheritAllConstructors() throws CannotCompileException, NotFoundException {<FILL_FUNCTION_BODY>} private boolean isInheritable(int mod, CtClass superclazz) { if (Modifier.isPrivate(mod)) return false; if (Modifier.isPackage(mod)) { String pname = getPackageName(); String pname2 = superclazz.getPackageName(); if (pname == null) return pname2 == null; return pname.equals(pname2); } return true; } }
CtClass superclazz; CtConstructor[] cs; superclazz = getSuperclass(); cs = superclazz.getDeclaredConstructors(); int n = 0; for (int i = 0; i < cs.length; ++i) { CtConstructor c = cs[i]; int mod = c.getModifiers(); if (isInheritable(mod, superclazz)) { CtConstructor cons = CtNewConstructor.make(c.getParameterTypes(), c.getExceptionTypes(), this); cons.setModifiers(mod & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE)); addConstructor(cons); ++n; } } if (n < 1) throw new CannotCompileException( "no inheritable constructor in " + superclazz.getName());
607
233
840
<methods>public void addConstructor(org.hotswap.agent.javassist.CtConstructor) throws org.hotswap.agent.javassist.CannotCompileException,public void addField(org.hotswap.agent.javassist.CtField, java.lang.String) throws org.hotswap.agent.javassist.CannotCompileException,public void addField(org.hotswap.agent.javassist.CtField, org.hotswap.agent.javassist.CtField.Initializer) throws org.hotswap.agent.javassist.CannotCompileException,public void addInterface(org.hotswap.agent.javassist.CtClass) ,public void addMethod(org.hotswap.agent.javassist.CtMethod) throws org.hotswap.agent.javassist.CannotCompileException,public void defrost() ,public void freeze() ,public org.hotswap.agent.javassist.compiler.AccessorMaker getAccessorMaker() ,public java.lang.Object getAnnotation(Class<?>) throws java.lang.ClassNotFoundException,public java.lang.Object[] getAnnotations() throws java.lang.ClassNotFoundException,public byte[] getAttribute(java.lang.String) ,public java.lang.Object[] getAvailableAnnotations() ,public org.hotswap.agent.javassist.bytecode.ClassFile getClassFile2() ,public org.hotswap.agent.javassist.bytecode.ClassFile getClassFile3(boolean) ,public org.hotswap.agent.javassist.CtConstructor getClassInitializer() ,public org.hotswap.agent.javassist.ClassPool getClassPool() ,public org.hotswap.agent.javassist.CtConstructor getConstructor(java.lang.String) throws org.hotswap.agent.javassist.NotFoundException,public org.hotswap.agent.javassist.CtConstructor[] getConstructors() ,public org.hotswap.agent.javassist.CtBehavior[] getDeclaredBehaviors() ,public org.hotswap.agent.javassist.CtConstructor[] getDeclaredConstructors() ,public org.hotswap.agent.javassist.CtField getDeclaredField(java.lang.String) throws org.hotswap.agent.javassist.NotFoundException,public org.hotswap.agent.javassist.CtField getDeclaredField(java.lang.String, java.lang.String) throws org.hotswap.agent.javassist.NotFoundException,public org.hotswap.agent.javassist.CtField[] getDeclaredFields() ,public org.hotswap.agent.javassist.CtMethod getDeclaredMethod(java.lang.String) throws org.hotswap.agent.javassist.NotFoundException,public org.hotswap.agent.javassist.CtMethod getDeclaredMethod(java.lang.String, org.hotswap.agent.javassist.CtClass[]) throws org.hotswap.agent.javassist.NotFoundException,public org.hotswap.agent.javassist.CtMethod[] getDeclaredMethods() ,public org.hotswap.agent.javassist.CtMethod[] getDeclaredMethods(java.lang.String) throws org.hotswap.agent.javassist.NotFoundException,public org.hotswap.agent.javassist.CtClass getDeclaringClass() throws org.hotswap.agent.javassist.NotFoundException,public org.hotswap.agent.javassist.CtBehavior getEnclosingBehavior() throws org.hotswap.agent.javassist.NotFoundException,public org.hotswap.agent.javassist.CtField getField(java.lang.String, java.lang.String) throws org.hotswap.agent.javassist.NotFoundException,public org.hotswap.agent.javassist.CtField[] getFields() ,public java.lang.String getGenericSignature() ,public org.hotswap.agent.javassist.CtClass[] getInterfaces() throws org.hotswap.agent.javassist.NotFoundException,public org.hotswap.agent.javassist.CtMethod getMethod(java.lang.String, java.lang.String) throws org.hotswap.agent.javassist.NotFoundException,public org.hotswap.agent.javassist.CtMethod[] getMethods() ,public int getModifiers() ,public org.hotswap.agent.javassist.CtClass[] getNestedClasses() throws org.hotswap.agent.javassist.NotFoundException,public org.hotswap.agent.javassist.CtClass getSuperclass() throws org.hotswap.agent.javassist.NotFoundException,public java.lang.String getSuperclassName() throws org.hotswap.agent.javassist.NotFoundException,public java.net.URL getURL() throws org.hotswap.agent.javassist.NotFoundException,public boolean hasAnnotation(java.lang.String) ,public void instrument(org.hotswap.agent.javassist.CodeConverter) throws org.hotswap.agent.javassist.CannotCompileException,public void instrument(org.hotswap.agent.javassist.expr.ExprEditor) throws org.hotswap.agent.javassist.CannotCompileException,public boolean isAnnotation() ,public boolean isEnum() ,public boolean isFrozen() ,public boolean isInnerClass() throws org.hotswap.agent.javassist.NotFoundException,public boolean isInterface() ,public boolean isModified() ,public org.hotswap.agent.javassist.CtConstructor makeClassInitializer() throws org.hotswap.agent.javassist.CannotCompileException,public org.hotswap.agent.javassist.CtClass makeNestedClass(java.lang.String, boolean) ,public java.lang.String makeUniqueName(java.lang.String) ,public void prune() ,public void rebuildClassFile() ,public void removeConstructor(org.hotswap.agent.javassist.CtConstructor) throws org.hotswap.agent.javassist.NotFoundException,public void removeField(org.hotswap.agent.javassist.CtField) throws org.hotswap.agent.javassist.NotFoundException,public void removeMethod(org.hotswap.agent.javassist.CtMethod) throws org.hotswap.agent.javassist.NotFoundException,public void replaceClassName(org.hotswap.agent.javassist.ClassMap) throws java.lang.RuntimeException,public void replaceClassName(java.lang.String, java.lang.String) throws java.lang.RuntimeException,public void setAttribute(java.lang.String, byte[]) ,public void setGenericSignature(java.lang.String) ,public void setInterfaces(org.hotswap.agent.javassist.CtClass[]) ,public void setModifiers(int) ,public void setName(java.lang.String) throws java.lang.RuntimeException,public void setSuperclass(org.hotswap.agent.javassist.CtClass) throws org.hotswap.agent.javassist.CannotCompileException,public boolean stopPruning(boolean) ,public boolean subclassOf(org.hotswap.agent.javassist.CtClass) ,public boolean subtypeOf(org.hotswap.agent.javassist.CtClass) throws org.hotswap.agent.javassist.NotFoundException,public void toBytecode(java.io.DataOutputStream) throws org.hotswap.agent.javassist.CannotCompileException, java.io.IOException<variables>private static final int GET_THRESHOLD,private org.hotswap.agent.javassist.compiler.AccessorMaker accessors,org.hotswap.agent.javassist.ClassPool classPool,org.hotswap.agent.javassist.bytecode.ClassFile classfile,private boolean doPruning,private org.hotswap.agent.javassist.FieldInitLink fieldInitializers,boolean gcConstPool,private int getCount,private Map<org.hotswap.agent.javassist.CtMethod,java.lang.String> hiddenMethods,private Reference<org.hotswap.agent.javassist.CtMember.Cache> memberCache,byte[] rawClassfile,private int uniqueNumberSeed,boolean wasChanged,private boolean wasFrozen,boolean wasPruned
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/CtNewWrappedConstructor.java
CtNewWrappedConstructor
wrapped
class CtNewWrappedConstructor extends CtNewWrappedMethod { private static final int PASS_NONE = CtNewConstructor.PASS_NONE; // private static final int PASS_ARRAY = CtNewConstructor.PASS_ARRAY; private static final int PASS_PARAMS = CtNewConstructor.PASS_PARAMS; public static CtConstructor wrapped(CtClass[] parameterTypes, CtClass[] exceptionTypes, int howToCallSuper, CtMethod body, ConstParameter constParam, CtClass declaring) throws CannotCompileException {<FILL_FUNCTION_BODY>} protected static Bytecode makeBody(CtClass declaring, ClassFile classfile, int howToCallSuper, CtMethod wrappedBody, CtClass[] parameters, ConstParameter cparam) throws CannotCompileException { int stacksize, stacksize2; int superclazz = classfile.getSuperclassId(); Bytecode code = new Bytecode(classfile.getConstPool(), 0, 0); code.setMaxLocals(false, parameters, 0); code.addAload(0); if (howToCallSuper == PASS_NONE) { stacksize = 1; code.addInvokespecial(superclazz, "<init>", "()V"); } else if (howToCallSuper == PASS_PARAMS) { stacksize = code.addLoadParameters(parameters, 1) + 1; code.addInvokespecial(superclazz, "<init>", Descriptor.ofConstructor(parameters)); } else { stacksize = compileParameterList(code, parameters, 1); String desc; if (cparam == null) { stacksize2 = 2; desc = ConstParameter.defaultConstDescriptor(); } else { stacksize2 = cparam.compile(code) + 2; desc = cparam.constDescriptor(); } if (stacksize < stacksize2) stacksize = stacksize2; code.addInvokespecial(superclazz, "<init>", desc); } if (wrappedBody == null) code.add(Bytecode.RETURN); else { stacksize2 = makeBody0(declaring, classfile, wrappedBody, false, parameters, CtClass.voidType, cparam, code); if (stacksize < stacksize2) stacksize = stacksize2; } code.setMaxStack(stacksize); return code; } }
try { CtConstructor cons = new CtConstructor(parameterTypes, declaring); cons.setExceptionTypes(exceptionTypes); Bytecode code = makeBody(declaring, declaring.getClassFile2(), howToCallSuper, body, parameterTypes, constParam); cons.getMethodInfo2().setCodeAttribute(code.toCodeAttribute()); // a stack map table is not needed. return cons; } catch (NotFoundException e) { throw new CannotCompileException(e); }
659
134
793
<methods>public static org.hotswap.agent.javassist.CtMethod wrapped(org.hotswap.agent.javassist.CtClass, java.lang.String, org.hotswap.agent.javassist.CtClass[], org.hotswap.agent.javassist.CtClass[], org.hotswap.agent.javassist.CtMethod, org.hotswap.agent.javassist.CtMethod.ConstParameter, org.hotswap.agent.javassist.CtClass) throws org.hotswap.agent.javassist.CannotCompileException<variables>private static final java.lang.String addedWrappedMethod
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/CtNewWrappedMethod.java
CtNewWrappedMethod
addBodyMethod
class CtNewWrappedMethod { private static final String addedWrappedMethod = "_added_m$"; public static CtMethod wrapped(CtClass returnType, String mname, CtClass[] parameterTypes, CtClass[] exceptionTypes, CtMethod body, ConstParameter constParam, CtClass declaring) throws CannotCompileException { CtMethod mt = new CtMethod(returnType, mname, parameterTypes, declaring); mt.setModifiers(body.getModifiers()); try { mt.setExceptionTypes(exceptionTypes); } catch (NotFoundException e) { throw new CannotCompileException(e); } Bytecode code = makeBody(declaring, declaring.getClassFile2(), body, parameterTypes, returnType, constParam); MethodInfo minfo = mt.getMethodInfo2(); minfo.setCodeAttribute(code.toCodeAttribute()); // a stack map has been already created. return mt; } static Bytecode makeBody(CtClass clazz, ClassFile classfile, CtMethod wrappedBody, CtClass[] parameters, CtClass returnType, ConstParameter cparam) throws CannotCompileException { boolean isStatic = Modifier.isStatic(wrappedBody.getModifiers()); Bytecode code = new Bytecode(classfile.getConstPool(), 0, 0); int stacksize = makeBody0(clazz, classfile, wrappedBody, isStatic, parameters, returnType, cparam, code); code.setMaxStack(stacksize); code.setMaxLocals(isStatic, parameters, 0); return code; } /* The generated method body does not need a stack map table * because it does not contain a branch instruction. */ protected static int makeBody0(CtClass clazz, ClassFile classfile, CtMethod wrappedBody, boolean isStatic, CtClass[] parameters, CtClass returnType, ConstParameter cparam, Bytecode code) throws CannotCompileException { if (!(clazz instanceof CtClassType)) throw new CannotCompileException("bad declaring class" + clazz.getName()); if (!isStatic) code.addAload(0); int stacksize = compileParameterList(code, parameters, (isStatic ? 0 : 1)); int stacksize2; String desc; if (cparam == null) { stacksize2 = 0; desc = ConstParameter.defaultDescriptor(); } else { stacksize2 = cparam.compile(code); desc = cparam.descriptor(); } checkSignature(wrappedBody, desc); String bodyname; try { bodyname = addBodyMethod((CtClassType)clazz, classfile, wrappedBody); /* if an exception is thrown below, the method added above * should be removed. (future work :<) */ } catch (BadBytecode e) { throw new CannotCompileException(e); } if (isStatic) code.addInvokestatic(Bytecode.THIS, bodyname, desc); else code.addInvokespecial(Bytecode.THIS, bodyname, desc); compileReturn(code, returnType); // consumes 2 stack entries if (stacksize < stacksize2 + 2) stacksize = stacksize2 + 2; return stacksize; } private static void checkSignature(CtMethod wrappedBody, String descriptor) throws CannotCompileException { if (!descriptor.equals(wrappedBody.getMethodInfo2().getDescriptor())) throw new CannotCompileException( "wrapped method with a bad signature: " + wrappedBody.getDeclaringClass().getName() + '.' + wrappedBody.getName()); } private static String addBodyMethod(CtClassType clazz, ClassFile classfile, CtMethod src) throws BadBytecode, CannotCompileException {<FILL_FUNCTION_BODY>} /* compileParameterList() returns the stack size used * by the produced code. * * @param regno the index of the local variable in which * the first argument is received. * (0: static method, 1: regular method.) */ static int compileParameterList(Bytecode code, CtClass[] params, int regno) { return JvstCodeGen.compileParameterList(code, params, regno); } /* * The produced codes cosume 1 or 2 stack entries. */ private static void compileReturn(Bytecode code, CtClass type) { if (type.isPrimitive()) { CtPrimitiveType pt = (CtPrimitiveType)type; if (pt != CtClass.voidType) { String wrapper = pt.getWrapperName(); code.addCheckcast(wrapper); code.addInvokevirtual(wrapper, pt.getGetMethodName(), pt.getGetMethodDescriptor()); } code.addOpcode(pt.getReturnOp()); } else { code.addCheckcast(type); code.addOpcode(Bytecode.ARETURN); } } }
Map<CtMethod,String> bodies = clazz.getHiddenMethods(); String bodyname = bodies.get(src); if (bodyname == null) { do { bodyname = addedWrappedMethod + clazz.getUniqueNumber(); } while (classfile.getMethod(bodyname) != null); ClassMap map = new ClassMap(); map.put(src.getDeclaringClass().getName(), clazz.getName()); MethodInfo body = new MethodInfo(classfile.getConstPool(), bodyname, src.getMethodInfo2(), map); int acc = body.getAccessFlags(); body.setAccessFlags(AccessFlag.setPrivate(acc)); body.addAttribute(new SyntheticAttribute(classfile.getConstPool())); // a stack map is copied. rebuilding it is not needed. classfile.addMethod(body); bodies.put(src, bodyname); CtMember.Cache cache = clazz.hasMemberCache(); if (cache != null) cache.addMethod(new CtMethod(body, clazz)); } return bodyname;
1,370
285
1,655
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/LoaderClassPath.java
LoaderClassPath
find
class LoaderClassPath implements ClassPath { private Reference<ClassLoader> clref; /** * Creates a search path representing a class loader. */ public LoaderClassPath(ClassLoader cl) { clref = new WeakReference<ClassLoader>(cl); } @Override public String toString() { return clref.get() == null ? "<null>" : clref.get().toString(); } /** * Obtains a class file from the class loader. * This method calls <code>getResourceAsStream(String)</code> * on the class loader. */ @Override public InputStream openClassfile(String classname) throws NotFoundException { String cname = classname.replace('.', '/') + ".class"; ClassLoader cl = clref.get(); if (cl == null) return null; // not found InputStream is = cl.getResourceAsStream(cname); return is; } /** * Obtains the URL of the specified class file. * This method calls <code>getResource(String)</code> * on the class loader. * * @return null if the class file could not be found. */ @Override public URL find(String classname) {<FILL_FUNCTION_BODY>} }
String cname = classname.replace('.', '/') + ".class"; ClassLoader cl = clref.get(); if (cl == null) return null; // not found URL url = cl.getResource(cname); return url;
349
67
416
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/Modifier.java
Modifier
isPackage
class Modifier { public static final int PUBLIC = AccessFlag.PUBLIC; public static final int PRIVATE = AccessFlag.PRIVATE; public static final int PROTECTED = AccessFlag.PROTECTED; public static final int STATIC = AccessFlag.STATIC; public static final int FINAL = AccessFlag.FINAL; public static final int SYNCHRONIZED = AccessFlag.SYNCHRONIZED; public static final int VOLATILE = AccessFlag.VOLATILE; public static final int VARARGS = AccessFlag.VARARGS; public static final int TRANSIENT = AccessFlag.TRANSIENT; public static final int NATIVE = AccessFlag.NATIVE; public static final int INTERFACE = AccessFlag.INTERFACE; public static final int ABSTRACT = AccessFlag.ABSTRACT; public static final int STRICT = AccessFlag.STRICT; public static final int ANNOTATION = AccessFlag.ANNOTATION; public static final int ENUM = AccessFlag.ENUM; /** * Returns true if the modifiers include the <code>public</code> * modifier. */ public static boolean isPublic(int mod) { return (mod & PUBLIC) != 0; } /** * Returns true if the modifiers include the <code>private</code> * modifier. */ public static boolean isPrivate(int mod) { return (mod & PRIVATE) != 0; } /** * Returns true if the modifiers include the <code>protected</code> * modifier. */ public static boolean isProtected(int mod) { return (mod & PROTECTED) != 0; } /** * Returns true if the modifiers do not include either * <code>public</code>, <code>protected</code>, or <code>private</code>. */ public static boolean isPackage(int mod) {<FILL_FUNCTION_BODY>} /** * Returns true if the modifiers include the <code>static</code> * modifier. */ public static boolean isStatic(int mod) { return (mod & STATIC) != 0; } /** * Returns true if the modifiers include the <code>final</code> * modifier. */ public static boolean isFinal(int mod) { return (mod & FINAL) != 0; } /** * Returns true if the modifiers include the <code>synchronized</code> * modifier. */ public static boolean isSynchronized(int mod) { return (mod & SYNCHRONIZED) != 0; } /** * Returns true if the modifiers include the <code>volatile</code> * modifier. */ public static boolean isVolatile(int mod) { return (mod & VOLATILE) != 0; } /** * Returns true if the modifiers include the <code>transient</code> * modifier. */ public static boolean isTransient(int mod) { return (mod & TRANSIENT) != 0; } /** * Returns true if the modifiers include the <code>native</code> * modifier. */ public static boolean isNative(int mod) { return (mod & NATIVE) != 0; } /** * Returns true if the modifiers include the <code>interface</code> * modifier. */ public static boolean isInterface(int mod) { return (mod & INTERFACE) != 0; } /** * Returns true if the modifiers include the <code>annotation</code> * modifier. * * @since 3.2 */ public static boolean isAnnotation(int mod) { return (mod & ANNOTATION) != 0; } /** * Returns true if the modifiers include the <code>enum</code> * modifier. * * @since 3.2 */ public static boolean isEnum(int mod) { return (mod & ENUM) != 0; } /** * Returns true if the modifiers include the <code>abstract</code> * modifier. */ public static boolean isAbstract(int mod) { return (mod & ABSTRACT) != 0; } /** * Returns true if the modifiers include the <code>strictfp</code> * modifier. */ public static boolean isStrict(int mod) { return (mod & STRICT) != 0; } /** * Returns true if the modifiers include the <code>varargs</code> * (variable number of arguments) modifier. */ public static boolean isVarArgs(int mod) { return (mod & VARARGS) != 0; } /** * Truns the public bit on. The protected and private bits are * cleared. */ public static int setPublic(int mod) { return (mod & ~(PRIVATE | PROTECTED)) | PUBLIC; } /** * Truns the protected bit on. The protected and public bits are * cleared. */ public static int setProtected(int mod) { return (mod & ~(PRIVATE | PUBLIC)) | PROTECTED; } /** * Truns the private bit on. The protected and private bits are * cleared. */ public static int setPrivate(int mod) { return (mod & ~(PROTECTED | PUBLIC)) | PRIVATE; } /** * Clears the public, protected, and private bits. */ public static int setPackage(int mod) { return (mod & ~(PROTECTED | PUBLIC | PRIVATE)); } /** * Clears a specified bit in <code>mod</code>. */ public static int clear(int mod, int clearBit) { return mod & ~clearBit; } /** * Return a string describing the access modifier flags in * the specified modifier. * * @param mod modifier flags. */ public static String toString(int mod) { return java.lang.reflect.Modifier.toString(mod); } }
return (mod & (PUBLIC | PRIVATE | PROTECTED)) == 0;
1,695
26
1,721
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/SerialVersionUID.java
SerialVersionUID
calculateDefault
class SerialVersionUID { /** * Adds serialVersionUID if one does not already exist. Call this before * modifying a class to maintain serialization compatability. */ public static void setSerialVersionUID(CtClass clazz) throws CannotCompileException, NotFoundException { // check for pre-existing field. try { clazz.getDeclaredField("serialVersionUID"); return; } catch (NotFoundException e) {} // check if the class is serializable. if (!isSerializable(clazz)) return; // add field with default value. CtField field = new CtField(CtClass.longType, "serialVersionUID", clazz); field.setModifiers(Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL); clazz.addField(field, calculateDefault(clazz) + "L"); } /** * Does the class implement Serializable? */ private static boolean isSerializable(CtClass clazz) throws NotFoundException { ClassPool pool = clazz.getClassPool(); return clazz.subtypeOf(pool.get("java.io.Serializable")); } /** * Calculate default value. See Java Serialization Specification, Stream * Unique Identifiers. * * @since 3.20 */ public static long calculateDefault(CtClass clazz) throws CannotCompileException {<FILL_FUNCTION_BODY>} private static String javaName(CtClass clazz) { return Descriptor.toJavaName(Descriptor.toJvmName(clazz)); } private static String javaName(String name) { return Descriptor.toJavaName(Descriptor.toJvmName(name)); } }
try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(bout); ClassFile classFile = clazz.getClassFile(); // class name. String javaName = javaName(clazz); out.writeUTF(javaName); CtMethod[] methods = clazz.getDeclaredMethods(); // class modifiers. int classMods = clazz.getModifiers(); if ((classMods & Modifier.INTERFACE) != 0) if (methods.length > 0) classMods = classMods | Modifier.ABSTRACT; else classMods = classMods & ~Modifier.ABSTRACT; out.writeInt(classMods); // interfaces. String[] interfaces = classFile.getInterfaces(); for (int i = 0; i < interfaces.length; i++) interfaces[i] = javaName(interfaces[i]); Arrays.sort(interfaces); for (int i = 0; i < interfaces.length; i++) out.writeUTF(interfaces[i]); // fields. CtField[] fields = clazz.getDeclaredFields(); Arrays.sort(fields, new Comparator<CtField>() { @Override public int compare(CtField field1, CtField field2) { return field1.getName().compareTo(field2.getName()); } }); for (int i = 0; i < fields.length; i++) { CtField field = fields[i]; int mods = field.getModifiers(); if (((mods & Modifier.PRIVATE) == 0) || ((mods & (Modifier.STATIC | Modifier.TRANSIENT)) == 0)) { out.writeUTF(field.getName()); out.writeInt(mods); out.writeUTF(field.getFieldInfo2().getDescriptor()); } } // static initializer. if (classFile.getStaticInitializer() != null) { out.writeUTF("<clinit>"); out.writeInt(Modifier.STATIC); out.writeUTF("()V"); } // constructors. CtConstructor[] constructors = clazz.getDeclaredConstructors(); Arrays.sort(constructors, new Comparator<CtConstructor>() { @Override public int compare(CtConstructor c1, CtConstructor c2) { return c1.getMethodInfo2().getDescriptor().compareTo( c2.getMethodInfo2().getDescriptor()); } }); for (int i = 0; i < constructors.length; i++) { CtConstructor constructor = constructors[i]; int mods = constructor.getModifiers(); if ((mods & Modifier.PRIVATE) == 0) { out.writeUTF("<init>"); out.writeInt(mods); out.writeUTF(constructor.getMethodInfo2() .getDescriptor().replace('/', '.')); } } // methods. Arrays.sort(methods, new Comparator<CtMethod>() { @Override public int compare(CtMethod m1, CtMethod m2) { int value = m1.getName().compareTo(m2.getName()); if (value == 0) value = m1.getMethodInfo2().getDescriptor() .compareTo(m2.getMethodInfo2().getDescriptor()); return value; } }); for (int i = 0; i < methods.length; i++) { CtMethod method = methods[i]; int mods = method.getModifiers() & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC | Modifier.FINAL | Modifier.SYNCHRONIZED | Modifier.NATIVE | Modifier.ABSTRACT | Modifier.STRICT); if ((mods & Modifier.PRIVATE) == 0) { out.writeUTF(method.getName()); out.writeInt(mods); out.writeUTF(method.getMethodInfo2() .getDescriptor().replace('/', '.')); } } // calculate hash. out.flush(); MessageDigest digest = MessageDigest.getInstance("SHA"); byte[] digested = digest.digest(bout.toByteArray()); long hash = 0; for (int i = Math.min(digested.length, 8) - 1; i >= 0; i--) hash = (hash << 8) | (digested[i] & 0xFF); return hash; } catch (IOException e) { throw new CannotCompileException(e); } catch (NoSuchAlgorithmException e) { throw new CannotCompileException(e); }
476
1,264
1,740
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/URLClassPath.java
URLClassPath
fetchClass
class URLClassPath implements ClassPath { protected String hostname; protected int port; protected String directory; protected String packageName; /** * Creates a search path specified with URL (http). * * <p>This search path is used only if a requested * class name starts with the name specified by <code>packageName</code>. * If <code>packageName</code> is "org.javassist." and a requested class is * "org.javassist.test.Main", then the given URL is used for loading that class. * The <code>URLClassPath</code> obtains a class file from: * * <pre>http://www.javassist.org:80/java/classes/org/javassist/test/Main.class * </pre> * * <p>Here, we assume that <code>host</code> is "www.javassist.org", * <code>port</code> is 80, and <code>directory</code> is "/java/classes/". * * <p>If <code>packageName</code> is <code>null</code>, the URL is used * for loading any class. * * @param host host name * @param port port number * @param directory directory name ending with "/". * It can be "/" (root directory). * It must start with "/". * @param packageName package name. It must end with "." (dot). */ public URLClassPath(String host, int port, String directory, String packageName) { hostname = host; this.port = port; this.directory = directory; this.packageName = packageName; } @Override public String toString() { return hostname + ":" + port + directory; } /** * Opens a class file with http. * * @return null if the class file could not be found. */ @Override public InputStream openClassfile(String classname) { try { URLConnection con = openClassfile0(classname); if (con != null) return con.getInputStream(); } catch (IOException e) {} return null; // not found } private URLConnection openClassfile0(String classname) throws IOException { if (packageName == null || classname.startsWith(packageName)) { String jarname = directory + classname.replace('.', '/') + ".class"; return fetchClass0(hostname, port, jarname); } return null; // not found } /** * Returns the URL. * * @return null if the class file could not be obtained. */ @Override public URL find(String classname) { try { URLConnection con = openClassfile0(classname); InputStream is = con.getInputStream(); if (is != null) { is.close(); return con.getURL(); } } catch (IOException e) {} return null; } /** * Reads a class file on an http server. * * @param host host name * @param port port number * @param directory directory name ending with "/". * It can be "/" (root directory). * It must start with "/". * @param classname fully-qualified class name */ public static byte[] fetchClass(String host, int port, String directory, String classname) throws IOException {<FILL_FUNCTION_BODY>} private static URLConnection fetchClass0(String host, int port, String filename) throws IOException { URL url; try { url = new URL("http", host, port, filename); } catch (MalformedURLException e) { // should never reache here. throw new IOException("invalid URL?"); } URLConnection con = url.openConnection(); con.connect(); return con; } }
byte[] b; URLConnection con = fetchClass0(host, port, directory + classname.replace('.', '/') + ".class"); int size = con.getContentLength(); InputStream s = con.getInputStream(); try { if (size <= 0) b = ClassPoolTail.readStream(s); else { b = new byte[size]; int len = 0; do { int n = s.read(b, len, size - len); if (n < 0) throw new IOException("the stream was closed: " + classname); len += n; } while (len < size); } } finally { s.close(); } return b;
1,060
196
1,256
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/AccessFlag.java
AccessFlag
isPackage
class AccessFlag { public static final int PUBLIC = 0x0001; public static final int PRIVATE = 0x0002; public static final int PROTECTED = 0x0004; public static final int STATIC = 0x0008; public static final int FINAL = 0x0010; public static final int SYNCHRONIZED = 0x0020; public static final int VOLATILE = 0x0040; public static final int BRIDGE = 0x0040; // for method_info public static final int TRANSIENT = 0x0080; public static final int VARARGS = 0x0080; // for method_info public static final int NATIVE = 0x0100; public static final int INTERFACE = 0x0200; public static final int ABSTRACT = 0x0400; public static final int STRICT = 0x0800; public static final int SYNTHETIC = 0x1000; public static final int ANNOTATION = 0x2000; public static final int ENUM = 0x4000; public static final int MANDATED = 0x8000; public static final int SUPER = 0x0020; public static final int MODULE = 0x8000; // Note: 0x0020 is assigned to both ACC_SUPER and ACC_SYNCHRONIZED // although java.lang.reflect.Modifier does not recognize ACC_SUPER. /** * Turns the public bit on. The protected and private bits are * cleared. */ public static int setPublic(int accflags) { return (accflags & ~(PRIVATE | PROTECTED)) | PUBLIC; } /** * Turns the protected bit on. The protected and public bits are * cleared. */ public static int setProtected(int accflags) { return (accflags & ~(PRIVATE | PUBLIC)) | PROTECTED; } /** * Truns the private bit on. The protected and private bits are * cleared. */ public static int setPrivate(int accflags) { return (accflags & ~(PROTECTED | PUBLIC)) | PRIVATE; } /** * Clears the public, protected, and private bits. */ public static int setPackage(int accflags) { return (accflags & ~(PROTECTED | PUBLIC | PRIVATE)); } /** * Returns true if the access flags include the public bit. */ public static boolean isPublic(int accflags) { return (accflags & PUBLIC) != 0; } /** * Returns true if the access flags include the protected bit. */ public static boolean isProtected(int accflags) { return (accflags & PROTECTED) != 0; } /** * Returns true if the access flags include the private bit. */ public static boolean isPrivate(int accflags) { return (accflags & PRIVATE) != 0; } /** * Returns true if the access flags include neither public, protected, * or private. */ public static boolean isPackage(int accflags) {<FILL_FUNCTION_BODY>} /** * Clears a specified bit in <code>accflags</code>. */ public static int clear(int accflags, int clearBit) { return accflags & ~clearBit; } /** * Converts a javassist.Modifier into * a javassist.bytecode.AccessFlag. * * @param modifier javassist.Modifier */ public static int of(int modifier) { return modifier; } /** * Converts a javassist.bytecode.AccessFlag * into a javassist.Modifier. * * @param accflags javassist.bytecode.Accessflag */ public static int toModifier(int accflags) { return accflags; } }
return (accflags & (PROTECTED | PUBLIC | PRIVATE)) == 0;
1,116
26
1,142
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/AnnotationDefaultAttribute.java
AnnotationDefaultAttribute
getDefaultValue
class AnnotationDefaultAttribute extends AttributeInfo { /** * The name of the <code>AnnotationDefault</code> attribute. */ public static final String tag = "AnnotationDefault"; /** * Constructs an <code>AnnotationDefault_attribute</code>. * * @param cp constant pool * @param info the contents of this attribute. It does not * include <code>attribute_name_index</code> or * <code>attribute_length</code>. */ public AnnotationDefaultAttribute(ConstPool cp, byte[] info) { super(cp, tag, info); } /** * Constructs an empty <code>AnnotationDefault_attribute</code>. * The default value can be set by <code>setDefaultValue()</code>. * * @param cp constant pool * @see #setDefaultValue(javassist.bytecode.annotation.MemberValue) */ public AnnotationDefaultAttribute(ConstPool cp) { this(cp, new byte[] { 0, 0 }); } /** * @param n the attribute name. */ AnnotationDefaultAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Copies this attribute and returns a new copy. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { AnnotationsAttribute.Copier copier = new AnnotationsAttribute.Copier(info, constPool, newCp, classnames); try { copier.memberValue(0); return new AnnotationDefaultAttribute(newCp, copier.close()); } catch (Exception e) { throw new RuntimeException(e.toString()); } } /** * Obtains the default value represented by this attribute. */ public MemberValue getDefaultValue() {<FILL_FUNCTION_BODY>} /** * Changes the default value represented by this attribute. * * @param value the new value. * @see javassist.bytecode.annotation.Annotation#createMemberValue(ConstPool, CtClass) */ public void setDefaultValue(MemberValue value) { ByteArrayOutputStream output = new ByteArrayOutputStream(); AnnotationsWriter writer = new AnnotationsWriter(output, constPool); try { value.write(writer); writer.close(); } catch (IOException e) { throw new RuntimeException(e); // should never reach here. } set(output.toByteArray()); } /** * Returns a string representation of this object. */ @Override public String toString() { return getDefaultValue().toString(); } }
try { return new AnnotationsAttribute.Parser(info, constPool) .parseMemberValue(); } catch (Exception e) { throw new RuntimeException(e.toString()); }
732
54
786
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/BootstrapMethodsAttribute.java
BootstrapMethod
getMethods
class BootstrapMethod { /** * Constructs an element of <code>bootstrap_methods</code>. * * @param method <code>bootstrap_method_ref</code>. * @param args <code>bootstrap_arguments</code>. */ public BootstrapMethod(int method, int[] args) { methodRef = method; arguments = args; } /** * <code>bootstrap_method_ref</code>. * The value at this index must be a <code>CONSTANT_MethodHandle_info</code>. */ public int methodRef; /** * <code>bootstrap_arguments</code>. */ public int[] arguments; } BootstrapMethodsAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Constructs a BootstrapMethods attribute. * * @param cp a constant pool table. * @param methods the contents. */ public BootstrapMethodsAttribute(ConstPool cp, BootstrapMethod[] methods) { super(cp, tag); int size = 2; for (int i = 0; i < methods.length; i++) size += 4 + methods[i].arguments.length * 2; byte[] data = new byte[size]; ByteArray.write16bit(methods.length, data, 0); // num_bootstrap_methods int pos = 2; for (int i = 0; i < methods.length; i++) { ByteArray.write16bit(methods[i].methodRef, data, pos); ByteArray.write16bit(methods[i].arguments.length, data, pos + 2); int[] args = methods[i].arguments; pos += 4; for (int k = 0; k < args.length; k++) { ByteArray.write16bit(args[k], data, pos); pos += 2; } } set(data); } /** * Obtains <code>bootstrap_methods</code> in this attribute. * * @return an array of <code>BootstrapMethod</code>. Since it * is a fresh copy, modifying the returned array does not * affect the original contents of this attribute. */ public BootstrapMethod[] getMethods() {<FILL_FUNCTION_BODY>
byte[] data = this.get(); int num = ByteArray.readU16bit(data, 0); BootstrapMethod[] methods = new BootstrapMethod[num]; int pos = 2; for (int i = 0; i < num; i++) { int ref = ByteArray.readU16bit(data, pos); int len = ByteArray.readU16bit(data, pos + 2); int[] args = new int[len]; pos += 4; for (int k = 0; k < len; k++) { args[k] = ByteArray.readU16bit(data, pos); pos += 2; } methods[i] = new BootstrapMethod(ref, args); } return methods;
628
198
826
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ByteArray.java
ByteArray
readS16bit
class ByteArray { /** * Reads an unsigned 16bit integer at the index. */ public static int readU16bit(byte[] code, int index) { return ((code[index] & 0xff) << 8) | (code[index + 1] & 0xff); } /** * Reads a signed 16bit integer at the index. */ public static int readS16bit(byte[] code, int index) {<FILL_FUNCTION_BODY>} /** * Writes a 16bit integer at the index. */ public static void write16bit(int value, byte[] code, int index) { code[index] = (byte)(value >>> 8); code[index + 1] = (byte)value; } /** * Reads a 32bit integer at the index. */ public static int read32bit(byte[] code, int index) { return (code[index] << 24) | ((code[index + 1] & 0xff) << 16) | ((code[index + 2] & 0xff) << 8) | (code[index + 3] & 0xff); } /** * Writes a 32bit integer at the index. */ public static void write32bit(int value, byte[] code, int index) { code[index] = (byte)(value >>> 24); code[index + 1] = (byte)(value >>> 16); code[index + 2] = (byte)(value >>> 8); code[index + 3] = (byte)value; } /** * Copies a 32bit integer. * * @param src the source byte array. * @param isrc the index into the source byte array. * @param dest the destination byte array. * @param idest the index into the destination byte array. */ static void copy32bit(byte[] src, int isrc, byte[] dest, int idest) { dest[idest] = src[isrc]; dest[idest + 1] = src[isrc + 1]; dest[idest + 2] = src[isrc + 2]; dest[idest + 3] = src[isrc + 3]; } }
return (code[index] << 8) | (code[index + 1] & 0xff);
603
28
631
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ByteStream.java
ByteStream
enlarge
class ByteStream extends OutputStream { private byte[] buf; private int count; public ByteStream() { this(32); } public ByteStream(int size) { buf = new byte[size]; count = 0; } public int getPos() { return count; } public int size() { return count; } public void writeBlank(int len) { enlarge(len); count += len; } @Override public void write(byte[] data) { write(data, 0, data.length); } @Override public void write(byte[] data, int off, int len) { enlarge(len); System.arraycopy(data, off, buf, count, len); count += len; } @Override public void write(int b) { enlarge(1); int oldCount = count; buf[oldCount] = (byte)b; count = oldCount + 1; } public void writeShort(int s) { enlarge(2); int oldCount = count; buf[oldCount] = (byte)(s >>> 8); buf[oldCount + 1] = (byte)s; count = oldCount + 2; } public void writeInt(int i) { enlarge(4); int oldCount = count; buf[oldCount] = (byte)(i >>> 24); buf[oldCount + 1] = (byte)(i >>> 16); buf[oldCount + 2] = (byte)(i >>> 8); buf[oldCount + 3] = (byte)i; count = oldCount + 4; } public void writeLong(long i) { enlarge(8); int oldCount = count; buf[oldCount] = (byte)(i >>> 56); buf[oldCount + 1] = (byte)(i >>> 48); buf[oldCount + 2] = (byte)(i >>> 40); buf[oldCount + 3] = (byte)(i >>> 32); buf[oldCount + 4] = (byte)(i >>> 24); buf[oldCount + 5] = (byte)(i >>> 16); buf[oldCount + 6] = (byte)(i >>> 8); buf[oldCount + 7] = (byte)i; count = oldCount + 8; } public void writeFloat(float v) { writeInt(Float.floatToIntBits(v)); } public void writeDouble(double v) { writeLong(Double.doubleToLongBits(v)); } public void writeUTF(String s) { int sLen = s.length(); int pos = count; enlarge(sLen + 2); byte[] buffer = buf; buffer[pos++] = (byte)(sLen >>> 8); buffer[pos++] = (byte)sLen; for (int i = 0; i < sLen; ++i) { char c = s.charAt(i); if (0x01 <= c && c <= 0x7f) buffer[pos++] = (byte)c; else { writeUTF2(s, sLen, i); return; } } count = pos; } private void writeUTF2(String s, int sLen, int offset) { int size = sLen; for (int i = offset; i < sLen; i++) { int c = s.charAt(i); if (c > 0x7ff) size += 2; // 3 bytes code else if (c == 0 || c > 0x7f) ++size; // 2 bytes code } if (size > 65535) throw new RuntimeException( "encoded string too long: " + sLen + size + " bytes"); enlarge(size + 2); int pos = count; byte[] buffer = buf; buffer[pos] = (byte)(size >>> 8); buffer[pos + 1] = (byte)size; pos += 2 + offset; for (int j = offset; j < sLen; ++j) { int c = s.charAt(j); if (0x01 <= c && c <= 0x7f) buffer[pos++] = (byte) c; else if (c > 0x07ff) { buffer[pos] = (byte)(0xe0 | ((c >> 12) & 0x0f)); buffer[pos + 1] = (byte)(0x80 | ((c >> 6) & 0x3f)); buffer[pos + 2] = (byte)(0x80 | (c & 0x3f)); pos += 3; } else { buffer[pos] = (byte)(0xc0 | ((c >> 6) & 0x1f)); buffer[pos + 1] = (byte)(0x80 | (c & 0x3f)); pos += 2; } } count = pos; } public void write(int pos, int value) { buf[pos] = (byte)value; } public void writeShort(int pos, int value) { buf[pos] = (byte)(value >>> 8); buf[pos + 1] = (byte)value; } public void writeInt(int pos, int value) { buf[pos] = (byte)(value >>> 24); buf[pos + 1] = (byte)(value >>> 16); buf[pos + 2] = (byte)(value >>> 8); buf[pos + 3] = (byte)value; } public byte[] toByteArray() { byte[] buf2 = new byte[count]; System.arraycopy(buf, 0, buf2, 0, count); return buf2; } public void writeTo(OutputStream out) throws IOException { out.write(buf, 0, count); } public void enlarge(int delta) {<FILL_FUNCTION_BODY>} }
int newCount = count + delta; if (newCount > buf.length) { int newLen = buf.length << 1; byte[] newBuf = new byte[newLen > newCount ? newLen : newCount]; System.arraycopy(buf, 0, newBuf, 0, count); buf = newBuf; }
1,601
89
1,690
<methods>public void <init>() ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public static java.io.OutputStream nullOutputStream() ,public abstract void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ClassFilePrinter.java
ClassFilePrinter
print
class ClassFilePrinter { /** * Prints the contents of a class file to the standard output stream. */ public static void print(ClassFile cf) { print(cf, new PrintWriter(System.out, true)); } /** * Prints the contents of a class file. */ public static void print(ClassFile cf, PrintWriter out) {<FILL_FUNCTION_BODY>} static void printAttributes(List<AttributeInfo> list, PrintWriter out, char kind) { if (list == null) return; for (AttributeInfo ai:list) { if (ai instanceof CodeAttribute) { CodeAttribute ca = (CodeAttribute)ai; out.println("attribute: " + ai.getName() + ": " + ai.getClass().getName()); out.println("max stack " + ca.getMaxStack() + ", max locals " + ca.getMaxLocals() + ", " + ca.getExceptionTable().size() + " catch blocks"); out.println("<code attribute begin>"); printAttributes(ca.getAttributes(), out, kind); out.println("<code attribute end>"); } else if (ai instanceof AnnotationsAttribute) { out.println("annnotation: " + ai.toString()); } else if (ai instanceof ParameterAnnotationsAttribute) { out.println("parameter annnotations: " + ai.toString()); } else if (ai instanceof StackMapTable) { out.println("<stack map table begin>"); StackMapTable.Printer.print((StackMapTable)ai, out); out.println("<stack map table end>"); } else if (ai instanceof StackMap) { out.println("<stack map begin>"); ((StackMap)ai).print(out); out.println("<stack map end>"); } else if (ai instanceof SignatureAttribute) { SignatureAttribute sa = (SignatureAttribute)ai; String sig = sa.getSignature(); out.println("signature: " + sig); try { String s; if (kind == 'c') s = SignatureAttribute.toClassSignature(sig).toString(); else if (kind == 'm') s = SignatureAttribute.toMethodSignature(sig).toString(); else s = SignatureAttribute.toFieldSignature(sig).toString(); out.println(" " + s); } catch (BadBytecode e) { out.println(" syntax error"); } } else out.println("attribute: " + ai.getName() + " (" + ai.get().length + " byte): " + ai.getClass().getName()); } } }
/* 0x0020 (SYNCHRONIZED) means ACC_SUPER if the modifiers * are of a class. */ int mod = AccessFlag.toModifier(cf.getAccessFlags() & ~AccessFlag.SYNCHRONIZED); out.println("major: " + cf.major + ", minor: " + cf.minor + " modifiers: " + Integer.toHexString(cf.getAccessFlags())); out.println(Modifier.toString(mod) + " class " + cf.getName() + " extends " + cf.getSuperclass()); String[] infs = cf.getInterfaces(); if (infs != null && infs.length > 0) { out.print(" implements "); out.print(infs[0]); for (int i = 1; i < infs.length; ++i) out.print(", " + infs[i]); out.println(); } out.println(); List<FieldInfo> fields = cf.getFields(); for (FieldInfo finfo:fields) { int acc = finfo.getAccessFlags(); out.println(Modifier.toString(AccessFlag.toModifier(acc)) + " " + finfo.getName() + "\t" + finfo.getDescriptor()); printAttributes(finfo.getAttributes(), out, 'f'); } out.println(); List<MethodInfo> methods = cf.getMethods(); for (MethodInfo minfo:methods) { int acc = minfo.getAccessFlags(); out.println(Modifier.toString(AccessFlag.toModifier(acc)) + " " + minfo.getName() + "\t" + minfo.getDescriptor()); printAttributes(minfo.getAttributes(), out, 'm'); out.println(); } out.println(); printAttributes(cf.getAttributes(), out, 'c');
697
498
1,195
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ClassFileWriter.java
MethodWriter
writeThrows
class MethodWriter { protected ByteStream output; protected ConstPoolWriter constPool; private int methodCount; protected int codeIndex; protected int throwsIndex; protected int stackIndex; private int startPos; private boolean isAbstract; private int catchPos; private int catchCount; MethodWriter(ConstPoolWriter cp) { output = new ByteStream(256); constPool = cp; methodCount = 0; codeIndex = 0; throwsIndex = 0; stackIndex = 0; } /** * Starts Adding a new method. * * @param accessFlags access flags. * @param name the method name. * @param descriptor the method signature. * @param exceptions throws clause. It may be null. * The class names must be the JVM-internal * representations like <code>java/lang/Exception</code>. * @param aw attributes to the <code>Method_info</code>. */ public void begin(int accessFlags, String name, String descriptor, String[] exceptions, AttributeWriter aw) { int nameIndex = constPool.addUtf8Info(name); int descIndex = constPool.addUtf8Info(descriptor); int[] intfs; if (exceptions == null) intfs = null; else intfs = constPool.addClassInfo(exceptions); begin(accessFlags, nameIndex, descIndex, intfs, aw); } /** * Starts adding a new method. * * @param accessFlags access flags. * @param name the method name. an index indicating its <code>CONSTANT_Utf8_info</code>. * @param descriptor the field type. an index indicating its <code>CONSTANT_Utf8_info</code>. * @param exceptions throws clause. indexes indicating <code>CONSTANT_Class_info</code>s. * It may be null. * @param aw attributes to the <code>Method_info</code>. */ public void begin(int accessFlags, int name, int descriptor, int[] exceptions, AttributeWriter aw) { ++methodCount; output.writeShort(accessFlags); output.writeShort(name); output.writeShort(descriptor); isAbstract = (accessFlags & AccessFlag.ABSTRACT) != 0; int attrCount = isAbstract ? 0 : 1; if (exceptions != null) ++attrCount; writeAttribute(output, aw, attrCount); if (exceptions != null) writeThrows(exceptions); if (!isAbstract) { if (codeIndex == 0) codeIndex = constPool.addUtf8Info(CodeAttribute.tag); startPos = output.getPos(); output.writeShort(codeIndex); output.writeBlank(12); // attribute_length, maxStack, maxLocals, code_lenth } catchPos = -1; catchCount = 0; } private void writeThrows(int[] exceptions) {<FILL_FUNCTION_BODY>} /** * Appends an 8bit value of bytecode. * * @see Opcode */ public void add(int b) { output.write(b); } /** * Appends a 16bit value of bytecode. */ public void add16(int b) { output.writeShort(b); } /** * Appends a 32bit value of bytecode. */ public void add32(int b) { output.writeInt(b); } /** * Appends a invokevirtual, inovkespecial, or invokestatic bytecode. * * @see Opcode */ public void addInvoke(int opcode, String targetClass, String methodName, String descriptor) { int target = constPool.addClassInfo(targetClass); int nt = constPool.addNameAndTypeInfo(methodName, descriptor); int method = constPool.addMethodrefInfo(target, nt); add(opcode); add16(method); } /** * Ends appending bytecode. */ public void codeEnd(int maxStack, int maxLocals) { if (!isAbstract) { output.writeShort(startPos + 6, maxStack); output.writeShort(startPos + 8, maxLocals); output.writeInt(startPos + 10, output.getPos() - startPos - 14); // code_length catchPos = output.getPos(); catchCount = 0; output.writeShort(0); // number of catch clauses } } /** * Appends an <code>exception_table</code> entry to the * <code>Code_attribute</code>. This method is available * only after the <code>codeEnd</code> method is called. * * @param catchType an index indicating a <code>CONSTANT_Class_info</code>. */ public void addCatch(int startPc, int endPc, int handlerPc, int catchType) { ++catchCount; output.writeShort(startPc); output.writeShort(endPc); output.writeShort(handlerPc); output.writeShort(catchType); } /** * Ends adding a new method. The <code>add</code> method must be * called before the <code>end</code> method is called. * * @param smap a stack map table. may be null. * @param aw attributes to the <code>Code_attribute</code>. * may be null. */ public void end(StackMapTable.Writer smap, AttributeWriter aw) { if (isAbstract) return; // exception_table_length output.writeShort(catchPos, catchCount); int attrCount = smap == null ? 0 : 1; writeAttribute(output, aw, attrCount); if (smap != null) { if (stackIndex == 0) stackIndex = constPool.addUtf8Info(StackMapTable.tag); output.writeShort(stackIndex); byte[] data = smap.toByteArray(); output.writeInt(data.length); output.write(data); } // Code attribute_length output.writeInt(startPos + 2, output.getPos() - startPos - 6); } /** * Returns the length of the bytecode that has been added so far. * * @return the length in bytes. * @since 3.19 */ public int size() { return output.getPos() - startPos - 14; } int numOfMethods() { return methodCount; } int dataSize() { return output.size(); } /** * Writes the added methods. */ void write(OutputStream out) throws IOException { output.writeTo(out); } }
if (throwsIndex == 0) throwsIndex = constPool.addUtf8Info(ExceptionsAttribute.tag); output.writeShort(throwsIndex); output.writeInt(exceptions.length * 2 + 2); output.writeShort(exceptions.length); for (int i = 0; i < exceptions.length; i++) output.writeShort(exceptions[i]);
1,871
102
1,973
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ConstantAttribute.java
ConstantAttribute
copy
class ConstantAttribute extends AttributeInfo { /** * The name of this attribute <code>"ConstantValue"</code>. */ public static final String tag = "ConstantValue"; ConstantAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Constructs a ConstantValue attribute. * * @param cp a constant pool table. * @param index <code>constantvalue_index</code> * of <code>ConstantValue_attribute</code>. */ public ConstantAttribute(ConstPool cp, int index) { super(cp, tag); byte[] bvalue = new byte[2]; bvalue[0] = (byte)(index >>> 8); bvalue[1] = (byte)index; set(bvalue); } /** * Returns <code>constantvalue_index</code>. */ public int getConstantValue() { return ByteArray.readU16bit(get(), 0); } /** * Makes a copy. Class names are replaced according to the * given <code>Map</code> object. * * @param newCp the constant pool table used by the new copy. * @param classnames pairs of replaced and substituted * class names. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) {<FILL_FUNCTION_BODY>} }
int index = getConstPool().copy(getConstantValue(), newCp, classnames); return new ConstantAttribute(newCp, index);
399
40
439
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/EnclosingMethodAttribute.java
EnclosingMethodAttribute
copy
class EnclosingMethodAttribute extends AttributeInfo { /** * The name of this attribute <code>"EnclosingMethod"</code>. */ public static final String tag = "EnclosingMethod"; EnclosingMethodAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Constructs an EnclosingMethod attribute. * * @param cp a constant pool table. * @param className the name of the innermost enclosing class. * @param methodName the name of the enclosing method. * @param methodDesc the descriptor of the enclosing method. */ public EnclosingMethodAttribute(ConstPool cp, String className, String methodName, String methodDesc) { super(cp, tag); int ci = cp.addClassInfo(className); int ni = cp.addNameAndTypeInfo(methodName, methodDesc); byte[] bvalue = new byte[4]; bvalue[0] = (byte)(ci >>> 8); bvalue[1] = (byte)ci; bvalue[2] = (byte)(ni >>> 8); bvalue[3] = (byte)ni; set(bvalue); } /** * Constructs an EnclosingMethod attribute. * The value of <code>method_index</code> is set to 0. * * @param cp a constant pool table. * @param className the name of the innermost enclosing class. */ public EnclosingMethodAttribute(ConstPool cp, String className) { super(cp, tag); int ci = cp.addClassInfo(className); int ni = 0; byte[] bvalue = new byte[4]; bvalue[0] = (byte)(ci >>> 8); bvalue[1] = (byte)ci; bvalue[2] = (byte)(ni >>> 8); bvalue[3] = (byte)ni; set(bvalue); } /** * Returns the value of <code>class_index</code>. */ public int classIndex() { return ByteArray.readU16bit(get(), 0); } /** * Returns the value of <code>method_index</code>. */ public int methodIndex() { return ByteArray.readU16bit(get(), 2); } /** * Returns the name of the class specified by <code>class_index</code>. */ public String className() { return getConstPool().getClassInfo(classIndex()); } /** * Returns the method name specified by <code>method_index</code>. * If the method is a class initializer (static constructor), * {@link MethodInfo#nameClinit} is returned. */ public String methodName() { ConstPool cp = getConstPool(); int mi = methodIndex(); if (mi == 0) return MethodInfo.nameClinit; int ni = cp.getNameAndTypeName(mi); return cp.getUtf8Info(ni); } /** * Returns the method descriptor specified by <code>method_index</code>. */ public String methodDescriptor() { ConstPool cp = getConstPool(); int mi = methodIndex(); int ti = cp.getNameAndTypeDescriptor(mi); return cp.getUtf8Info(ti); } /** * Makes a copy. Class names are replaced according to the * given <code>Map</code> object. * * @param newCp the constant pool table used by the new copy. * @param classnames pairs of replaced and substituted * class names. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) {<FILL_FUNCTION_BODY>} }
if (methodIndex() == 0) return new EnclosingMethodAttribute(newCp, className()); return new EnclosingMethodAttribute(newCp, className(), methodName(), methodDescriptor());
1,027
53
1,080
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ExceptionsAttribute.java
ExceptionsAttribute
setExceptions
class ExceptionsAttribute extends AttributeInfo { /** * The name of this attribute <code>"Exceptions"</code>. */ public static final String tag = "Exceptions"; ExceptionsAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Constructs a copy of an exceptions attribute. * * @param cp constant pool table. * @param src source attribute. */ private ExceptionsAttribute(ConstPool cp, ExceptionsAttribute src, Map<String,String> classnames) { super(cp, tag); copyFrom(src, classnames); } /** * Constructs a new exceptions attribute. * * @param cp constant pool table. */ public ExceptionsAttribute(ConstPool cp) { super(cp, tag); byte[] data = new byte[2]; data[0] = data[1] = 0; // empty this.info = data; } /** * Makes a copy. Class names are replaced according to the * given <code>Map</code> object. * * @param newCp the constant pool table used by the new copy. * @param classnames pairs of replaced and substituted * class names. It can be <code>null</code>. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { return new ExceptionsAttribute(newCp, this, classnames); } /** * Copies the contents from a source attribute. * Specified class names are replaced during the copy. * * @param srcAttr source Exceptions attribute * @param classnames pairs of replaced and substituted * class names. */ private void copyFrom(ExceptionsAttribute srcAttr, Map<String,String> classnames) { ConstPool srcCp = srcAttr.constPool; ConstPool destCp = this.constPool; byte[] src = srcAttr.info; int num = src.length; byte[] dest = new byte[num]; dest[0] = src[0]; dest[1] = src[1]; // the number of elements. for (int i = 2; i < num; i += 2) { int index = ByteArray.readU16bit(src, i); ByteArray.write16bit(srcCp.copy(index, destCp, classnames), dest, i); } this.info = dest; } /** * Returns <code>exception_index_table[]</code>. */ public int[] getExceptionIndexes() { byte[] blist = info; int n = blist.length; if (n <= 2) return null; int[] elist = new int[n / 2 - 1]; int k = 0; for (int j = 2; j < n; j += 2) elist[k++] = ((blist[j] & 0xff) << 8) | (blist[j + 1] & 0xff); return elist; } /** * Returns the names of exceptions that the method may throw. */ public String[] getExceptions() { byte[] blist = info; int n = blist.length; if (n <= 2) return null; String[] elist = new String[n / 2 - 1]; int k = 0; for (int j = 2; j < n; j += 2) { int index = ((blist[j] & 0xff) << 8) | (blist[j + 1] & 0xff); elist[k++] = constPool.getClassInfo(index); } return elist; } /** * Sets <code>exception_index_table[]</code>. */ public void setExceptionIndexes(int[] elist) { int n = elist.length; byte[] blist = new byte[n * 2 + 2]; ByteArray.write16bit(n, blist, 0); for (int i = 0; i < n; ++i) ByteArray.write16bit(elist[i], blist, i * 2 + 2); info = blist; } /** * Sets the names of exceptions that the method may throw. */ public void setExceptions(String[] elist) {<FILL_FUNCTION_BODY>} /** * Returns <code>number_of_exceptions</code>. */ public int tableLength() { return info.length / 2 - 1; } /** * Returns the value of <code>exception_index_table[nth]</code>. */ public int getException(int nth) { int index = nth * 2 + 2; // nth >= 0 return ((info[index] & 0xff) << 8) | (info[index + 1] & 0xff); } }
int n = elist.length; byte[] blist = new byte[n * 2 + 2]; ByteArray.write16bit(n, blist, 0); for (int i = 0; i < n; ++i) ByteArray.write16bit(constPool.addClassInfo(elist[i]), blist, i * 2 + 2); info = blist;
1,329
106
1,435
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/FieldInfo.java
FieldInfo
getConstantValue
class FieldInfo { ConstPool constPool; int accessFlags; int name; String cachedName; String cachedType; int descriptor; List<AttributeInfo> attribute; // may be null. private FieldInfo(ConstPool cp) { constPool = cp; accessFlags = 0; attribute = null; } /** * Constructs a <code>field_info</code> structure. * * @param cp a constant pool table * @param fieldName field name * @param desc field descriptor * * @see Descriptor */ public FieldInfo(ConstPool cp, String fieldName, String desc) { this(cp); name = cp.addUtf8Info(fieldName); cachedName = fieldName; descriptor = cp.addUtf8Info(desc); } FieldInfo(ConstPool cp, DataInputStream in) throws IOException { this(cp); read(in); } /** * Returns a string representation of the object. */ @Override public String toString() { return getName() + " " + getDescriptor(); } /** * Copies all constant pool items to a given new constant pool * and replaces the original items with the new ones. * This is used for garbage collecting the items of removed fields * and methods. * * @param cp the destination */ void compact(ConstPool cp) { name = cp.addUtf8Info(getName()); descriptor = cp.addUtf8Info(getDescriptor()); attribute = AttributeInfo.copyAll(attribute, cp); constPool = cp; } void prune(ConstPool cp) { List<AttributeInfo> newAttributes = new ArrayList<AttributeInfo>(); AttributeInfo invisibleAnnotations = getAttribute(AnnotationsAttribute.invisibleTag); if (invisibleAnnotations != null) { invisibleAnnotations = invisibleAnnotations.copy(cp, null); newAttributes.add(invisibleAnnotations); } AttributeInfo visibleAnnotations = getAttribute(AnnotationsAttribute.visibleTag); if (visibleAnnotations != null) { visibleAnnotations = visibleAnnotations.copy(cp, null); newAttributes.add(visibleAnnotations); } AttributeInfo signature = getAttribute(SignatureAttribute.tag); if (signature != null) { signature = signature.copy(cp, null); newAttributes.add(signature); } int index = getConstantValue(); if (index != 0) { index = constPool.copy(index, cp, null); newAttributes.add(new ConstantAttribute(cp, index)); } attribute = newAttributes; name = cp.addUtf8Info(getName()); descriptor = cp.addUtf8Info(getDescriptor()); constPool = cp; } /** * Returns the constant pool table used * by this <code>field_info</code>. */ public ConstPool getConstPool() { return constPool; } /** * Returns the field name. */ public String getName() { if (cachedName == null) cachedName = constPool.getUtf8Info(name); return cachedName; } /** * Sets the field name. */ public void setName(String newName) { name = constPool.addUtf8Info(newName); cachedName = newName; } /** * Returns the access flags. * * @see AccessFlag */ public int getAccessFlags() { return accessFlags; } /** * Sets the access flags. * * @see AccessFlag */ public void setAccessFlags(int acc) { accessFlags = acc; } /** * Returns the field descriptor. * * @see Descriptor */ public String getDescriptor() { return constPool.getUtf8Info(descriptor); } /** * Sets the field descriptor. * * @see Descriptor */ public void setDescriptor(String desc) { if (!desc.equals(getDescriptor())) descriptor = constPool.addUtf8Info(desc); } /** * Finds a ConstantValue attribute and returns the index into * the <code>constant_pool</code> table. * * @return 0 if a ConstantValue attribute is not found. */ public int getConstantValue() {<FILL_FUNCTION_BODY>} /** * Returns all the attributes. The returned <code>List</code> object * is shared with this object. If you add a new attribute to the list, * the attribute is also added to the field represented by this * object. If you remove an attribute from the list, it is also removed * from the field. * * @return a list of <code>AttributeInfo</code> objects. * @see AttributeInfo */ public List<AttributeInfo> getAttributes() { if (attribute == null) attribute = new ArrayList<AttributeInfo>(); return attribute; } /** * Returns the attribute with the specified name. * It returns null if the specified attribute is not found. * * <p>An attribute name can be obtained by, for example, * {@link AnnotationsAttribute#visibleTag} or * {@link AnnotationsAttribute#invisibleTag}. * </p> * * @param name attribute name * @see #getAttributes() */ public AttributeInfo getAttribute(String name) { return AttributeInfo.lookup(attribute, name); } /** * Removes an attribute with the specified name. * * @param name attribute name. * @return the removed attribute or null. * @since 3.21 */ public AttributeInfo removeAttribute(String name) { return AttributeInfo.remove(attribute, name); } /** * Appends an attribute. If there is already an attribute with * the same name, the new one substitutes for it. * * @see #getAttributes() */ public void addAttribute(AttributeInfo info) { if (attribute == null) attribute = new ArrayList<AttributeInfo>(); AttributeInfo.remove(attribute, info.getName()); attribute.add(info); } private void read(DataInputStream in) throws IOException { accessFlags = in.readUnsignedShort(); name = in.readUnsignedShort(); descriptor = in.readUnsignedShort(); int n = in.readUnsignedShort(); attribute = new ArrayList<AttributeInfo>(); for (int i = 0; i < n; ++i) attribute.add(AttributeInfo.read(constPool, in)); } void write(DataOutputStream out) throws IOException { out.writeShort(accessFlags); out.writeShort(name); out.writeShort(descriptor); if (attribute == null) out.writeShort(0); else { out.writeShort(attribute.size()); AttributeInfo.writeAll(attribute, out); } } }
if ((accessFlags & AccessFlag.STATIC) == 0) return 0; ConstantAttribute attr = (ConstantAttribute)getAttribute(ConstantAttribute.tag); if (attr == null) return 0; return attr.getConstantValue();
1,883
69
1,952
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/LineNumberAttribute.java
Pc
toNearPc
class Pc { /** * The index into the code array. */ public int index; /** * The line number. */ public int line; } /** * Returns the index into the code array at which the code for * the specified line (or the nearest line after the specified one) * begins. * * @param line the line number. * @return a pair of the index and the line number of the * bytecode at that index. */ public Pc toNearPc(int line) {<FILL_FUNCTION_BODY>
int n = tableLength(); int nearPc = 0; int distance = 0; if (n > 0) { distance = lineNumber(0) - line; nearPc = startPc(0); } for (int i = 1; i < n; ++i) { int d = lineNumber(i) - line; if ((d < 0 && d > distance) || (d >= 0 && (d < distance || distance < 0))) { distance = d; nearPc = startPc(i); } } Pc res = new Pc(); res.index = nearPc; res.line = line + distance; return res;
160
185
345
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/LongVector.java
LongVector
addElement
class LongVector { static final int ASIZE = 128; static final int ABITS = 7; // ASIZE = 2^ABITS static final int VSIZE = 8; private ConstInfo[][] objects; private int elements; public LongVector() { objects = new ConstInfo[VSIZE][]; elements = 0; } public LongVector(int initialSize) { int vsize = ((initialSize >> ABITS) & ~(VSIZE - 1)) + VSIZE; objects = new ConstInfo[vsize][]; elements = 0; } public int size() { return elements; } public int capacity() { return objects.length * ASIZE; } public ConstInfo elementAt(int i) { if (i < 0 || elements <= i) return null; return objects[i >> ABITS][i & (ASIZE - 1)]; } public void addElement(ConstInfo value) {<FILL_FUNCTION_BODY>} }
int nth = elements >> ABITS; int offset = elements & (ASIZE - 1); int len = objects.length; if (nth >= len) { ConstInfo[][] newObj = new ConstInfo[len + VSIZE][]; System.arraycopy(objects, 0, newObj, 0, len); objects = newObj; } if (objects[nth] == null) objects[nth] = new ConstInfo[ASIZE]; objects[nth][offset] = value; elements++;
267
146
413
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/MethodParametersAttribute.java
MethodParametersAttribute
copy
class MethodParametersAttribute extends AttributeInfo { /** * The name of this attribute <code>"MethodParameters"</code>. */ public static final String tag = "MethodParameters"; MethodParametersAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Constructs an attribute. * * @param cp a constant pool table. * @param names an array of parameter names. * The i-th element is the name of the i-th parameter. * @param flags an array of parameter access flags. */ public MethodParametersAttribute(ConstPool cp, String[] names, int[] flags) { super(cp, tag); byte[] data = new byte[names.length * 4 + 1]; data[0] = (byte)names.length; for (int i = 0; i < names.length; i++) { ByteArray.write16bit(cp.addUtf8Info(names[i]), data, i * 4 + 1); ByteArray.write16bit(flags[i], data, i * 4 + 3); } set(data); } /** * Returns <code>parameters_count</code>, which is the number of * parameters. */ public int size() { return info[0] & 0xff; } /** * Returns the value of <code>name_index</code> of the i-th element of <code>parameters</code>. * * @param i the position of the parameter. */ public int name(int i) { return ByteArray.readU16bit(info, i * 4 + 1); } /** * Returns the value of <code>access_flags</code> of the i-th element of <code>parameters</code>. * * @param i the position of the parameter. * @see AccessFlag */ public int accessFlags(int i) { return ByteArray.readU16bit(info, i * 4 + 3); } /** * Makes a copy. * * @param newCp the constant pool table used by the new copy. * @param classnames ignored. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) {<FILL_FUNCTION_BODY>} }
int s = size(); ConstPool cp = getConstPool(); String[] names = new String[s]; int[] flags = new int[s]; for (int i = 0; i < s; i++) { names[i] = cp.getUtf8Info(name(i)); flags[i] = accessFlags(i); } return new MethodParametersAttribute(newCp, names, flags);
641
110
751
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/NestHostAttribute.java
NestHostAttribute
copy
class NestHostAttribute extends AttributeInfo { /** * The name of this attribute <code>"NestHost"</code>. */ public static final String tag = "NestHost"; NestHostAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } private NestHostAttribute(ConstPool cp, int hostIndex) { super(cp, tag, new byte[2]); ByteArray.write16bit(hostIndex, get(), 0); } /** * Makes a copy. Class names are replaced according to the * given <code>Map</code> object. * * @param newCp the constant pool table used by the new copy. * @param classnames pairs of replaced and substituted * class names. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String, String> classnames) {<FILL_FUNCTION_BODY>} /** * Returns <code>host_class_index</code>. The constant pool entry * at this entry is a <code>CONSTANT_Class_info</code> structure. * @return the value of <code>host_class_index</code>. */ public int hostClassIndex() { return ByteArray.readU16bit(info, 0); } }
int hostIndex = ByteArray.readU16bit(get(), 0); int newHostIndex = getConstPool().copy(hostIndex, newCp, classnames); return new NestHostAttribute(newCp, newHostIndex);
363
63
426
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/NestMembersAttribute.java
NestMembersAttribute
copy
class NestMembersAttribute extends AttributeInfo { /** * The name of this attribute <code>"NestMembers"</code>. */ public static final String tag = "NestMembers"; NestMembersAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } private NestMembersAttribute(ConstPool cp, byte[] info) { super(cp, tag, info); } /** * Makes a copy. Class names are replaced according to the * given <code>Map</code> object. * * @param newCp the constant pool table used by the new copy. * @param classnames pairs of replaced and substituted * class names. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String, String> classnames) {<FILL_FUNCTION_BODY>} /** * Returns <code>number_of_classes</code>. * @return the number of the classes recorded in this attribute. */ public int numberOfClasses() { return ByteArray.readU16bit(info, 0); } /** Returns <code>classes[index]</code>. * * @param index the index into <code>classes</code>. * @return the value at the given index in the <code>classes</code> array. * It is an index into the constant pool. * The constant pool entry at the returned index is a * <code>CONSTANT_Class_info</code> structure. */ public int memberClass(int index) { return ByteArray.readU16bit(info, index * 2 + 2); } }
byte[] src = get(); byte[] dest = new byte[src.length]; ConstPool cp = getConstPool(); int n = ByteArray.readU16bit(src, 0); ByteArray.write16bit(n, dest, 0); for (int i = 0, j = 2; i < n; ++i, j += 2) { int index = ByteArray.readU16bit(src, j); int newIndex = cp.copy(index, newCp, classnames); ByteArray.write16bit(newIndex, dest, j); } return new NestMembersAttribute(newCp, dest);
454
170
624
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ParameterAnnotationsAttribute.java
ParameterAnnotationsAttribute
getAnnotations
class ParameterAnnotationsAttribute extends AttributeInfo { /** * The name of the <code>RuntimeVisibleParameterAnnotations</code> * attribute. */ public static final String visibleTag = "RuntimeVisibleParameterAnnotations"; /** * The name of the <code>RuntimeInvisibleParameterAnnotations</code> * attribute. */ public static final String invisibleTag = "RuntimeInvisibleParameterAnnotations"; /** * Constructs * a <code>Runtime(In)VisibleParameterAnnotations_attribute</code>. * * @param cp constant pool * @param attrname attribute name (<code>visibleTag</code> or * <code>invisibleTag</code>). * @param info the contents of this attribute. It does not * include <code>attribute_name_index</code> or * <code>attribute_length</code>. */ public ParameterAnnotationsAttribute(ConstPool cp, String attrname, byte[] info) { super(cp, attrname, info); } /** * Constructs an empty * <code>Runtime(In)VisibleParameterAnnotations_attribute</code>. * A new annotation can be later added to the created attribute * by <code>setAnnotations()</code>. * * @param cp constant pool * @param attrname attribute name (<code>visibleTag</code> or * <code>invisibleTag</code>). * @see #setAnnotations(Annotation[][]) */ public ParameterAnnotationsAttribute(ConstPool cp, String attrname) { this(cp, attrname, new byte[] { 0 }); } /** * @param n the attribute name. */ ParameterAnnotationsAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Returns <code>num_parameters</code>. */ public int numParameters() { return info[0] & 0xff; } /** * Copies this attribute and returns a new copy. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { Copier copier = new Copier(info, constPool, newCp, classnames); try { copier.parameters(); return new ParameterAnnotationsAttribute(newCp, getName(), copier.close()); } catch (Exception e) { throw new RuntimeException(e.toString()); } } /** * Parses the annotations and returns a data structure representing * that parsed annotations. Note that changes of the node values of the * returned tree are not reflected on the annotations represented by * this object unless the tree is copied back to this object by * <code>setAnnotations()</code>. * * @return Each element of the returned array represents an array of * annotations that are associated with each method parameter. * * @see #setAnnotations(Annotation[][]) */ public Annotation[][] getAnnotations() {<FILL_FUNCTION_BODY>} /** * Changes the annotations represented by this object according to * the given array of <code>Annotation</code> objects. * * @param params the data structure representing the * new annotations. Every element of this array * is an array of <code>Annotation</code> and * it represens annotations of each method parameter. */ public void setAnnotations(Annotation[][] params) { ByteArrayOutputStream output = new ByteArrayOutputStream(); AnnotationsWriter writer = new AnnotationsWriter(output, constPool); try { writer.numParameters(params.length); for (Annotation[] anno:params) { writer.numAnnotations(anno.length); for (int j = 0; j < anno.length; ++j) anno[j].write(writer); } writer.close(); } catch (IOException e) { throw new RuntimeException(e); // should never reach here. } set(output.toByteArray()); } /** * @param oldname a JVM class name. * @param newname a JVM class name. */ @Override void renameClass(String oldname, String newname) { Map<String,String> map = new HashMap<String,String>(); map.put(oldname, newname); renameClass(map); } @Override void renameClass(Map<String,String> classnames) { Renamer renamer = new Renamer(info, getConstPool(), classnames); try { renamer.parameters(); } catch (Exception e) { throw new RuntimeException(e); } } @Override void getRefClasses(Map<String,String> classnames) { renameClass(classnames); } /** * Returns a string representation of this object. */ @Override public String toString() { Annotation[][] aa = getAnnotations(); StringBuilder sbuf = new StringBuilder(); for (Annotation[] a : aa) { for (Annotation i : a) sbuf.append(i.toString()).append(" "); sbuf.append(", "); } return sbuf.toString().replaceAll(" (?=,)|, $",""); } }
try { return new Parser(info, constPool).parseParameters(); } catch (Exception e) { throw new RuntimeException(e.toString()); }
1,433
47
1,480
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/StackMap.java
SwitchShifter
locals
class SwitchShifter extends Walker { private int where, gap; public SwitchShifter(StackMap smt, int where, int gap) { super(smt); this.where = where; this.gap = gap; } @Override public int locals(int pos, int offset, int num) {<FILL_FUNCTION_BODY>} }
if (where == pos + offset) ByteArray.write16bit(offset - gap, info, pos - 4); else if (where == pos) ByteArray.write16bit(offset + gap, info, pos - 4); return super.locals(pos, offset, num);
100
79
179
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/StackMapTable.java
NewRemover
fullFrame
class NewRemover extends SimpleCopy { int posOfNew; public NewRemover(byte[] data, int pos) { super(data); posOfNew = pos; } @Override public void sameLocals(int pos, int offsetDelta, int stackTag, int stackData) { if (stackTag == UNINIT && stackData == posOfNew) super.sameFrame(pos, offsetDelta); else super.sameLocals(pos, offsetDelta, stackTag, stackData); } @Override public void fullFrame(int pos, int offsetDelta, int[] localTags, int[] localData, int[] stackTags, int[] stackData) {<FILL_FUNCTION_BODY>} }
int n = stackTags.length - 1; for (int i = 0; i < n; i++) if (stackTags[i] == UNINIT && stackData[i] == posOfNew && stackTags[i + 1] == UNINIT && stackData[i + 1] == posOfNew) { n++; int[] stackTags2 = new int[n - 2]; int[] stackData2 = new int[n - 2]; int k = 0; for (int j = 0; j < n; j++) if (j == i) j++; else { stackTags2[k] = stackTags[j]; stackData2[k++] = stackData[j]; } stackTags = stackTags2; stackData = stackData2; break; } super.fullFrame(pos, offsetDelta, localTags, localData, stackTags, stackData);
190
243
433
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/TypeAnnotationsAttribute.java
SubWalker
targetInfo
class SubWalker { byte[] info; SubWalker(byte[] attrInfo) { info = attrInfo; } final int targetInfo(int pos, int type) throws Exception {<FILL_FUNCTION_BODY>} void typeParameterTarget(int pos, int targetType, int typeParameterIndex) throws Exception {} void supertypeTarget(int pos, int superTypeIndex) throws Exception {} void typeParameterBoundTarget(int pos, int targetType, int typeParameterIndex, int boundIndex) throws Exception {} void emptyTarget(int pos, int targetType) throws Exception {} void formalParameterTarget(int pos, int formalParameterIndex) throws Exception {} void throwsTarget(int pos, int throwsTypeIndex) throws Exception {} int localvarTarget(int pos, int targetType, int tableLength) throws Exception { for (int i = 0; i < tableLength; i++) { int start = ByteArray.readU16bit(info, pos); int length = ByteArray.readU16bit(info, pos + 2); int index = ByteArray.readU16bit(info, pos + 4); localvarTarget(pos, targetType, start, length, index); pos += 6; } return pos; } void localvarTarget(int pos, int targetType, int startPc, int length, int index) throws Exception {} void catchTarget(int pos, int exceptionTableIndex) throws Exception {} void offsetTarget(int pos, int targetType, int offset) throws Exception {} void typeArgumentTarget(int pos, int targetType, int offset, int typeArgumentIndex) throws Exception {} final int typePath(int pos) throws Exception { int len = info[pos++] & 0xff; return typePath(pos, len); } int typePath(int pos, int pathLength) throws Exception { for (int i = 0; i < pathLength; i++) { int kind = info[pos] & 0xff; int index = info[pos + 1] & 0xff; typePath(pos, kind, index); pos += 2; } return pos; } void typePath(int pos, int typePathKind, int typeArgumentIndex) throws Exception {} }
switch (type) { case 0x00: case 0x01: { int index = info[pos] & 0xff; typeParameterTarget(pos, type, index); return pos + 1; } case 0x10: { int index = ByteArray.readU16bit(info, pos); supertypeTarget(pos, index); return pos + 2; } case 0x11: case 0x12: { int param = info[pos] & 0xff; int bound = info[pos + 1] & 0xff; typeParameterBoundTarget(pos, type, param, bound); return pos + 2; } case 0x13: case 0x14: case 0x15: emptyTarget(pos, type); return pos; case 0x16: { int index = info[pos] & 0xff; formalParameterTarget(pos, index); return pos + 1; } case 0x17: { int index = ByteArray.readU16bit(info, pos); throwsTarget(pos, index); return pos + 2; } case 0x40: case 0x41: { int len = ByteArray.readU16bit(info, pos); return localvarTarget(pos + 2, type, len); } case 0x42: { int index = ByteArray.readU16bit(info, pos); catchTarget(pos, index); return pos + 2; } case 0x43: case 0x44: case 0x45: case 0x46: { int offset = ByteArray.readU16bit(info, pos); offsetTarget(pos, type, offset); return pos + 2; } case 0x47: case 0x48: case 0x49: case 0x4a: case 0x4b: { int offset = ByteArray.readU16bit(info, pos); int index = info[pos + 2] & 0xff; typeArgumentTarget(pos, type, offset, index); return pos + 3; } default: throw new RuntimeException("invalid target type: " + type); }
588
611
1,199
<methods>public void <init>(org.hotswap.agent.javassist.bytecode.ConstPool, java.lang.String, byte[]) ,public org.hotswap.agent.javassist.bytecode.AttributeInfo copy(org.hotswap.agent.javassist.bytecode.ConstPool, Map<java.lang.String,java.lang.String>) ,public byte[] get() ,public org.hotswap.agent.javassist.bytecode.ConstPool getConstPool() ,public java.lang.String getName() ,public int length() ,public void set(byte[]) <variables>protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,byte[] info,int name
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/ControlFlow.java
Node
toString
class Node { private Block block; private Node parent; private Node[] children; Node(Block b) { block = b; parent = null; } /** * Returns a <code>String</code> representation. */ @Override public String toString() {<FILL_FUNCTION_BODY>} /** * Returns the basic block indicated by this node. */ public Block block() { return block; } /** * Returns the parent of this node. */ public Node parent() { return parent; } /** * Returns the number of the children of this node. */ public int children() { return children.length; } /** * Returns the n-th child of this node. * * @param n an index in the array of children. */ public Node child(int n) { return children[n]; } /* * After executing this method, distance[] represents the post order of the tree nodes. * It also represents distances from the root; a bigger number represents a shorter * distance. parent is set to its parent in the depth first spanning tree. */ int makeDepth1stTree(Node caller, boolean[] visited, int counter, int[] distance, Access access) { int index = block.index; if (visited[index]) return counter; visited[index] = true; parent = caller; BasicBlock[] exits = access.exits(this); if (exits != null) for (int i = 0; i < exits.length; i++) { Node n = access.node(exits[i]); counter = n.makeDepth1stTree(this, visited, counter, distance, access); } distance[index] = counter++; return counter; } boolean makeDominatorTree(boolean[] visited, int[] distance, Access access) { int index = block.index; if (visited[index]) return false; visited[index] = true; boolean changed = false; BasicBlock[] exits = access.exits(this); if (exits != null) for (int i = 0; i < exits.length; i++) { Node n = access.node(exits[i]); if (n.makeDominatorTree(visited, distance, access)) changed = true; } BasicBlock[] entrances = access.entrances(this); if (entrances != null) for (int i = 0; i < entrances.length; i++) { if (parent != null) { Node n = getAncestor(parent, access.node(entrances[i]), distance); if (n != parent) { parent = n; changed = true; } } } return changed; } private static Node getAncestor(Node n1, Node n2, int[] distance) { while (n1 != n2) { if (distance[n1.block.index] < distance[n2.block.index]) n1 = n1.parent; else n2 = n2.parent; if (n1 == null || n2 == null) return null; } return n1; } private static void setChildren(Node[] all) { int size = all.length; int[] nchildren = new int[size]; for (int i = 0; i < size; i++) nchildren[i] = 0; for (int i = 0; i < size; i++) { Node p = all[i].parent; if (p != null) nchildren[p.block.index]++; } for (int i = 0; i < size; i++) all[i].children = new Node[nchildren[i]]; for (int i = 0; i < size; i++) nchildren[i] = 0; for (int i = 0; i < size; i++) { Node n = all[i]; Node p = n.parent; if (p != null) p.children[nchildren[p.block.index]++] = n; } } }
StringBuffer sbuf = new StringBuffer(); sbuf.append("Node[pos=").append(block().position()); sbuf.append(", parent="); sbuf.append(parent == null ? "*" : Integer.toString(parent.block().position())); sbuf.append(", children{"); for (int i = 0; i < children.length; i++) sbuf.append(children[i].block().position()).append(", "); sbuf.append("}]"); return sbuf.toString();
1,112
133
1,245
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/FramePrinter.java
FramePrinter
printLocals
class FramePrinter { private final PrintStream stream; /** * Constructs a bytecode printer. */ public FramePrinter(PrintStream stream) { this.stream = stream; } /** * Prints all the methods declared in the given class. */ public static void print(CtClass clazz, PrintStream stream) { (new FramePrinter(stream)).print(clazz); } /** * Prints all the methods declared in the given class. */ public void print(CtClass clazz) { CtMethod[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { print(methods[i]); } } private String getMethodString(CtMethod method) { try { return Modifier.toString(method.getModifiers()) + " " + method.getReturnType().getName() + " " + method.getName() + Descriptor.toString(method.getSignature()) + ";"; } catch (NotFoundException e) { throw new RuntimeException(e); } } /** * Prints the instructions and the frame states of the given method. */ public void print(CtMethod method) { stream.println("\n" + getMethodString(method)); MethodInfo info = method.getMethodInfo2(); ConstPool pool = info.getConstPool(); CodeAttribute code = info.getCodeAttribute(); if (code == null) return; Frame[] frames; try { frames = (new Analyzer()).analyze(method.getDeclaringClass(), info); } catch (BadBytecode e) { throw new RuntimeException(e); } int spacing = String.valueOf(code.getCodeLength()).length(); CodeIterator iterator = code.iterator(); while (iterator.hasNext()) { int pos; try { pos = iterator.next(); } catch (BadBytecode e) { throw new RuntimeException(e); } stream.println(pos + ": " + InstructionPrinter.instructionString(iterator, pos, pool)); addSpacing(spacing + 3); Frame frame = frames[pos]; if (frame == null) { stream.println("--DEAD CODE--"); continue; } printStack(frame); addSpacing(spacing + 3); printLocals(frame); } } private void printStack(Frame frame) { stream.print("stack ["); int top = frame.getTopIndex(); for (int i = 0; i <= top; i++) { if (i > 0) stream.print(", "); Type type = frame.getStack(i); stream.print(type); } stream.println("]"); } private void printLocals(Frame frame) {<FILL_FUNCTION_BODY>} private void addSpacing(int count) { while (count-- > 0) stream.print(' '); } }
stream.print("locals ["); int length = frame.localsLength(); for (int i = 0; i < length; i++) { if (i > 0) stream.print(", "); Type type = frame.getLocal(i); stream.print(type == null ? "empty" : type.toString()); } stream.println("]");
798
98
896
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/IntQueue.java
Entry
take
class Entry { private IntQueue.Entry next; private int value; private Entry(int value) { this.value = value; } } private IntQueue.Entry head; private IntQueue.Entry tail; void add(int value) { IntQueue.Entry entry = new Entry(value); if (tail != null) tail.next = entry; tail = entry; if (head == null) head = entry; } boolean isEmpty() { return head == null; } int take() {<FILL_FUNCTION_BODY>
if (head == null) throw new NoSuchElementException(); int value = head.value; head = head.next; if (head == null) tail = null; return value;
161
58
219
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/MultiArrayType.java
MultiArrayType
toString
class MultiArrayType extends Type { private MultiType component; private int dims; public MultiArrayType(MultiType component, int dims) { super(null); this.component = component; this.dims = dims; } @Override public CtClass getCtClass() { CtClass clazz = component.getCtClass(); if (clazz == null) return null; ClassPool pool = clazz.getClassPool(); if (pool == null) pool = ClassPool.getDefault(); String name = arrayName(clazz.getName(), dims); try { return pool.get(name); } catch (NotFoundException e) { throw new RuntimeException(e); } } @Override boolean popChanged() { return component.popChanged(); } @Override public int getDimensions() { return dims; } @Override public Type getComponent() { return dims == 1 ? (Type)component : new MultiArrayType(component, dims - 1); } @Override public int getSize() { return 1; } @Override public boolean isArray() { return true; } @Override public boolean isAssignableFrom(Type type) { throw new UnsupportedOperationException("Not implemented"); } @Override public boolean isReference() { return true; } public boolean isAssignableTo(Type type) { if (eq(type.getCtClass(), Type.OBJECT.getCtClass())) return true; if (eq(type.getCtClass(), Type.CLONEABLE.getCtClass())) return true; if (eq(type.getCtClass(), Type.SERIALIZABLE.getCtClass())) return true; if (! type.isArray()) return false; Type typeRoot = getRootComponent(type); int typeDims = type.getDimensions(); if (typeDims > dims) return false; if (typeDims < dims) { if (eq(typeRoot.getCtClass(), Type.OBJECT.getCtClass())) return true; if (eq(typeRoot.getCtClass(), Type.CLONEABLE.getCtClass())) return true; if (eq(typeRoot.getCtClass(), Type.SERIALIZABLE.getCtClass())) return true; return false; } return component.isAssignableTo(typeRoot); } @Override public int hashCode() { return component.hashCode() + dims; } @Override public boolean equals(Object o) { if (! (o instanceof MultiArrayType)) return false; MultiArrayType multi = (MultiArrayType)o; return component.equals(multi.component) && dims == multi.dims; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
// follows the same detailed formating scheme as component return arrayName(component.toString(), dims);
805
28
833
<methods>public boolean equals(java.lang.Object) ,public static org.hotswap.agent.javassist.bytecode.analysis.Type get(org.hotswap.agent.javassist.CtClass) ,public org.hotswap.agent.javassist.bytecode.analysis.Type getComponent() ,public org.hotswap.agent.javassist.CtClass getCtClass() ,public int getDimensions() ,public int getSize() ,public int hashCode() ,public boolean isArray() ,public boolean isAssignableFrom(org.hotswap.agent.javassist.bytecode.analysis.Type) ,public boolean isReference() ,public boolean isSpecial() ,public org.hotswap.agent.javassist.bytecode.analysis.Type merge(org.hotswap.agent.javassist.bytecode.analysis.Type) ,public java.lang.String toString() <variables>public static final org.hotswap.agent.javassist.bytecode.analysis.Type BOGUS,public static final org.hotswap.agent.javassist.bytecode.analysis.Type BOOLEAN,public static final org.hotswap.agent.javassist.bytecode.analysis.Type BYTE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type CHAR,public static final org.hotswap.agent.javassist.bytecode.analysis.Type CLONEABLE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type DOUBLE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type FLOAT,public static final org.hotswap.agent.javassist.bytecode.analysis.Type INTEGER,public static final org.hotswap.agent.javassist.bytecode.analysis.Type LONG,public static final org.hotswap.agent.javassist.bytecode.analysis.Type OBJECT,public static final org.hotswap.agent.javassist.bytecode.analysis.Type RETURN_ADDRESS,public static final org.hotswap.agent.javassist.bytecode.analysis.Type SERIALIZABLE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type SHORT,public static final org.hotswap.agent.javassist.bytecode.analysis.Type THROWABLE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type TOP,public static final org.hotswap.agent.javassist.bytecode.analysis.Type UNINIT,public static final org.hotswap.agent.javassist.bytecode.analysis.Type VOID,private final non-sealed org.hotswap.agent.javassist.CtClass clazz,private static final Map<org.hotswap.agent.javassist.CtClass,org.hotswap.agent.javassist.bytecode.analysis.Type> prims,private final non-sealed boolean special
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/MultiType.java
MultiType
isAssignableTo
class MultiType extends Type { private Map<String,CtClass> interfaces; private Type resolved; private Type potentialClass; private MultiType mergeSource; private boolean changed = false; public MultiType(Map<String,CtClass> interfaces) { this(interfaces, null); } public MultiType(Map<String,CtClass> interfaces, Type potentialClass) { super(null); this.interfaces = interfaces; this.potentialClass = potentialClass; } /** * Gets the class that corresponds with this type. If this information * is not yet known, java.lang.Object will be returned. */ @Override public CtClass getCtClass() { if (resolved != null) return resolved.getCtClass(); return Type.OBJECT.getCtClass(); } /** * Always returns null since this type is never used for an array. */ @Override public Type getComponent() { return null; } /** * Always returns 1, since this type is a reference. */ @Override public int getSize() { return 1; } /** * Always reutnrs false since this type is never used for an array */ @Override public boolean isArray() { return false; } /** * Returns true if the internal state has changed. */ @Override boolean popChanged() { boolean changed = this.changed; this.changed = false; return changed; } @Override public boolean isAssignableFrom(Type type) { throw new UnsupportedOperationException("Not implemented"); } public boolean isAssignableTo(Type type) {<FILL_FUNCTION_BODY>} private void propogateState() { MultiType source = mergeSource; while (source != null) { source.interfaces = interfaces; source.potentialClass = potentialClass; source = source.mergeSource; } } private void propogateResolved() { MultiType source = mergeSource; while (source != null) { source.resolved = resolved; source = source.mergeSource; } } /** * Always returns true, since this type is always a reference. * * @return true */ @Override public boolean isReference() { return true; } private Map<String,CtClass> getAllMultiInterfaces(MultiType type) { Map<String,CtClass> map = new HashMap<String,CtClass>(); for (CtClass intf:type.interfaces.values()) { map.put(intf.getName(), intf); getAllInterfaces(intf, map); } return map; } private Map<String,CtClass> mergeMultiInterfaces(MultiType type1, MultiType type2) { Map<String,CtClass> map1 = getAllMultiInterfaces(type1); Map<String,CtClass> map2 = getAllMultiInterfaces(type2); return findCommonInterfaces(map1, map2); } private Map<String,CtClass> mergeMultiAndSingle(MultiType multi, Type single) { Map<String,CtClass> map1 = getAllMultiInterfaces(multi); Map<String,CtClass> map2 = getAllInterfaces(single.getCtClass(), null); return findCommonInterfaces(map1, map2); } private boolean inMergeSource(MultiType source) { while (source != null) { if (source == this) return true; source = source.mergeSource; } return false; } @Override public Type merge(Type type) { if (this == type) return this; if (type == UNINIT) return this; if (type == BOGUS) return BOGUS; if (type == null) return this; if (resolved != null) return resolved.merge(type); if (potentialClass != null) { Type mergePotential = potentialClass.merge(type); if (! mergePotential.equals(potentialClass) || mergePotential.popChanged()) { potentialClass = Type.OBJECT.equals(mergePotential) ? null : mergePotential; changed = true; } } Map<String,CtClass> merged; if (type instanceof MultiType) { MultiType multi = (MultiType)type; if (multi.resolved != null) { merged = mergeMultiAndSingle(this, multi.resolved); } else { merged = mergeMultiInterfaces(multi, this); if (! inMergeSource(multi)) mergeSource = multi; } } else { merged = mergeMultiAndSingle(this, type); } // Keep all previous merge paths up to date if (merged.size() > 1 || (merged.size() == 1 && potentialClass != null)) { // Check for changes if (merged.size() != interfaces.size()) changed = true; else if (changed == false) for (String key:merged.keySet()) if (!interfaces.containsKey(key)) changed = true; interfaces = merged; propogateState(); return this; } if (merged.size() == 1) resolved = Type.get(merged.values().iterator().next()); else if (potentialClass != null) resolved = potentialClass; else resolved = OBJECT; propogateResolved(); return resolved; } @Override public int hashCode() { if (resolved != null) return resolved.hashCode(); return interfaces.keySet().hashCode(); } @Override public boolean equals(Object o) { if (! (o instanceof MultiType)) return false; MultiType multi = (MultiType) o; if (resolved != null) return resolved.equals(multi.resolved); else if (multi.resolved != null) return false; return interfaces.keySet().equals(multi.interfaces.keySet()); } @Override public String toString() { if (resolved != null) return resolved.toString(); StringBuffer buffer = new StringBuffer("{"); for (String key:interfaces.keySet()) buffer.append(key).append(", "); if (potentialClass != null) buffer.append("*").append(potentialClass.toString()); else buffer.setLength(buffer.length() - 2); buffer.append("}"); return buffer.toString(); } }
if (resolved != null) return type.isAssignableFrom(resolved); if (Type.OBJECT.equals(type)) return true; if (potentialClass != null && !type.isAssignableFrom(potentialClass)) potentialClass = null; Map<String,CtClass> map = mergeMultiAndSingle(this, type); if (map.size() == 1 && potentialClass == null) { // Update previous merge paths to the same resolved type resolved = Type.get(map.values().iterator().next()); propogateResolved(); return true; } // Keep all previous merge paths up to date if (map.size() >= 1) { interfaces = map; propogateState(); return true; } if (potentialClass != null) { resolved = potentialClass; propogateResolved(); return true; } return false;
1,780
250
2,030
<methods>public boolean equals(java.lang.Object) ,public static org.hotswap.agent.javassist.bytecode.analysis.Type get(org.hotswap.agent.javassist.CtClass) ,public org.hotswap.agent.javassist.bytecode.analysis.Type getComponent() ,public org.hotswap.agent.javassist.CtClass getCtClass() ,public int getDimensions() ,public int getSize() ,public int hashCode() ,public boolean isArray() ,public boolean isAssignableFrom(org.hotswap.agent.javassist.bytecode.analysis.Type) ,public boolean isReference() ,public boolean isSpecial() ,public org.hotswap.agent.javassist.bytecode.analysis.Type merge(org.hotswap.agent.javassist.bytecode.analysis.Type) ,public java.lang.String toString() <variables>public static final org.hotswap.agent.javassist.bytecode.analysis.Type BOGUS,public static final org.hotswap.agent.javassist.bytecode.analysis.Type BOOLEAN,public static final org.hotswap.agent.javassist.bytecode.analysis.Type BYTE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type CHAR,public static final org.hotswap.agent.javassist.bytecode.analysis.Type CLONEABLE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type DOUBLE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type FLOAT,public static final org.hotswap.agent.javassist.bytecode.analysis.Type INTEGER,public static final org.hotswap.agent.javassist.bytecode.analysis.Type LONG,public static final org.hotswap.agent.javassist.bytecode.analysis.Type OBJECT,public static final org.hotswap.agent.javassist.bytecode.analysis.Type RETURN_ADDRESS,public static final org.hotswap.agent.javassist.bytecode.analysis.Type SERIALIZABLE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type SHORT,public static final org.hotswap.agent.javassist.bytecode.analysis.Type THROWABLE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type TOP,public static final org.hotswap.agent.javassist.bytecode.analysis.Type UNINIT,public static final org.hotswap.agent.javassist.bytecode.analysis.Type VOID,private final non-sealed org.hotswap.agent.javassist.CtClass clazz,private static final Map<org.hotswap.agent.javassist.CtClass,org.hotswap.agent.javassist.bytecode.analysis.Type> prims,private final non-sealed boolean special
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/Subroutine.java
Subroutine
toString
class Subroutine { //private Set callers = new HashSet(); private List<Integer> callers = new ArrayList<Integer>(); private Set<Integer> access = new HashSet<Integer>(); private int start; public Subroutine(int start, int caller) { this.start = start; callers.add(caller); } public void addCaller(int caller) { callers.add(caller); } public int start() { return start; } public void access(int index) { access.add(index); } public boolean isAccessed(int index) { return access.contains(index); } public Collection<Integer> accessed() { return access; } public Collection<Integer> callers() { return callers; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "start = " + start + " callers = " + callers.toString();
250
24
274
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/SubroutineScanner.java
SubroutineScanner
scanTableSwitch
class SubroutineScanner implements Opcode { private Subroutine[] subroutines; Map<Integer,Subroutine> subTable = new HashMap<Integer,Subroutine>(); Set<Integer> done = new HashSet<Integer>(); public Subroutine[] scan(MethodInfo method) throws BadBytecode { CodeAttribute code = method.getCodeAttribute(); CodeIterator iter = code.iterator(); subroutines = new Subroutine[code.getCodeLength()]; subTable.clear(); done.clear(); scan(0, iter, null); ExceptionTable exceptions = code.getExceptionTable(); for (int i = 0; i < exceptions.size(); i++) { int handler = exceptions.handlerPc(i); // If an exception is thrown in subroutine, the handler // is part of the same subroutine. scan(handler, iter, subroutines[exceptions.startPc(i)]); } return subroutines; } private void scan(int pos, CodeIterator iter, Subroutine sub) throws BadBytecode { // Skip already processed blocks if (done.contains(pos)) return; done.add(pos); int old = iter.lookAhead(); iter.move(pos); boolean next; do { pos = iter.next(); next = scanOp(pos, iter, sub) && iter.hasNext(); } while (next); iter.move(old); } private boolean scanOp(int pos, CodeIterator iter, Subroutine sub) throws BadBytecode { subroutines[pos] = sub; int opcode = iter.byteAt(pos); if (opcode == TABLESWITCH) { scanTableSwitch(pos, iter, sub); return false; } if (opcode == LOOKUPSWITCH) { scanLookupSwitch(pos, iter, sub); return false; } // All forms of return and throw end current code flow if (Util.isReturn(opcode) || opcode == RET || opcode == ATHROW) return false; if (Util.isJumpInstruction(opcode)) { int target = Util.getJumpTarget(pos, iter); if (opcode == JSR || opcode == JSR_W) { Subroutine s = subTable.get(target); if (s == null) { s = new Subroutine(target, pos); subTable.put(target, s); scan(target, iter, s); } else { s.addCaller(pos); } } else { scan(target, iter, sub); // GOTO ends current code flow if (Util.isGoto(opcode)) return false; } } return true; } private void scanLookupSwitch(int pos, CodeIterator iter, Subroutine sub) throws BadBytecode { int index = (pos & ~3) + 4; // default scan(pos + iter.s32bitAt(index), iter, sub); int npairs = iter.s32bitAt(index += 4); int end = npairs * 8 + (index += 4); // skip "match" for (index += 4; index < end; index += 8) { int target = iter.s32bitAt(index) + pos; scan(target, iter, sub); } } private void scanTableSwitch(int pos, CodeIterator iter, Subroutine sub) throws BadBytecode {<FILL_FUNCTION_BODY>} }
// Skip 4 byte alignment padding int index = (pos & ~3) + 4; // default scan(pos + iter.s32bitAt(index), iter, sub); int low = iter.s32bitAt(index += 4); int high = iter.s32bitAt(index += 4); int end = (high - low + 1) * 4 + (index += 4); // Offset table for (; index < end; index += 4) { int target = iter.s32bitAt(index) + pos; scan(target, iter, sub); }
941
157
1,098
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/Util.java
Util
isJumpInstruction
class Util implements Opcode { public static int getJumpTarget(int pos, CodeIterator iter) { int opcode = iter.byteAt(pos); pos += (opcode == JSR_W || opcode == GOTO_W) ? iter.s32bitAt(pos + 1) : iter.s16bitAt(pos + 1); return pos; } public static boolean isJumpInstruction(int opcode) {<FILL_FUNCTION_BODY>} public static boolean isGoto(int opcode) { return opcode == GOTO || opcode == GOTO_W; } public static boolean isJsr(int opcode) { return opcode == JSR || opcode == JSR_W; } public static boolean isReturn(int opcode) { return (opcode >= IRETURN && opcode <= RETURN); } }
return (opcode >= IFEQ && opcode <= JSR) || opcode == IFNULL || opcode == IFNONNULL || opcode == JSR_W || opcode == GOTO_W;
232
52
284
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/annotation/Annotation.java
Pair
addMemberValue
class Pair { int name; MemberValue value; } ConstPool pool; int typeIndex; Map<String,Pair> members; // this sould be LinkedHashMap // but it is not supported by JDK 1.3. /** * Constructs an annotation including no members. A member can be * later added to the created annotation by <code>addMemberValue()</code>. * * @param type the index into the constant pool table. * the entry at that index must be the * <code>CONSTANT_Utf8_Info</code> structure * repreenting the name of the annotation interface type. * @param cp the constant pool table. * * @see #addMemberValue(String, MemberValue) */ public Annotation(int type, ConstPool cp) { pool = cp; typeIndex = type; members = null; } /** * Constructs an annotation including no members. A member can be * later added to the created annotation by <code>addMemberValue()</code>. * * @param typeName the fully-qualified name of the annotation interface type. * @param cp the constant pool table. * * @see #addMemberValue(String, MemberValue) */ public Annotation(String typeName, ConstPool cp) { this(cp.addUtf8Info(Descriptor.of(typeName)), cp); } /** * Constructs an annotation that can be accessed through the interface * represented by <code>clazz</code>. The values of the members are * not specified. * * @param cp the constant pool table. * @param clazz the interface. * @throws NotFoundException when the clazz is not found */ public Annotation(ConstPool cp, CtClass clazz) throws NotFoundException { // todo Enums are not supported right now. this(cp.addUtf8Info(Descriptor.of(clazz.getName())), cp); if (!clazz.isInterface()) throw new RuntimeException( "Only interfaces are allowed for Annotation creation."); CtMethod[] methods = clazz.getDeclaredMethods(); if (methods.length > 0) members = new LinkedHashMap<String,Pair>(); for (CtMethod m:methods) addMemberValue(m.getName(), createMemberValue(cp, m.getReturnType())); } /** * Makes an instance of <code>MemberValue</code>. * * @param cp the constant pool table. * @param type the type of the member. * @return the member value * @throws NotFoundException when the type is not found */ public static MemberValue createMemberValue(ConstPool cp, CtClass type) throws NotFoundException { if (type == CtClass.booleanType) return new BooleanMemberValue(cp); else if (type == CtClass.byteType) return new ByteMemberValue(cp); else if (type == CtClass.charType) return new CharMemberValue(cp); else if (type == CtClass.shortType) return new ShortMemberValue(cp); else if (type == CtClass.intType) return new IntegerMemberValue(cp); else if (type == CtClass.longType) return new LongMemberValue(cp); else if (type == CtClass.floatType) return new FloatMemberValue(cp); else if (type == CtClass.doubleType) return new DoubleMemberValue(cp); else if (type.getName().equals("java.lang.Class")) return new ClassMemberValue(cp); else if (type.getName().equals("java.lang.String")) return new StringMemberValue(cp); else if (type.isArray()) { CtClass arrayType = type.getComponentType(); MemberValue member = createMemberValue(cp, arrayType); return new ArrayMemberValue(member, cp); } else if (type.isInterface()) { Annotation info = new Annotation(cp, type); return new AnnotationMemberValue(info, cp); } else { // treat as enum. I know this is not typed, // but JBoss has an Annotation Compiler for JDK 1.4 // and I want it to work with that. - Bill Burke EnumMemberValue emv = new EnumMemberValue(cp); emv.setType(type.getName()); return emv; } } /** * Adds a new member. * * @param nameIndex the index into the constant pool table. * The entry at that index must be * a <code>CONSTANT_Utf8_info</code> structure. * structure representing the member name. * @param value the member value. */ public void addMemberValue(int nameIndex, MemberValue value) {<FILL_FUNCTION_BODY>
Pair p = new Pair(); p.name = nameIndex; p.value = value; addMemberValue(p);
1,304
38
1,342
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/annotation/AnnotationMemberValue.java
AnnotationMemberValue
getType
class AnnotationMemberValue extends MemberValue { Annotation value; /** * Constructs an annotation member. The initial value is not specified. */ public AnnotationMemberValue(ConstPool cp) { this(null, cp); } /** * Constructs an annotation member. The initial value is specified by * the first parameter. */ public AnnotationMemberValue(Annotation a, ConstPool cp) { super('@', cp); value = a; } @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) throws ClassNotFoundException { return AnnotationImpl.make(cl, getType(cl), cp, value); } @Override Class<?> getType(ClassLoader cl) throws ClassNotFoundException {<FILL_FUNCTION_BODY>} /** * Obtains the value. */ public Annotation getValue() { return value; } /** * Sets the value of this member. */ public void setValue(Annotation newValue) { value = newValue; } /** * Obtains the string representation of this object. */ @Override public String toString() { return value.toString(); } /** * Writes the value. */ @Override public void write(AnnotationsWriter writer) throws IOException { writer.annotationValue(); value.write(writer); } /** * Accepts a visitor. */ @Override public void accept(MemberValueVisitor visitor) { visitor.visitAnnotationMemberValue(this); } }
if (value == null) throw new ClassNotFoundException("no type specified"); return loadClass(cl, value.getTypeName());
431
37
468
<methods>public abstract void accept(org.hotswap.agent.javassist.bytecode.annotation.MemberValueVisitor) ,public abstract void write(org.hotswap.agent.javassist.bytecode.annotation.AnnotationsWriter) throws java.io.IOException<variables>org.hotswap.agent.javassist.bytecode.ConstPool cp,char tag
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/annotation/ArrayMemberValue.java
ArrayMemberValue
getValue
class ArrayMemberValue extends MemberValue { MemberValue type; MemberValue[] values; /** * Constructs an array. The initial value or type are not specified. */ public ArrayMemberValue(ConstPool cp) { super('[', cp); type = null; values = null; } /** * Constructs an array. The initial value is not specified. * * @param t the type of the array elements. */ public ArrayMemberValue(MemberValue t, ConstPool cp) { super('[', cp); type = t; values = null; } @Override Object getValue(ClassLoader cl, ClassPool cp, Method method) throws ClassNotFoundException {<FILL_FUNCTION_BODY>} @Override Class<?> getType(ClassLoader cl) throws ClassNotFoundException { if (type == null) throw new ClassNotFoundException("no array type specified"); Object a = Array.newInstance(type.getType(cl), 0); return a.getClass(); } /** * Obtains the type of the elements. * * @return null if the type is not specified. */ public MemberValue getType() { return type; } /** * Obtains the elements of the array. */ public MemberValue[] getValue() { return values; } /** * Sets the elements of the array. */ public void setValue(MemberValue[] elements) { values = elements; if (elements != null && elements.length > 0) type = elements[0]; } /** * Obtains the string representation of this object. */ @Override public String toString() { StringBuffer buf = new StringBuffer("{"); if (values != null) { for (int i = 0; i < values.length; i++) { buf.append(values[i].toString()); if (i + 1 < values.length) buf.append(", "); } } buf.append("}"); return buf.toString(); } /** * Writes the value. */ @Override public void write(AnnotationsWriter writer) throws IOException { int num = values == null ? 0 : values.length; writer.arrayValue(num); for (int i = 0; i < num; ++i) values[i].write(writer); } /** * Accepts a visitor. */ @Override public void accept(MemberValueVisitor visitor) { visitor.visitArrayMemberValue(this); } }
if (values == null) throw new ClassNotFoundException( "no array elements found: " + method.getName()); int size = values.length; Class<?> clazz; if (type == null) { clazz = method.getReturnType().getComponentType(); if (clazz == null || size > 0) throw new ClassNotFoundException("broken array type: " + method.getName()); } else clazz = type.getType(cl); Object a = Array.newInstance(clazz, size); for (int i = 0; i < size; i++) Array.set(a, i, values[i].getValue(cl, cp, method)); return a;
698
188
886
<methods>public abstract void accept(org.hotswap.agent.javassist.bytecode.annotation.MemberValueVisitor) ,public abstract void write(org.hotswap.agent.javassist.bytecode.annotation.AnnotationsWriter) throws java.io.IOException<variables>org.hotswap.agent.javassist.bytecode.ConstPool cp,char tag
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/annotation/ClassMemberValue.java
ClassMemberValue
getValue
class ClassMemberValue extends MemberValue { int valueIndex; /** * Constructs a class value. The initial value is specified * by the constant pool entry at the given index. * * @param index the index of a CONSTANT_Utf8_info structure. */ public ClassMemberValue(int index, ConstPool cp) { super('c', cp); this.valueIndex = index; } /** * Constructs a class value. * * @param className the initial value. */ public ClassMemberValue(String className, ConstPool cp) { super('c', cp); setValue(className); } /** * Constructs a class value. * The initial value is java.lang.Class. */ public ClassMemberValue(ConstPool cp) { super('c', cp); setValue("java.lang.Class"); } @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) throws ClassNotFoundException { final String classname = getValue(); if (classname.equals("void")) return void.class; else if (classname.equals("int")) return int.class; else if (classname.equals("byte")) return byte.class; else if (classname.equals("long")) return long.class; else if (classname.equals("double")) return double.class; else if (classname.equals("float")) return float.class; else if (classname.equals("char")) return char.class; else if (classname.equals("short")) return short.class; else if (classname.equals("boolean")) return boolean.class; else return loadClass(cl, classname); } @Override Class<?> getType(ClassLoader cl) throws ClassNotFoundException { return loadClass(cl, "java.lang.Class"); } /** * Obtains the value of the member. * * @return fully-qualified class name. */ public String getValue() {<FILL_FUNCTION_BODY>} /** * Sets the value of the member. * * @param newClassName fully-qualified class name. */ public void setValue(String newClassName) { String setTo = Descriptor.of(newClassName); valueIndex = cp.addUtf8Info(setTo); } /** * Obtains the string representation of this object. */ @Override public String toString() { return getValue().replace('$', '.') + ".class"; } /** * Writes the value. */ @Override public void write(AnnotationsWriter writer) throws IOException { writer.classInfoIndex(cp.getUtf8Info(valueIndex)); } /** * Accepts a visitor. */ @Override public void accept(MemberValueVisitor visitor) { visitor.visitClassMemberValue(this); } }
String v = cp.getUtf8Info(valueIndex); try { return SignatureAttribute.toTypeSignature(v).jvmTypeName(); } catch (BadBytecode e) { throw new RuntimeException(e); }
795
64
859
<methods>public abstract void accept(org.hotswap.agent.javassist.bytecode.annotation.MemberValueVisitor) ,public abstract void write(org.hotswap.agent.javassist.bytecode.annotation.AnnotationsWriter) throws java.io.IOException<variables>org.hotswap.agent.javassist.bytecode.ConstPool cp,char tag
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/annotation/EnumMemberValue.java
EnumMemberValue
getValue
class EnumMemberValue extends MemberValue { int typeIndex, valueIndex; /** * Constructs an enum constant value. The initial value is specified * by the constant pool entries at the given indexes. * * @param type the index of a CONSTANT_Utf8_info structure * representing the enum type. * @param value the index of a CONSTANT_Utf8_info structure. * representing the enum value. */ public EnumMemberValue(int type, int value, ConstPool cp) { super('e', cp); this.typeIndex = type; this.valueIndex = value; } /** * Constructs an enum constant value. * The initial value is not specified. */ public EnumMemberValue(ConstPool cp) { super('e', cp); typeIndex = valueIndex = 0; } @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) throws ClassNotFoundException {<FILL_FUNCTION_BODY>} @Override Class<?> getType(ClassLoader cl) throws ClassNotFoundException { return loadClass(cl, getType()); } /** * Obtains the enum type name. * * @return a fully-qualified type name. */ public String getType() { return Descriptor.toClassName(cp.getUtf8Info(typeIndex)); } /** * Changes the enum type name. * * @param typename a fully-qualified type name. */ public void setType(String typename) { typeIndex = cp.addUtf8Info(Descriptor.of(typename)); } /** * Obtains the name of the enum constant value. */ public String getValue() { return cp.getUtf8Info(valueIndex); } /** * Changes the name of the enum constant value. */ public void setValue(String name) { valueIndex = cp.addUtf8Info(name); } @Override public String toString() { return getType() + "." + getValue(); } /** * Writes the value. */ @Override public void write(AnnotationsWriter writer) throws IOException { writer.enumConstValue(cp.getUtf8Info(typeIndex), getValue()); } /** * Accepts a visitor. */ @Override public void accept(MemberValueVisitor visitor) { visitor.visitEnumMemberValue(this); } }
try { return getType(cl).getField(getValue()).get(null); } catch (NoSuchFieldException e) { throw new ClassNotFoundException(getType() + "." + getValue()); } catch (IllegalAccessException e) { throw new ClassNotFoundException(getType() + "." + getValue()); }
673
91
764
<methods>public abstract void accept(org.hotswap.agent.javassist.bytecode.annotation.MemberValueVisitor) ,public abstract void write(org.hotswap.agent.javassist.bytecode.annotation.AnnotationsWriter) throws java.io.IOException<variables>org.hotswap.agent.javassist.bytecode.ConstPool cp,char tag
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/annotation/MemberValue.java
MemberValue
loadClass
class MemberValue { ConstPool cp; char tag; MemberValue(char tag, ConstPool cp) { this.cp = cp; this.tag = tag; } /** * Returns the value. If the value type is a primitive type, the * returned value is boxed. */ abstract Object getValue(ClassLoader cl, ClassPool cp, Method m) throws ClassNotFoundException; abstract Class<?> getType(ClassLoader cl) throws ClassNotFoundException; static Class<?> loadClass(ClassLoader cl, String classname) throws ClassNotFoundException, NoSuchClassError {<FILL_FUNCTION_BODY>} private static String convertFromArray(String classname) { int index = classname.indexOf("[]"); if (index != -1) { String rawType = classname.substring(0, index); StringBuffer sb = new StringBuffer(Descriptor.of(rawType)); while (index != -1) { sb.insert(0, "["); index = classname.indexOf("[]", index + 1); } return sb.toString().replace('/', '.'); } return classname; } /** * Accepts a visitor. */ public abstract void accept(MemberValueVisitor visitor); /** * Writes the value. */ public abstract void write(AnnotationsWriter w) throws IOException; }
try { return Class.forName(convertFromArray(classname), true, cl); } catch (LinkageError e) { throw new NoSuchClassError(classname, e); }
370
56
426
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/stackmap/TypeData.java
ClassName
getArrayType
class ClassName extends TypeData { private String name; // dot separated. public ClassName(String n) { name = n; } @Override public String getName() { return name; } @Override public BasicType isBasicType() { return null; } @Override public boolean is2WordType() { return false; } @Override public int getTypeTag() { return StackMapTable.OBJECT; } @Override public int getTypeData(ConstPool cp) { return cp.addClassInfo(getName()); } @Override public boolean eq(TypeData d) { return name.equals(d.getName()); } @Override public void setType(String typeName, ClassPool cp) throws BadBytecode {} @Override public TypeData getArrayType(int dim) throws NotFoundException {<FILL_FUNCTION_BODY>} @Override String toString2(Set<TypeData> set) { return name; } }
if (dim == 0) return this; else if (dim > 0) { char[] dimType = new char[dim]; for (int i = 0; i < dim; i++) dimType[i] = '['; String elementType = getName(); if (elementType.charAt(0) != '[') elementType = "L" + elementType.replace('.', '/') + ";"; return new ClassName(new String(dimType) + elementType); } else { for (int i = 0; i < -dim; i++) if (name.charAt(i) != '[') throw new NotFoundException("no " + dim + " dimensional array type: " + getName()); char type = name.charAt(-dim); if (type == '[') return new ClassName(name.substring(-dim)); else if (type == 'L') return new ClassName(name.substring(-dim + 1, name.length() - 1).replace('/', '.')); else if (type == TypeTag.DOUBLE.decodedName) return TypeTag.DOUBLE; else if (type == TypeTag.FLOAT.decodedName) return TypeTag.FLOAT; else if (type == TypeTag.LONG.decodedName) return TypeTag.LONG; else return TypeTag.INTEGER; }
268
366
634
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/stackmap/TypedBlock.java
Maker
initFirstBlock
class Maker extends BasicBlock.Maker { @Override protected BasicBlock makeBlock(int pos) { return new TypedBlock(pos); } @Override protected BasicBlock[] makeArray(int size) { return new TypedBlock[size]; } } /** * Initializes the first block by the given method descriptor. * * @param block the first basic block that this method initializes. * @param className a dot-separated fully qualified class name. * For example, <code>javassist.bytecode.stackmap.BasicBlock</code>. * @param methodDesc method descriptor. * @param isStatic true if the method is a static method. * @param isConstructor true if the method is a constructor. */ void initFirstBlock(int maxStack, int maxLocals, String className, String methodDesc, boolean isStatic, boolean isConstructor) throws BadBytecode {<FILL_FUNCTION_BODY>
if (methodDesc.charAt(0) != '(') throw new BadBytecode("no method descriptor: " + methodDesc); stackTop = 0; stackTypes = TypeData.make(maxStack); TypeData[] locals = TypeData.make(maxLocals); if (isConstructor) locals[0] = new TypeData.UninitThis(className); else if (!isStatic) locals[0] = new TypeData.ClassName(className); int n = isStatic ? -1 : 0; int i = 1; try { while ((i = descToTag(methodDesc, i, ++n, locals)) > 0) if (locals[n].is2WordType()) locals[++n] = TypeTag.TOP; } catch (StringIndexOutOfBoundsException e) { throw new BadBytecode("bad method descriptor: " + methodDesc); } numLocals = n; localsTypes = locals;
256
253
509
<methods>public static org.hotswap.agent.javassist.bytecode.stackmap.BasicBlock find(org.hotswap.agent.javassist.bytecode.stackmap.BasicBlock[], int) throws org.hotswap.agent.javassist.bytecode.BadBytecode,public java.lang.String toString() <variables>protected org.hotswap.agent.javassist.bytecode.stackmap.BasicBlock[] exit,protected int incoming,protected int length,protected int position,protected boolean stop,protected org.hotswap.agent.javassist.bytecode.stackmap.BasicBlock.Catch toCatch
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/MemberResolver.java
Method
compareSignature
class Method { public CtClass declaring; public MethodInfo info; public int notmatch; public Method(CtClass c, MethodInfo i, int n) { declaring = c; info = i; notmatch = n; } /** * Returns true if the invoked method is static. */ public boolean isStatic() { int acc = info.getAccessFlags(); return (acc & AccessFlag.STATIC) != 0; } } public Method lookupMethod(CtClass clazz, CtClass currentClass, MethodInfo current, String methodName, int[] argTypes, int[] argDims, String[] argClassNames) throws CompileError { Method maybe = null; // to enable the creation of a recursively called method if (current != null && clazz == currentClass) if (current.getName().equals(methodName)) { int res = compareSignature(current.getDescriptor(), argTypes, argDims, argClassNames); if (res != NO) { Method r = new Method(clazz, current, res); if (res == YES) return r; maybe = r; } } Method m = lookupMethod(clazz, methodName, argTypes, argDims, argClassNames, maybe != null); if (m != null) return m; return maybe; } private Method lookupMethod(CtClass clazz, String methodName, int[] argTypes, int[] argDims, String[] argClassNames, boolean onlyExact) throws CompileError { Method maybe = null; ClassFile cf = clazz.getClassFile2(); // If the class is an array type, the class file is null. // If so, search the super class java.lang.Object for clone() etc. if (cf != null) { List<MethodInfo> list = cf.getMethods(); for (MethodInfo minfo:list) { if (minfo.getName().equals(methodName) && (minfo.getAccessFlags() & AccessFlag.BRIDGE) == 0) { int res = compareSignature(minfo.getDescriptor(), argTypes, argDims, argClassNames); if (res != NO) { Method r = new Method(clazz, minfo, res); if (res == YES) return r; else if (maybe == null || maybe.notmatch > res) maybe = r; } } } } if (onlyExact) maybe = null; else if (maybe != null) return maybe; int mod = clazz.getModifiers(); boolean isIntf = Modifier.isInterface(mod); try { // skip searching java.lang.Object if clazz is an interface type. if (!isIntf) { CtClass pclazz = clazz.getSuperclass(); if (pclazz != null) { Method r = lookupMethod(pclazz, methodName, argTypes, argDims, argClassNames, onlyExact); if (r != null) return r; } } } catch (NotFoundException e) {} try { CtClass[] ifs = clazz.getInterfaces(); for (CtClass intf:ifs) { Method r = lookupMethod(intf, methodName, argTypes, argDims, argClassNames, onlyExact); if (r != null) return r; } if (isIntf) { // finally search java.lang.Object. CtClass pclazz = clazz.getSuperclass(); if (pclazz != null) { Method r = lookupMethod(pclazz, methodName, argTypes, argDims, argClassNames, onlyExact); if (r != null) return r; } } } catch (NotFoundException e) {} return maybe; } private static final int YES = 0; private static final int NO = -1; /* * Returns YES if actual parameter types matches the given signature. * * argTypes, argDims, and argClassNames represent actual parameters. * * This method does not correctly implement the Java method dispatch * algorithm. * * If some of the parameter types exactly match but others are subtypes of * the corresponding type in the signature, this method returns the number * of parameter types that do not exactly match. */ private int compareSignature(String desc, int[] argTypes, int[] argDims, String[] argClassNames) throws CompileError {<FILL_FUNCTION_BODY>
int result = YES; int i = 1; int nArgs = argTypes.length; if (nArgs != Descriptor.numOfParameters(desc)) return NO; int len = desc.length(); for (int n = 0; i < len; ++n) { char c = desc.charAt(i++); if (c == ')') return (n == nArgs ? result : NO); else if (n >= nArgs) return NO; int dim = 0; while (c == '[') { ++dim; c = desc.charAt(i++); } if (argTypes[n] == NULL) { if (dim == 0 && c != 'L') return NO; if (c == 'L') i = desc.indexOf(';', i) + 1; } else if (argDims[n] != dim) { if (!(dim == 0 && c == 'L' && desc.startsWith("java/lang/Object;", i))) return NO; // if the thread reaches here, c must be 'L'. i = desc.indexOf(';', i) + 1; result++; if (i <= 0) return NO; // invalid descriptor? } else if (c == 'L') { // not compare int j = desc.indexOf(';', i); if (j < 0 || argTypes[n] != CLASS) return NO; String cname = desc.substring(i, j); if (!cname.equals(argClassNames[n])) { CtClass clazz = lookupClassByJvmName(argClassNames[n]); try { if (clazz.subtypeOf(lookupClassByJvmName(cname))) result++; else return NO; } catch (NotFoundException e) { result++; // should be NO? } } i = j + 1; } else { int t = descToType(c); int at = argTypes[n]; if (t != at) if (t == INT && (at == SHORT || at == BYTE || at == CHAR)) result++; else return NO; } } return NO;
1,231
603
1,834
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/SymbolTable.java
SymbolTable
lookup
class SymbolTable extends HashMap<String,Declarator> { /** default serialVersionUID */ private static final long serialVersionUID = 1L; private SymbolTable parent; public SymbolTable() { this(null); } public SymbolTable(SymbolTable p) { super(); parent = p; } public SymbolTable getParent() { return parent; } public Declarator lookup(String name) {<FILL_FUNCTION_BODY>} public void append(String name, Declarator value) { put(name, value); } }
Declarator found = get(name); if (found == null && parent != null) return parent.lookup(name); return found;
149
42
191
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public void <init>(int, float) ,public void clear() ,public java.lang.Object clone() ,public org.hotswap.agent.javassist.compiler.ast.Declarator compute(java.lang.String, BiFunction<? super java.lang.String,? super org.hotswap.agent.javassist.compiler.ast.Declarator,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public org.hotswap.agent.javassist.compiler.ast.Declarator computeIfAbsent(java.lang.String, Function<? super java.lang.String,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public org.hotswap.agent.javassist.compiler.ast.Declarator computeIfPresent(java.lang.String, BiFunction<? super java.lang.String,? super org.hotswap.agent.javassist.compiler.ast.Declarator,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,org.hotswap.agent.javassist.compiler.ast.Declarator>> entrySet() ,public void forEach(BiConsumer<? super java.lang.String,? super org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public org.hotswap.agent.javassist.compiler.ast.Declarator get(java.lang.Object) ,public org.hotswap.agent.javassist.compiler.ast.Declarator getOrDefault(java.lang.Object, org.hotswap.agent.javassist.compiler.ast.Declarator) ,public boolean isEmpty() ,public Set<java.lang.String> keySet() ,public org.hotswap.agent.javassist.compiler.ast.Declarator merge(java.lang.String, org.hotswap.agent.javassist.compiler.ast.Declarator, BiFunction<? super org.hotswap.agent.javassist.compiler.ast.Declarator,? super org.hotswap.agent.javassist.compiler.ast.Declarator,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public org.hotswap.agent.javassist.compiler.ast.Declarator put(java.lang.String, org.hotswap.agent.javassist.compiler.ast.Declarator) ,public void putAll(Map<? extends java.lang.String,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public org.hotswap.agent.javassist.compiler.ast.Declarator putIfAbsent(java.lang.String, org.hotswap.agent.javassist.compiler.ast.Declarator) ,public org.hotswap.agent.javassist.compiler.ast.Declarator remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public org.hotswap.agent.javassist.compiler.ast.Declarator replace(java.lang.String, org.hotswap.agent.javassist.compiler.ast.Declarator) ,public boolean replace(java.lang.String, org.hotswap.agent.javassist.compiler.ast.Declarator, org.hotswap.agent.javassist.compiler.ast.Declarator) ,public void replaceAll(BiFunction<? super java.lang.String,? super org.hotswap.agent.javassist.compiler.ast.Declarator,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public int size() ,public Collection<org.hotswap.agent.javassist.compiler.ast.Declarator> values() <variables>static final int DEFAULT_INITIAL_CAPACITY,static final float DEFAULT_LOAD_FACTOR,static final int MAXIMUM_CAPACITY,static final int MIN_TREEIFY_CAPACITY,static final int TREEIFY_THRESHOLD,static final int UNTREEIFY_THRESHOLD,transient Set<Entry<java.lang.String,org.hotswap.agent.javassist.compiler.ast.Declarator>> entrySet,final float loadFactor,transient int modCount,private static final long serialVersionUID,transient int size,transient Node<java.lang.String,org.hotswap.agent.javassist.compiler.ast.Declarator>[] table,int threshold
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/ASTList.java
ASTList
toString
class ASTList extends ASTree { /** default serialVersionUID */ private static final long serialVersionUID = 1L; private ASTree left; private ASTList right; public ASTList(ASTree _head, ASTList _tail) { left = _head; right = _tail; } public ASTList(ASTree _head) { left = _head; right = null; } public static ASTList make(ASTree e1, ASTree e2, ASTree e3) { return new ASTList(e1, new ASTList(e2, new ASTList(e3))); } @Override public ASTree getLeft() { return left; } @Override public ASTree getRight() { return right; } @Override public void setLeft(ASTree _left) { left = _left; } @Override public void setRight(ASTree _right) { right = (ASTList)_right; } /** * Returns the car part of the list. */ public ASTree head() { return left; } public void setHead(ASTree _head) { left = _head; } /** * Returns the cdr part of the list. */ public ASTList tail() { return right; } public void setTail(ASTList _tail) { right = _tail; } @Override public void accept(Visitor v) throws CompileError { v.atASTList(this); } @Override public String toString() {<FILL_FUNCTION_BODY>} /** * Returns the number of the elements in this list. */ public int length() { return length(this); } public static int length(ASTList list) { if (list == null) return 0; int n = 0; while (list != null) { list = list.right; ++n; } return n; } /** * Returns a sub list of the list. The sub list begins with the * n-th element of the list. * * @param nth zero or more than zero. */ public ASTList sublist(int nth) { ASTList list = this; while (nth-- > 0) list = list.right; return list; } /** * Substitutes <code>newObj</code> for <code>oldObj</code> in the * list. */ public boolean subst(ASTree newObj, ASTree oldObj) { for (ASTList list = this; list != null; list = list.right) if (list.left == oldObj) { list.left = newObj; return true; } return false; } /** * Appends an object to a list. */ public static ASTList append(ASTList a, ASTree b) { return concat(a, new ASTList(b)); } /** * Concatenates two lists. */ public static ASTList concat(ASTList a, ASTList b) { if (a == null) return b; ASTList list = a; while (list.right != null) list = list.right; list.right = b; return a; } }
StringBuffer sbuf = new StringBuffer(); sbuf.append("(<"); sbuf.append(getTag()); sbuf.append('>'); ASTList list = this; while (list != null) { sbuf.append(' '); ASTree a = list.left; sbuf.append(a == null ? "<null>" : a.toString()); list = list.right; } sbuf.append(')'); return sbuf.toString();
911
132
1,043
<methods>public non-sealed void <init>() ,public abstract void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public java.lang.String toString() <variables>private static final long serialVersionUID
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/ASTree.java
ASTree
toString
class ASTree implements Serializable { /** default serialVersionUID */ private static final long serialVersionUID = 1L; public ASTree getLeft() { return null; } public ASTree getRight() { return null; } public void setLeft(ASTree _left) {} public void setRight(ASTree _right) {} /** * Is a method for the visitor pattern. It calls * <code>atXXX()</code> on the given visitor, where * <code>XXX</code> is the class name of the node object. */ public abstract void accept(Visitor v) throws CompileError; @Override public String toString() {<FILL_FUNCTION_BODY>} /** * Returns the type of this node. This method is used by * <code>toString()</code>. */ protected String getTag() { String name = getClass().getName(); return name.substring(name.lastIndexOf('.') + 1); } }
StringBuffer sbuf = new StringBuffer(); sbuf.append('<'); sbuf.append(getTag()); sbuf.append('>'); return sbuf.toString();
268
50
318
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/Declarator.java
Declarator
astToClassName
class Declarator extends ASTList implements TokenId { /** default serialVersionUID */ private static final long serialVersionUID = 1L; protected int varType; protected int arrayDim; protected int localVar; protected String qualifiedClass; // JVM-internal representation public Declarator(int type, int dim) { super(null); varType = type; arrayDim = dim; localVar = -1; qualifiedClass = null; } public Declarator(ASTList className, int dim) { super(null); varType = CLASS; arrayDim = dim; localVar = -1; qualifiedClass = astToClassName(className, '/'); } /* For declaring a pre-defined? local variable. */ public Declarator(int type, String jvmClassName, int dim, int var, Symbol sym) { super(null); varType = type; arrayDim = dim; localVar = var; qualifiedClass = jvmClassName; setLeft(sym); append(this, null); // initializer } public Declarator make(Symbol sym, int dim, ASTree init) { Declarator d = new Declarator(this.varType, this.arrayDim + dim); d.qualifiedClass = this.qualifiedClass; d.setLeft(sym); append(d, init); return d; } /* Returns CLASS, BOOLEAN, BYTE, CHAR, SHORT, INT, LONG, FLOAT, * or DOUBLE (or VOID) */ public int getType() { return varType; } public int getArrayDim() { return arrayDim; } public void addArrayDim(int d) { arrayDim += d; } public String getClassName() { return qualifiedClass; } public void setClassName(String s) { qualifiedClass = s; } public Symbol getVariable() { return (Symbol)getLeft(); } public void setVariable(Symbol sym) { setLeft(sym); } public ASTree getInitializer() { ASTList t = tail(); if (t != null) return t.head(); return null; } public void setLocalVar(int n) { localVar = n; } public int getLocalVar() { return localVar; } @Override public String getTag() { return "decl"; } @Override public void accept(Visitor v) throws CompileError { v.atDeclarator(this); } public static String astToClassName(ASTList name, char sep) { if (name == null) return null; StringBuffer sbuf = new StringBuffer(); astToClassName(sbuf, name, sep); return sbuf.toString(); } private static void astToClassName(StringBuffer sbuf, ASTList name, char sep) {<FILL_FUNCTION_BODY>} }
for (;;) { ASTree h = name.head(); if (h instanceof Symbol) sbuf.append(((Symbol)h).get()); else if (h instanceof ASTList) astToClassName(sbuf, (ASTList)h, sep); name = name.tail(); if (name == null) break; sbuf.append(sep); }
775
105
880
<methods>public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public static org.hotswap.agent.javassist.compiler.ast.ASTList append(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList concat(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public org.hotswap.agent.javassist.compiler.ast.ASTree head() ,public int length() ,public static int length(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList make(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setHead(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setTail(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTList sublist(int) ,public boolean subst(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public org.hotswap.agent.javassist.compiler.ast.ASTList tail() ,public java.lang.String toString() <variables>private org.hotswap.agent.javassist.compiler.ast.ASTree left,private org.hotswap.agent.javassist.compiler.ast.ASTList right,private static final long serialVersionUID
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/DoubleConst.java
DoubleConst
compute
class DoubleConst extends ASTree { /** default serialVersionUID */ private static final long serialVersionUID = 1L; protected double value; protected int type; public DoubleConst(double v, int tokenId) { value = v; type = tokenId; } public double get() { return value; } public void set(double v) { value = v; } /* Returns DoubleConstant or FloatConstant */ public int getType() { return type; } @Override public String toString() { return Double.toString(value); } @Override public void accept(Visitor v) throws CompileError { v.atDoubleConst(this); } public ASTree compute(int op, ASTree right) { if (right instanceof IntConst) return compute0(op, (IntConst)right); else if (right instanceof DoubleConst) return compute0(op, (DoubleConst)right); else return null; } private DoubleConst compute0(int op, DoubleConst right) { int newType; if (this.type == TokenId.DoubleConstant || right.type == TokenId.DoubleConstant) newType = TokenId.DoubleConstant; else newType = TokenId.FloatConstant; return compute(op, this.value, right.value, newType); } private DoubleConst compute0(int op, IntConst right) { return compute(op, this.value, right.value, this.type); } private static DoubleConst compute(int op, double value1, double value2, int newType) {<FILL_FUNCTION_BODY>} }
double newValue; switch (op) { case '+' : newValue = value1 + value2; break; case '-' : newValue = value1 - value2; break; case '*' : newValue = value1 * value2; break; case '/' : newValue = value1 / value2; break; case '%' : newValue = value1 % value2; break; default : return null; } return new DoubleConst(newValue, newType);
433
149
582
<methods>public non-sealed void <init>() ,public abstract void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public java.lang.String toString() <variables>private static final long serialVersionUID
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/Expr.java
Expr
getName
class Expr extends ASTList implements TokenId { /* operator must be either of: * (unary) +, (unary) -, ++, --, !, ~, * ARRAY, . (dot), MEMBER (static member access). * Otherwise, the object should be an instance of a subclass. */ /** default serialVersionUID */ private static final long serialVersionUID = 1L; protected int operatorId; Expr(int op, ASTree _head, ASTList _tail) { super(_head, _tail); operatorId = op; } Expr(int op, ASTree _head) { super(_head); operatorId = op; } public static Expr make(int op, ASTree oprand1, ASTree oprand2) { return new Expr(op, oprand1, new ASTList(oprand2)); } public static Expr make(int op, ASTree oprand1) { return new Expr(op, oprand1); } public int getOperator() { return operatorId; } public void setOperator(int op) { operatorId = op; } public ASTree oprand1() { return getLeft(); } public void setOprand1(ASTree expr) { setLeft(expr); } public ASTree oprand2() { return getRight().getLeft(); } public void setOprand2(ASTree expr) { getRight().setLeft(expr); } @Override public void accept(Visitor v) throws CompileError { v.atExpr(this); } public String getName() {<FILL_FUNCTION_BODY>} @Override protected String getTag() { return "op:" + getName(); } }
int id = operatorId; if (id < 128) return String.valueOf((char)id); else if (NEQ <= id && id <= ARSHIFT_E) return opNames[id - NEQ]; else if (id == INSTANCEOF) return "instanceof"; else return String.valueOf(id);
482
95
577
<methods>public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public static org.hotswap.agent.javassist.compiler.ast.ASTList append(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList concat(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public org.hotswap.agent.javassist.compiler.ast.ASTree head() ,public int length() ,public static int length(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList make(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setHead(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setTail(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTList sublist(int) ,public boolean subst(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public org.hotswap.agent.javassist.compiler.ast.ASTList tail() ,public java.lang.String toString() <variables>private org.hotswap.agent.javassist.compiler.ast.ASTree left,private org.hotswap.agent.javassist.compiler.ast.ASTList right,private static final long serialVersionUID
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/IntConst.java
IntConst
compute0
class IntConst extends ASTree { /** default serialVersionUID */ private static final long serialVersionUID = 1L; protected long value; protected int type; public IntConst(long v, int tokenId) { value = v; type = tokenId; } public long get() { return value; } public void set(long v) { value = v; } /* Returns IntConstant, CharConstant, or LongConstant. */ public int getType() { return type; } @Override public String toString() { return Long.toString(value); } @Override public void accept(Visitor v) throws CompileError { v.atIntConst(this); } public ASTree compute(int op, ASTree right) { if (right instanceof IntConst) return compute0(op, (IntConst)right); else if (right instanceof DoubleConst) return compute0(op, (DoubleConst)right); else return null; } private IntConst compute0(int op, IntConst right) {<FILL_FUNCTION_BODY>} private DoubleConst compute0(int op, DoubleConst right) { double value1 = this.value; double value2 = right.value; double newValue; switch (op) { case '+' : newValue = value1 + value2; break; case '-' : newValue = value1 - value2; break; case '*' : newValue = value1 * value2; break; case '/' : newValue = value1 / value2; break; case '%' : newValue = value1 % value2; break; default : return null; } return new DoubleConst(newValue, right.type); } }
int type1 = this.type; int type2 = right.type; int newType; if (type1 == TokenId.LongConstant || type2 == TokenId.LongConstant) newType = TokenId.LongConstant; else if (type1 == TokenId.CharConstant && type2 == TokenId.CharConstant) newType = TokenId.CharConstant; else newType = TokenId.IntConstant; long value1 = this.value; long value2 = right.value; long newValue; switch (op) { case '+' : newValue = value1 + value2; break; case '-' : newValue = value1 - value2; break; case '*' : newValue = value1 * value2; break; case '/' : newValue = value1 / value2; break; case '%' : newValue = value1 % value2; break; case '|' : newValue = value1 | value2; break; case '^' : newValue = value1 ^ value2; break; case '&' : newValue = value1 & value2; break; case TokenId.LSHIFT : newValue = value << (int)value2; newType = type1; break; case TokenId.RSHIFT : newValue = value >> (int)value2; newType = type1; break; case TokenId.ARSHIFT : newValue = value >>> (int)value2; newType = type1; break; default : return null; } return new IntConst(newValue, newType);
473
464
937
<methods>public non-sealed void <init>() ,public abstract void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public java.lang.String toString() <variables>private static final long serialVersionUID
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/MethodDecl.java
MethodDecl
isConstructor
class MethodDecl extends ASTList { /** default serialVersionUID */ private static final long serialVersionUID = 1L; public static final String initName = "<init>"; public MethodDecl(ASTree _head, ASTList _tail) { super(_head, _tail); } public boolean isConstructor() {<FILL_FUNCTION_BODY>} public ASTList getModifiers() { return (ASTList)getLeft(); } public Declarator getReturn() { return (Declarator)tail().head(); } public ASTList getParams() { return (ASTList)sublist(2).head(); } public ASTList getThrows() { return (ASTList)sublist(3).head(); } public Stmnt getBody() { return (Stmnt)sublist(4).head(); } @Override public void accept(Visitor v) throws CompileError { v.atMethodDecl(this); } }
Symbol sym = getReturn().getVariable(); return sym != null && initName.equals(sym.get());
246
31
277
<methods>public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public static org.hotswap.agent.javassist.compiler.ast.ASTList append(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList concat(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public org.hotswap.agent.javassist.compiler.ast.ASTree head() ,public int length() ,public static int length(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList make(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setHead(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setTail(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTList sublist(int) ,public boolean subst(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public org.hotswap.agent.javassist.compiler.ast.ASTList tail() ,public java.lang.String toString() <variables>private org.hotswap.agent.javassist.compiler.ast.ASTree left,private org.hotswap.agent.javassist.compiler.ast.ASTList right,private static final long serialVersionUID
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/NewExpr.java
NewExpr
getInitializer
class NewExpr extends ASTList implements TokenId { /** default serialVersionUID */ private static final long serialVersionUID = 1L; protected boolean newArray; protected int arrayType; public NewExpr(ASTList className, ASTList args) { super(className, new ASTList(args)); newArray = false; arrayType = CLASS; } public NewExpr(int type, ASTList arraySize, ArrayInit init) { super(null, new ASTList(arraySize)); newArray = true; arrayType = type; if (init != null) append(this, init); } public static NewExpr makeObjectArray(ASTList className, ASTList arraySize, ArrayInit init) { NewExpr e = new NewExpr(className, arraySize); e.newArray = true; if (init != null) append(e, init); return e; } public boolean isArray() { return newArray; } /* TokenId.CLASS, TokenId.INT, ... */ public int getArrayType() { return arrayType; } public ASTList getClassName() { return (ASTList)getLeft(); } public ASTList getArguments() { return (ASTList)getRight().getLeft(); } public ASTList getArraySize() { return getArguments(); } public ArrayInit getInitializer() {<FILL_FUNCTION_BODY>} @Override public void accept(Visitor v) throws CompileError { v.atNewExpr(this); } @Override protected String getTag() { return newArray ? "new[]" : "new"; } }
ASTree t = getRight().getRight(); if (t == null) return null; return (ArrayInit)t.getLeft();
435
41
476
<methods>public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public static org.hotswap.agent.javassist.compiler.ast.ASTList append(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList concat(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public org.hotswap.agent.javassist.compiler.ast.ASTree head() ,public int length() ,public static int length(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList make(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setHead(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setTail(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTList sublist(int) ,public boolean subst(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public org.hotswap.agent.javassist.compiler.ast.ASTList tail() ,public java.lang.String toString() <variables>private org.hotswap.agent.javassist.compiler.ast.ASTree left,private org.hotswap.agent.javassist.compiler.ast.ASTList right,private static final long serialVersionUID
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/Pair.java
Pair
toString
class Pair extends ASTree { /** default serialVersionUID */ private static final long serialVersionUID = 1L; protected ASTree left, right; public Pair(ASTree _left, ASTree _right) { left = _left; right = _right; } @Override public void accept(Visitor v) throws CompileError { v.atPair(this); } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public ASTree getLeft() { return left; } @Override public ASTree getRight() { return right; } @Override public void setLeft(ASTree _left) { left = _left; } @Override public void setRight(ASTree _right) { right = _right; } }
StringBuffer sbuf = new StringBuffer(); sbuf.append("(<Pair> "); sbuf.append(left == null ? "<null>" : left.toString()); sbuf.append(" . "); sbuf.append(right == null ? "<null>" : right.toString()); sbuf.append(')'); return sbuf.toString();
217
94
311
<methods>public non-sealed void <init>() ,public abstract void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public java.lang.String toString() <variables>private static final long serialVersionUID
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/Stmnt.java
Stmnt
getTag
class Stmnt extends ASTList implements TokenId { /** default serialVersionUID */ private static final long serialVersionUID = 1L; protected int operatorId; public Stmnt(int op, ASTree _head, ASTList _tail) { super(_head, _tail); operatorId = op; } public Stmnt(int op, ASTree _head) { super(_head); operatorId = op; } public Stmnt(int op) { this(op, null); } public static Stmnt make(int op, ASTree oprand1, ASTree oprand2) { return new Stmnt(op, oprand1, new ASTList(oprand2)); } public static Stmnt make(int op, ASTree op1, ASTree op2, ASTree op3) { return new Stmnt(op, op1, new ASTList(op2, new ASTList(op3))); } @Override public void accept(Visitor v) throws CompileError { v.atStmnt(this); } public int getOperator() { return operatorId; } @Override protected String getTag() {<FILL_FUNCTION_BODY>} }
if (operatorId < 128) return "stmnt:" + (char)operatorId; return "stmnt:" + operatorId;
325
39
364
<methods>public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public static org.hotswap.agent.javassist.compiler.ast.ASTList append(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList concat(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public org.hotswap.agent.javassist.compiler.ast.ASTree head() ,public int length() ,public static int length(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList make(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setHead(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setTail(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTList sublist(int) ,public boolean subst(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public org.hotswap.agent.javassist.compiler.ast.ASTList tail() ,public java.lang.String toString() <variables>private org.hotswap.agent.javassist.compiler.ast.ASTree left,private org.hotswap.agent.javassist.compiler.ast.ASTList right,private static final long serialVersionUID
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformAfter.java
TransformAfter
match2
class TransformAfter extends TransformBefore { public TransformAfter(Transformer next, CtMethod origMethod, CtMethod afterMethod) throws NotFoundException { super(next, origMethod, afterMethod); } @Override protected int match2(int pos, CodeIterator iterator) throws BadBytecode {<FILL_FUNCTION_BODY>} }
iterator.move(pos); iterator.insert(saveCode); iterator.insert(loadCode); int p = iterator.insertGap(3); iterator.setMark(p); iterator.insert(loadCode); pos = iterator.next(); p = iterator.getMark(); iterator.writeByte(iterator.byteAt(pos), p); iterator.write16bit(iterator.u16bitAt(pos + 1), p + 1); iterator.writeByte(INVOKESTATIC, pos); iterator.write16bit(newIndex, pos + 1); iterator.move(p); return iterator.next();
98
178
276
<methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer, org.hotswap.agent.javassist.CtMethod, org.hotswap.agent.javassist.CtMethod) throws org.hotswap.agent.javassist.NotFoundException,public int extraLocals() ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) <variables>protected byte[] loadCode,protected int locals,protected int maxLocals,protected org.hotswap.agent.javassist.CtClass[] parameterTypes,protected byte[] saveCode
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformBefore.java
TransformBefore
match2
class TransformBefore extends TransformCall { protected CtClass[] parameterTypes; protected int locals; protected int maxLocals; protected byte[] saveCode, loadCode; public TransformBefore(Transformer next, CtMethod origMethod, CtMethod beforeMethod) throws NotFoundException { super(next, origMethod, beforeMethod); // override methodDescriptor = origMethod.getMethodInfo2().getDescriptor(); parameterTypes = origMethod.getParameterTypes(); locals = 0; maxLocals = 0; saveCode = loadCode = null; } @Override public void initialize(ConstPool cp, CodeAttribute attr) { super.initialize(cp, attr); locals = 0; maxLocals = attr.getMaxLocals(); saveCode = loadCode = null; } @Override protected int match(int c, int pos, CodeIterator iterator, int typedesc, ConstPool cp) throws BadBytecode { if (newIndex == 0) { String desc = Descriptor.ofParameters(parameterTypes) + 'V'; desc = Descriptor.insertParameter(classname, desc); int nt = cp.addNameAndTypeInfo(newMethodname, desc); int ci = cp.addClassInfo(newClassname); newIndex = cp.addMethodrefInfo(ci, nt); constPool = cp; } if (saveCode == null) makeCode(parameterTypes, cp); return match2(pos, iterator); } protected int match2(int pos, CodeIterator iterator) throws BadBytecode {<FILL_FUNCTION_BODY>} @Override public int extraLocals() { return locals; } protected void makeCode(CtClass[] paramTypes, ConstPool cp) { Bytecode save = new Bytecode(cp, 0, 0); Bytecode load = new Bytecode(cp, 0, 0); int var = maxLocals; int len = (paramTypes == null) ? 0 : paramTypes.length; load.addAload(var); makeCode2(save, load, 0, len, paramTypes, var + 1); save.addAstore(var); saveCode = save.get(); loadCode = load.get(); } private void makeCode2(Bytecode save, Bytecode load, int i, int n, CtClass[] paramTypes, int var) { if (i < n) { int size = load.addLoad(var, paramTypes[i]); makeCode2(save, load, i + 1, n, paramTypes, var + size); save.addStore(var, paramTypes[i]); } else locals = var - maxLocals; } }
iterator.move(pos); iterator.insert(saveCode); iterator.insert(loadCode); int p = iterator.insertGap(3); iterator.writeByte(INVOKESTATIC, p); iterator.write16bit(newIndex, p + 1); iterator.insert(loadCode); return iterator.next();
717
97
814
<methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer, org.hotswap.agent.javassist.CtMethod, org.hotswap.agent.javassist.CtMethod) ,public void <init>(org.hotswap.agent.javassist.convert.Transformer, java.lang.String, org.hotswap.agent.javassist.CtMethod) ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) ,public int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.bytecode.BadBytecode<variables>protected java.lang.String classname,protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,protected java.lang.String methodDescriptor,protected java.lang.String methodname,protected java.lang.String newClassname,protected int newIndex,protected boolean newMethodIsPrivate,protected java.lang.String newMethodname
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformCall.java
TransformCall
transform
class TransformCall extends Transformer { protected String classname, methodname, methodDescriptor; protected String newClassname, newMethodname; protected boolean newMethodIsPrivate; /* cache */ protected int newIndex; protected ConstPool constPool; public TransformCall(Transformer next, CtMethod origMethod, CtMethod substMethod) { this(next, origMethod.getName(), substMethod); classname = origMethod.getDeclaringClass().getName(); } public TransformCall(Transformer next, String oldMethodName, CtMethod substMethod) { super(next); methodname = oldMethodName; methodDescriptor = substMethod.getMethodInfo2().getDescriptor(); classname = newClassname = substMethod.getDeclaringClass().getName(); newMethodname = substMethod.getName(); constPool = null; newMethodIsPrivate = Modifier.isPrivate(substMethod.getModifiers()); } @Override public void initialize(ConstPool cp, CodeAttribute attr) { if (constPool != cp) newIndex = 0; } /** * Modify INVOKEINTERFACE, INVOKESPECIAL, INVOKESTATIC and INVOKEVIRTUAL * so that a different method is invoked. The class name in the operand * of these instructions might be a subclass of the target class specified * by <code>classname</code>. This method transforms the instruction * in that case unless the subclass overrides the target method. */ @Override public int transform(CtClass clazz, int pos, CodeIterator iterator, ConstPool cp) throws BadBytecode {<FILL_FUNCTION_BODY>} private boolean matchClass(String name, ClassPool pool) { if (classname.equals(name)) return true; try { CtClass clazz = pool.get(name); CtClass declClazz = pool.get(classname); if (clazz.subtypeOf(declClazz)) try { CtMethod m = clazz.getMethod(methodname, methodDescriptor); return m.getDeclaringClass().getName().equals(classname); } catch (NotFoundException e) { // maybe the original method has been removed. return true; } } catch (NotFoundException e) { return false; } return false; } protected int match(int c, int pos, CodeIterator iterator, int typedesc, ConstPool cp) throws BadBytecode { if (newIndex == 0) { int nt = cp.addNameAndTypeInfo(cp.addUtf8Info(newMethodname), typedesc); int ci = cp.addClassInfo(newClassname); if (c == INVOKEINTERFACE) newIndex = cp.addInterfaceMethodrefInfo(ci, nt); else { if (newMethodIsPrivate && c == INVOKEVIRTUAL) iterator.writeByte(INVOKESPECIAL, pos); newIndex = cp.addMethodrefInfo(ci, nt); } constPool = cp; } iterator.write16bit(newIndex, pos + 1); return pos; } }
int c = iterator.byteAt(pos); if (c == INVOKEINTERFACE || c == INVOKESPECIAL || c == INVOKESTATIC || c == INVOKEVIRTUAL) { int index = iterator.u16bitAt(pos + 1); String cname = cp.eqMember(methodname, methodDescriptor, index); if (cname != null && matchClass(cname, clazz.getClassPool())) { int ntinfo = cp.getMemberNameAndType(index); pos = match(c, pos, iterator, cp.getNameAndTypeDescriptor(ntinfo), cp); } } return pos;
854
178
1,032
<methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer) ,public void clean() ,public int extraLocals() ,public int extraStack() ,public org.hotswap.agent.javassist.convert.Transformer getNext() ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.CtClass, org.hotswap.agent.javassist.bytecode.MethodInfo) throws org.hotswap.agent.javassist.CannotCompileException,public abstract int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.CannotCompileException, org.hotswap.agent.javassist.bytecode.BadBytecode<variables>private org.hotswap.agent.javassist.convert.Transformer next
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformFieldAccess.java
TransformFieldAccess
transform
class TransformFieldAccess extends Transformer { private String newClassname, newFieldname; private String fieldname; private CtClass fieldClass; private boolean isPrivate; /* cache */ private int newIndex; private ConstPool constPool; public TransformFieldAccess(Transformer next, CtField field, String newClassname, String newFieldname) { super(next); this.fieldClass = field.getDeclaringClass(); this.fieldname = field.getName(); this.isPrivate = Modifier.isPrivate(field.getModifiers()); this.newClassname = newClassname; this.newFieldname = newFieldname; this.constPool = null; } @Override public void initialize(ConstPool cp, CodeAttribute attr) { if (constPool != cp) newIndex = 0; } /** * Modify GETFIELD, GETSTATIC, PUTFIELD, and PUTSTATIC so that * a different field is accessed. The new field must be declared * in a superclass of the class in which the original field is * declared. */ @Override public int transform(CtClass clazz, int pos, CodeIterator iterator, ConstPool cp) {<FILL_FUNCTION_BODY>} }
int c = iterator.byteAt(pos); if (c == GETFIELD || c == GETSTATIC || c == PUTFIELD || c == PUTSTATIC) { int index = iterator.u16bitAt(pos + 1); String typedesc = TransformReadField.isField(clazz.getClassPool(), cp, fieldClass, fieldname, isPrivate, index); if (typedesc != null) { if (newIndex == 0) { int nt = cp.addNameAndTypeInfo(newFieldname, typedesc); newIndex = cp.addFieldrefInfo( cp.addClassInfo(newClassname), nt); constPool = cp; } iterator.write16bit(newIndex, pos + 1); } } return pos;
339
214
553
<methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer) ,public void clean() ,public int extraLocals() ,public int extraStack() ,public org.hotswap.agent.javassist.convert.Transformer getNext() ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.CtClass, org.hotswap.agent.javassist.bytecode.MethodInfo) throws org.hotswap.agent.javassist.CannotCompileException,public abstract int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.CannotCompileException, org.hotswap.agent.javassist.bytecode.BadBytecode<variables>private org.hotswap.agent.javassist.convert.Transformer next
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformNew.java
TransformNew
transform
class TransformNew extends Transformer { private int nested; private String classname, trapClass, trapMethod; public TransformNew(Transformer next, String classname, String trapClass, String trapMethod) { super(next); this.classname = classname; this.trapClass = trapClass; this.trapMethod = trapMethod; } @Override public void initialize(ConstPool cp, CodeAttribute attr) { nested = 0; } /** * Replace a sequence of * NEW classname * DUP * ... * INVOKESPECIAL * with * NOP * NOP * ... * INVOKESTATIC trapMethod in trapClass */ @Override public int transform(CtClass clazz, int pos, CodeIterator iterator, ConstPool cp) throws CannotCompileException {<FILL_FUNCTION_BODY>} private int computeMethodref(int typedesc, ConstPool cp) { int classIndex = cp.addClassInfo(trapClass); int mnameIndex = cp.addUtf8Info(trapMethod); typedesc = cp.addUtf8Info( Descriptor.changeReturnType(classname, cp.getUtf8Info(typedesc))); return cp.addMethodrefInfo(classIndex, cp.addNameAndTypeInfo(mnameIndex, typedesc)); } }
int index; int c = iterator.byteAt(pos); if (c == NEW) { index = iterator.u16bitAt(pos + 1); if (cp.getClassInfo(index).equals(classname)) { if (iterator.byteAt(pos + 3) != DUP) throw new CannotCompileException( "NEW followed by no DUP was found"); iterator.writeByte(NOP, pos); iterator.writeByte(NOP, pos + 1); iterator.writeByte(NOP, pos + 2); iterator.writeByte(NOP, pos + 3); ++nested; StackMapTable smt = (StackMapTable)iterator.get().getAttribute(StackMapTable.tag); if (smt != null) smt.removeNew(pos); StackMap sm = (StackMap)iterator.get().getAttribute(StackMap.tag); if (sm != null) sm.removeNew(pos); } } else if (c == INVOKESPECIAL) { index = iterator.u16bitAt(pos + 1); int typedesc = cp.isConstructor(classname, index); if (typedesc != 0 && nested > 0) { int methodref = computeMethodref(typedesc, cp); iterator.writeByte(INVOKESTATIC, pos); iterator.write16bit(methodref, pos + 1); --nested; } } return pos;
379
397
776
<methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer) ,public void clean() ,public int extraLocals() ,public int extraStack() ,public org.hotswap.agent.javassist.convert.Transformer getNext() ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.CtClass, org.hotswap.agent.javassist.bytecode.MethodInfo) throws org.hotswap.agent.javassist.CannotCompileException,public abstract int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.CannotCompileException, org.hotswap.agent.javassist.bytecode.BadBytecode<variables>private org.hotswap.agent.javassist.convert.Transformer next
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformNewClass.java
TransformNewClass
transform
class TransformNewClass extends Transformer { private int nested; private String classname, newClassName; private int newClassIndex, newMethodNTIndex, newMethodIndex; public TransformNewClass(Transformer next, String classname, String newClassName) { super(next); this.classname = classname; this.newClassName = newClassName; } @Override public void initialize(ConstPool cp, CodeAttribute attr) { nested = 0; newClassIndex = newMethodNTIndex = newMethodIndex = 0; } /** * Modifies a sequence of * NEW classname * DUP * ... * INVOKESPECIAL classname:method */ @Override public int transform(CtClass clazz, int pos, CodeIterator iterator, ConstPool cp) throws CannotCompileException {<FILL_FUNCTION_BODY>} }
int index; int c = iterator.byteAt(pos); if (c == NEW) { index = iterator.u16bitAt(pos + 1); if (cp.getClassInfo(index).equals(classname)) { if (iterator.byteAt(pos + 3) != DUP) throw new CannotCompileException( "NEW followed by no DUP was found"); if (newClassIndex == 0) newClassIndex = cp.addClassInfo(newClassName); iterator.write16bit(newClassIndex, pos + 1); ++nested; } } else if (c == INVOKESPECIAL) { index = iterator.u16bitAt(pos + 1); int typedesc = cp.isConstructor(classname, index); if (typedesc != 0 && nested > 0) { int nt = cp.getMethodrefNameAndType(index); if (newMethodNTIndex != nt) { newMethodNTIndex = nt; newMethodIndex = cp.addMethodrefInfo(newClassIndex, nt); } iterator.write16bit(newMethodIndex, pos + 1); --nested; } } return pos;
246
326
572
<methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer) ,public void clean() ,public int extraLocals() ,public int extraStack() ,public org.hotswap.agent.javassist.convert.Transformer getNext() ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.CtClass, org.hotswap.agent.javassist.bytecode.MethodInfo) throws org.hotswap.agent.javassist.CannotCompileException,public abstract int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.CannotCompileException, org.hotswap.agent.javassist.bytecode.BadBytecode<variables>private org.hotswap.agent.javassist.convert.Transformer next
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformReadField.java
TransformReadField
transform
class TransformReadField extends Transformer { protected String fieldname; protected CtClass fieldClass; protected boolean isPrivate; protected String methodClassname, methodName; public TransformReadField(Transformer next, CtField field, String methodClassname, String methodName) { super(next); this.fieldClass = field.getDeclaringClass(); this.fieldname = field.getName(); this.methodClassname = methodClassname; this.methodName = methodName; this.isPrivate = Modifier.isPrivate(field.getModifiers()); } static String isField(ClassPool pool, ConstPool cp, CtClass fclass, String fname, boolean is_private, int index) { if (!cp.getFieldrefName(index).equals(fname)) return null; try { CtClass c = pool.get(cp.getFieldrefClassName(index)); if (c == fclass || (!is_private && isFieldInSuper(c, fclass, fname))) return cp.getFieldrefType(index); } catch (NotFoundException e) {} return null; } static boolean isFieldInSuper(CtClass clazz, CtClass fclass, String fname) { if (!clazz.subclassOf(fclass)) return false; try { CtField f = clazz.getField(fname); return f.getDeclaringClass() == fclass; } catch (NotFoundException e) {} return false; } @Override public int transform(CtClass tclazz, int pos, CodeIterator iterator, ConstPool cp) throws BadBytecode {<FILL_FUNCTION_BODY>} }
int c = iterator.byteAt(pos); if (c == GETFIELD || c == GETSTATIC) { int index = iterator.u16bitAt(pos + 1); String typedesc = isField(tclazz.getClassPool(), cp, fieldClass, fieldname, isPrivate, index); if (typedesc != null) { if (c == GETSTATIC) { iterator.move(pos); pos = iterator.insertGap(1); // insertGap() may insert 4 bytes. iterator.writeByte(ACONST_NULL, pos); pos = iterator.next(); } String type = "(Ljava/lang/Object;)" + typedesc; int mi = cp.addClassInfo(methodClassname); int methodref = cp.addMethodrefInfo(mi, methodName, type); iterator.writeByte(INVOKESTATIC, pos); iterator.write16bit(methodref, pos + 1); return pos; } } return pos;
450
268
718
<methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer) ,public void clean() ,public int extraLocals() ,public int extraStack() ,public org.hotswap.agent.javassist.convert.Transformer getNext() ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.CtClass, org.hotswap.agent.javassist.bytecode.MethodInfo) throws org.hotswap.agent.javassist.CannotCompileException,public abstract int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.CannotCompileException, org.hotswap.agent.javassist.bytecode.BadBytecode<variables>private org.hotswap.agent.javassist.convert.Transformer next
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformWriteField.java
TransformWriteField
transform
class TransformWriteField extends TransformReadField { public TransformWriteField(Transformer next, CtField field, String methodClassname, String methodName) { super(next, field, methodClassname, methodName); } @Override public int transform(CtClass tclazz, int pos, CodeIterator iterator, ConstPool cp) throws BadBytecode {<FILL_FUNCTION_BODY>} }
int c = iterator.byteAt(pos); if (c == PUTFIELD || c == PUTSTATIC) { int index = iterator.u16bitAt(pos + 1); String typedesc = isField(tclazz.getClassPool(), cp, fieldClass, fieldname, isPrivate, index); if (typedesc != null) { if (c == PUTSTATIC) { CodeAttribute ca = iterator.get(); iterator.move(pos); char c0 = typedesc.charAt(0); if (c0 == 'J' || c0 == 'D') { // long or double // insertGap() may insert 4 bytes. pos = iterator.insertGap(3); iterator.writeByte(ACONST_NULL, pos); iterator.writeByte(DUP_X2, pos + 1); iterator.writeByte(POP, pos + 2); ca.setMaxStack(ca.getMaxStack() + 2); } else { // insertGap() may insert 4 bytes. pos = iterator.insertGap(2); iterator.writeByte(ACONST_NULL, pos); iterator.writeByte(SWAP, pos + 1); ca.setMaxStack(ca.getMaxStack() + 1); } pos = iterator.next(); } int mi = cp.addClassInfo(methodClassname); String type = "(Ljava/lang/Object;" + typedesc + ")V"; int methodref = cp.addMethodrefInfo(mi, methodName, type); iterator.writeByte(INVOKESTATIC, pos); iterator.write16bit(methodref, pos + 1); } } return pos;
114
453
567
<methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer, org.hotswap.agent.javassist.CtField, java.lang.String, java.lang.String) ,public int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.bytecode.BadBytecode<variables>protected org.hotswap.agent.javassist.CtClass fieldClass,protected java.lang.String fieldname,protected boolean isPrivate,protected java.lang.String methodClassname,protected java.lang.String methodName
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/expr/Cast.java
Cast
replace
class Cast extends Expr { /** * Undocumented constructor. Do not use; internal-use only. */ protected Cast(int pos, CodeIterator i, CtClass declaring, MethodInfo m) { super(pos, i, declaring, m); } /** * Returns the method or constructor containing the type cast * expression represented by this object. */ @Override public CtBehavior where() { return super.where(); } /** * Returns the line number of the source line containing the * type-cast expression. * * @return -1 if this information is not available. */ @Override public int getLineNumber() { return super.getLineNumber(); } /** * Returns the source file containing the type-cast expression. * * @return null if this information is not available. */ @Override public String getFileName() { return super.getFileName(); } /** * Returns the <code>CtClass</code> object representing * the type specified by the cast. */ public CtClass getType() throws NotFoundException { ConstPool cp = getConstPool(); int pos = currentPos; int index = iterator.u16bitAt(pos + 1); String name = cp.getClassInfo(index); return thisClass.getClassPool().getCtClass(name); } /** * Returns the list of exceptions that the expression may throw. * This list includes both the exceptions that the try-catch statements * including the expression can catch and the exceptions that * the throws declaration allows the method to throw. */ @Override public CtClass[] mayThrow() { return super.mayThrow(); } /** * Replaces the explicit cast operator with the bytecode derived from * the given source text. * * <p>$0 is available but the value is <code>null</code>. * * @param statement a Java statement except try-catch. */ @Override public void replace(String statement) throws CannotCompileException {<FILL_FUNCTION_BODY>} /* <type> $proceed(Object obj) */ static class ProceedForCast implements ProceedHandler { int index; CtClass retType; ProceedForCast(int i, CtClass t) { index = i; retType = t; } @Override public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args) throws CompileError { if (gen.getMethodArgsLength(args) != 1) throw new CompileError(Javac.proceedName + "() cannot take more than one parameter " + "for cast"); gen.atMethodArgs(args, new int[1], new int[1], new String[1]); bytecode.addOpcode(Opcode.CHECKCAST); bytecode.addIndex(index); gen.setType(retType); } @Override public void setReturnType(JvstTypeChecker c, ASTList args) throws CompileError { c.atMethodArgs(args, new int[1], new int[1], new String[1]); c.setType(retType); } } }
thisClass.getClassFile(); // to call checkModify(). @SuppressWarnings("unused") ConstPool constPool = getConstPool(); int pos = currentPos; int index = iterator.u16bitAt(pos + 1); Javac jc = new Javac(thisClass); ClassPool cp = thisClass.getClassPool(); CodeAttribute ca = iterator.get(); try { CtClass[] params = new CtClass[] { cp.get(javaLangObject) }; CtClass retType = getType(); int paramVar = ca.getMaxLocals(); jc.recordParams(javaLangObject, params, true, paramVar, withinStatic()); int retVar = jc.recordReturnType(retType, true); jc.recordProceed(new ProceedForCast(index, retType)); /* Is $_ included in the source code? */ checkResultValue(retType, statement); Bytecode bytecode = jc.getBytecode(); storeStack(params, true, paramVar, bytecode); jc.recordLocalVariables(ca, pos); bytecode.addConstZero(retType); bytecode.addStore(retVar, retType); // initialize $_ jc.compileStmnt(statement); bytecode.addLoad(retVar, retType); replace0(pos, bytecode, 3); } catch (CompileError e) { throw new CannotCompileException(e); } catch (NotFoundException e) { throw new CannotCompileException(e); } catch (BadBytecode e) { throw new CannotCompileException("broken method"); }
865
439
1,304
<methods>public org.hotswap.agent.javassist.CtClass getEnclosingClass() ,public java.lang.String getFileName() ,public int getLineNumber() ,public int indexOfBytecode() ,public org.hotswap.agent.javassist.CtClass[] mayThrow() ,public abstract void replace(java.lang.String) throws org.hotswap.agent.javassist.CannotCompileException,public void replace(java.lang.String, org.hotswap.agent.javassist.expr.ExprEditor) throws org.hotswap.agent.javassist.CannotCompileException,public org.hotswap.agent.javassist.CtBehavior where() <variables>int currentPos,boolean edited,org.hotswap.agent.javassist.bytecode.CodeIterator iterator,static final java.lang.String javaLangObject,int maxLocals,int maxStack,org.hotswap.agent.javassist.CtClass thisClass,org.hotswap.agent.javassist.bytecode.MethodInfo thisMethod
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/expr/ExprEditor.java
LoopContext
loopBody
class LoopContext { NewOp newList; int maxLocals; int maxStack; LoopContext(int locals) { maxLocals = locals; maxStack = 0; newList = null; } void updateMax(int locals, int stack) { if (maxLocals < locals) maxLocals = locals; if (maxStack < stack) maxStack = stack; } } final boolean loopBody(CodeIterator iterator, CtClass clazz, MethodInfo minfo, LoopContext context) throws CannotCompileException {<FILL_FUNCTION_BODY>
try { Expr expr = null; int pos = iterator.next(); int c = iterator.byteAt(pos); if (c < Opcode.GETSTATIC) // c < 178 /* skip */; else if (c < Opcode.NEWARRAY) { // c < 188 if (c == Opcode.INVOKESTATIC || c == Opcode.INVOKEINTERFACE || c == Opcode.INVOKEVIRTUAL) { expr = new MethodCall(pos, iterator, clazz, minfo); edit((MethodCall)expr); } else if (c == Opcode.GETFIELD || c == Opcode.GETSTATIC || c == Opcode.PUTFIELD || c == Opcode.PUTSTATIC) { expr = new FieldAccess(pos, iterator, clazz, minfo, c); edit((FieldAccess)expr); } else if (c == Opcode.NEW) { int index = iterator.u16bitAt(pos + 1); context.newList = new NewOp(context.newList, pos, minfo.getConstPool().getClassInfo(index)); } else if (c == Opcode.INVOKESPECIAL) { NewOp newList = context.newList; if (newList != null && minfo.getConstPool().isConstructor(newList.type, iterator.u16bitAt(pos + 1)) > 0) { expr = new NewExpr(pos, iterator, clazz, minfo, newList.type, newList.pos); edit((NewExpr)expr); context.newList = newList.next; } else { MethodCall mcall = new MethodCall(pos, iterator, clazz, minfo); if (mcall.getMethodName().equals(MethodInfo.nameInit)) { ConstructorCall ccall = new ConstructorCall(pos, iterator, clazz, minfo); expr = ccall; edit(ccall); } else { expr = mcall; edit(mcall); } } } } else { // c >= 188 if (c == Opcode.NEWARRAY || c == Opcode.ANEWARRAY || c == Opcode.MULTIANEWARRAY) { expr = new NewArray(pos, iterator, clazz, minfo, c); edit((NewArray)expr); } else if (c == Opcode.INSTANCEOF) { expr = new Instanceof(pos, iterator, clazz, minfo); edit((Instanceof)expr); } else if (c == Opcode.CHECKCAST) { expr = new Cast(pos, iterator, clazz, minfo); edit((Cast)expr); } } if (expr != null && expr.edited()) { context.updateMax(expr.locals(), expr.stack()); return true; } return false; } catch (BadBytecode e) { throw new CannotCompileException(e); }
169
818
987
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/expr/FieldAccess.java
ProceedForWrite
doit
class ProceedForWrite implements ProceedHandler { CtClass fieldType; int opcode; int targetVar, index; ProceedForWrite(CtClass type, int op, int i, int var) { fieldType = type; targetVar = var; opcode = op; index = i; } @Override public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args) throws CompileError {<FILL_FUNCTION_BODY>} @Override public void setReturnType(JvstTypeChecker c, ASTList args) throws CompileError { c.atMethodArgs(args, new int[1], new int[1], new String[1]); c.setType(CtClass.voidType); c.addNullIfVoid(); } }
if (gen.getMethodArgsLength(args) != 1) throw new CompileError(Javac.proceedName + "() cannot take more than one parameter " + "for field writing"); int stack; if (isStatic(opcode)) stack = 0; else { stack = -1; bytecode.addAload(targetVar); } gen.atMethodArgs(args, new int[1], new int[1], new String[1]); gen.doNumCast(fieldType); if (fieldType instanceof CtPrimitiveType) stack -= ((CtPrimitiveType)fieldType).getDataSize(); else --stack; bytecode.add(opcode); bytecode.addIndex(index); bytecode.growStack(stack); gen.setType(CtClass.voidType); gen.addNullIfVoid();
226
235
461
<methods>public org.hotswap.agent.javassist.CtClass getEnclosingClass() ,public java.lang.String getFileName() ,public int getLineNumber() ,public int indexOfBytecode() ,public org.hotswap.agent.javassist.CtClass[] mayThrow() ,public abstract void replace(java.lang.String) throws org.hotswap.agent.javassist.CannotCompileException,public void replace(java.lang.String, org.hotswap.agent.javassist.expr.ExprEditor) throws org.hotswap.agent.javassist.CannotCompileException,public org.hotswap.agent.javassist.CtBehavior where() <variables>int currentPos,boolean edited,org.hotswap.agent.javassist.bytecode.CodeIterator iterator,static final java.lang.String javaLangObject,int maxLocals,int maxStack,org.hotswap.agent.javassist.CtClass thisClass,org.hotswap.agent.javassist.bytecode.MethodInfo thisMethod
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/expr/Handler.java
Handler
getType
class Handler extends Expr { private static String EXCEPTION_NAME = "$1"; private ExceptionTable etable; private int index; /** * Undocumented constructor. Do not use; internal-use only. */ protected Handler(ExceptionTable et, int nth, CodeIterator it, CtClass declaring, MethodInfo m) { super(et.handlerPc(nth), it, declaring, m); etable = et; index = nth; } /** * Returns the method or constructor containing the catch clause. */ @Override public CtBehavior where() { return super.where(); } /** * Returns the source line number of the catch clause. * * @return -1 if this information is not available. */ @Override public int getLineNumber() { return super.getLineNumber(); } /** * Returns the source file containing the catch clause. * * @return null if this information is not available. */ @Override public String getFileName() { return super.getFileName(); } /** * Returns the list of exceptions that the catch clause may throw. */ @Override public CtClass[] mayThrow() { return super.mayThrow(); } /** * Returns the type handled by the catch clause. * If this is a <code>finally</code> block, <code>null</code> is returned. */ public CtClass getType() throws NotFoundException {<FILL_FUNCTION_BODY>} /** * Returns true if this is a <code>finally</code> block. */ public boolean isFinally() { return etable.catchType(index) == 0; } /** * This method has not been implemented yet. * * @param statement a Java statement except try-catch. */ @Override public void replace(String statement) throws CannotCompileException { throw new RuntimeException("not implemented yet"); } /** * Inserts bytecode at the beginning of the catch clause. * The caught exception is stored in <code>$1</code>. * * @param src the source code representing the inserted bytecode. * It must be a single statement or block. */ public void insertBefore(String src) throws CannotCompileException { edited = true; @SuppressWarnings("unused") ConstPool cp = getConstPool(); CodeAttribute ca = iterator.get(); Javac jv = new Javac(thisClass); Bytecode b = jv.getBytecode(); b.setStackDepth(1); b.setMaxLocals(ca.getMaxLocals()); try { CtClass type = getType(); int var = jv.recordVariable(type, EXCEPTION_NAME); jv.recordReturnType(type, false); b.addAstore(var); jv.compileStmnt(src); b.addAload(var); int oldHandler = etable.handlerPc(index); b.addOpcode(Opcode.GOTO); b.addIndex(oldHandler - iterator.getCodeLength() - b.currentPc() + 1); maxStack = b.getMaxStack(); maxLocals = b.getMaxLocals(); int pos = iterator.append(b.get()); iterator.append(b.getExceptionTable(), pos); etable.setHandlerPc(index, pos); } catch (NotFoundException e) { throw new CannotCompileException(e); } catch (CompileError e) { throw new CannotCompileException(e); } } }
int type = etable.catchType(index); if (type == 0) return null; ConstPool cp = getConstPool(); String name = cp.getClassInfo(type); return thisClass.getClassPool().getCtClass(name);
980
69
1,049
<methods>public org.hotswap.agent.javassist.CtClass getEnclosingClass() ,public java.lang.String getFileName() ,public int getLineNumber() ,public int indexOfBytecode() ,public org.hotswap.agent.javassist.CtClass[] mayThrow() ,public abstract void replace(java.lang.String) throws org.hotswap.agent.javassist.CannotCompileException,public void replace(java.lang.String, org.hotswap.agent.javassist.expr.ExprEditor) throws org.hotswap.agent.javassist.CannotCompileException,public org.hotswap.agent.javassist.CtBehavior where() <variables>int currentPos,boolean edited,org.hotswap.agent.javassist.bytecode.CodeIterator iterator,static final java.lang.String javaLangObject,int maxLocals,int maxStack,org.hotswap.agent.javassist.CtClass thisClass,org.hotswap.agent.javassist.bytecode.MethodInfo thisMethod
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/expr/Instanceof.java
Instanceof
replace
class Instanceof extends Expr { /** * Undocumented constructor. Do not use; internal-use only. */ protected Instanceof(int pos, CodeIterator i, CtClass declaring, MethodInfo m) { super(pos, i, declaring, m); } /** * Returns the method or constructor containing the instanceof * expression represented by this object. */ @Override public CtBehavior where() { return super.where(); } /** * Returns the line number of the source line containing the * instanceof expression. * * @return -1 if this information is not available. */ @Override public int getLineNumber() { return super.getLineNumber(); } /** * Returns the source file containing the * instanceof expression. * * @return null if this information is not available. */ @Override public String getFileName() { return super.getFileName(); } /** * Returns the <code>CtClass</code> object representing * the type name on the right hand side * of the instanceof operator. */ public CtClass getType() throws NotFoundException { ConstPool cp = getConstPool(); int pos = currentPos; int index = iterator.u16bitAt(pos + 1); String name = cp.getClassInfo(index); return thisClass.getClassPool().getCtClass(name); } /** * Returns the list of exceptions that the expression may throw. * This list includes both the exceptions that the try-catch statements * including the expression can catch and the exceptions that * the throws declaration allows the method to throw. */ @Override public CtClass[] mayThrow() { return super.mayThrow(); } /** * Replaces the instanceof operator with the bytecode derived from * the given source text. * * <p>$0 is available but the value is <code>null</code>. * * @param statement a Java statement except try-catch. */ @Override public void replace(String statement) throws CannotCompileException {<FILL_FUNCTION_BODY>} /* boolean $proceed(Object obj) */ static class ProceedForInstanceof implements ProceedHandler { int index; ProceedForInstanceof(int i) { index = i; } @Override public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args) throws CompileError { if (gen.getMethodArgsLength(args) != 1) throw new CompileError(Javac.proceedName + "() cannot take more than one parameter " + "for instanceof"); gen.atMethodArgs(args, new int[1], new int[1], new String[1]); bytecode.addOpcode(Opcode.INSTANCEOF); bytecode.addIndex(index); gen.setType(CtClass.booleanType); } @Override public void setReturnType(JvstTypeChecker c, ASTList args) throws CompileError { c.atMethodArgs(args, new int[1], new int[1], new String[1]); c.setType(CtClass.booleanType); } } }
thisClass.getClassFile(); // to call checkModify(). @SuppressWarnings("unused") ConstPool constPool = getConstPool(); int pos = currentPos; int index = iterator.u16bitAt(pos + 1); Javac jc = new Javac(thisClass); ClassPool cp = thisClass.getClassPool(); CodeAttribute ca = iterator.get(); try { CtClass[] params = new CtClass[] { cp.get(javaLangObject) }; CtClass retType = CtClass.booleanType; int paramVar = ca.getMaxLocals(); jc.recordParams(javaLangObject, params, true, paramVar, withinStatic()); int retVar = jc.recordReturnType(retType, true); jc.recordProceed(new ProceedForInstanceof(index)); // because $type is not the return type... jc.recordType(getType()); /* Is $_ included in the source code? */ checkResultValue(retType, statement); Bytecode bytecode = jc.getBytecode(); storeStack(params, true, paramVar, bytecode); jc.recordLocalVariables(ca, pos); bytecode.addConstZero(retType); bytecode.addStore(retVar, retType); // initialize $_ jc.compileStmnt(statement); bytecode.addLoad(retVar, retType); replace0(pos, bytecode, 3); } catch (CompileError e) { throw new CannotCompileException(e); } catch (NotFoundException e) { throw new CannotCompileException(e); } catch (BadBytecode e) { throw new CannotCompileException("broken method"); }
865
465
1,330
<methods>public org.hotswap.agent.javassist.CtClass getEnclosingClass() ,public java.lang.String getFileName() ,public int getLineNumber() ,public int indexOfBytecode() ,public org.hotswap.agent.javassist.CtClass[] mayThrow() ,public abstract void replace(java.lang.String) throws org.hotswap.agent.javassist.CannotCompileException,public void replace(java.lang.String, org.hotswap.agent.javassist.expr.ExprEditor) throws org.hotswap.agent.javassist.CannotCompileException,public org.hotswap.agent.javassist.CtBehavior where() <variables>int currentPos,boolean edited,org.hotswap.agent.javassist.bytecode.CodeIterator iterator,static final java.lang.String javaLangObject,int maxLocals,int maxStack,org.hotswap.agent.javassist.CtClass thisClass,org.hotswap.agent.javassist.bytecode.MethodInfo thisMethod
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/expr/MethodCall.java
MethodCall
replace
class MethodCall extends Expr { /** * Undocumented constructor. Do not use; internal-use only. */ protected MethodCall(int pos, CodeIterator i, CtClass declaring, MethodInfo m) { super(pos, i, declaring, m); } private int getNameAndType(ConstPool cp) { int pos = currentPos; int c = iterator.byteAt(pos); int index = iterator.u16bitAt(pos + 1); if (c == INVOKEINTERFACE) return cp.getInterfaceMethodrefNameAndType(index); return cp.getMethodrefNameAndType(index); } /** * Returns the method or constructor containing the method-call * expression represented by this object. */ @Override public CtBehavior where() { return super.where(); } /** * Returns the line number of the source line containing the * method call. * * @return -1 if this information is not available. */ @Override public int getLineNumber() { return super.getLineNumber(); } /** * Returns the source file containing the method call. * * @return null if this information is not available. */ @Override public String getFileName() { return super.getFileName(); } /** * Returns the class of the target object, * which the method is called on. */ protected CtClass getCtClass() throws NotFoundException { return thisClass.getClassPool().get(getClassName()); } /** * Returns the class name of the target object, * which the method is called on. */ public String getClassName() { String cname; ConstPool cp = getConstPool(); int pos = currentPos; int c = iterator.byteAt(pos); int index = iterator.u16bitAt(pos + 1); if (c == INVOKEINTERFACE) cname = cp.getInterfaceMethodrefClassName(index); else cname = cp.getMethodrefClassName(index); if (cname.charAt(0) == '[') cname = Descriptor.toClassName(cname); return cname; } /** * Returns the name of the called method. */ public String getMethodName() { ConstPool cp = getConstPool(); int nt = getNameAndType(cp); return cp.getUtf8Info(cp.getNameAndTypeName(nt)); } /** * Returns the called method. */ public CtMethod getMethod() throws NotFoundException { return getCtClass().getMethod(getMethodName(), getSignature()); } /** * Returns the method signature (the parameter types * and the return type). * The method signature is represented by a character string * called method descriptor, which is defined in the JVM specification. * * @see javassist.CtBehavior#getSignature() * @see javassist.bytecode.Descriptor * @since 3.1 */ public String getSignature() { ConstPool cp = getConstPool(); int nt = getNameAndType(cp); return cp.getUtf8Info(cp.getNameAndTypeDescriptor(nt)); } /** * Returns the list of exceptions that the expression may throw. * This list includes both the exceptions that the try-catch statements * including the expression can catch and the exceptions that * the throws declaration allows the method to throw. */ @Override public CtClass[] mayThrow() { return super.mayThrow(); } /** * Returns true if the called method is of a superclass of the current * class. */ public boolean isSuper() { return iterator.byteAt(currentPos) == INVOKESPECIAL && !where().getDeclaringClass().getName().equals(getClassName()); } /* * Returns the parameter types of the called method. public CtClass[] getParameterTypes() throws NotFoundException { return Descriptor.getParameterTypes(getMethodDesc(), thisClass.getClassPool()); } */ /* * Returns the return type of the called method. public CtClass getReturnType() throws NotFoundException { return Descriptor.getReturnType(getMethodDesc(), thisClass.getClassPool()); } */ /** * Replaces the method call with the bytecode derived from * the given source text. * * <p>$0 is available even if the called method is static. * * @param statement a Java statement except try-catch. */ @Override public void replace(String statement) throws CannotCompileException {<FILL_FUNCTION_BODY>} }
thisClass.getClassFile(); // to call checkModify(). ConstPool constPool = getConstPool(); int pos = currentPos; int index = iterator.u16bitAt(pos + 1); String classname, methodname, signature; int opcodeSize; int c = iterator.byteAt(pos); if (c == INVOKEINTERFACE) { opcodeSize = 5; classname = constPool.getInterfaceMethodrefClassName(index); methodname = constPool.getInterfaceMethodrefName(index); signature = constPool.getInterfaceMethodrefType(index); } else if (c == INVOKESTATIC || c == INVOKESPECIAL || c == INVOKEVIRTUAL) { opcodeSize = 3; classname = constPool.getMethodrefClassName(index); methodname = constPool.getMethodrefName(index); signature = constPool.getMethodrefType(index); } else throw new CannotCompileException("not method invocation"); Javac jc = new Javac(thisClass); ClassPool cp = thisClass.getClassPool(); CodeAttribute ca = iterator.get(); try { CtClass[] params = Descriptor.getParameterTypes(signature, cp); CtClass retType = Descriptor.getReturnType(signature, cp); int paramVar = ca.getMaxLocals(); jc.recordParams(classname, params, true, paramVar, withinStatic()); int retVar = jc.recordReturnType(retType, true); if (c == INVOKESTATIC) jc.recordStaticProceed(classname, methodname); else if (c == INVOKESPECIAL) jc.recordSpecialProceed(Javac.param0Name, classname, methodname, signature, index); else jc.recordProceed(Javac.param0Name, methodname); /* Is $_ included in the source code? */ checkResultValue(retType, statement); Bytecode bytecode = jc.getBytecode(); storeStack(params, c == INVOKESTATIC, paramVar, bytecode); jc.recordLocalVariables(ca, pos); if (retType != CtClass.voidType) { bytecode.addConstZero(retType); bytecode.addStore(retVar, retType); // initialize $_ } jc.compileStmnt(statement); if (retType != CtClass.voidType) bytecode.addLoad(retVar, retType); replace0(pos, bytecode, opcodeSize); } catch (CompileError e) { throw new CannotCompileException(e); } catch (NotFoundException e) { throw new CannotCompileException(e); } catch (BadBytecode e) { throw new CannotCompileException("broken method"); }
1,260
756
2,016
<methods>public org.hotswap.agent.javassist.CtClass getEnclosingClass() ,public java.lang.String getFileName() ,public int getLineNumber() ,public int indexOfBytecode() ,public org.hotswap.agent.javassist.CtClass[] mayThrow() ,public abstract void replace(java.lang.String) throws org.hotswap.agent.javassist.CannotCompileException,public void replace(java.lang.String, org.hotswap.agent.javassist.expr.ExprEditor) throws org.hotswap.agent.javassist.CannotCompileException,public org.hotswap.agent.javassist.CtBehavior where() <variables>int currentPos,boolean edited,org.hotswap.agent.javassist.bytecode.CodeIterator iterator,static final java.lang.String javaLangObject,int maxLocals,int maxStack,org.hotswap.agent.javassist.CtClass thisClass,org.hotswap.agent.javassist.bytecode.MethodInfo thisMethod
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/runtime/Desc.java
Desc
getClassType
class Desc { /** * Specifies how a <code>java.lang.Class</code> object is loaded. * * <p>If true, it is loaded by: * <pre>Thread.currentThread().getContextClassLoader().loadClass()</pre> * <p>If false, it is loaded by <code>Class.forName()</code>. * The default value is false. */ public static boolean useContextClassLoader = false; private static final ThreadLocal<Boolean> USE_CONTEXT_CLASS_LOADER_LOCALLY = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; public static void setUseContextClassLoaderLocally() { USE_CONTEXT_CLASS_LOADER_LOCALLY.set(true); } public static void resetUseContextClassLoaderLocally() { USE_CONTEXT_CLASS_LOADER_LOCALLY.remove(); } private static Class<?> getClassObject(String name) throws ClassNotFoundException { if (useContextClassLoader || USE_CONTEXT_CLASS_LOADER_LOCALLY.get()) return Class.forName(name, true, Thread.currentThread().getContextClassLoader()); return Class.forName(name); } /** * Interprets the given class name. * It is used for implementing <code>$class</code>. */ public static Class<?> getClazz(String name) { try { return getClassObject(name); } catch (ClassNotFoundException e) { throw new RuntimeException( "$class: internal error, could not find class '" + name + "' (Desc.useContextClassLoader: " + Boolean.toString(useContextClassLoader) + ")", e); } } /** * Interprets the given type descriptor representing a method * signature. It is used for implementing <code>$sig</code>. */ public static Class<?>[] getParams(String desc) { if (desc.charAt(0) != '(') throw new RuntimeException("$sig: internal error"); return getType(desc, desc.length(), 1, 0); } /** * Interprets the given type descriptor. * It is used for implementing <code>$type</code>. */ public static Class<?> getType(String desc) { Class<?>[] result = getType(desc, desc.length(), 0, 0); if (result == null || result.length != 1) throw new RuntimeException("$type: internal error"); return result[0]; } private static Class<?>[] getType(String desc, int descLen, int start, int num) { Class<?> clazz; if (start >= descLen) return new Class[num]; char c = desc.charAt(start); switch (c) { case 'Z' : clazz = Boolean.TYPE; break; case 'C' : clazz = Character.TYPE; break; case 'B' : clazz = Byte.TYPE; break; case 'S' : clazz = Short.TYPE; break; case 'I' : clazz = Integer.TYPE; break; case 'J' : clazz = Long.TYPE; break; case 'F' : clazz = Float.TYPE; break; case 'D' : clazz = Double.TYPE; break; case 'V' : clazz = Void.TYPE; break; case 'L' : case '[' : return getClassType(desc, descLen, start, num); default : return new Class[num]; } Class<?>[] result = getType(desc, descLen, start + 1, num + 1); result[num] = clazz; return result; } private static Class<?>[] getClassType(String desc, int descLen, int start, int num) {<FILL_FUNCTION_BODY>} }
int end = start; while (desc.charAt(end) == '[') ++end; if (desc.charAt(end) == 'L') { end = desc.indexOf(';', end); if (end < 0) throw new IndexOutOfBoundsException("bad descriptor"); } String cname; if (desc.charAt(start) == 'L') cname = desc.substring(start + 1, end); else cname = desc.substring(start, end + 1); Class<?>[] result = getType(desc, descLen, end + 1, num + 1); try { result[num] = getClassObject(cname.replace('/', '.')); } catch (ClassNotFoundException e) { // "new RuntimeException(e)" is not available in JDK 1.3. throw new RuntimeException(e.getMessage()); } return result;
1,081
243
1,324
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/scopedpool/ScopedClassPoolRepositoryImpl.java
ScopedClassPoolRepositoryImpl
registerClassLoader
class ScopedClassPoolRepositoryImpl implements ScopedClassPoolRepository { /** The instance */ private static final ScopedClassPoolRepositoryImpl instance = new ScopedClassPoolRepositoryImpl(); /** Whether to prune */ private boolean prune = true; /** Whether to prune when added to the classpool's cache */ boolean pruneWhenCached; /** The registered classloaders */ protected Map<ClassLoader,ScopedClassPool> registeredCLs = Collections .synchronizedMap(new WeakHashMap<ClassLoader,ScopedClassPool>()); /** The default class pool */ protected ClassPool classpool; /** The factory for creating class pools */ protected ScopedClassPoolFactory factory = new ScopedClassPoolFactoryImpl(); /** * Get the instance. * * @return the instance. */ public static ScopedClassPoolRepository getInstance() { return instance; } /** * Singleton. */ private ScopedClassPoolRepositoryImpl() { classpool = ClassPool.getDefault(); // FIXME This doesn't look correct ClassLoader cl = Thread.currentThread().getContextClassLoader(); classpool.insertClassPath(new LoaderClassPath(cl)); } /** * Returns the value of the prune attribute. * * @return the prune. */ @Override public boolean isPrune() { return prune; } /** * Set the prune attribute. * * @param prune a new value. */ @Override public void setPrune(boolean prune) { this.prune = prune; } /** * Create a scoped classpool. * * @param cl the classloader. * @param src the original classpool. * @return the classpool */ @Override public ScopedClassPool createScopedClassPool(ClassLoader cl, ClassPool src) { return factory.create(cl, src, this); } @Override public ClassPool findClassPool(ClassLoader cl) { if (cl == null) return registerClassLoader(ClassLoader.getSystemClassLoader()); return registerClassLoader(cl); } /** * Register a classloader. * * @param ucl the classloader. * @return the classpool */ @Override public ClassPool registerClassLoader(ClassLoader ucl) {<FILL_FUNCTION_BODY>} /** * Get the registered classloaders. */ @Override public Map<ClassLoader,ScopedClassPool> getRegisteredCLs() { clearUnregisteredClassLoaders(); return registeredCLs; } /** * This method will check to see if a register classloader has been * undeployed (as in JBoss) */ @Override public void clearUnregisteredClassLoaders() { List<ClassLoader> toUnregister = null; synchronized (registeredCLs) { for (Map.Entry<ClassLoader,ScopedClassPool> reg:registeredCLs.entrySet()) { if (reg.getValue().isUnloadedClassLoader()) { ClassLoader cl = reg.getValue().getClassLoader(); if (cl != null) { if (toUnregister == null) toUnregister = new ArrayList<ClassLoader>(); toUnregister.add(cl); } registeredCLs.remove(reg.getKey()); } } if (toUnregister != null) for (ClassLoader cl:toUnregister) unregisterClassLoader(cl); } } @Override public void unregisterClassLoader(ClassLoader cl) { synchronized (registeredCLs) { ScopedClassPool pool = registeredCLs.remove(cl); if (pool != null) pool.close(); } } public void insertDelegate(ScopedClassPoolRepository delegate) { // Noop - this is the end } @Override public void setClassPoolFactory(ScopedClassPoolFactory factory) { this.factory = factory; } @Override public ScopedClassPoolFactory getClassPoolFactory() { return factory; } }
synchronized (registeredCLs) { // FIXME: Probably want to take this method out later // so that AOP framework can be independent of JMX // This is in here so that we can remove a UCL from the ClassPool as // a // ClassPool.classpath if (registeredCLs.containsKey(ucl)) { return registeredCLs.get(ucl); } ScopedClassPool pool = createScopedClassPool(ucl, classpool); registeredCLs.put(ucl, pool); return pool; }
1,106
144
1,250
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/Dump.java
Dump
main
class Dump { private Dump() {} /** * Main method. * * @param args <code>args[0]</code> is the class file name. */ public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
if (args.length != 1) { System.err.println("Usage: java Dump <class file name>"); return; } DataInputStream in = new DataInputStream( new FileInputStream(args[0])); ClassFile w = new ClassFile(in); PrintWriter out = new PrintWriter(System.out, true); out.println("*** constant pool ***"); w.getConstPool().print(out); out.println(); out.println("*** members ***"); ClassFilePrinter.print(w, out);
80
143
223
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/framedump.java
framedump
main
class framedump { private framedump() {} /** * Main method. * * @param args <code>args[0]</code> is the class file name. */ public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
if (args.length != 1) { System.err.println("Usage: java javassist.tools.framedump <fully-qualified class name>"); return; } ClassPool pool = ClassPool.getDefault(); CtClass clazz = pool.get(args[0]); System.out.println("Frame Dump of " + clazz.getName() + ":"); FramePrinter.print(clazz, System.out);
81
119
200
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/reflect/Compiler.java
Compiler
parse
class Compiler { public static void main(String[] args) throws Exception { if (args.length == 0) { help(System.err); return; } CompiledClass[] entries = new CompiledClass[args.length]; int n = parse(args, entries); if (n < 1) { System.err.println("bad parameter."); return; } processClasses(entries, n); } private static void processClasses(CompiledClass[] entries, int n) throws Exception { Reflection implementor = new Reflection(); ClassPool pool = ClassPool.getDefault(); implementor.start(pool); for (int i = 0; i < n; ++i) { CtClass c = pool.get(entries[i].classname); if (entries[i].metaobject != null || entries[i].classobject != null) { String metaobj, classobj; if (entries[i].metaobject == null) metaobj = "org.hotswap.agent.javassist.tools.reflect.Metaobject"; else metaobj = entries[i].metaobject; if (entries[i].classobject == null) classobj = "org.hotswap.agent.javassist.tools.reflect.ClassMetaobject"; else classobj = entries[i].classobject; if (!implementor.makeReflective(c, pool.get(metaobj), pool.get(classobj))) System.err.println("Warning: " + c.getName() + " is reflective. It was not changed."); System.err.println(c.getName() + ": " + metaobj + ", " + classobj); } else System.err.println(c.getName() + ": not reflective"); } for (int i = 0; i < n; ++i) { implementor.onLoad(pool, entries[i].classname); pool.get(entries[i].classname).writeFile(); } } private static int parse(String[] args, CompiledClass[] result) {<FILL_FUNCTION_BODY>} private static void help(PrintStream out) { out.println("Usage: java javassist.tools.reflect.Compiler"); out.println(" (<class> [-m <metaobject>] [-c <class metaobject>])+"); } }
int n = -1; for (int i = 0; i < args.length; ++i) { String a = args[i]; if (a.equals("-m")) if (n < 0 || i + 1 > args.length) return -1; else result[n].metaobject = args[++i]; else if (a.equals("-c")) if (n < 0 || i + 1 > args.length) return -1; else result[n].classobject = args[++i]; else if (a.charAt(0) == '-') return -1; else { CompiledClass cc = new CompiledClass(); cc.classname = a; cc.metaobject = null; cc.classobject = null; result[++n] = cc; } } return n + 1;
635
228
863
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/reflect/Metaobject.java
Metaobject
getMethodName
class Metaobject implements Serializable { /** default serialVersionUID */ private static final long serialVersionUID = 1L; protected ClassMetaobject classmetaobject; protected Metalevel baseobject; protected Method[] methods; /** * Constructs a <code>Metaobject</code>. The metaobject is * constructed before the constructor is called on the base-level * object. * * @param self the object that this metaobject is associated with. * @param args the parameters passed to the constructor of * <code>self</code>. */ public Metaobject(Object self, Object[] args) { baseobject = (Metalevel)self; classmetaobject = baseobject._getClass(); methods = classmetaobject.getReflectiveMethods(); } /** * Constructs a <code>Metaobject</code> without initialization. * If calling this constructor, a subclass should be responsible * for initialization. */ protected Metaobject() { baseobject = null; classmetaobject = null; methods = null; } private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(baseobject); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { baseobject = (Metalevel)in.readObject(); classmetaobject = baseobject._getClass(); methods = classmetaobject.getReflectiveMethods(); } /** * Obtains the class metaobject associated with this metaobject. * * @see javassist.tools.reflect.ClassMetaobject */ public final ClassMetaobject getClassMetaobject() { return classmetaobject; } /** * Obtains the object controlled by this metaobject. */ public final Object getObject() { return baseobject; } /** * Changes the object controlled by this metaobject. * * @param self the object */ public final void setObject(Object self) { baseobject = (Metalevel)self; classmetaobject = baseobject._getClass(); methods = classmetaobject.getReflectiveMethods(); // call _setMetaobject() after the metaobject is settled. baseobject._setMetaobject(this); } /** * Returns the name of the method specified * by <code>identifier</code>. */ public final String getMethodName(int identifier) {<FILL_FUNCTION_BODY>} /** * Returns an array of <code>Class</code> objects representing the * formal parameter types of the method specified * by <code>identifier</code>. */ public final Class<?>[] getParameterTypes(int identifier) { return methods[identifier].getParameterTypes(); } /** * Returns a <code>Class</code> objects representing the * return type of the method specified by <code>identifier</code>. */ public final Class<?> getReturnType(int identifier) { return methods[identifier].getReturnType(); } /** * Is invoked when public fields of the base-level * class are read and the runtime system intercepts it. * This method simply returns the value of the field. * * <p>Every subclass of this class should redefine this method. */ public Object trapFieldRead(String name) { Class<?> jc = getClassMetaobject().getJavaClass(); try { return jc.getField(name).get(getObject()); } catch (NoSuchFieldException e) { throw new RuntimeException(e.toString()); } catch (IllegalAccessException e) { throw new RuntimeException(e.toString()); } } /** * Is invoked when public fields of the base-level * class are modified and the runtime system intercepts it. * This method simply sets the field to the given value. * * <p>Every subclass of this class should redefine this method. */ public void trapFieldWrite(String name, Object value) { Class<?> jc = getClassMetaobject().getJavaClass(); try { jc.getField(name).set(getObject(), value); } catch (NoSuchFieldException e) { throw new RuntimeException(e.toString()); } catch (IllegalAccessException e) { throw new RuntimeException(e.toString()); } } /** * Is invoked when base-level method invocation is intercepted. * This method simply executes the intercepted method invocation * with the original parameters and returns the resulting value. * * <p>Every subclass of this class should redefine this method. * * <p>Note: this method is not invoked if the base-level method * is invoked by a constructor in the super class. For example, * * <pre> * abstract class A { * abstract void initialize(); * A() { * initialize(); // not intercepted * } * } * * class B extends A { * void initialize() { System.out.println("initialize()"); } * B() { * super(); * initialize(); // intercepted * } * }</pre> * * <p>if an instance of B is created, * the invocation of initialize() in B is intercepted only once. * The first invocation by the constructor in A is not intercepted. * This is because the link between a base-level object and a * metaobject is not created until the execution of a * constructor of the super class finishes. */ public Object trapMethodcall(int identifier, Object[] args) throws Throwable { try { return methods[identifier].invoke(getObject(), args); } catch (java.lang.reflect.InvocationTargetException e) { throw e.getTargetException(); } catch (java.lang.IllegalAccessException e) { throw new CannotInvokeException(e); } } }
String mname = methods[identifier].getName(); int j = ClassMetaobject.methodPrefixLen; for (;;) { char c = mname.charAt(j++); if (c < '0' || '9' < c) break; } return mname.substring(j);
1,592
83
1,675
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/reflect/Sample.java
Sample
trap
class Sample { private Metaobject _metaobject; private static ClassMetaobject _classobject; public Object trap(Object[] args, int identifier) throws Throwable {<FILL_FUNCTION_BODY>} public static Object trapStatic(Object[] args, int identifier) throws Throwable { return _classobject.trapMethodcall(identifier, args); } public static Object trapRead(Object[] args, String name) { if (args[0] == null) return _classobject.trapFieldRead(name); return ((Metalevel)args[0])._getMetaobject().trapFieldRead(name); } public static Object trapWrite(Object[] args, String name) { Metalevel base = (Metalevel)args[0]; if (base == null) _classobject.trapFieldWrite(name, args[1]); else base._getMetaobject().trapFieldWrite(name, args[1]); return null; } }
Metaobject mobj; mobj = _metaobject; if (mobj == null) return ClassMetaobject.invoke(this, identifier, args); return mobj.trapMethodcall(identifier, args);
261
59
320
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/rmi/AppletServer.java
AppletServer
lookupName
class AppletServer extends Webserver { private StubGenerator stubGen; private Map<String,ExportedObject> exportedNames; private List<ExportedObject> exportedObjects; private static final byte[] okHeader = "HTTP/1.0 200 OK\r\n\r\n".getBytes(); /** * Constructs a web server. * * @param port port number */ public AppletServer(String port) throws IOException, NotFoundException, CannotCompileException { this(Integer.parseInt(port)); } /** * Constructs a web server. * * @param port port number */ public AppletServer(int port) throws IOException, NotFoundException, CannotCompileException { this(ClassPool.getDefault(), new StubGenerator(), port); } /** * Constructs a web server. * * @param port port number * @param src the source of classs files. */ public AppletServer(int port, ClassPool src) throws IOException, NotFoundException, CannotCompileException { this(new ClassPool(src), new StubGenerator(), port); } private AppletServer(ClassPool loader, StubGenerator gen, int port) throws IOException, NotFoundException, CannotCompileException { super(port); exportedNames = new Hashtable<String,ExportedObject>(); exportedObjects = new Vector<ExportedObject>(); stubGen = gen; addTranslator(loader, gen); } /** * Begins the HTTP service. */ @Override public void run() { super.run(); } /** * Exports an object. * This method produces the bytecode of the proxy class used * to access the exported object. A remote applet can load * the proxy class and call a method on the exported object. * * @param name the name used for looking the object up. * @param obj the exported object. * @return the object identifier * * @see javassist.tools.rmi.ObjectImporter#lookupObject(String) */ public synchronized int exportObject(String name, Object obj) throws CannotCompileException { Class<?> clazz = obj.getClass(); ExportedObject eo = new ExportedObject(); eo.object = obj; eo.methods = clazz.getMethods(); exportedObjects.add(eo); eo.identifier = exportedObjects.size() - 1; if (name != null) exportedNames.put(name, eo); try { stubGen.makeProxyClass(clazz); } catch (NotFoundException e) { throw new CannotCompileException(e); } return eo.identifier; } /** * Processes a request from a web browser (an ObjectImporter). */ @Override public void doReply(InputStream in, OutputStream out, String cmd) throws IOException, BadHttpRequest { if (cmd.startsWith("POST /rmi ")) processRMI(in, out); else if (cmd.startsWith("POST /lookup ")) lookupName(cmd, in, out); else super.doReply(in, out, cmd); } private void processRMI(InputStream ins, OutputStream outs) throws IOException { ObjectInputStream in = new ObjectInputStream(ins); int objectId = in.readInt(); int methodId = in.readInt(); Exception err = null; Object rvalue = null; try { ExportedObject eo = exportedObjects.get(objectId); Object[] args = readParameters(in); rvalue = convertRvalue(eo.methods[methodId].invoke(eo.object, args)); } catch(Exception e) { err = e; logging2(e.toString()); } outs.write(okHeader); ObjectOutputStream out = new ObjectOutputStream(outs); if (err != null) { out.writeBoolean(false); out.writeUTF(err.toString()); } else try { out.writeBoolean(true); out.writeObject(rvalue); } catch (NotSerializableException e) { logging2(e.toString()); } catch (InvalidClassException e) { logging2(e.toString()); } out.flush(); out.close(); in.close(); } private Object[] readParameters(ObjectInputStream in) throws IOException, ClassNotFoundException { int n = in.readInt(); Object[] args = new Object[n]; for (int i = 0; i < n; ++i) { Object a = in.readObject(); if (a instanceof RemoteRef) { RemoteRef ref = (RemoteRef)a; ExportedObject eo = exportedObjects.get(ref.oid); a = eo.object; } args[i] = a; } return args; } private Object convertRvalue(Object rvalue) throws CannotCompileException { if (rvalue == null) return null; // the return type is void. String classname = rvalue.getClass().getName(); if (stubGen.isProxyClass(classname)) return new RemoteRef(exportObject(null, rvalue), classname); return rvalue; } private void lookupName(String cmd, InputStream ins, OutputStream outs) throws IOException {<FILL_FUNCTION_BODY>} }
ObjectInputStream in = new ObjectInputStream(ins); String name = DataInputStream.readUTF(in); ExportedObject found = exportedNames.get(name); outs.write(okHeader); ObjectOutputStream out = new ObjectOutputStream(outs); if (found == null) { logging2(name + "not found."); out.writeInt(-1); // error code out.writeUTF("error"); } else { logging2(name); out.writeInt(found.identifier); out.writeUTF(found.object.getClass().getName()); } out.flush(); out.close(); in.close();
1,492
170
1,662
<methods>public void <init>(java.lang.String) throws java.io.IOException,public void <init>(int) throws java.io.IOException,public void addTranslator(org.hotswap.agent.javassist.ClassPool, org.hotswap.agent.javassist.Translator) throws org.hotswap.agent.javassist.NotFoundException, org.hotswap.agent.javassist.CannotCompileException,public void doReply(java.io.InputStream, java.io.OutputStream, java.lang.String) throws java.io.IOException, org.hotswap.agent.javassist.tools.web.BadHttpRequest,public void end() throws java.io.IOException,public void logging(java.lang.String) ,public void logging(java.lang.String, java.lang.String) ,public void logging(java.lang.String, java.lang.String, java.lang.String) ,public void logging2(java.lang.String) ,public static void main(java.lang.String[]) throws java.io.IOException,public void run() ,public void setClassPool(org.hotswap.agent.javassist.ClassPool) <variables>private org.hotswap.agent.javassist.ClassPool classPool,public java.lang.String debugDir,private static final byte[] endofline,public java.lang.String htmlfileBase,private java.net.ServerSocket socket,protected org.hotswap.agent.javassist.Translator translator,private static final int typeClass,private static final int typeGif,private static final int typeHtml,private static final int typeJpeg,private static final int typeText
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/web/Viewer.java
Viewer
loadClass
class Viewer extends ClassLoader { private String server; private int port; /** * Starts a program. */ public static void main(String[] args) throws Throwable { if (args.length >= 3) { Viewer cl = new Viewer(args[0], Integer.parseInt(args[1])); String[] args2 = new String[args.length - 3]; System.arraycopy(args, 3, args2, 0, args.length - 3); cl.run(args[2], args2); } else System.err.println( "Usage: java javassist.tools.web.Viewer <host> <port> class [args ...]"); } /** * Constructs a viewer. * * @param host server name * @param p port number */ public Viewer(String host, int p) { server = host; port = p; } /** * Returns the server name. */ public String getServer() { return server; } /** * Returns the port number. */ public int getPort() { return port; } /** * Invokes main() in the class specified by <code>classname</code>. * * @param classname executed class * @param args the arguments passed to <code>main()</code>. */ public void run(String classname, String[] args) throws Throwable { Class<?> c = loadClass(classname); try { c.getDeclaredMethod("main", new Class[] { String[].class }) .invoke(null, new Object[] { args }); } catch (java.lang.reflect.InvocationTargetException e) { throw e.getTargetException(); } } /** * Requests the class loader to load a class. */ @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {<FILL_FUNCTION_BODY>} /** * Finds the specified class. The implementation in this class * fetches the class from the http server. If the class is * either <code>java.*</code>, <code>javax.*</code>, or * <code>Viewer</code>, then it is loaded by the parent class * loader. * * <p>This method can be overridden by a subclass of * <code>Viewer</code>. */ @Override protected Class<?> findClass(String name) throws ClassNotFoundException { Class<?> c = null; if (name.startsWith("java.") || name.startsWith("javax.") || name.equals("org.hotswap.agent.javassist.tools.web.Viewer")) c = findSystemClass(name); if (c == null) try { byte[] b = fetchClass(name); if (b != null) c = defineClass(name, b, 0, b.length); } catch (Exception e) { } return c; } /** * Fetches the class file of the specified class from the http * server. */ protected byte[] fetchClass(String classname) throws Exception { byte[] b; URL url = new URL("http", server, port, "/" + classname.replace('.', '/') + ".class"); URLConnection con = url.openConnection(); con.connect(); int size = con.getContentLength(); InputStream s = con.getInputStream(); if (size <= 0) b = readStream(s); else { b = new byte[size]; int len = 0; do { int n = s.read(b, len, size - len); if (n < 0) { s.close(); throw new IOException("the stream was closed: " + classname); } len += n; } while (len < size); } s.close(); return b; } private byte[] readStream(InputStream fin) throws IOException { byte[] buf = new byte[4096]; int size = 0; int len = 0; do { size += len; if (buf.length - size <= 0) { byte[] newbuf = new byte[buf.length * 2]; System.arraycopy(buf, 0, newbuf, 0, size); buf = newbuf; } len = fin.read(buf, size, buf.length - size); } while (len >= 0); byte[] result = new byte[size]; System.arraycopy(buf, 0, result, 0, size); return result; } }
Class<?> c = findLoadedClass(name); if (c == null) c = findClass(name); if (c == null) throw new ClassNotFoundException(name); if (resolve) resolveClass(c); return c;
1,260
74
1,334
<methods>public void clearAssertionStatus() ,public final java.lang.Package getDefinedPackage(java.lang.String) ,public final java.lang.Package[] getDefinedPackages() ,public java.lang.String getName() ,public final java.lang.ClassLoader getParent() ,public static java.lang.ClassLoader getPlatformClassLoader() ,public java.net.URL getResource(java.lang.String) ,public java.io.InputStream getResourceAsStream(java.lang.String) ,public Enumeration<java.net.URL> getResources(java.lang.String) throws java.io.IOException,public static java.lang.ClassLoader getSystemClassLoader() ,public static java.net.URL getSystemResource(java.lang.String) ,public static java.io.InputStream getSystemResourceAsStream(java.lang.String) ,public static Enumeration<java.net.URL> getSystemResources(java.lang.String) throws java.io.IOException,public final java.lang.Module getUnnamedModule() ,public final boolean isRegisteredAsParallelCapable() ,public Class<?> loadClass(java.lang.String) throws java.lang.ClassNotFoundException,public Stream<java.net.URL> resources(java.lang.String) ,public void setClassAssertionStatus(java.lang.String, boolean) ,public void setDefaultAssertionStatus(boolean) ,public void setPackageAssertionStatus(java.lang.String, boolean) <variables>static final boolean $assertionsDisabled,final java.lang.Object assertionLock,Map<java.lang.String,java.lang.Boolean> classAssertionStatus,private volatile ConcurrentHashMap<?,?> classLoaderValueMap,private final ArrayList<Class<?>> classes,private boolean defaultAssertionStatus,private final java.security.ProtectionDomain defaultDomain,private final jdk.internal.loader.NativeLibraries libraries,private final java.lang.String name,private final java.lang.String nameAndId,private static final java.security.cert.Certificate[] nocerts,private final ConcurrentHashMap<java.lang.String,java.security.cert.Certificate[]> package2certs,private Map<java.lang.String,java.lang.Boolean> packageAssertionStatus,private final ConcurrentHashMap<java.lang.String,java.lang.NamedPackage> packages,private final ConcurrentHashMap<java.lang.String,java.lang.Object> parallelLockMap,private final java.lang.ClassLoader parent,private static volatile java.lang.ClassLoader scl,private final java.lang.Module unnamedModule
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/HotSwapAgent.java
HotSwapAgent
createJarFile
class HotSwapAgent { private static Instrumentation instrumentation = null; /** * Obtains the {@code Instrumentation} object. * * @return null when it is not available. */ public Instrumentation instrumentation() { return instrumentation; } /** * The entry point invoked when this agent is started by {@code -javaagent}. */ public static void premain(String agentArgs, Instrumentation inst) throws Throwable { agentmain(agentArgs, inst); } /** * The entry point invoked when this agent is started after the JVM starts. */ public static void agentmain(String agentArgs, Instrumentation inst) throws Throwable { if (!inst.isRedefineClassesSupported()) throw new RuntimeException("this JVM does not support redefinition of classes"); instrumentation = inst; } /** * Redefines a class. */ public static void redefine(Class<?> oldClass, CtClass newClass) throws NotFoundException, IOException, CannotCompileException { Class<?>[] old = { oldClass }; CtClass[] newClasses = { newClass }; redefine(old, newClasses); } /** * Redefines classes. */ public static void redefine(Class<?>[] oldClasses, CtClass[] newClasses) throws NotFoundException, IOException, CannotCompileException { startAgent(); ClassDefinition[] defs = new ClassDefinition[oldClasses.length]; for (int i = 0; i < oldClasses.length; i++) defs[i] = new ClassDefinition(oldClasses[i], newClasses[i].toBytecode()); try { instrumentation.redefineClasses(defs); } catch (ClassNotFoundException e) { throw new NotFoundException(e.getMessage(), e); } catch (UnmodifiableClassException e) { throw new CannotCompileException(e.getMessage(), e); } } /** * Ensures that the agent is ready. * It attempts to dynamically start the agent if necessary. */ private static void startAgent() throws NotFoundException { if (instrumentation != null) return; try { File agentJar = createJarFile(); String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName(); String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@')); VirtualMachine vm = VirtualMachine.attach(pid); vm.loadAgent(agentJar.getAbsolutePath(), null); vm.detach(); } catch (Exception e) { throw new NotFoundException("hotswap agent", e); } for (int sec = 0; sec < 10 /* sec */; sec++) { if (instrumentation != null) return; try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } throw new NotFoundException("hotswap agent (timeout)"); } /** * Creates an agent file for using {@code HotSwapAgent}. */ public static File createAgentJarFile(String fileName) throws IOException, CannotCompileException, NotFoundException { return createJarFile(new File(fileName)); } private static File createJarFile() throws IOException, CannotCompileException, NotFoundException { File jar = File.createTempFile("agent", ".jar"); jar.deleteOnExit(); return createJarFile(jar); } private static File createJarFile(File jar) throws IOException, CannotCompileException, NotFoundException {<FILL_FUNCTION_BODY>} }
Manifest manifest = new Manifest(); Attributes attrs = manifest.getMainAttributes(); attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0"); attrs.put(new Attributes.Name("Premain-Class"), HotSwapAgent.class.getName()); attrs.put(new Attributes.Name("Agent-Class"), HotSwapAgent.class.getName()); attrs.put(new Attributes.Name("Can-Retransform-Classes"), "true"); attrs.put(new Attributes.Name("Can-Redefine-Classes"), "true"); JarOutputStream jos = null; try { jos = new JarOutputStream(new FileOutputStream(jar), manifest); String cname = HotSwapAgent.class.getName(); JarEntry e = new JarEntry(cname.replace('.', '/') + ".class"); jos.putNextEntry(e); ClassPool pool = ClassPool.getDefault(); CtClass clazz = pool.get(cname); jos.write(clazz.toBytecode()); jos.closeEntry(); } finally { if (jos != null) jos.close(); } return jar;
1,000
309
1,309
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/HotSwapper.java
HotSwapper
reload
class HotSwapper { private VirtualMachine jvm; private MethodEntryRequest request; private Map<ReferenceType,byte[]> newClassFiles; private Trigger trigger; private static final String HOST_NAME = "localhost"; private static final String TRIGGER_NAME = Trigger.class.getName(); /** * Connects to the JVM. * * @param port the port number used for the connection to the JVM. */ public HotSwapper(int port) throws IOException, IllegalConnectorArgumentsException { this(Integer.toString(port)); } /** * Connects to the JVM. * * @param port the port number used for the connection to the JVM. */ public HotSwapper(String port) throws IOException, IllegalConnectorArgumentsException { jvm = null; request = null; newClassFiles = null; trigger = new Trigger(); AttachingConnector connector = (AttachingConnector)findConnector("com.sun.jdi.SocketAttach"); Map<String,Connector.Argument> arguments = connector.defaultArguments(); arguments.get("hostname").setValue(HOST_NAME); arguments.get("port").setValue(port); jvm = connector.attach(arguments); EventRequestManager manager = jvm.eventRequestManager(); request = methodEntryRequests(manager, TRIGGER_NAME); } private Connector findConnector(String connector) throws IOException { List<Connector> connectors = Bootstrap.virtualMachineManager().allConnectors(); for (Connector con:connectors) if (con.name().equals(connector)) return con; throw new IOException("Not found: " + connector); } private static MethodEntryRequest methodEntryRequests( EventRequestManager manager, String classpattern) { MethodEntryRequest mereq = manager.createMethodEntryRequest(); mereq.addClassFilter(classpattern); mereq.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); return mereq; } /* Stops triggering a hotswapper when reload() is called. */ @SuppressWarnings("unused") private void deleteEventRequest(EventRequestManager manager, MethodEntryRequest request) { manager.deleteEventRequest(request); } /** * Reloads a class. * * @param className the fully-qualified class name. * @param classFile the contents of the class file. */ public void reload(String className, byte[] classFile) { ReferenceType classtype = toRefType(className); Map<ReferenceType,byte[]> map = new HashMap<ReferenceType,byte[]>(); map.put(classtype, classFile); reload2(map, className); } /** * Reloads a class. * * @param classFiles a map between fully-qualified class names * and class files. The type of the class names * is <code>String</code> and the type of the * class files is <code>byte[]</code>. */ public void reload(Map<String,byte[]> classFiles) {<FILL_FUNCTION_BODY>} private ReferenceType toRefType(String className) { List<ReferenceType> list = jvm.classesByName(className); if (list == null || list.isEmpty()) throw new RuntimeException("no such class: " + className); return list.get(0); } private void reload2(Map<ReferenceType,byte[]> map, String msg) { synchronized (trigger) { startDaemon(); newClassFiles = map; request.enable(); trigger.doSwap(); request.disable(); Map<ReferenceType,byte[]> ncf = newClassFiles; if (ncf != null) { newClassFiles = null; throw new RuntimeException("failed to reload: " + msg); } } } private void startDaemon() { new Thread() { private void errorMsg(Throwable e) { System.err.print("Exception in thread \"HotSwap\" "); e.printStackTrace(System.err); } @Override public void run() { EventSet events = null; try { events = waitEvent(); EventIterator iter = events.eventIterator(); while (iter.hasNext()) { Event event = iter.nextEvent(); if (event instanceof MethodEntryEvent) { hotswap(); break; } } } catch (Throwable e) { errorMsg(e); } try { if (events != null) events.resume(); } catch (Throwable e) { errorMsg(e); } } }.start(); } EventSet waitEvent() throws InterruptedException { EventQueue queue = jvm.eventQueue(); return queue.remove(); } void hotswap() { Map<ReferenceType,byte[]> map = newClassFiles; jvm.redefineClasses(map); newClassFiles = null; } }
Map<ReferenceType,byte[]> map = new HashMap<ReferenceType,byte[]>(); String className = null; for (Map.Entry<String,byte[]> e:classFiles.entrySet()) { className = e.getKey(); map.put(toRefType(className), e.getValue()); } if (className != null) reload2(map, className + " etc.");
1,373
106
1,479
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/DefineClassHelper.java
Java7
getDefineClassMethodHandle
class Java7 extends Helper { private final SecurityActions stack = SecurityActions.stack; private final MethodHandle defineClass = getDefineClassMethodHandle(); private final MethodHandle getDefineClassMethodHandle() {<FILL_FUNCTION_BODY>} @Override Class<?> defineClass(String name, byte[] b, int off, int len, Class<?> neighbor, ClassLoader loader, ProtectionDomain protectionDomain) throws ClassFormatError { if (stack.getCallerClass() != DefineClassHelper.class) throw new IllegalAccessError("Access denied for caller."); try { return (Class<?>) defineClass.invokeWithArguments( loader, name, b, off, len, protectionDomain); } catch (Throwable e) { if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ClassFormatError) throw (ClassFormatError) e; throw new ClassFormatError(e.getMessage()); } } }
if (privileged != null && stack.getCallerClass() != this.getClass()) throw new IllegalAccessError("Access denied for caller."); try { return SecurityActions.getMethodHandle(ClassLoader.class, "defineClass", new Class[] { String.class, byte[].class, int.class, int.class, ProtectionDomain.class }); } catch (NoSuchMethodException e) { throw new RuntimeException("cannot initialize", e); }
249
126
375
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/DefinePackageHelper.java
JavaOther
definePackage
class JavaOther extends Helper { private final SecurityActions stack = SecurityActions.stack; private final Method definePackage = getDefinePackageMethod(); private Method getDefinePackageMethod() { if (stack.getCallerClass() != this.getClass()) throw new IllegalAccessError("Access denied for caller."); try { return SecurityActions.getDeclaredMethod(ClassLoader.class, "definePackage", new Class[] { String.class, String.class, String.class, String.class, String.class, String.class, String.class, URL.class }); } catch (NoSuchMethodException e) { throw new RuntimeException("cannot initialize", e); } } @Override Package definePackage(ClassLoader loader, String name, String specTitle, String specVersion, String specVendor, String implTitle, String implVersion, String implVendor, URL sealBase) throws IllegalArgumentException { if (stack.getCallerClass() != DefinePackageHelper.class) throw new IllegalAccessError("Access denied for caller."); try { definePackage.setAccessible(true); return (Package) definePackage.invoke(loader, new Object[] { name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase }); } catch (Throwable e) { if (e instanceof InvocationTargetException) { Throwable t = ((InvocationTargetException) e).getTargetException(); if (t instanceof IllegalArgumentException) throw (IllegalArgumentException) t; } if (e instanceof RuntimeException) throw (RuntimeException) e; } finally { definePackage.setAccessible(false); } return null; } }; private static final Helper privileged = ClassFile.MAJOR_VERSION >= ClassFile.JAVA_9 ? new Java9() : ClassFile.MAJOR_VERSION >= ClassFile.JAVA_7 ? new Java7() : new JavaOther(); /** * Defines a new package. If the package is already defined, this method * performs nothing. * * <p>You do not necessarily need to * call this method. If this method is called, then * <code>getPackage()</code> on the <code>Class</code> object returned * by <code>toClass()</code> will return a non-null object.</p> * * <p>The jigsaw module introduced by Java 9 has broken this method. * In Java 9 or later, the VM argument * <code>--add-opens java.base/java.lang=ALL-UNNAMED</code> * has to be given to the JVM so that this method can run. * </p> * * @param loader the class loader passed to <code>toClass()</code> or * the default one obtained by <code>getClassLoader()</code>. * @param className the package name. * @see Class#getClassLoader() * @see CtClass#toClass() */ public static void definePackage(String className, ClassLoader loader) throws CannotCompileException {<FILL_FUNCTION_BODY>
try { privileged.definePackage(loader, className, null, null, null, null, null, null, null); } catch (IllegalArgumentException e) { // if the package is already defined, an IllegalArgumentException // is thrown. return; } catch (Exception e) { throw new CannotCompileException(e); }
837
97
934
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/FactoryHelper.java
FactoryHelper
writeFile0
class FactoryHelper { /** * Returns an index for accessing arrays in this class. * * @throws RuntimeException if a given type is not a primitive type. */ public static final int typeIndex(Class<?> type) { for (int i = 0; i < primitiveTypes.length; i++) if (primitiveTypes[i] == type) return i; throw new RuntimeException("bad type:" + type.getName()); } /** * <code>Class</code> objects representing primitive types. */ public static final Class<?>[] primitiveTypes = { Boolean.TYPE, Byte.TYPE, Character.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE, Void.TYPE }; /** * The fully-qualified names of wrapper classes for primitive types. */ public static final String[] wrapperTypes = { "java.lang.Boolean", "java.lang.Byte", "java.lang.Character", "java.lang.Short", "java.lang.Integer", "java.lang.Long", "java.lang.Float", "java.lang.Double", "java.lang.Void" }; /** * The descriptors of the constructors of wrapper classes. */ public static final String[] wrapperDesc = { "(Z)V", "(B)V", "(C)V", "(S)V", "(I)V", "(J)V", "(F)V", "(D)V" }; /** * The names of methods for obtaining a primitive value * from a wrapper object. For example, <code>intValue()</code> * is such a method for obtaining an integer value from a * <code>java.lang.Integer</code> object. */ public static final String[] unwarpMethods = { "booleanValue", "byteValue", "charValue", "shortValue", "intValue", "longValue", "floatValue", "doubleValue" }; /** * The descriptors of the unwrapping methods contained * in <code>unwrapMethods</code>. */ public static final String[] unwrapDesc = { "()Z", "()B", "()C", "()S", "()I", "()J", "()F", "()D" }; /** * The data size of primitive types. <code>long</code> * and <code>double</code> are 2; the others are 1. */ public static final int[] dataSize = { 1, 1, 1, 1, 1, 2, 1, 2 }; /** * Loads a class file by a given class loader. * This method uses a default protection domain for the class * but it may not work with a security manager or a signed jar file. * * @see #toClass(ClassFile,Class,ClassLoader,ProtectionDomain) * @deprecated */ public static Class<?> toClass(ClassFile cf, ClassLoader loader) throws CannotCompileException { return toClass(cf, null, loader, null); } /** * Loads a class file by a given class loader. * * @param neighbor a class belonging to the same package that * the loaded class belongs to. * It can be null. * @param loader The class loader. It can be null if {@code neighbor} * is not null. * @param domain if it is null, a default domain is used. * @since 3.3 */ public static Class<?> toClass(ClassFile cf, Class<?> neighbor, ClassLoader loader, ProtectionDomain domain) throws CannotCompileException { try { byte[] b = toBytecode(cf); if (ProxyFactory.onlyPublicMethods) return DefineClassHelper.toPublicClass(cf.getName(), b); else return DefineClassHelper.toClass(cf.getName(), neighbor, loader, domain, b); } catch (IOException e) { throw new CannotCompileException(e); } } /** * Loads a class file by a given lookup. * * @param lookup used to define the class. * @since 3.24 */ public static Class<?> toClass(ClassFile cf, java.lang.invoke.MethodHandles.Lookup lookup) throws CannotCompileException { try { byte[] b = toBytecode(cf); return DefineClassHelper.toClass(lookup, b); } catch (IOException e) { throw new CannotCompileException(e); } } private static byte[] toBytecode(ClassFile cf) throws IOException { ByteArrayOutputStream barray = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(barray); try { cf.write(out); } finally { out.close(); } return barray.toByteArray(); } /** * Writes a class file. */ public static void writeFile(ClassFile cf, String directoryName) throws CannotCompileException { try { writeFile0(cf, directoryName); } catch (IOException e) { throw new CannotCompileException(e); } } private static void writeFile0(ClassFile cf, String directoryName) throws CannotCompileException, IOException {<FILL_FUNCTION_BODY>} }
String classname = cf.getName(); String filename = directoryName + File.separatorChar + classname.replace('.', File.separatorChar) + ".class"; int pos = filename.lastIndexOf(File.separatorChar); if (pos > 0) { String dir = filename.substring(0, pos); if (!dir.equals(".")) new File(dir).mkdirs(); } DataOutputStream out = new DataOutputStream(new BufferedOutputStream( new FileOutputStream(filename))); try { cf.write(out); } catch (IOException e) { throw e; } finally { out.close(); }
1,423
177
1,600
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/ProxyObjectInputStream.java
ProxyObjectInputStream
readClassDescriptor
class ProxyObjectInputStream extends ObjectInputStream { /** * create an input stream which can be used to deserialize an object graph which includes proxies created * using class ProxyFactory. the classloader used to resolve proxy superclass and interface names * read from the input stream will default to the current thread's context class loader or the system * classloader if the context class loader is null. * @param in * @throws java.io.StreamCorruptedException whenever ObjectInputStream would also do so * @throws IOException whenever ObjectInputStream would also do so * @throws SecurityException whenever ObjectInputStream would also do so * @throws NullPointerException if in is null */ public ProxyObjectInputStream(InputStream in) throws IOException { super(in); loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } } /** * Reset the loader to be * @param loader */ public void setClassLoader(ClassLoader loader) { if (loader != null) { this.loader = loader; } else { loader = ClassLoader.getSystemClassLoader(); } } @Override protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} /** * the loader to use to resolve classes for proxy superclass and interface names read * from the stream. defaults to the context class loader of the thread which creates * the input stream or the system class loader if the context class loader is null. */ private ClassLoader loader; }
boolean isProxy = readBoolean(); if (isProxy) { String name = (String)readObject(); Class<?> superClass = loader.loadClass(name); int length = readInt(); Class<?>[] interfaces = new Class[length]; for (int i = 0; i < length; i++) { name = (String)readObject(); interfaces[i] = loader.loadClass(name); } length = readInt(); byte[] signature = new byte[length]; read(signature); ProxyFactory factory = new ProxyFactory(); // we must always use the cache and never use writeReplace when using // ProxyObjectOutputStream and ProxyObjectInputStream factory.setUseCache(true); factory.setUseWriteReplace(false); factory.setSuperclass(superClass); factory.setInterfaces(interfaces); Class<?> proxyClass = factory.createClass(signature); return ObjectStreamClass.lookup(proxyClass); } return super.readClassDescriptor();
410
261
671
<methods>public void <init>(java.io.InputStream) throws java.io.IOException,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public void defaultReadObject() throws java.io.IOException, java.lang.ClassNotFoundException,public final java.io.ObjectInputFilter getObjectInputFilter() ,public int read() throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public boolean readBoolean() throws java.io.IOException,public byte readByte() throws java.io.IOException,public char readChar() throws java.io.IOException,public double readDouble() throws java.io.IOException,public java.io.ObjectInputStream.GetField readFields() throws java.io.IOException, java.lang.ClassNotFoundException,public float readFloat() throws java.io.IOException,public void readFully(byte[]) throws java.io.IOException,public void readFully(byte[], int, int) throws java.io.IOException,public int readInt() throws java.io.IOException,public java.lang.String readLine() throws java.io.IOException,public long readLong() throws java.io.IOException,public final java.lang.Object readObject() throws java.io.IOException, java.lang.ClassNotFoundException,public short readShort() throws java.io.IOException,public java.lang.String readUTF() throws java.io.IOException,public java.lang.Object readUnshared() throws java.io.IOException, java.lang.ClassNotFoundException,public int readUnsignedByte() throws java.io.IOException,public int readUnsignedShort() throws java.io.IOException,public void registerValidation(java.io.ObjectInputValidation, int) throws java.io.NotActiveException, java.io.InvalidObjectException,public final void setObjectInputFilter(java.io.ObjectInputFilter) ,public int skipBytes(int) throws java.io.IOException<variables>static final boolean $assertionsDisabled,private static final int NULL_HANDLE,private static final jdk.internal.misc.Unsafe UNSAFE,private final java.io.ObjectInputStream.BlockDataInputStream bin,private boolean closed,private java.io.SerialCallbackContext curContext,private boolean defaultDataEnd,private long depth,private final boolean enableOverride,private boolean enableResolve,private final java.io.ObjectInputStream.HandleTable handles,private int passHandle,private static final Map<java.lang.String,Class<?>> primClasses,private java.io.ObjectInputFilter serialFilter,private boolean streamFilterSet,private long totalObjectRefs,private static final java.lang.Object unsharedMarker,private final java.io.ObjectInputStream.ValidationList vlist
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/ProxyObjectOutputStream.java
ProxyObjectOutputStream
writeClassDescriptor
class ProxyObjectOutputStream extends ObjectOutputStream { /** * create an output stream which can be used to serialize an object graph which includes proxies created * using class ProxyFactory * @param out * @throws IOException whenever ObjectOutputStream would also do so * @throws SecurityException whenever ObjectOutputStream would also do so * @throws NullPointerException if out is null */ public ProxyObjectOutputStream(OutputStream out) throws IOException { super(out); } @Override protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException {<FILL_FUNCTION_BODY>} }
Class<?> cl = desc.forClass(); if (ProxyFactory.isProxyClass(cl)) { writeBoolean(true); Class<?> superClass = cl.getSuperclass(); Class<?>[] interfaces = cl.getInterfaces(); byte[] signature = ProxyFactory.getFilterSignature(cl); String name = superClass.getName(); writeObject(name); // we don't write the marker interface ProxyObject writeInt(interfaces.length - 1); for (int i = 0; i < interfaces.length; i++) { Class<?> interfaze = interfaces[i]; if (interfaze != ProxyObject.class && interfaze != Proxy.class) { name = interfaces[i].getName(); writeObject(name); } } writeInt(signature.length); write(signature); } else { writeBoolean(false); super.writeClassDescriptor(desc); }
153
247
400
<methods>public void <init>(java.io.OutputStream) throws java.io.IOException,public void close() throws java.io.IOException,public void defaultWriteObject() throws java.io.IOException,public void flush() throws java.io.IOException,public java.io.ObjectOutputStream.PutField putFields() throws java.io.IOException,public void reset() throws java.io.IOException,public void useProtocolVersion(int) throws java.io.IOException,public void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException,public void writeBoolean(boolean) throws java.io.IOException,public void writeByte(int) throws java.io.IOException,public void writeBytes(java.lang.String) throws java.io.IOException,public void writeChar(int) throws java.io.IOException,public void writeChars(java.lang.String) throws java.io.IOException,public void writeDouble(double) throws java.io.IOException,public void writeFields() throws java.io.IOException,public void writeFloat(float) throws java.io.IOException,public void writeInt(int) throws java.io.IOException,public void writeLong(long) throws java.io.IOException,public final void writeObject(java.lang.Object) throws java.io.IOException,public void writeShort(int) throws java.io.IOException,public void writeUTF(java.lang.String) throws java.io.IOException,public void writeUnshared(java.lang.Object) throws java.io.IOException<variables>static final boolean $assertionsDisabled,private final java.io.ObjectOutputStream.BlockDataOutputStream bout,private java.io.SerialCallbackContext curContext,private java.io.ObjectOutputStream.PutFieldImpl curPut,private final java.io.ObjectOutputStream.DebugTraceInfoStack debugInfoStack,private int depth,private final boolean enableOverride,private boolean enableReplace,private static final boolean extendedDebugInfo,private final java.io.ObjectOutputStream.HandleTable handles,private byte[] primVals,private int protocol,private final java.io.ObjectOutputStream.ReplaceTable subs
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/RuntimeSupport.java
DefaultMethodHandler
findMethod
class DefaultMethodHandler implements MethodHandler, Serializable { /** default serialVersionUID */ private static final long serialVersionUID = 1L; @Override public Object invoke(Object self, Method m, Method proceed, Object[] args) throws Exception { return proceed.invoke(self, args); } }; /** * Finds two methods specified by the parameters and stores them * into the given array. * * @throws RuntimeException if the methods are not found. * @see javassist.util.proxy.ProxyFactory */ public static void find2Methods(Class<?> clazz, String superMethod, String thisMethod, int index, String desc, java.lang.reflect.Method[] methods) { methods[index + 1] = thisMethod == null ? null : findMethod(clazz, thisMethod, desc); methods[index] = findSuperClassMethod(clazz, superMethod, desc); } /** * Finds two methods specified by the parameters and stores them * into the given array. * * <p>Added back for JBoss Seam. See JASSIST-206.</p> * * @throws RuntimeException if the methods are not found. * @see javassist.util.proxy.ProxyFactory * @deprecated replaced by {@link #find2Methods(Class, String, String, int, String, Method[])} */ @Deprecated public static void find2Methods(Object self, String superMethod, String thisMethod, int index, String desc, java.lang.reflect.Method[] methods) { methods[index + 1] = thisMethod == null ? null : findMethod(self, thisMethod, desc); methods[index] = findSuperMethod(self, superMethod, desc); } /** * Finds a method with the given name and descriptor. * It searches only the class of self. * * <p>Added back for JBoss Seam. See JASSIST-206.</p> * * @throws RuntimeException if the method is not found. * @deprecated replaced by {@link #findMethod(Class, String, String)} */ @Deprecated public static Method findMethod(Object self, String name, String desc) {<FILL_FUNCTION_BODY>
Method m = findMethod2(self.getClass(), name, desc); if (m == null) error(self.getClass(), name, desc); return m;
597
48
645
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/SerializedProxy.java
SerializedProxy
loadClass
class SerializedProxy implements Serializable { /** default serialVersionUID */ private static final long serialVersionUID = 1L; private String superClass; private String[] interfaces; private byte[] filterSignature; private MethodHandler handler; SerializedProxy(Class<?> proxy, byte[] sig, MethodHandler h) { filterSignature = sig; handler = h; superClass = proxy.getSuperclass().getName(); Class<?>[] infs = proxy.getInterfaces(); int n = infs.length; interfaces = new String[n - 1]; String setterInf = ProxyObject.class.getName(); String setterInf2 = Proxy.class.getName(); for (int i = 0; i < n; i++) { String name = infs[i].getName(); if (!name.equals(setterInf) && !name.equals(setterInf2)) interfaces[i] = name; } } /** * Load class. * * @param className the class name * @return loaded class * @throws ClassNotFoundException for any error */ protected Class<?> loadClass(final String className) throws ClassNotFoundException {<FILL_FUNCTION_BODY>} Object readResolve() throws ObjectStreamException { try { int n = interfaces.length; Class<?>[] infs = new Class[n]; for (int i = 0; i < n; i++) infs[i] = loadClass(interfaces[i]); ProxyFactory f = new ProxyFactory(); f.setSuperclass(loadClass(superClass)); f.setInterfaces(infs); Proxy proxy = (Proxy)f.createClass(filterSignature).getConstructor().newInstance(); proxy.setHandler(handler); return proxy; } catch (NoSuchMethodException e) { throw new InvalidClassException(e.getMessage()); } catch (InvocationTargetException e) { throw new InvalidClassException(e.getMessage()); } catch (ClassNotFoundException e) { throw new InvalidClassException(e.getMessage()); } catch (InstantiationException e2) { throw new InvalidObjectException(e2.getMessage()); } catch (IllegalAccessException e3) { throw new InvalidClassException(e3.getMessage()); } } }
try { return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>(){ @Override public Class<?> run() throws Exception{ ClassLoader cl = Thread.currentThread().getContextClassLoader(); return Class.forName(className, true, cl); } }); } catch (PrivilegedActionException pae) { throw new RuntimeException("cannot load the class: " + className, pae.getException()); }
605
126
731
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/logging/AgentLogger.java
AgentLogger
isLevelEnabled
class AgentLogger { /** * Get logger for a class * * @param clazz class to log * @return logger */ public static AgentLogger getLogger(Class clazz) { return new AgentLogger(clazz); } private static Map<String, Level> currentLevels = new HashMap<>(); public static void setLevel(String classPrefix, Level level) { currentLevels.put(classPrefix, level); } private static Level rootLevel = Level.INFO; public static void setLevel(Level level) { rootLevel = level; } private static AgentLoggerHandler handler = new AgentLoggerHandler(); public static void setHandler(AgentLoggerHandler handler) { AgentLogger.handler = handler; } public static AgentLoggerHandler getHandler() { return handler; } public static void setDateTimeFormat(String dateTimeFormat) { handler.setDateTimeFormat(dateTimeFormat); } /** * Standard logging levels. */ public enum Level { ERROR, RELOAD, WARNING, INFO, DEBUG, TRACE } private Class clazz; private AgentLogger(Class clazz) { this.clazz = clazz; } public boolean isLevelEnabled(Level level) {<FILL_FUNCTION_BODY>} public void log(Level level, String message, Throwable throwable, Object... args) { if (isLevelEnabled(level)) handler.print(clazz, level, message, throwable, args); } public void log(Level level, String message, Object... args) { log(level, message, null, args); } public void error(String message, Object... args) { log(Level.ERROR, message, args); } public void error(String message, Throwable throwable, Object... args) { log(Level.ERROR, message, throwable, args); } public void reload(String message, Object... args) { log(Level.RELOAD, message, args); } public void reload(String message, Throwable throwable, Object... args) { log(Level.RELOAD, message, throwable, args); } public void warning(String message, Object... args) { log(Level.WARNING, message, args); } public void warning(String message, Throwable throwable, Object... args) { log(Level.WARNING, message, throwable, args); } public void info(String message, Object... args) { log(Level.INFO, message, args); } public void info(String message, Throwable throwable, Object... args) { log(Level.INFO, message, throwable, args); } public void debug(String message, Object... args) { log(Level.DEBUG, message, args); } public void debug(String message, Throwable throwable, Object... args) { log(Level.DEBUG, message, throwable, args); } public void trace(String message, Object... args) { log(Level.TRACE, message, args); } public void trace(String message, Throwable throwable, Object... args) { log(Level.TRACE, message, throwable, args); } public boolean isDebugEnabled() { return isLevelEnabled(Level.DEBUG); } public boolean isWarnEnabled() { return isLevelEnabled(Level.WARNING); } }
Level classLevel = rootLevel; String className = clazz.getName(); String longestPrefix = ""; for (String classPrefix : currentLevels.keySet()) { if (className.startsWith(classPrefix)) { if (classPrefix.length() > longestPrefix.length()) { longestPrefix = classPrefix; classLevel = currentLevels.get(classPrefix); } } } // iterate levels in order from most serious. If classLevel is first, it preciedes required level and log is disabled for (Level l : Level.values()) { if (l == level) return true; if (l == classLevel) return false; } throw new IllegalArgumentException("Should not happen.");
916
190
1,106
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/logging/AgentLoggerHandler.java
AgentLoggerHandler
formatErrorTrace
class AgentLoggerHandler { // stream to receive the log PrintStream outputStream; SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); /** * Setup custom stream (default is System.out). * * @param outputStream custom stream */ public void setPrintStream(PrintStream outputStream) { this.outputStream = outputStream; } // print a message to System.out and optionally to custom stream protected void printMessage(String message) { String log = "HOTSWAP AGENT: " + sdf.format(new Date()) + " " + message; System.out.println(log); if (outputStream != null) outputStream.println(log); } public void print(Class clazz, AgentLogger.Level level, String message, Throwable throwable, Object... args) { // replace {} in string with actual parameters String messageWithArgs = message; for (Object arg : args) { int index = messageWithArgs.indexOf("{}"); if (index >= 0) { messageWithArgs = messageWithArgs.substring(0, index) + String.valueOf(arg) + messageWithArgs.substring(index + 2); } } StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(level); stringBuffer.append(" ("); stringBuffer.append(clazz.getName()); stringBuffer.append(") - "); stringBuffer.append(messageWithArgs); if (throwable != null) { stringBuffer.append("\n"); stringBuffer.append(formatErrorTrace(throwable)); } printMessage(stringBuffer.toString()); } private String formatErrorTrace(Throwable throwable) {<FILL_FUNCTION_BODY>} public void setDateTimeFormat(String dateTimeFormat) { sdf = new SimpleDateFormat(dateTimeFormat); } }
StringWriter errors = new StringWriter(); throwable.printStackTrace(new PrintWriter(errors)); return errors.toString();
496
35
531
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/hotswapper/HotSwapper.java
HotSwapper
newClass
class HotSwapper { /** * Swap class definition from another class file. * <p/> * This is mainly useful for unit testing - declare multiple version of a class and then * hotswap definition and do the tests. * * @param original original class currently in use * @param swap fully qualified class name of class to swap * @throws Exception swap exception */ public static void swapClasses(Class original, String swap) throws Exception { // need to recreate classpool on each swap to avoid stale class definition ClassPool classPool = new ClassPool(); classPool.appendClassPath(new LoaderClassPath(original.getClassLoader())); CtClass ctClass = classPool.getAndRename(swap, original.getName()); reload(original, ctClass.toBytecode()); } private static void reload(Class original, byte[] bytes) { Map<Class<?>, byte[]> reloadMap = new HashMap<>(); reloadMap.put(original, bytes); PluginManager.getInstance().hotswap(reloadMap); } public static Class newClass(String className, String directory, ClassLoader cl){<FILL_FUNCTION_BODY>} }
try { ClassPool classPool = new ClassPool(); classPool.appendClassPath(new LoaderClassPath(cl)); CtClass makeClass = classPool.makeClass(className); makeClass.writeFile(directory); return makeClass.toClass(); } catch (Throwable ex) { Logger.getLogger(HotSwapper.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException(ex); }
317
121
438
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/hotswapper/HotSwapperJpda.java
HotSwapperJpda
run
class HotSwapperJpda { private VirtualMachine jvm; private MethodEntryRequest request; private Map<ReferenceType,byte[]> newClassFiles; private Trigger trigger; private static final String HOST_NAME = "localhost"; private static final String TRIGGER_NAME = Trigger.class.getName(); /** * Connects to the JVM. * * @param port the port number used for the connection to the JVM. */ public HotSwapperJpda(int port) throws IOException, IllegalConnectorArgumentsException { this(Integer.toString(port)); } /** * Connects to the JVM. * * @param port the port number used for the connection to the JVM. */ public HotSwapperJpda(String port) throws IOException, IllegalConnectorArgumentsException { jvm = null; request = null; newClassFiles = null; trigger = new Trigger(); AttachingConnector connector = (AttachingConnector)findConnector("com.sun.jdi.SocketAttach"); Map<String,Connector.Argument> arguments = connector.defaultArguments(); arguments.get("hostname").setValue(HOST_NAME); arguments.get("port").setValue(port); jvm = connector.attach(arguments); EventRequestManager manager = jvm.eventRequestManager(); request = methodEntryRequests(manager, TRIGGER_NAME); } private Connector findConnector(String connector) throws IOException { List<Connector> connectors = Bootstrap.virtualMachineManager().allConnectors(); for (Connector con:connectors) if (con.name().equals(connector)) return con; throw new IOException("Not found: " + connector); } private static MethodEntryRequest methodEntryRequests( EventRequestManager manager, String classpattern) { MethodEntryRequest mereq = manager.createMethodEntryRequest(); mereq.addClassFilter(classpattern); mereq.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); return mereq; } /* Stops triggering a hotswapper when reload() is called. */ @SuppressWarnings("unused") private void deleteEventRequest(EventRequestManager manager, MethodEntryRequest request) { manager.deleteEventRequest(request); } /** * Reloads a class. * * @param className the fully-qualified class name. * @param classFile the contents of the class file. */ public void reload(String className, byte[] classFile) { ReferenceType classtype = toRefType(className); Map<ReferenceType,byte[]> map = new HashMap<ReferenceType,byte[]>(); map.put(classtype, classFile); reload2(map, className); } /** * Reloads a class. * * @param classFiles a map between fully-qualified class names * and class files. The type of the class names * is <code>String</code> and the type of the * class files is <code>byte[]</code>. */ public void reload(Map<String,byte[]> classFiles) { Map<ReferenceType,byte[]> map = new HashMap<ReferenceType,byte[]>(); String className = null; for (Map.Entry<String,byte[]> e:classFiles.entrySet()) { className = e.getKey(); map.put(toRefType(className), e.getValue()); } if (className != null) reload2(map, className + " etc."); } private ReferenceType toRefType(String className) { List<ReferenceType> list = jvm.classesByName(className); if (list == null || list.isEmpty()) throw new RuntimeException("no such class: " + className); return list.get(0); } private void reload2(Map<ReferenceType,byte[]> map, String msg) { synchronized (trigger) { startDaemon(); newClassFiles = map; request.enable(); trigger.doSwap(); request.disable(); Map<ReferenceType,byte[]> ncf = newClassFiles; if (ncf != null) { newClassFiles = null; throw new RuntimeException("failed to reload: " + msg); } } } private void startDaemon() { new Thread() { private void errorMsg(Throwable e) { System.err.print("Exception in thread \"HotSwap\" "); e.printStackTrace(System.err); } @Override public void run() {<FILL_FUNCTION_BODY>} }.start(); } EventSet waitEvent() throws InterruptedException { EventQueue queue = jvm.eventQueue(); return queue.remove(); } void hotswap() { Map<ReferenceType,byte[]> map = newClassFiles; jvm.redefineClasses(map); newClassFiles = null; } /** * Swap class definition from another class file. * <p/> * This is mainly useful for unit testing - declare multiple version of a class and then * hotswap definition and do the tests. * * @param original original class currently in use * @param swap fully qualified class name of class to swap * @throws Exception swap exception */ public void swapClasses(Class original, String swap) throws Exception { // need to recreate classpool on each swap to avoid stale class definition ClassPool classPool = new ClassPool(); classPool.appendClassPath(new LoaderClassPath(original.getClassLoader())); CtClass ctClass = classPool.getAndRename(swap, original.getName()); reload(original.getName(), ctClass.toBytecode()); } }
EventSet events = null; try { events = waitEvent(); EventIterator iter = events.eventIterator(); while (iter.hasNext()) { Event event = iter.nextEvent(); if (event instanceof MethodEntryEvent) { hotswap(); break; } } } catch (Throwable e) { errorMsg(e); } try { if (events != null) events.resume(); } catch (Throwable e) { errorMsg(e); }
1,535
141
1,676
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/hotswapper/HotswapperCommand.java
HotswapperCommand
hotswap
class HotswapperCommand { private static AgentLogger LOGGER = AgentLogger.getLogger(HotswapperCommand.class); // HotSwapperJpda will connect to JPDA on first hotswap command and remain connected. // The HotSwapperJpda class from javaassist is copied to the plugin, because it needs to reside // in the application classloader to avoid NoClassDefFound error on tools.jar classes. private static HotSwapperJpda hotSwapper = null; public static synchronized void hotswap(String port, final HashMap<Class<?>, byte[]> reloadMap) {<FILL_FUNCTION_BODY>} }
// synchronize on the reloadMap object - do not allow addition while in process synchronized (reloadMap) { if (hotSwapper == null) { LOGGER.debug("Starting HotSwapperJpda agent on JPDA transport socket - port {}, classloader {}", port, HotswapperCommand.class.getClassLoader()); try { hotSwapper = new HotSwapperJpda(port); } catch (IOException e) { LOGGER.error("Unable to connect to debug session. Did you start the application with debug enabled " + "(i.e. java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000)", e); } catch (Exception e) { LOGGER.error("Unable to connect to debug session. Please check port property setting '{}'.", e, port); } } if (hotSwapper != null) { LOGGER.debug("Reloading classes {}", Arrays.toString(reloadMap.keySet().toArray())); // convert to Map Class name -> bytecode // We loose some information here, reload use always first class name that it finds reference to. Map<String, byte[]> reloadMapClassNames = new HashMap<>(); for (Map.Entry<Class<?>, byte[]> entry : reloadMap.entrySet()) { reloadMapClassNames.put(entry.getKey().getName(), entry.getValue()); } // actual hotswap via JPDA hotSwapper.reload(reloadMapClassNames); reloadMap.clear(); LOGGER.debug("HotSwapperJpda agent reload complete."); } }
175
437
612
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/hotswapper/HotswapperPlugin.java
HotswapperPlugin
initHotswapCommand
class HotswapperPlugin { private static AgentLogger LOGGER = AgentLogger.getLogger(HotswapperPlugin.class); @Init Scheduler scheduler; @Init PluginManager pluginManager; // synchronize on this map to wait for previous processing final Map<Class<?>, byte[]> reloadMap = new HashMap<>(); // command to do actual hotswap. Single command to merge possible multiple reload actions. Command hotswapCommand; /** * For each changed class create a reload command. */ @OnClassFileEvent(classNameRegexp = ".*", events = {FileEvent.MODIFY, FileEvent.CREATE}) public void watchReload(CtClass ctClass, ClassLoader appClassLoader, URL url) throws IOException, CannotCompileException { if (!ClassLoaderHelper.isClassLoaded(appClassLoader, ctClass.getName())) { LOGGER.trace("Class {} not loaded yet, no need for autoHotswap, skipped URL {}", ctClass.getName(), url); return; } LOGGER.debug("Class {} will be reloaded from URL {}", ctClass.getName(), url); // search for a class to reload Class clazz; try { clazz = appClassLoader.loadClass(ctClass.getName()); } catch (ClassNotFoundException e) { LOGGER.warning("Hotswapper tries to reload class {}, which is not known to application classLoader {}.", ctClass.getName(), appClassLoader); return; } synchronized (reloadMap) { reloadMap.put(clazz, ctClass.toBytecode()); } scheduler.scheduleCommand(hotswapCommand, 100, Scheduler.DuplicateSheduleBehaviour.SKIP); } /** * Create a hotswap command using hotSwappper. * * @param appClassLoader it can be run in any classloader with tools.jar on classpath. AppClassLoader can * be setup by maven dependency (jetty plugin), use this classloader. * @param port attach the hotswapper */ public void initHotswapCommand(ClassLoader appClassLoader, String port) {<FILL_FUNCTION_BODY>} /** * For each classloader check for autoHotswap configuration instance with hotswapper. */ @Init public static void init(PluginConfiguration pluginConfiguration, ClassLoader appClassLoader) { if (appClassLoader == null) { LOGGER.debug("Bootstrap class loader is null, hotswapper skipped."); return; } LOGGER.debug("Init plugin at classLoader {}", appClassLoader); // init only if the classloader contains directly the property file (not in parent classloader) if (!HotswapAgent.isAutoHotswap() && !pluginConfiguration.containsPropertyFile()) { LOGGER.debug("ClassLoader {} does not contain hotswap-agent.properties file, hotswapper skipped.", appClassLoader); return; } // and autoHotswap enabled if (!HotswapAgent.isAutoHotswap() && !pluginConfiguration.getPropertyBoolean("autoHotswap")) { LOGGER.debug("ClassLoader {} has autoHotswap disabled, hotswapper skipped.", appClassLoader); return; } String port = pluginConfiguration.getProperty("autoHotswap.port"); HotswapperPlugin plugin = PluginManagerInvoker.callInitializePlugin(HotswapperPlugin.class, appClassLoader); if (plugin != null) { plugin.initHotswapCommand(appClassLoader, port); } else { LOGGER.debug("Hotswapper is disabled in {}", appClassLoader); } } }
if (port != null && port.length() > 0) { hotswapCommand = new ReflectionCommand(this, HotswapperCommand.class.getName(), "hotswap", appClassLoader, port, reloadMap); } else { hotswapCommand = new Command() { @Override public void executeCommand() { pluginManager.hotswap(reloadMap); } @Override public String toString() { return "pluginManager.hotswap(" + Arrays.toString(reloadMap.keySet().toArray()) + ")"; } }; }
992
163
1,155
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/jdk/JdkPlugin.java
JdkPlugin
flushObjectStreamCaches
class JdkPlugin { private static AgentLogger LOGGER = AgentLogger.getLogger(JdkPlugin.class); /** * Flag to check reload status. It is necessary (in unit tests)to wait for reload is finished before the test * can continue. Set flag to true in the test class and wait until the flag is false again. */ public static boolean reloadFlag; @OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE, skipSynthetic=false) public static void flushBeanIntrospectorCaches(ClassLoader classLoader, CtClass ctClass) { try { LOGGER.debug("Flushing {} from introspector", ctClass.getName()); Class<?> clazz = classLoader.loadClass(ctClass.getName()); Class<?> threadGroupCtxClass = classLoader.loadClass("java.beans.ThreadGroupContext"); Class<?> introspectorClass = classLoader.loadClass("java.beans.Introspector"); synchronized (classLoader) { Object contexts = ReflectionHelper.get(null, threadGroupCtxClass, "contexts"); Object table[] = (Object[]) ReflectionHelper.get(contexts, "table"); if (table != null) { for (Object o: table) { if (o != null) { Object threadGroupContext = ReflectionHelper.get(o, "value"); if (threadGroupContext != null) { LOGGER.trace("Removing from threadGroupContext"); ReflectionHelper.invoke(threadGroupContext, threadGroupCtxClass, "removeBeanInfo", new Class[] { Class.class }, clazz); } } } } ReflectionHelper.invoke(null, introspectorClass, "flushFromCaches", new Class[] { Class.class }, clazz); } } catch (Exception e) { LOGGER.error("flushBeanIntrospectorCaches() exception {}.", e.getMessage()); } finally { reloadFlag = false; } } @OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE, skipSynthetic=false) public static void flushObjectStreamCaches(ClassLoader classLoader, CtClass ctClass) {<FILL_FUNCTION_BODY>} }
Class<?> clazz; Object localDescs; Object reflectors; try { LOGGER.debug("Flushing {} from ObjectStreamClass caches", ctClass.getName()); clazz = classLoader.loadClass(ctClass.getName()); Class<?> objectStreamClassCache = classLoader.loadClass("java.io.ObjectStreamClass$Caches"); localDescs = ReflectionHelper.get(null, objectStreamClassCache, "localDescs"); reflectors = ReflectionHelper.get(null, objectStreamClassCache, "reflectors"); } catch (Exception e) { LOGGER.error("flushObjectStreamCaches() java.io.ObjectStreamClass$Caches not found.", e.getMessage()); return; } boolean java17; try { ((Map) localDescs).clear(); ((Map) reflectors).clear(); java17 = false; } catch (Exception e) { java17 = true; } if (java17) { try { Object localDescsMap = ReflectionHelper.get(localDescs, "map"); ReflectionHelper.invoke(localDescsMap, localDescsMap.getClass(), "remove", new Class[] { Class.class }, clazz); Object reflectorsMap = ReflectionHelper.get(reflectors, "map"); ReflectionHelper.invoke(reflectorsMap, reflectorsMap.getClass(), "remove", new Class[] { Class.class }, clazz); } catch (Exception e) { LOGGER.error("flushObjectStreamCaches() exception {}.", e.getMessage()); } }
590
410
1,000
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/jvm/AnonymousClassInfo.java
AnonymousClassInfo
getMethodSignature
class AnonymousClassInfo { // name of the anonymous class String className; // signatures String classSignature; String methodSignature; String fieldsSignature; String enclosingMethodSignature; public AnonymousClassInfo(Class c) { this.className = c.getName(); StringBuilder classSignature = new StringBuilder(c.getSuperclass().getName()); for (Class intef : c.getInterfaces()) { classSignature.append(";"); classSignature.append(intef.getName()); } this.classSignature = classSignature.toString(); StringBuilder methodsSignature = new StringBuilder(); for (Method m : c.getDeclaredMethods()) { getMethodSignature(methodsSignature, m); } this.methodSignature = methodsSignature.toString(); StringBuilder fieldsSignature = new StringBuilder(); for (Field f : c.getDeclaredFields()) { // replace declarig class for constant because of unit tests (class name change) fieldsSignature.append(f.getType().getName()); fieldsSignature.append(" "); fieldsSignature.append(f.getName()); fieldsSignature.append(";"); } this.fieldsSignature = fieldsSignature.toString(); StringBuilder enclosingMethodSignature = new StringBuilder(); Method enclosingMethod = c.getEnclosingMethod(); if (enclosingMethod != null) { getMethodSignature(enclosingMethodSignature, enclosingMethod); } this.enclosingMethodSignature = enclosingMethodSignature.toString(); } public AnonymousClassInfo(String className) { this.className = className; } private void getMethodSignature(StringBuilder methodsSignature, Method m) { methodsSignature.append(m.getReturnType().getName()); methodsSignature.append(" "); methodsSignature.append(m.getName()); methodsSignature.append("("); for (Class paramType : m.getParameterTypes()) methodsSignature.append(paramType.getName()); methodsSignature.append(")"); methodsSignature.append(";"); } public AnonymousClassInfo(CtClass c) { try { this.className = c.getName(); StringBuilder classSignature = new StringBuilder(c.getSuperclassName()); for (CtClass intef : c.getInterfaces()) { classSignature.append(";"); classSignature.append(intef.getName()); } this.classSignature = classSignature.toString(); StringBuilder methodsSignature = new StringBuilder(); for (CtMethod m : c.getDeclaredMethods()) { getMethodSignature(methodsSignature, m); } this.methodSignature = methodsSignature.toString(); StringBuilder fieldsSignature = new StringBuilder(); for (CtField f : c.getDeclaredFields()) { fieldsSignature.append(f.getType().getName()); fieldsSignature.append(" "); fieldsSignature.append(f.getName()); fieldsSignature.append(";"); } this.fieldsSignature = fieldsSignature.toString(); StringBuilder enclosingMethodSignature = new StringBuilder(); try { CtMethod enclosingMethod = c.getEnclosingMethod(); if (enclosingMethod != null) { getMethodSignature(enclosingMethodSignature, enclosingMethod); } } catch (Exception e) { // OK, enclosing method not defined or out of scope } this.enclosingMethodSignature = enclosingMethodSignature.toString(); } catch (Throwable t) { throw new IllegalStateException("Error creating AnonymousClassInfo from " + c.getName(), t); } } private void getMethodSignature(StringBuilder methodsSignature, CtMethod m) throws NotFoundException {<FILL_FUNCTION_BODY>} public String getClassName() { return className; } public String getClassSignature() { return classSignature; } public String getMethodSignature() { return methodSignature; } public String getFieldsSignature() { return fieldsSignature; } public String getEnclosingMethodSignature() { return enclosingMethodSignature; } /** * Exact match including enclosing method. */ public boolean matchExact(AnonymousClassInfo other) { return getClassSignature().equals(other.getClassSignature()) && getMethodSignature().equals(other.getMethodSignature()) && getFieldsSignature().equals(other.getFieldsSignature()) && getEnclosingMethodSignature().equals(other.getEnclosingMethodSignature()); } /** * Exact match of class, interfaces, declared methods and fields. * May be different enclosing method. */ public boolean matchSignatures(AnonymousClassInfo other) { return getClassSignature().equals(other.getClassSignature()) && getMethodSignature().equals(other.getMethodSignature()) && getFieldsSignature().equals(other.getFieldsSignature()); } /** * The least matching variant - same class signature can be still resolved by hotswap. */ public boolean matchClassSignature(AnonymousClassInfo other) { return getClassSignature().equals(other.getClassSignature()); } }
methodsSignature.append(m.getReturnType().getName()); methodsSignature.append(" "); methodsSignature.append(m.getName()); methodsSignature.append("("); for (CtClass paramType : m.getParameterTypes()) methodsSignature.append(paramType.getName()); methodsSignature.append(")"); methodsSignature.append(";");
1,315
92
1,407
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/jvm/ClassInitPlugin.java
ClassInitPlugin
patch
class ClassInitPlugin { private static AgentLogger LOGGER = AgentLogger.getLogger(ClassInitPlugin.class); private static final String HOTSWAP_AGENT_CLINIT_METHOD = "$$ha$clinit"; public static boolean reloadFlag; @OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE) public static void patch(final CtClass ctClass, final ClassLoader classLoader, final Class<?> originalClass) throws IOException, CannotCompileException, NotFoundException {<FILL_FUNCTION_BODY>} private static boolean checkOldEnumValues(CtClass ctClass, Class<?> originalClass) { if (ctClass.isEnum()) { // Check if some field from original enumeration was deleted Enum<?>[] enumConstants = (Enum<?>[]) originalClass.getEnumConstants(); for (Enum<?> en : enumConstants) { try { CtField existing = ctClass.getDeclaredField(en.toString()); } catch (NotFoundException e) { LOGGER.debug("Enum field deleted. $VALUES will be reinitialized {}", en.toString()); return true; } } } else { LOGGER.error("Patching " + HOTSWAP_AGENT_CLINIT_METHOD + " method failed. Enum type expected {}", ctClass.getName()); } return false; } private static boolean isSyntheticClass(Class<?> classBeingRedefined) { return classBeingRedefined.getSimpleName().contains("$$_javassist") || classBeingRedefined.getSimpleName().contains("$$_jvst") || classBeingRedefined.getName().startsWith("com.sun.proxy.$Proxy") || classBeingRedefined.getSimpleName().contains("$$"); } }
if (isSyntheticClass(originalClass)) { return; } final String className = ctClass.getName(); try { CtMethod origMethod = ctClass.getDeclaredMethod(HOTSWAP_AGENT_CLINIT_METHOD); ctClass.removeMethod(origMethod); } catch (org.hotswap.agent.javassist.NotFoundException ex) { // swallow } CtConstructor clinit = ctClass.getClassInitializer(); if (clinit != null) { LOGGER.debug("Adding " + HOTSWAP_AGENT_CLINIT_METHOD + " to class: {}", className); CtConstructor haClinit = new CtConstructor(clinit, ctClass, null); haClinit.getMethodInfo().setName(HOTSWAP_AGENT_CLINIT_METHOD); haClinit.setModifiers(Modifier.PUBLIC | Modifier.STATIC); ctClass.addConstructor(haClinit); final boolean reinitializeStatics[] = new boolean[] { false }; haClinit.instrument( new ExprEditor() { public void edit(FieldAccess f) throws CannotCompileException { try { if (f.isStatic() && f.isWriter()) { Field originalField = null; try { originalField = originalClass.getDeclaredField(f.getFieldName()); } catch (NoSuchFieldException e) { LOGGER.debug("New field will be initialized {}", f.getFieldName()); reinitializeStatics[0] = true; } if (originalField != null) { // Enum class contains an array field, in javac it's name starts with $VALUES, // in eclipse compiler starts with ENUM$VALUES if (originalClass.isEnum() && f.getSignature().startsWith("[L") && (f.getFieldName().startsWith("$VALUES") || f.getFieldName().startsWith("ENUM$VALUES"))) { if (reinitializeStatics[0]) { LOGGER.debug("New field will be initialized {}", f.getFieldName()); } else { reinitializeStatics[0] = checkOldEnumValues(ctClass, originalClass); } } else { LOGGER.debug("Skipping old field {}", f.getFieldName()); f.replace("{}"); } } } } catch (Exception e) { LOGGER.error("Patching " + HOTSWAP_AGENT_CLINIT_METHOD + " method failed.", e); } } } ); if (reinitializeStatics[0]) { PluginManager.getInstance().getScheduler().scheduleCommand(new Command() { @Override public void executeCommand() { try { Class<?> clazz = classLoader.loadClass(className); Method m = clazz.getDeclaredMethod(HOTSWAP_AGENT_CLINIT_METHOD, new Class[] {}); if (m != null) { m.setAccessible(true); m.invoke(null, new Object[] {}); LOGGER.debug("Initializer {} invoked for class {}", HOTSWAP_AGENT_CLINIT_METHOD, className); } else { LOGGER.error("Class initializer {} not found", HOTSWAP_AGENT_CLINIT_METHOD); } } catch (Exception e) { LOGGER.error("Error initializing redefined class {}", e, className); } finally { reloadFlag = false; } } }, 150); // Hack : init must be called after dependant class redefinition. Since the class can // be proxied, the class init must be scheduled after proxy redefinition. Currently proxy // redefinition (in ProxyPlugin) is scheduled with 100ms delay, therefore we use delay 150ms. } else { reloadFlag = false; } }
474
1,032
1,506
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/watchResources/WatchResourcesPlugin.java
WatchResourcesPlugin
init
class WatchResourcesPlugin { private static AgentLogger LOGGER = AgentLogger.getLogger(WatchResourcesPlugin.class); @Init Watcher watcher; @Init ClassLoader appClassLoader; // Classloader to return only modified resources on watchResources path. WatchResourcesClassLoader watchResourcesClassLoader = new WatchResourcesClassLoader(false); /** * For each classloader check for watchResources configuration instance with hotswapper. */ @Init public static void init(PluginManager pluginManager, PluginConfiguration pluginConfiguration, ClassLoader appClassLoader) {<FILL_FUNCTION_BODY>} /** * Init the plugin instance for resources. * * @param watchResources resources to watch */ private void init(URL[] watchResources) { // configure the classloader to return only changed resources on watchResources path watchResourcesClassLoader.initWatchResources(watchResources, watcher); if (appClassLoader instanceof HotswapAgentClassLoaderExt) { ((HotswapAgentClassLoaderExt) appClassLoader).$$ha$setWatchResourceLoader(watchResourcesClassLoader); } else if (URLClassPathHelper.isApplicable(appClassLoader)) { // modify the application classloader to look for resources first in watchResourcesClassLoader URLClassPathHelper.setWatchResourceLoader(appClassLoader, watchResourcesClassLoader); } } }
LOGGER.debug("Init plugin at classLoader {}", appClassLoader); // synthetic classloader, skip if (appClassLoader instanceof WatchResourcesClassLoader.UrlOnlyClassLoader) return; // init only if the classloader contains directly the property file (not in parent classloader) if (!pluginConfiguration.containsPropertyFile()) { LOGGER.debug("ClassLoader {} does not contain hotswap-agent.properties file, WatchResources skipped.", appClassLoader); return; } // and watch resources are set URL[] watchResources = pluginConfiguration.getWatchResources(); if (watchResources.length == 0) { LOGGER.debug("ClassLoader {} has hotswap-agent.properties watchResources empty.", appClassLoader); return; } if (!URLClassPathHelper.isApplicable(appClassLoader) && !(appClassLoader instanceof HotswapAgentClassLoaderExt)) { LOGGER.warning("Unable to modify application classloader. Classloader '{}' is of type '{}'," + "unknown classloader type.\n" + "*** watchResources configuration property will not be handled on JVM level ***", appClassLoader, appClassLoader.getClass()); return; } // create new plugin instance WatchResourcesPlugin plugin = (WatchResourcesPlugin) pluginManager.getPluginRegistry() .initializePlugin(WatchResourcesPlugin.class.getName(), appClassLoader); // and init it with watchResources path plugin.init(watchResources);
347
375
722
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/AnnotationHelper.java
AnnotationHelper
hasAnnotation
class AnnotationHelper { public static boolean hasAnnotation(Class clazz, String annotationClass) {<FILL_FUNCTION_BODY>} public static boolean hasAnnotation(CtClass clazz, String annotationClass) { AnnotationsAttribute ainfo = (AnnotationsAttribute) clazz.getClassFile2(). getAttribute(AnnotationsAttribute.visibleTag); if (ainfo != null) { for (org.hotswap.agent.javassist.bytecode.annotation.Annotation annot : ainfo.getAnnotations()) { if (annot.getTypeName().equals(annotationClass)) return true; } } return false; } public static boolean hasAnnotation(Class<?> clazz, Iterable<String> annotationClasses) { for (String pathAnnotation : annotationClasses) { if (AnnotationHelper.hasAnnotation(clazz, pathAnnotation)) { return true; } } return false; } public static boolean hasAnnotation(CtClass clazz, Iterable<String> annotationClasses) { for (String pathAnnotation : annotationClasses) { if (AnnotationHelper.hasAnnotation(clazz, pathAnnotation)) { return true; } } return false; } }
for (Annotation annot : clazz.getDeclaredAnnotations()) if (annot.annotationType().getName().equals(annotationClass)) return true; return false;
315
46
361
<no_super_class>