com.strobel.assembler.metadata.ITypeLoader Java Examples

The following examples show how to use com.strobel.assembler.metadata.ITypeLoader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UimaDecompiler.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * A special type loader that substitutes the byteArray for the given class name
 * @param classNameSlashes the name to look for to substitute
 * @param byteArray the value to substitute
 */
private void setDecompilerSettingsForByteArray(String classNameSlashes, byte[] byteArray) {
  ITypeLoader tl = new ITypeLoader() {
    
    @Override
    public boolean tryLoadType(String internalName, Buffer buffer) {
      if (classNameSlashes.equals(internalName)) {
        int length = byteArray.length;
        buffer.reset(length);
        System.arraycopy(byteArray, 0, buffer.array(), 0, length);
        return true;
      } else {
        return false;
      }
    }      
  }; 
  ITypeLoader tc = new CompositeTypeLoader(tl, getClasspathTypeLoader(), new InputTypeLoader());
  decompilerSettings.setTypeLoader(tc);
}
 
Example #2
Source File: HuntBugsMojo.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private void addDependency(Artifact art, List<ITypeLoader> deps) throws IOException {
    if ("compile".equals(art.getScope())) {
        ArtifactRepository localRepository = session.getLocalRepository();
        File f = localRepository.find(art).getFile();
        if (f != null) {
            Path path = f.toPath();
            if (!quiet) {
                getLog().info("HuntBugs: +dep " + path);
            }
            if (Files.isRegularFile(path) && art.getType().equals("jar")) {
                deps.add(new JarTypeLoader(new JarFile(path.toFile())));
            } else if (Files.isDirectory(path)) {
                deps.add(new ClasspathTypeLoader(path.toString()));
            }
        }
    }
}
 
Example #3
Source File: HuntBugsMojo.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
private Repository constructRepository() throws IOException {
    Repository repo = new DirRepository(classesDirectory.toPath());
    
    if (!quiet) {
        getLog().info("HuntBugs: +dir " + classesDirectory);
    }

    // collecting project dependencies including pom and transitive dependencies
    ArtifactFilter artifactFilter = new ScopeArtifactFilter("compile");
    DependencyNode rootNode;
    try {
        rootNode = treeBuilder.buildDependencyTree(project, session.getLocalRepository(), artifactFilter);
    } catch (DependencyTreeBuilderException e) {
        throw new RuntimeException(e);
    }
    CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
    rootNode.accept(visitor);

    // converting dependencies to type loaders
    List<DependencyNode> nodes = visitor.getNodes();
    List<ITypeLoader> deps = new ArrayList<>();
    for (DependencyNode dependencyNode : nodes) {
        int state = dependencyNode.getState();

        // checking that transitive dependency is NOT excluded
        if (state == DependencyNode.INCLUDED) {
            Artifact artifact = dependencyNode.getArtifact();
            addDependency(artifact, deps);
        }
    }
    
    if (deps.isEmpty()) {
        return repo;
    }
    
    return new CompositeRepository(
        Arrays.asList(repo, new AuxRepository(new CompositeTypeLoader(deps.toArray(new ITypeLoader[0])))));
}
 
Example #4
Source File: ProcyonDecompiler.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Decompiles the given .class file and creates the specified output source file.
 *
 * @param classFilePath the .class file to be decompiled.
 * @param outputDir The directory where decompiled .java files will be placed.
 */
