com.strobel.decompiler.DecompilerSettings Java Examples

The following examples show how to use com.strobel.decompiler.DecompilerSettings. 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: ProcyonDecompiler.java    From java-disassembler with GNU General Public License v3.0 6 votes vote down vote up
public DecompilerSettings getDecompilerSettings() {
        DecompilerSettings procyonSettings = new DecompilerSettings();
        procyonSettings.setFlattenSwitchBlocks(settings.getEntry("fsb").getBool());
        procyonSettings.setForceExplicitImports(!settings.getEntry("ci").getBool());
        procyonSettings.setForceExplicitTypeArguments(settings.getEntry("ei").getBool());
        procyonSettings.setRetainRedundantCasts(settings.getEntry("ec").getBool());
        procyonSettings.setShowSyntheticMembers(settings.getEntry("ss").getBool());
        procyonSettings.setExcludeNestedTypes(settings.getEntry("ent").getBool());
//        procyonSettings.setOutputDirectory(options.getOutputDirectory());
        procyonSettings.setIncludeLineNumbersInBytecode(settings.getEntry("dl").getBool());
        procyonSettings.setRetainPointlessSwitches(settings.getEntry("ps").getBool());
        procyonSettings.setUnicodeOutputEnabled(settings.getEntry("unicode").getBool());
        procyonSettings.setMergeVariables(settings.getEntry("mv").getBool());
        procyonSettings.setShowDebugLineNumbers(settings.getEntry("dl").getBool());
        procyonSettings.setSimplifyMemberReferences(settings.getEntry("sm").getBool());
        procyonSettings.setDisableForEachTransforms(settings.getEntry("disable-foreach").getBool());
        procyonSettings.setTypeLoader(new InputTypeLoader());
//        procyonSettings.setLanguage(Languages.bytecode());
//        procyonSettings.setLanguage(settings.getEntry("Unoptimized AST").getBool() ? Languages.bytecodeAstUnoptimized() : Languages.bytecodeAst());
        return procyonSettings;
    }
 
Example #2
Source File: ProcyonDecompilerController.java    From standalone-app with Apache License 2.0 6 votes vote down vote up
@Override
    protected void registerSettings() {
        registerSetting(Boolean.class, new RawBooleanSetting("includelinenumbers", "Include line numbers in raw bytecode mode", true, DecompilerSettings::setIncludeLineNumbersInBytecode));
        registerSetting(Boolean.class, new RawBooleanSetting("showsyntheticmembers", "Show synthetic (compiler-generated) members.", false, DecompilerSettings::setShowSyntheticMembers));
        registerSetting(Boolean.class, new RawBooleanSetting("genexforcatch", "Always generate exception variables for catch blocks", true, DecompilerSettings::setAlwaysGenerateExceptionVariableForCatchBlocks));
        registerSetting(Boolean.class, new RawBooleanSetting("forceexplicitimports", "[DEPRECATED] Explicit imports are now enabled by default.  This option will be removed in a future release.", false, DecompilerSettings::setForceExplicitImports));
        registerSetting(Boolean.class, new RawBooleanSetting("forceexplicittypeargs", "Always print type arguments to generic methods.", false, DecompilerSettings::setForceExplicitTypeArguments));
        registerSetting(Boolean.class, new RawBooleanSetting("flattenswitch", "Drop the braces statements around switch sections when possible.", false, DecompilerSettings::setFlattenSwitchBlocks));
        registerSetting(Boolean.class, new RawBooleanSetting("exclnested", "Exclude nested types when decompiling their enclosing types.", false, DecompilerSettings::setExcludeNestedTypes));
        registerSetting(Boolean.class, new RawBooleanSetting("retaincasts", "Do not remove redundant explicit casts.", false, DecompilerSettings::setRetainRedundantCasts));
        registerSetting(Boolean.class, new RawBooleanSetting("retainswitches", "Do not lift the contents of switches having only a default label.", false, DecompilerSettings::setRetainPointlessSwitches));
        registerSetting(Boolean.class, new RawBooleanSetting("unicode", "Enable Unicode output (printable non-ASCII characters will not be escaped).", false, DecompilerSettings::setUnicodeOutputEnabled));
//        registerSetting(Boolean.class, new RawBooleanSetting("errordiag", "Include error diagnostics", true, DecompilerSettings::setIncludeErrorDiagnostics));
        registerSetting(Boolean.class, new RawBooleanSetting("mergevar", "Attempt to merge as many variables as possible.  This may lead to fewer declarations, but at the expense of inlining and useful naming.  This feature is experimental and may be removed or become the standard behavior in future releases.", false, DecompilerSettings::setMergeVariables));
        registerSetting(Boolean.class, new RawBooleanSetting("disablefortransform", "Disable \'for each\' loop transforms.", false, DecompilerSettings::setDisableForEachTransforms));
        registerSetting(Boolean.class, new RawBooleanSetting("showlinenumbers", "For debugging, show Java line numbers as inline comments (implies including line numbers)", true, DecompilerSettings::setShowDebugLineNumbers));
        registerSetting(Boolean.class, new RawBooleanSetting("simplifymembers", "Simplify type-qualified member references in Java output [EXPERIMENTAL].", false, DecompilerSettings::setSimplifyMemberReferences));

    }
 
