List of usage examples for org.eclipse.jdt.internal.compiler.classfmt ClassFileReader ClassFileReader
public ClassFileReader(byte classFileBytes[], char[] fileName) throws ClassFormatException
From source file:com.codenvy.ide.ext.java.server.internal.core.search.indexing.BinaryIndexer.java
License:Open Source License
public void indexDocument() { try {/*from www. j a v a 2s. c o m*/ final byte[] contents = this.document.getByteContents(); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=107124 // contents can potentially be null if a IOException occurs while retrieving the contents if (contents == null) return; final String path = this.document.getPath(); ClassFileReader reader = new ClassFileReader(contents, path == null ? null : path.toCharArray()); // first add type references char[] className = replace('/', '.', reader.getName()); // looks like java/lang/String // need to extract the package name and the simple name int packageNameIndex = CharOperation.lastIndexOf('.', className); char[] packageName = null; char[] name = null; if (packageNameIndex >= 0) { packageName = CharOperation.subarray(className, 0, packageNameIndex); name = CharOperation.subarray(className, packageNameIndex + 1, className.length); } else { packageName = CharOperation.NO_CHAR; name = className; } char[] enclosingTypeName = null; boolean isNestedType = reader.isNestedType(); if (isNestedType) { if (reader.isAnonymous()) { name = CharOperation.NO_CHAR; } else { name = reader.getInnerSourceName(); } if (reader.isLocal() || reader.isAnonymous()) { // set specific ['0'] value for local and anonymous to be able to filter them enclosingTypeName = ONE_ZERO; } else { char[] fullEnclosingName = reader.getEnclosingTypeName(); int nameLength = fullEnclosingName.length - packageNameIndex - 1; if (nameLength <= 0) { // See PR 1GIR345: ITPJCORE:ALL - Indexer: NegativeArraySizeException return; } enclosingTypeName = new char[nameLength]; System.arraycopy(fullEnclosingName, packageNameIndex + 1, enclosingTypeName, 0, nameLength); } } // type parameters char[][] typeParameterSignatures = null; char[] genericSignature = reader.getGenericSignature(); if (genericSignature != null) { CharOperation.replace(genericSignature, '/', '.'); typeParameterSignatures = Signature.getTypeParameters(genericSignature); } // eliminate invalid innerclasses (1G4KCF7) if (name == null) return; char[][] superinterfaces = replace('/', '.', reader.getInterfaceNames()); char[][] enclosingTypeNames = enclosingTypeName == null ? null : new char[][] { enclosingTypeName }; int modifiers = reader.getModifiers(); switch (TypeDeclaration.kind(modifiers)) { case TypeDeclaration.CLASS_DECL: char[] superclass = replace('/', '.', reader.getSuperclassName()); addClassDeclaration(modifiers, packageName, name, enclosingTypeNames, superclass, superinterfaces, typeParameterSignatures, false); break; case TypeDeclaration.INTERFACE_DECL: addInterfaceDeclaration(modifiers, packageName, name, enclosingTypeNames, superinterfaces, typeParameterSignatures, false); break; case TypeDeclaration.ENUM_DECL: superclass = replace('/', '.', reader.getSuperclassName()); addEnumDeclaration(modifiers, packageName, name, enclosingTypeNames, superclass, superinterfaces, false); break; case TypeDeclaration.ANNOTATION_TYPE_DECL: addAnnotationTypeDeclaration(modifiers, packageName, name, enclosingTypeNames, false); break; } // Look for references in class annotations IBinaryAnnotation[] annotations = reader.getAnnotations(); if (annotations != null) { for (int a = 0, length = annotations.length; a < length; a++) { IBinaryAnnotation annotation = annotations[a]; addBinaryAnnotation(annotation); } } long tagBits = reader.getTagBits() & TagBits.AllStandardAnnotationsMask; if (tagBits != 0) { addBinaryStandardAnnotations(tagBits); } int extraFlags = ExtraFlags.getExtraFlags(reader); // first reference all methods declarations and field declarations MethodInfo[] methods = (MethodInfo[]) reader.getMethods(); boolean noConstructor = true; if (methods != null) { for (int i = 0, max = methods.length; i < max; i++) { MethodInfo method = methods[i]; boolean isConstructor = method.isConstructor(); char[] descriptor = method.getMethodDescriptor(); char[][] parameterTypes = decodeParameterTypes(descriptor, isConstructor && isNestedType); char[] returnType = decodeReturnType(descriptor); char[][] exceptionTypes = replace('/', '.', method.getExceptionTypeNames()); if (isConstructor) { noConstructor = false; char[] signature = method.getGenericSignature(); if (signature == null) { if (reader.isNestedType() && ((modifiers & ClassFileConstants.AccStatic) == 0)) { signature = removeFirstSyntheticParameter(descriptor); } else { signature = descriptor; } } addConstructorDeclaration(name, parameterTypes == null ? 0 : parameterTypes.length, signature, parameterTypes, method.getArgumentNames(), method.getModifiers(), packageName, modifiers, exceptionTypes, extraFlags); } else { if (!method.isClinit()) { addMethodDeclaration(method.getSelector(), parameterTypes, returnType, exceptionTypes); } } // look for references in method annotations annotations = method.getAnnotations(); if (annotations != null) { for (int a = 0, length = annotations.length; a < length; a++) { IBinaryAnnotation annotation = annotations[a]; addBinaryAnnotation(annotation); } } tagBits = method.getTagBits() & TagBits.AllStandardAnnotationsMask; if (tagBits != 0) { addBinaryStandardAnnotations(tagBits); } } } if (noConstructor) { addDefaultConstructorDeclaration(className, packageName, modifiers, extraFlags); } FieldInfo[] fields = (FieldInfo[]) reader.getFields(); if (fields != null) { for (int i = 0, max = fields.length; i < max; i++) { FieldInfo field = fields[i]; char[] fieldName = field.getName(); char[] fieldType = decodeFieldType(replace('/', '.', field.getTypeName())); addFieldDeclaration(fieldType, fieldName); // look for references in field annotations annotations = field.getAnnotations(); if (annotations != null) { for (int a = 0, length = annotations.length; a < length; a++) { IBinaryAnnotation annotation = annotations[a]; addBinaryAnnotation(annotation); } } tagBits = field.getTagBits() & TagBits.AllStandardAnnotationsMask; if (tagBits != 0) { addBinaryStandardAnnotations(tagBits); } } } // record all references found inside the .class file extractReferenceFromConstantPool(contents, reader); } catch (ClassFormatException e) { // ignore this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (RuntimeException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=182154 // logging the entry that could not be indexed and continue with the next one // we remove all entries relative to the boggus document this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ } }
From source file:com.google.gwt.dev.javac.Dependencies.java
License:Apache License
private boolean hasStructuralChanges(CompiledClass mine, CompiledClass theirs) { try {/*from w ww . j a v a 2s . co m*/ ClassFileReader cfr = new ClassFileReader(theirs.getBytes(), null); return cfr.hasStructuralChanges(mine.getBytes()); } catch (ClassFormatException e) { throw new RuntimeException("Unexpected error reading compiled class", e); } }
From source file:io.takari.maven.plugins.compile.jdt.CompilerJdt.java
License:Open Source License
private boolean digestClassFile(Output<File> output, byte[] definition) { boolean significantChange = true; try {//from w ww .j av a 2 s. c om ClassFileReader reader = new ClassFileReader(definition, output.getResource().getAbsolutePath().toCharArray()); byte[] hash = digester.digest(reader); if (hash != null) { byte[] oldHash = (byte[]) context.setAttribute(output.getResource(), ATTR_CLASS_DIGEST, hash); significantChange = oldHash == null || !Arrays.equals(hash, oldHash); } } catch (ClassFormatException e) { // ignore this class } return significantChange; }
From source file:net.sf.j2s.core.builder.IncrementalImageBuilder.java
License:Open Source License
protected boolean writeClassFileCheck(IFile file, String fileName, byte[] newBytes) throws CoreException { try {//from w ww. ja va 2s.c om byte[] oldBytes = Util.getResourceContentsAsByteArray(file); notEqual: if (newBytes.length == oldBytes.length) { for (int i = newBytes.length; --i >= 0;) if (newBytes[i] != oldBytes[i]) break notEqual; return false; // bytes are identical so skip them } URI location = file.getLocationURI(); if (location == null) return false; // unable to determine location of this class file String filePath = location.getSchemeSpecificPart(); ClassFileReader reader = new ClassFileReader(oldBytes, filePath.toCharArray()); // ignore local types since they're only visible inside a single method if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) { if (JavaBuilder.DEBUG) System.out.println("Type has structural changes " + fileName); //$NON-NLS-1$ addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); } } catch (ClassFormatException e) { addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); } return true; }
From source file:org.eclipse.che.jdt.internal.core.search.indexing.BinaryIndexer.java
License:Open Source License
public void indexDocument() { try {//from w w w . j a va2 s .co m final byte[] contents = this.document.getByteContents(); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=107124 // contents can potentially be null if a IOException occurs while retrieving the contents if (contents == null) return; final String path = this.document.getPath(); ClassFileReader reader = new ClassFileReader(contents, path == null ? null : path.toCharArray()); // first add type references char[] className = replace('/', '.', reader.getName()); // looks like java/lang/String // need to extract the package name and the simple name int packageNameIndex = CharOperation.lastIndexOf('.', className); char[] packageName = null; char[] name = null; if (packageNameIndex >= 0) { packageName = CharOperation.subarray(className, 0, packageNameIndex); name = CharOperation.subarray(className, packageNameIndex + 1, className.length); } else { packageName = CharOperation.NO_CHAR; name = className; } char[] enclosingTypeName = null; boolean isNestedType = reader.isNestedType(); if (isNestedType) { if (reader.isAnonymous()) { name = CharOperation.NO_CHAR; } else { name = reader.getInnerSourceName(); } if (reader.isLocal() || reader.isAnonymous()) { // set specific ['0'] value for local and anonymous to be able to filter them enclosingTypeName = ONE_ZERO; } else { char[] fullEnclosingName = reader.getEnclosingTypeName(); int nameLength = fullEnclosingName.length - packageNameIndex - 1; if (nameLength <= 0) { // See PR 1GIR345: ITPJCORE:ALL - Indexer: NegativeArraySizeException return; } enclosingTypeName = new char[nameLength]; System.arraycopy(fullEnclosingName, packageNameIndex + 1, enclosingTypeName, 0, nameLength); } } // type parameters char[][] typeParameterSignatures = null; char[] genericSignature = reader.getGenericSignature(); if (genericSignature != null) { CharOperation.replace(genericSignature, '/', '.'); typeParameterSignatures = Signature.getTypeParameters(genericSignature); } // eliminate invalid innerclasses (1G4KCF7) if (name == null) return; char[][] superinterfaces = replace('/', '.', reader.getInterfaceNames()); char[][] enclosingTypeNames = enclosingTypeName == null ? null : new char[][] { enclosingTypeName }; int modifiers = reader.getModifiers(); switch (TypeDeclaration.kind(modifiers)) { case TypeDeclaration.CLASS_DECL: char[] superclass = replace('/', '.', reader.getSuperclassName()); addClassDeclaration(modifiers, packageName, name, enclosingTypeNames, superclass, superinterfaces, typeParameterSignatures, false); break; case TypeDeclaration.INTERFACE_DECL: addInterfaceDeclaration(modifiers, packageName, name, enclosingTypeNames, superinterfaces, typeParameterSignatures, false); break; case TypeDeclaration.ENUM_DECL: superclass = replace('/', '.', reader.getSuperclassName()); addEnumDeclaration(modifiers, packageName, name, enclosingTypeNames, superclass, superinterfaces, false); break; case TypeDeclaration.ANNOTATION_TYPE_DECL: addAnnotationTypeDeclaration(modifiers, packageName, name, enclosingTypeNames, false); break; } // Look for references in class annotations IBinaryAnnotation[] annotations = reader.getAnnotations(); if (annotations != null) { for (int a = 0, length = annotations.length; a < length; a++) { IBinaryAnnotation annotation = annotations[a]; addBinaryAnnotation(annotation); } } long tagBits = reader.getTagBits() & TagBits.AllStandardAnnotationsMask; if (tagBits != 0) { addBinaryStandardAnnotations(tagBits); } int extraFlags = ExtraFlags.getExtraFlags(reader); // first reference all methods declarations and field declarations MethodInfo[] methods = (MethodInfo[]) reader.getMethods(); boolean noConstructor = true; if (methods != null) { for (int i = 0, max = methods.length; i < max; i++) { MethodInfo method = methods[i]; boolean isConstructor = method.isConstructor(); char[] descriptor = method.getMethodDescriptor(); char[][] parameterTypes = decodeParameterTypes(descriptor, isConstructor && isNestedType); char[] returnType = decodeReturnType(descriptor); char[][] exceptionTypes = replace('/', '.', method.getExceptionTypeNames()); if (isConstructor) { noConstructor = false; char[] signature = method.getGenericSignature(); if (signature == null) { if (reader.isNestedType() && ((modifiers & ClassFileConstants.AccStatic) == 0)) { signature = removeFirstSyntheticParameter(descriptor); } else { signature = descriptor; } } addConstructorDeclaration(name, parameterTypes == null ? 0 : parameterTypes.length, signature, parameterTypes, method.getArgumentNames(), method.getModifiers(), packageName, modifiers, exceptionTypes, extraFlags); } else { if (!method.isClinit()) { addMethodDeclaration(method.getSelector(), parameterTypes, returnType, exceptionTypes); } } // look for references in method annotations annotations = method.getAnnotations(); if (annotations != null) { for (int a = 0, length = annotations.length; a < length; a++) { IBinaryAnnotation annotation = annotations[a]; addBinaryAnnotation(annotation); } } tagBits = method.getTagBits() & TagBits.AllStandardAnnotationsMask; if (tagBits != 0) { addBinaryStandardAnnotations(tagBits); } } } if (noConstructor) { addDefaultConstructorDeclaration(className, packageName, modifiers, extraFlags); } FieldInfo[] fields = (FieldInfo[]) reader.getFields(); if (fields != null) { for (int i = 0, max = fields.length; i < max; i++) { FieldInfo field = fields[i]; char[] fieldName = field.getName(); char[] fieldType = decodeFieldType(replace('/', '.', field.getTypeName())); addFieldDeclaration(fieldType, fieldName); // look for references in field annotations annotations = field.getAnnotations(); if (annotations != null) { for (int a = 0, length = annotations.length; a < length; a++) { IBinaryAnnotation annotation = annotations[a]; addBinaryAnnotation(annotation); } } tagBits = field.getTagBits() & TagBits.AllStandardAnnotationsMask; if (tagBits != 0) { addBinaryStandardAnnotations(tagBits); } } } // record all references found inside the .class file extractReferenceFromConstantPool(contents, reader); } catch (ClassFormatException e) { // ignore this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue " + "against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (RuntimeException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=182154 // logging the entry that could not be indexed and continue with the next one // we remove all entries relative to the boggus document this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue " + "again" + "st the .class file vendor"); //$NON-NLS-2$ //$NON-NLS-2$ } }
From source file:org.eclipse.objectteams.otdt.internal.core.compiler.model.MethodModel.java
License:Open Source License
/** * Ensure we have bytes and constantPoolOffsets ready to use. *//* ww w . j a v a 2s .co m*/ private void setupByteCode(boolean bytesRequired) { if (this._bytes == null || this._constantPoolOffsets == null) { try { MethodBinding binding = (this._binding == null) ? this._decl.binding : this._binding; assert binding.declaringClass.isTeam(); ClassFileReader reader = null; if (this._bytes == null) { if (this._classFile == null && this._decl != null) { char[] className = binding.declaringClass.constantPoolName(); this._classFile = (ClassFile) this._decl.compilationResult.compiledTypes.get(className); if (this._classFile != null && !this._classFile.isForType(binding.declaringClass)) { this._classFile = null; // has been reset thus cannot be used for this type any more. } } // here we made the best attempt to obtain a classfile, use it if possible: if (this._classFile != null && this._classFile.isForType(this._binding.declaringClass)) { this._bytes = this._classFile.getBytes(); this._structOffset += this._classFile.headerOffset; // structOffset did not yet include the headerOffset int olen = this._classFile.constantPool.currentIndex; System.arraycopy(this._classFile.constantPool.offsets, 0, this._constantPoolOffsets = new int[olen], 0, olen); this._classFile = null; // don't use any more return; } } if (this._bytes != null) { // create a reader for in-memory bytes in order to recalculate constant pool offsets reader = new ClassFileReader(this._bytes, RoleModel.NO_SOURCE_FILE); // STATE_BYTECODE_PREPARED } else { // Currently only team-ctors use a MethodModel for byte code retrieval. // Use the stored file name for reading the byte code from disc: if (binding.declaringClass.isTeam()) reader = binding.declaringClass.getTeamModel().read(); if (reader == null) { if (bytesRequired) throw new InternalCompilerError( "No byte code available for " + new String(binding.readableName())); //$NON-NLS-1$ return; } this._bytes = reader.getBytes(); } this._classFile = null; // don't use any more // now we have both a reader and bytes this._constantPoolOffsets = reader.getConstantPoolOffsets(); // find bytecode offset of this method: char[] mySignature = this._binding.signature(); for (IBinaryMethod m : reader.getMethods()) { if (CharOperation.equals(m.getSelector(), this._binding.selector) && CharOperation.equals(m.getMethodDescriptor(), mySignature)) { this._structOffset = ((MethodInfo) m).getStructOffset(); return; } } if (bytesRequired) throw new InternalCompilerError("Method " + String.valueOf(this._binding.readableName()) //$NON-NLS-1$ + "not found in class file " + String.valueOf(reader.getFileName())); //$NON-NLS-1$ } catch (ClassFormatException ex) { throw new InternalCompilerError(ex.getMessage()); } catch (IOException ex) { throw new InternalCompilerError(ex.getMessage()); } } }
From source file:org.eclipse.objectteams.otdt.internal.core.compiler.model.RoleModel.java
License:Open Source License
private void restoreCPOffsets() { try {/*from ww w. j av a 2s . com*/ byte[] code = getByteCode(); if (code != null) { ClassFileReader reader = new ClassFileReader(code, NO_SOURCE_FILE); // not recording OT-attributes this._constantPoolOffsets = reader.getConstantPoolOffsets(); } } catch (ClassFormatException ex) { throw new InternalCompilerError(ex.toString()); } }
From source file:org.eclipse.wst.xml.core.internal.contentmodel.tapestry.travelpackage.TapestryClassLoader.java
License:Open Source License
public TapestryCoreComponents loadComponentAttributesFromClassFile(IPackageFragmentRoot fragmentRoot, String prefix, ClassFile packi) throws JavaModelException, ClassFormatException { ClassFileReader reader = new ClassFileReader(packi.getBytes(), null); TapestryCoreComponents component = new TapestryCoreComponents(); component.setName(String.valueOf(reader.getSourceName())); component.setElementLabel(prefix + ":" + component.getName().toLowerCase()); if (reader.getFields() != null) for (IBinaryField field : reader.getFields()) { boolean parameter = false; if (field.getAnnotations() == null) continue; for (IBinaryAnnotation anno : field.getAnnotations()) { if (String.valueOf(anno.getTypeName()).endsWith("/Parameter;")) { parameter = true;/* w ww. j ava2s . c om*/ break; } } if (parameter) { component.addParameter(String.valueOf(field.getName())); } } String parentClassName = String.valueOf(reader.getSuperclassName()); if (parentClassName != null && !parentClassName.isEmpty() && !parentClassName.equals("java/lang/Object")) { List<String> parameters = loadParametersFromParentClass(fragmentRoot, parentClassName); for (String parameter : parameters) { component.addParameter(parameter); } } return component; }
From source file:org.eclipse.wst.xml.core.internal.contentmodel.tapestry.travelpackage.TapestryClassLoader.java
License:Open Source License
public List<String> loadParametersFromParentClass(IPackageFragmentRoot root, String classFileName) { List<String> list = new ArrayList<String>(); if (classFileName.indexOf('/') < 0) return list; String packageName = classFileName.substring(0, classFileName.lastIndexOf('/')).replace('/', '.'); String className = classFileName.substring(classFileName.lastIndexOf('/') + 1) + ".class"; try {//from ww w.java 2s . co m PackageFragment packInstance = (PackageFragment) root.getPackageFragment(packageName); for (Object packo : packInstance.getChildrenOfType(IJavaElement.CLASS_FILE)) { ClassFile packi = (ClassFile) packo; if (packi.getElementName().equals(className)) { ClassFileReader reader = null; try { reader = new ClassFileReader(packi.getBytes(), null); } catch (ClassFormatException e) { e.printStackTrace(); } if (reader.getFields() != null) for (IBinaryField field : reader.getFields()) { boolean parameter = false; if (field.getAnnotations() == null) continue; for (IBinaryAnnotation anno : field.getAnnotations()) { if (String.valueOf(anno.getTypeName()).endsWith("/Parameter;")) { parameter = true; break; } } if (parameter) { list.add(String.valueOf(field.getName())); } } String parentClassName = String.valueOf(reader.getSuperclassName()); if (parentClassName != null && !parentClassName.isEmpty() && !parentClassName.equals("java/lang/Object")) { list.addAll(loadParametersFromParentClass(root, parentClassName)); } return list; } } } catch (JavaModelException e) { e.printStackTrace(); } return list; }
From source file:org.rapidoid.compile.impl.SimpleNameEnvironment.java
License:Apache License
protected NameEnvironmentAnswer type(String fullclassName) { try {// w w w . j a v a 2s .co m byte[] classFileBytes = IO.classBytes(fullclassName); if (classFileBytes == null) { return null; } IBinaryType binaryType = new ClassFileReader(classFileBytes, null); AccessRestriction accessRestriction = null; NameEnvironmentAnswer answer = new NameEnvironmentAnswer(binaryType, accessRestriction); return answer; } catch (Exception e) { throw U.rte(e); } }