@Override
public DecompilationResult decompileClassFile(Path rootDir, Path classFilePath, Path outputDir)
            throws DecompilationException
{
    Checks.checkDirectoryToBeRead(rootDir.toFile(), "Classes root dir");
    File classFile = classFilePath.toFile();
    Checks.checkFileToBeRead(classFile, "Class file");
    Checks.checkDirectoryToBeFilled(outputDir.toFile(), "Output directory");

    log.info("Decompiling .class '" + classFilePath + "' to '" + outputDir + "' from: '" + rootDir + "'");

    String name = classFilePath.normalize().toAbsolutePath().toString().substring(rootDir.toAbsolutePath().toString().length() + 1);
    final String typeName = StringUtils.removeEnd(name, ".class");// .replace('/', '.');

    DecompilationResult result = new DecompilationResult();
    try
    {
        DecompilerSettings settings = getDefaultSettings(outputDir.toFile());
        this.procyonConf.setDecompilerSettings(settings); // TODO: This is horrible mess.

        final ITypeLoader typeLoader = new CompositeTypeLoader(new WindupClasspathTypeLoader(rootDir.toString()), new ClasspathTypeLoader());
        WindupMetadataSystem metadataSystem = new WindupMetadataSystem(typeLoader);
        File outputFile = this.decompileType(settings, metadataSystem, typeName);
        result.addDecompiled(Collections.singletonList(classFilePath.toString()), outputFile.getAbsolutePath());
    }
    catch (Throwable e)
    {
        DecompilationFailure failure = new DecompilationFailure("Error during decompilation of "
                    + classFilePath.toString() + ":\n    " + e.getMessage(), Collections.singletonList(name), e);
        log.severe(failure.getMessage());
        result.addFailure(failure);
    }

    return result;
}
 