Example #3
Source File: FileSaver.java    From Luyten with Apache License 2.0 6 votes vote down vote up
public void saveText(final String text, final File file) {
	new Thread(new Runnable() {
		@Override
		public void run() {
			DecompilerSettings settings = cloneSettings();
			boolean isUnicodeEnabled = settings.isUnicodeOutputEnabled();
			long time = System.currentTimeMillis();
			try (FileOutputStream fos = new FileOutputStream(file);
					OutputStreamWriter writer = isUnicodeEnabled ? new OutputStreamWriter(fos, "UTF-8")
							: new OutputStreamWriter(fos);
					BufferedWriter bw = new BufferedWriter(writer);) {
				label.setText("Extracting: " + file.getName());
				bar.setVisible(true);
				bw.write(text);
				bw.flush();
				label.setText("Completed: " + getTime(time));
			} catch (Exception e1) {
				label.setText("Cannot save file: " + file.getName());
				Luyten.showExceptionDialog("Unable to save file!\n", e1);
			} finally {
				setExtracting(false);
				bar.setVisible(false);
			}
		}
	}).start();
}
 
Example #4
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 #5
Source File: ProcyonDecompiler.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Constructs the path from FQCN, validates writability, and creates a writer.
 */
private static synchronized FileOutputWriter createFileWriter(final TypeDefinition type, final DecompilerSettings settings)
            throws IOException
{
    final String outputDirectory = settings.getOutputDirectory();

    final String fileName = type.getName() + settings.getLanguage().getFileExtension();
    final String packageName = type.getPackageName();

    // foo.Bar -> foo/Bar.java
    final String subDir = StringUtils.defaultIfEmpty(packageName, "").replace('.', File.separatorChar);
    final String outputPath = PathHelper.combine(outputDirectory, subDir, fileName);

    final File outputFile = new File(outputPath);
    final File parentDir = outputFile.getParentFile();

    if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs())
    {
        throw new IllegalStateException("Could not create directory:" + parentDir);
    }

    if (!outputFile.exists() && !outputFile.createNewFile())
    {
        throw new IllegalStateException("Could not create output file: " + outputPath);
    }

    return new FileOutputWriter(outputFile, settings);
}
 
Example #6
Source File: ProcyonDecompiler.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Default settings set type loader to ClasspathTypeLoader if not set before.
 */
private DecompilerSettings getDefaultSettings(File outputDir)
{
    DecompilerSettings settings = new DecompilerSettings();
    procyonConf.setDecompilerSettings(settings);
    settings.setOutputDirectory(outputDir.getPath());
    settings.setShowSyntheticMembers(false);
    settings.setForceExplicitImports(true);

    if (settings.getTypeLoader() == null)
        settings.setTypeLoader(new ClasspathTypeLoader());
    return settings;
}
 
Example #7
Source File: ProcyonDecompiler.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
public DecompileExecutor(DecompilerSettings settings, WindupMetadataSystem metadataSystem, String typeName)
{
    this.settings = settings;
    this.metadataSystem = metadataSystem;
    this.typeName = typeName;
    setDaemon(true);
}
 
