com.strobel.decompiler.PlainTextOutput Java Examples

The following examples show how to use com.strobel.decompiler.PlainTextOutput. 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: ZipEntryDecompiler.java    From custom-bytecode-analyzer with GNU General Public License v3.0 7 votes vote down vote up
@Override
public String decompile(InputStream inputStream, String entryName) throws IOException {
  logger.debug("Decompiling... {}", entryName);
  File tempFile = createTempFile(entryName, inputStream);
  tempFile.deleteOnExit();

  String decompiledFileName = getDecompiledFileName(entryName);
  File decompiledFile = new File(decompiledFileName);
  decompiledFile.getParentFile().mkdirs();

  StringWriter pw = new StringWriter();
  try {
    com.strobel.decompiler.Decompiler.decompile(tempFile.getAbsolutePath(), new PlainTextOutput(pw));
  } catch (Exception e) {
    logger.info("Error while decompiling {}. " , entryName);
    throw e;
  }
  pw.flush();

  String decompiledFileContent = pw.toString();
  FileUtils.writeStringToFile(decompiledFile, decompiledFileContent);
  return decompiledFileContent;
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
Source File: Model.java    From Luyten with Apache License 2.0 5 votes vote down vote up
public void startWarmUpThread() {
	new Thread() {
		public void run() {
			try {
				Thread.sleep(500);
				String internalName = FindBox.class.getName();
				TypeReference type = metadataSystem.lookupType(internalName);
				TypeDefinition resolvedType = null;
				if ((type == null) || ((resolvedType = type.resolve()) == null)) {
					return;
				}
				StringWriter stringwriter = new StringWriter();
				PlainTextOutput plainTextOutput = new PlainTextOutput(stringwriter);
				plainTextOutput
						.setUnicodeOutputEnabled(decompilationOptions.getSettings().isUnicodeOutputEnabled());
				settings.getLanguage().decompileType(resolvedType, plainTextOutput, decompilationOptions);
				String decompiledSource = stringwriter.toString();
				OpenFile open = new OpenFile(internalName, "*/" + internalName, getTheme(), mainWindow);
				open.setContent(decompiledSource);
				JTabbedPane pane = new JTabbedPane();
				pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
				pane.addTab("title", open.scrollPane);
				pane.setSelectedIndex(pane.indexOfTab("title"));
			} catch (Exception e) {
				Luyten.showExceptionDialog("Exception!", e);
			}
		}
	}.start();
}
 
Example #7
Source File: OpenFile.java    From Luyten with Apache License 2.0 5 votes vote down vote up
private void decompileWithoutLinks() {
	this.invalidateContent();
	isNavigationLinksValid = false;
	textArea.setHyperlinksEnabled(false);

	StringWriter stringwriter = new StringWriter();
	PlainTextOutput plainTextOutput = new PlainTextOutput(stringwriter);
	plainTextOutput.setUnicodeOutputEnabled(decompilationOptions.getSettings().isUnicodeOutputEnabled());
	settings.getLanguage().decompileType(type, plainTextOutput, decompilationOptions);
	setContentPreserveLastScrollPosition(stringwriter.toString());
	this.isContentValid = true;
}
 
Example #8
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 #9
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 #10
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 #11
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 #12
Source File: UimaDecompiler.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
private String decompileToStringCommon(String className) {
  PlainTextOutput pto = new PlainTextOutput();
  String classNameSlashes = className.replace('.', '/');
  Decompiler.decompile(classNameSlashes, pto, decompilerSettings);
  return pto.toString(); 
}