Example #5
Source File: UimaDecompiler.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
private ITypeLoader getClasspathTypeLoader() {
    return new ITypeLoader() {
      
      @Override
      public boolean tryLoadType(String internalName, Buffer buffer) {
        
        // read the class as a resource, and put into temporary byte array output stream
        // because we need to know the length
//        System.out.println("debug trying to load " + internalName);
        internalName = internalName.replace('.', '/') + ".class";
        InputStream stream = classLoader.getResourceAsStream(internalName);
        if (stream == null) {
//          System.out.println("debug failed to load " + internalName);
          return false;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 16);        
        byte[] b = new byte[1024 * 16]; 
        int numberRead;
        try {
          while (0 <= (numberRead = stream.read(b))){
            baos.write(b, 0, numberRead);
          }
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
        
        // Copy result (based on length) into output buffer spot
        int length = baos.size();
        b = baos.toByteArray();
        buffer.reset(length);
        System.arraycopy(b, 0, buffer.array(), 0, length);
//        System.out.println("debug OK loading " + internalName);
        return true;
      }      
    };    
  }
 
Example #6
Source File: LuytenTypeLoader.java    From Luyten with Apache License 2.0 5 votes vote down vote up
@Override
public boolean tryLoadType(final String internalName, final Buffer buffer) {
	for (final ITypeLoader typeLoader : _typeLoaders) {
		if (typeLoader.tryLoadType(internalName, buffer)) {
			return true;
		}

		buffer.reset();
	}

	return false;
}
 
Example #7
Source File: ProcyonDecompiler.java    From bytecode-viewer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean tryLoadType(final String internalName,
                           final Buffer buffer) {
    for (final ITypeLoader typeLoader : _typeLoaders) {
        if (typeLoader.tryLoadType(internalName, buffer)) {
            return true;
        }

        buffer.reset();
    }

    return false;
}
 
Example #8
Source File: ClassFile.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static TypeReference lookupType(String path, ITypeLoader loader) {
  MetadataSystem metadataSystem = new MetadataSystem(loader);
  /* Hack to get around classes whose descriptors clash with primitive types. */
  if (path.length() == 1) {
    MetadataParser parser = new MetadataParser(IMetadataResolver.EMPTY);
    return metadataSystem.resolve(parser.parseTypeDescriptor(path));
  }
  return metadataSystem.lookupType(path);
}
 
Example #9
Source File: HuntBugs.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
private ITypeLoader createTypeLoader(Path path) {
    try {
        return Files.isDirectory(path) ? new ClasspathTypeLoader(path.toString()) : new JarTypeLoader(new JarFile(path.toFile()));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #10
Source File: ComposedTypeLoader.java    From Recaf with MIT License 5 votes vote down vote up
@Override
public boolean tryLoadType(String s, Buffer buffer) {
    for (ITypeLoader loader : this.loaders) {
        if (loader.tryLoadType(s, buffer)) return true;
        buffer.reset();
    }
    return false;
}
 
Example #11
Source File: ProcyonDecompiler.java    From Recaf with MIT License 5 votes vote down vote up
@Override
public String decompile(String name) {
    ITypeLoader loader = new ComposedTypeLoader(Arrays.asList(
            new RecafTypeLoader(getController()), new InputTypeLoader()
    ));
    Map<String, Boolean> options = getOptions();
    DecompilerSettings settings = new DecompilerSettings();
    settings.setFlattenSwitchBlocks(options.get("flatten-switch-blocks"));
    settings.setForceExplicitImports(!options.get("collapse-imports"));
    settings.setForceExplicitTypeArguments(options.get("force-explicit-type-arguments"));
    settings.setRetainRedundantCasts(options.get("retain-redundant-casts"));
    settings.setShowSyntheticMembers(options.get("show-synthetic-members"));
    settings.setExcludeNestedTypes(options.get("exclude-nested-types"));
    settings.setRetainPointlessSwitches(options.get("retain-pointless-switches"));
    settings.setUnicodeOutputEnabled(options.get("unicode-output"));
    settings.setMergeVariables(options.get("merge-variables"));
    settings.setShowDebugLineNumbers(options.get("show-debug-line-numbers"));
    settings.setSimplifyMemberReferences(options.get("simplify-member-references"));
    settings.setForceFullyQualifiedReferences(options.get("force-fully-qualified-references"));
    settings.setDisableForEachTransforms(options.get("disable-for-each-transforms"));
    settings.setTypeLoader(loader);
    settings.setJavaFormattingOptions(JavaFormattingOptions.createDefault());
    MetadataSystem system = new MetadataSystem(loader);
    system.setEagerMethodLoadingEnabled(options.get("eager-methods-loading"));
    TypeReference ref = system.lookupType(name);
    DecompilationOptions decompilationOptions = new DecompilationOptions();
    decompilationOptions.setSettings(settings);
    decompilationOptions.setFullDecompilation(true);
    StringWriter writer = new StringWriter();
    settings.getLanguage().decompileType(ref.resolve(), new PlainTextOutput(writer), decompilationOptions);
    return writer.toString();
}
 
Example #12
Source File: Repository.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
static Repository createNullRepository() {
    return new Repository() {
        @Override
        public void visit(String rootPackage, RepositoryVisitor visitor) {
            // nothing to do
        }

        @Override
        public ITypeLoader createTypeLoader() {
            return (internalName, buffer) -> false;
        }
    };
}
 
Example #13
Source File: JarRepository.java    From huntbugs with Apache License 2.0 4 votes vote down vote up
@Override
public ITypeLoader createTypeLoader() {
    return new JarTypeLoader(file);
}
 
Example #14
Source File: UimaDecompiler.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
private void setDecompilerSettingsForClassLoader() {
  ITypeLoader tc = new CompositeTypeLoader(getClasspathTypeLoader(), new InputTypeLoader());
  decompilerSettings.setTypeLoader(tc);
}
 
Example #15
Source File: ProcyonDecompiler.java    From JByteMod-Beta with GNU General Public License v2.0 4 votes vote down vote up
public String decompile(byte[] b, MethodNode mn) {
  try {
  //TODO decompile method only
    DecompilerSettings settings = new DecompilerSettings();
    try {
      for (Field f : settings.getClass().getDeclaredFields()) {
        if (f.getType() == boolean.class) {
          f.setAccessible(true);
          f.setBoolean(settings, JByteMod.ops.get("procyon" + f.getName()).getBoolean());
        }
      }
    } catch (Throwable t) {
      t.printStackTrace();
    }
    settings.setShowSyntheticMembers(true);
    MetadataSystem metadataSystem = new MetadataSystem(new ITypeLoader() {
      private InputTypeLoader backLoader = new InputTypeLoader();

      @Override
      public boolean tryLoadType(String s, Buffer buffer) {
        if (s.equals(cn.name)) {
          buffer.putByteArray(b, 0, b.length);
          buffer.position(0);
          return true;
        } else {
          return backLoader.tryLoadType(s, buffer);
        }
      }
    });
    TypeReference type = metadataSystem.lookupType(cn.name);
    DecompilationOptions decompilationOptions = new DecompilationOptions();
    decompilationOptions.setSettings(DecompilerSettings.javaDefaults());
    decompilationOptions.setFullDecompilation(true);
    TypeDefinition resolvedType = null;
    if (type == null || ((resolvedType = type.resolve()) == null)) {
      new ErrorDisplay("Unable to resolve type.");
      return "error";
    }
    StringWriter stringwriter = new StringWriter();
    settings.getLanguage().decompileType(resolvedType, new PlainTextOutput(stringwriter), decompilationOptions);
    String decompiledSource = stringwriter.toString();
    return decompiledSource;
  } catch (Exception e) {
    e.printStackTrace();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    return sw.toString();
  }
}
 
Example #16
Source File: CompositeRepository.java    From huntbugs with Apache License 2.0 4 votes vote down vote up
@Override
public ITypeLoader createTypeLoader() {
    return new CompositeTypeLoader(repos.stream().map(Repository::createTypeLoader).toArray(ITypeLoader[]::new));
}
 
Example #17
Source File: LuytenTypeLoader.java    From Luyten with Apache License 2.0 4 votes vote down vote up
public final List<ITypeLoader> getTypeLoaders() {
	return _typeLoaders;
}
 
Example #18
Source File: LuytenTypeLoader.java    From Luyten with Apache License 2.0 4 votes vote down vote up
public LuytenTypeLoader() {
	_typeLoaders = new ArrayList<ITypeLoader>();
	_typeLoaders.add(new InputTypeLoader());
}
 
Example #19
Source File: Model.java    From Luyten with Apache License 2.0 4 votes vote down vote up
private State(String key, File file, JarFile jarFile, ITypeLoader typeLoader) {
	this.key = VerifyArgument.notNull(key, "key");
	this.file = VerifyArgument.notNull(file, "file");
	this.jarFile = jarFile;
	this.typeLoader = typeLoader;
}
 
Example #20
Source File: AuxRepository.java    From huntbugs with Apache License 2.0 4 votes vote down vote up
public AuxRepository(ITypeLoader loader) {
    this.loader = loader;
}
 
Example #21
Source File: ProcyonDecompiler.java    From bytecode-viewer with GNU General Public License v3.0 4 votes vote down vote up
public final List<ITypeLoader> getTypeLoaders() {
    return _typeLoaders;
}
 
Example #22
Source File: ProcyonDecompiler.java    From bytecode-viewer with GNU General Public License v3.0 4 votes vote down vote up
public LuytenTypeLoader() {
    _typeLoaders = new ArrayList<ITypeLoader>();
    _typeLoaders.add(new InputTypeLoader());
}
 
Example #23
Source File: ComposedTypeLoader.java    From Recaf with MIT License 4 votes vote down vote up
ComposedTypeLoader(Collection<ITypeLoader> loaders) {
    this.loaders = loaders;
}
 
Example #24
Source File: FilteredRepository.java    From huntbugs with Apache License 2.0 4 votes vote down vote up
@Override
public ITypeLoader createTypeLoader() {
    return repository.createTypeLoader();
}
 
Example #25
Source File: DirRepository.java    From huntbugs with Apache License 2.0 4 votes vote down vote up
@Override
public ITypeLoader createTypeLoader() {
    return new ClasspathTypeLoader(root.toString());
}
 
Example #26
Source File: AuxRepository.java    From huntbugs with Apache License 2.0 4 votes vote down vote up
@Override
public ITypeLoader createTypeLoader() {
    return loader;
}
 
Example #27
Source File: Repository.java    From huntbugs with Apache License 2.0 votes vote down vote up
ITypeLoader createTypeLoader();