Example #8
Source File: ProcyonDecompiler.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * The metadata cache can become huge over time. This simply flushes it periodically.
 */
private void refreshMetadataCache(final Queue<WindupMetadataSystem> metadataSystemCache, final DecompilerSettings settings)
{
    metadataSystemCache.clear();
    for (int i = 0; i < this.getNumberOfThreads(); i++)
    {
        metadataSystemCache.add(new NoRetryMetadataSystem(settings.getTypeLoader()));
    }
}
 
Example #9
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 #10
Source File: FileSaver.java    From Luyten with Apache License 2.0 5 votes vote down vote up
private DecompilerSettings cloneSettings() {
	DecompilerSettings settings = ConfigSaver.getLoadedInstance().getDecompilerSettings();
	DecompilerSettings newSettings = new DecompilerSettings();
	if (newSettings.getJavaFormattingOptions() == null) {
		newSettings.setJavaFormattingOptions(JavaFormattingOptions.createDefault());
	}
	// synchronized: against main menu changes
	synchronized (settings) {
		newSettings.setExcludeNestedTypes(settings.getExcludeNestedTypes());
		newSettings.setFlattenSwitchBlocks(settings.getFlattenSwitchBlocks());
		newSettings.setForceExplicitImports(settings.getForceExplicitImports());
		newSettings.setForceExplicitTypeArguments(settings.getForceExplicitTypeArguments());
		newSettings.setOutputFileHeaderText(settings.getOutputFileHeaderText());
		newSettings.setLanguage(settings.getLanguage());
		newSettings.setShowSyntheticMembers(settings.getShowSyntheticMembers());
		newSettings.setAlwaysGenerateExceptionVariableForCatchBlocks(
				settings.getAlwaysGenerateExceptionVariableForCatchBlocks());
		newSettings.setOutputDirectory(settings.getOutputDirectory());
		newSettings.setRetainRedundantCasts(settings.getRetainRedundantCasts());
		newSettings.setIncludeErrorDiagnostics(settings.getIncludeErrorDiagnostics());
		newSettings.setIncludeLineNumbersInBytecode(settings.getIncludeLineNumbersInBytecode());
		newSettings.setRetainPointlessSwitches(settings.getRetainPointlessSwitches());
		newSettings.setUnicodeOutputEnabled(settings.isUnicodeOutputEnabled());
		newSettings.setMergeVariables(settings.getMergeVariables());
		newSettings.setShowDebugLineNumbers(settings.getShowDebugLineNumbers());
	}
	return newSettings;
}
 
Example #11
Source File: FileSaver.java    From Luyten with Apache License 2.0 5 votes vote down vote up
private void doSaveClassDecompiled(File inFile, File outFile) throws Exception {
	DecompilerSettings settings = cloneSettings();
	LuytenTypeLoader typeLoader = new LuytenTypeLoader();
	MetadataSystem metadataSystem = new MetadataSystem(typeLoader);
	TypeReference type = metadataSystem.lookupType(inFile.getCanonicalPath());

	DecompilationOptions decompilationOptions = new DecompilationOptions();
	decompilationOptions.setSettings(settings);
	decompilationOptions.setFullDecompilation(true);

	boolean isUnicodeEnabled = decompilationOptions.getSettings().isUnicodeOutputEnabled();
	TypeDefinition resolvedType = null;
	if (type == null || ((resolvedType = type.resolve()) == null)) {
		throw new Exception("Unable to resolve type.");
	}
	StringWriter stringwriter = new StringWriter();
	PlainTextOutput plainTextOutput = new PlainTextOutput(stringwriter);
	plainTextOutput.setUnicodeOutputEnabled(isUnicodeEnabled);
	settings.getLanguage().decompileType(resolvedType, plainTextOutput, decompilationOptions);
	String decompiledSource = stringwriter.toString();

	System.out.println("[SaveAll]: " + inFile.getName() + " -> " + outFile.getName());
	try (FileOutputStream fos = new FileOutputStream(outFile);
			OutputStreamWriter writer = isUnicodeEnabled ? new OutputStreamWriter(fos, "UTF-8")
					: new OutputStreamWriter(fos);
			BufferedWriter bw = new BufferedWriter(writer);) {
		bw.write(decompiledSource);
		bw.flush();
	}
}
 
Example #12
Source File: ConfigSaver.java    From Luyten with Apache License 2.0 5 votes vote down vote up
/**
 * Do not load, get the loaded instance
 */
private void loadConfig() {
	decompilerSettings = new DecompilerSettings();
	if (decompilerSettings.getJavaFormattingOptions() == null) {
		decompilerSettings.setJavaFormattingOptions(JavaFormattingOptions.createDefault());
	}
	luytenPreferences = new LuytenPreferences();
	mainWindowPosition = new WindowPosition();
	findWindowPosition = new WindowPosition();
	try {
		Preferences prefs = Preferences.userNodeForPackage(ConfigSaver.class);
		if (!prefs.get(LANGUAGE_NAME_ID, decompilerSettings.getLanguage().getName())
				.equals(decompilerSettings.getLanguage().getName()))
			prefs.put(LANGUAGE_NAME_ID, decompilerSettings.getLanguage().getName());

		decompilerSettings.setFlattenSwitchBlocks(
				prefs.getBoolean(FLATTEN_SWITCH_BLOCKS_ID, decompilerSettings.getFlattenSwitchBlocks()));
		decompilerSettings.setForceExplicitImports(
				prefs.getBoolean(FORCE_EXPLICIT_IMPORTS_ID, decompilerSettings.getForceExplicitImports()));
		decompilerSettings.setShowSyntheticMembers(
				prefs.getBoolean(SHOW_SYNTHETIC_MEMBERS_ID, decompilerSettings.getShowSyntheticMembers()));
		decompilerSettings.setExcludeNestedTypes(
				prefs.getBoolean(EXCLUDE_NESTED_TYPES_ID, decompilerSettings.getExcludeNestedTypes()));
		decompilerSettings.setForceExplicitTypeArguments(prefs.getBoolean(FORCE_EXPLICIT_TYPE_ARGUMENTS_ID,
				decompilerSettings.getForceExplicitTypeArguments()));
		decompilerSettings.setRetainRedundantCasts(
				prefs.getBoolean(RETAIN_REDUNDANT_CASTS_ID, decompilerSettings.getRetainRedundantCasts()));
		decompilerSettings.setIncludeErrorDiagnostics(
				prefs.getBoolean(INCLUDE_ERROR_DIAGNOSTICS_ID, decompilerSettings.getIncludeErrorDiagnostics()));
		decompilerSettings.setLanguage(
				findLanguageByName(prefs.get(LANGUAGE_NAME_ID, decompilerSettings.getLanguage().getName())));
		decompilerSettings.setUnicodeOutputEnabled(prefs.getBoolean(UNICODE_REPLACE_ENABLED_ID, false));

		mainWindowPosition = loadWindowPosition(prefs, MAIN_WINDOW_ID_PREFIX);
		findWindowPosition = loadWindowPosition(prefs, FIND_WINDOW_ID_PREFIX);
		luytenPreferences = loadLuytenPreferences(prefs);
	} catch (Exception e) {
		Luyten.showExceptionDialog("Exception!", e);
	}
}
 
Example #13
Source File: ProcyonDecompiler.java    From bytecode-viewer with GNU General Public License v3.0 5 votes vote down vote up
public DecompilerSettings getDecompilerSettings() {
    DecompilerSettings settings = new DecompilerSettings();
    settings.setAlwaysGenerateExceptionVariableForCatchBlocks(BytecodeViewer.viewer.chckbxmntmNewCheckItem_6
            .isSelected());
    settings.setExcludeNestedTypes(BytecodeViewer.viewer.chckbxmntmNewCheckItem_11
            .isSelected());
    settings.setShowDebugLineNumbers(BytecodeViewer.viewer.chckbxmntmShowDebugLine
            .isSelected());
    settings.setIncludeLineNumbersInBytecode(BytecodeViewer.viewer.chckbxmntmNewCheckItem_3
            .isSelected());
    settings.setIncludeErrorDiagnostics(BytecodeViewer.viewer.chckbxmntmNewCheckItem_4
            .isSelected());
    settings.setShowSyntheticMembers(BytecodeViewer.viewer.chckbxmntmNewCheckItem_7
            .isSelected());
    settings.setSimplifyMemberReferences(BytecodeViewer.viewer.chckbxmntmSimplifyMemberReferences
            .isSelected());
    settings.setMergeVariables(BytecodeViewer.viewer.mnMergeVariables
            .isSelected());
    settings.setForceExplicitTypeArguments(BytecodeViewer.viewer.chckbxmntmNewCheckItem_8
            .isSelected());
    settings.setForceExplicitImports(BytecodeViewer.viewer.chckbxmntmNewCheckItem_9
            .isSelected());
    settings.setFlattenSwitchBlocks(BytecodeViewer.viewer.chckbxmntmNewCheckItem_10
            .isSelected());
    settings.setRetainPointlessSwitches(BytecodeViewer.viewer.chckbxmntmNewCheckItem_2
            .isSelected());
    settings.setRetainRedundantCasts(BytecodeViewer.viewer.chckbxmntmNewCheckItem_5
            .isSelected());
    settings.setUnicodeOutputEnabled(BytecodeViewer.viewer.chckbxmntmNewCheckItem_1
            .isSelected());
    settings.setJavaFormattingOptions(JavaFormattingOptions.createDefault());
    return settings;
}
 
Example #14
Source File: ProcyonDecompiler.java    From steady with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public File decompileClassFile(File inputClassFile) {

	//Default settings for the decompilers
	final DecompilerSettings settings = new DecompilerSettings();
	settings.setShowSyntheticMembers(true);
	settings.setSimplifyMemberReferences(true);
	settings.setExcludeNestedTypes(true);

	String classFilePath = inputClassFile.getPath();
	String fileNameWithOutExt = FilenameUtils.removeExtension(inputClassFile.getName());
	File outFile = new File(inputClassFile.getParent(), fileNameWithOutExt + ".java");

	try {

		final FileOutputStream stream = new FileOutputStream(outFile.toString());
		final OutputStreamWriter writer = new OutputStreamWriter(stream, FileUtil.getCharset());

		try {
			Decompiler.decompile(
					classFilePath,
					new PlainTextOutput(writer),
					settings
					);
		}
		finally {
			writer.close();
			stream.close();
		}
	}
	catch (final IOException e) {
		log.debug(e.getMessage());
	}

	return outFile;
}
 
Example #15
Source File: DecompileClasses.java    From apk-decompiler with GNU General Public License v2.0 5 votes vote down vote up
private void decompile(File classFile, File srcFolder) {
	try {
		File outputFile = convertClassFileToOutputFile(classFile, srcFolder);
		outputFile.getParentFile().mkdirs();
		PlainTextOutput output = new PlainTextOutput(new OutputStreamWriter(new FileOutputStream(outputFile.getAbsolutePath())));
		DecompilerSettings settings = DecompilerSettings.javaDefaults();
		settings.setForceExplicitImports(true);
		settings.setOutputFileHeaderText("Generated with Procyon v" + Procyon.version());

		Decompiler.decompile(classFile.getAbsolutePath(), output, settings);
	} catch (IOException ex) {
		Logger.error("Unable to decompile " + classFile.getAbsolutePath(), ex);
	}
}
 
Example #16
Source File: DecompileClasses.java    From apk-decompiler with GNU General Public License v2.0 5 votes vote down vote up
private void decompile(File classFile, File srcFolder) {
	try {
		File outputFile = convertClassFileToOutputFile(classFile, srcFolder);
		outputFile.getParentFile().mkdirs();
		PlainTextOutput output = new PlainTextOutput(new OutputStreamWriter(new FileOutputStream(outputFile.getAbsolutePath())));
		DecompilerSettings settings = DecompilerSettings.javaDefaults();
		settings.setForceExplicitImports(true);
		settings.setOutputFileHeaderText("Generated with Procyon v" + Procyon.version());

		Decompiler.decompile(classFile.getAbsolutePath(), output, settings);
	} catch (IOException ex) {
		Logger.error("Unable to decompile " + classFile.getAbsolutePath(), ex);
	}
}
 
Example #17
Source File: ClassFile.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static CompilationUnit decompileClassFile(TypeReference typeRef) {
  TypeDefinition typeDef = typeRef.resolve();
  DeobfuscationUtilities.processType(typeDef);
  DecompilationOptions options = new DecompilationOptions();
  DecompilerSettings settings = DecompilerSettings.javaDefaults();
  settings.setShowSyntheticMembers(true);
  options.setSettings(settings);
  options.setFullDecompilation(true);
  return Languages.java().decompileTypeToAst(typeDef, options);
}
 
Example #18
Source File: ProcyonDecompilerController.java    From standalone-app with Apache License 2.0 4 votes vote down vote up
@Override
protected DecompilerSettings defaultSettings() {
    return getDecompiler().defaultSettings();
}
 
Example #19
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 #20
Source File: ProcyonDecompiler.java    From java-disassembler with GNU General Public License v3.0 4 votes vote down vote up
@Override
public String decompileClassNode(FileContainer container, final ClassNode cn) {
    try {
        byte[] bytes = JDA.getClassBytes(container, cn);
        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(bytes, 0, bytes.length);
                    buffer.position(0);
                    return true;
                } else {
                    String classFilename = s + ".class";
                    FileContainer otherContainer = JDA.findContainerForFile(classFilename);
                    if (otherContainer != null) {
                        byte[] toUse = otherContainer.getFiles().get(classFilename);
                        if (toUse != null) {
                            buffer.putByteArray(toUse, 0, toUse.length);
                            buffer.position(0);
                            return true;
                        }
                    }
                    return backLoader.tryLoadType(s, buffer);
                }
            }
        });
        TypeReference type = metadataSystem.lookupType(cn.name);
        DecompilationOptions decompilationOptions = new DecompilationOptions();
        DecompilerSettings settings = getDecompilerSettings();
        decompilationOptions.setSettings(settings);
        decompilationOptions.setFullDecompilation(true);
        TypeDefinition resolvedType;
        if (type == null || ((resolvedType = type.resolve()) == null)) {
            throw new Exception("Unable to resolve type.");
        }
        StringWriter stringwriter = new StringWriter();
        settings.getLanguage().decompileType(resolvedType, new PlainTextOutput(stringwriter), decompilationOptions);
        String decompiledSource = stringwriter.toString();
        return decompiledSource;
    } catch (Throwable e) {
        return parseException(e);
    }
}
 
Example #21
Source File: ProcyonConfiguration.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
public ProcyonConfiguration setDecompilerSettings(DecompilerSettings decompilerSettings)
{
    this.decompilerSettings = decompilerSettings;
    return this;
}
 
Example #22
Source File: ProcyonConfiguration.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
public DecompilerSettings getDecompilerSettings()
{
    return decompilerSettings;
}
 
Example #23
Source File: FileOutputWriter.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
FileOutputWriter(final File file, final DecompilerSettings settings) throws IOException
{
    super(new FileOutputStream(file), Charset.forName("UTF-8"));
    this.file = file;
}
 
Example #24
Source File: ProcyonDecompilerController.java    From standalone-app with Apache License 2.0 4 votes vote down vote up
RawBooleanSetting(String id, String desc, boolean defaultValue, BiConsumer<DecompilerSettings, Boolean> consumer) {
    super(Boolean.class, defaultValue, ConfigurationSerializer.BOOLEAN, id, desc);
    this.consumer = consumer;
}
 
Example #25
Source File: ProcyonDecompilerController.java    From standalone-app with Apache License 2.0 4 votes vote down vote up
@Override
public void apply(DecompilerSettings settings, Boolean value) {
    consumer.accept(settings, value);
}
 
Example #26
Source File: ConfigSaver.java    From Luyten with Apache License 2.0 4 votes vote down vote up
public DecompilerSettings getDecompilerSettings() {
	return decompilerSettings;
}
 
Example #27
Source File: ProcyonDisassemblerController.java    From standalone-app with Apache License 2.0 4 votes vote down vote up
@Override
protected DecompilerSettings defaultSettings() {
    return getDisassembler().defaultSettings();
}
 
Example #28
Source File: DecompilerLinkProvider.java    From Luyten with Apache License 2.0 4 votes vote down vote up
public void setDecompilerReferences(MetadataSystem metadataSystem, DecompilerSettings settings,
		DecompilationOptions decompilationOptions) {
	this.metadataSystem = metadataSystem;
	this.settings = settings;
	this.decompilationOptions = decompilationOptions;
}
 
Example #29
Source File: FindAllBox.java    From Luyten with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(ActionEvent event) {
	tmp_thread = new Thread() {
		public void run() {
			if (findButton.getText().equals("Stop")) {
				if (tmp_thread != null)
					tmp_thread.interrupt();
				setStatus("Stopped.");
				findButton.setText("Find");
				locked = false;
			} else {
				findButton.setText("Stop");
				classesList.clear();
				ConfigSaver configSaver = ConfigSaver.getLoadedInstance();
				DecompilerSettings settings = configSaver.getDecompilerSettings();
				File inFile = MainWindow.model.getOpenedFile();
				boolean filter = ConfigSaver.getLoadedInstance().getLuytenPreferences()
						.isFilterOutInnerClassEntries();
				try {
					JarFile jfile = new JarFile(inFile);
					Enumeration<JarEntry> entLength = jfile.entries();
					initProgressBar(Collections.list(entLength).size());
					Enumeration<JarEntry> ent = jfile.entries();
					while (ent.hasMoreElements() && findButton.getText().equals("Stop")) {
						JarEntry entry = ent.nextElement();
						String name = entry.getName();
						setStatus(name);
						if (filter && name.contains("$"))
							continue;
						if(locked || classname.isSelected()){
							locked = true;
							if(search(entry.getName()))
								addClassName(entry.getName());
						}else{
							if (entry.getName().endsWith(".class")) {
								synchronized (settings) {
									String internalName = StringUtilities.removeRight(entry.getName(), ".class");
									TypeReference type = Model.metadataSystem.lookupType(internalName);
									TypeDefinition resolvedType = null;
									if (type == null || ((resolvedType = type.resolve()) == null)) {
										throw new Exception("Unable to resolve type.");
									}
									StringWriter stringwriter = new StringWriter();
									DecompilationOptions decompilationOptions;
									decompilationOptions = new DecompilationOptions();
									decompilationOptions.setSettings(settings);
									decompilationOptions.setFullDecompilation(true);
									PlainTextOutput plainTextOutput = new PlainTextOutput(stringwriter);
									plainTextOutput.setUnicodeOutputEnabled(
											decompilationOptions.getSettings().isUnicodeOutputEnabled());
									settings.getLanguage().decompileType(resolvedType, plainTextOutput,
											decompilationOptions);
									if (search(stringwriter.toString()))
										addClassName(entry.getName());
								}
							} else {

								StringBuilder sb = new StringBuilder();
								long nonprintableCharactersCount = 0;
								try (InputStreamReader inputStreamReader = new InputStreamReader(
										jfile.getInputStream(entry));
										BufferedReader reader = new BufferedReader(inputStreamReader);) {
									String line;
									while ((line = reader.readLine()) != null) {
										sb.append(line).append("\n");

										for (byte nextByte : line.getBytes()) {
											if (nextByte <= 0) {
												nonprintableCharactersCount++;
											}
										}

									}
								}
								if (nonprintableCharactersCount < 5 && search(sb.toString()))
									addClassName(entry.getName());
							}
						}
					}
					setSearching(false);
					if (findButton.getText().equals("Stop")) {
						setStatus("Done.");
						findButton.setText("Find");
						locked = false;
					}
					jfile.close();
					locked = false;
				} catch (Exception e) {
					Luyten.showExceptionDialog("Exception!", e);
				}

			}
		}
	};
	tmp_thread.start();

}
 
Example #30
Source File: OpenFile.java    From Luyten with Apache License 2.0 4 votes vote down vote up
public void setDecompilerReferences(MetadataSystem metadataSystem, DecompilerSettings settings,
		DecompilationOptions decompilationOptions) {
	this.metadataSystem = metadataSystem;
	this.settings = settings;
	this.decompilationOptions = decompilationOptions;
}