-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCfrDecompiler.java
More file actions
262 lines (231 loc) · 10.2 KB
/
CfrDecompiler.java
File metadata and controls
262 lines (231 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package com.jaipilot.cli.classpath;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.benf.cfr.reader.api.CfrDriver;
import org.benf.cfr.reader.api.OutputSinkFactory;
import org.benf.cfr.reader.api.SinkReturns;
final class CfrDecompiler {
private static final System.Logger LOGGER = System.getLogger(CfrDecompiler.class.getName());
Optional<String> decompile(Path classContainer, String classEntryPath) {
if (classContainer == null || classEntryPath == null || classEntryPath.isBlank()) {
return Optional.empty();
}
Path normalizedContainer = classContainer.toAbsolutePath().normalize();
if (Files.isDirectory(normalizedContainer)) {
Path classFile = normalizedContainer.resolve(classEntryPath).toAbsolutePath().normalize();
if (!Files.isRegularFile(classFile)) {
return Optional.empty();
}
return decompileClassFile(classFile);
}
String fileName = normalizedContainer.getFileName() == null
? ""
: normalizedContainer.getFileName().toString();
if (fileName.endsWith(".jar")) {
return decompileFromJar(normalizedContainer, classEntryPath);
}
if (fileName.endsWith(".class") && Files.isRegularFile(normalizedContainer)) {
return decompileClassFile(normalizedContainer);
}
return Optional.empty();
}
private Optional<String> decompileFromJar(Path jarPath, String classEntryPath) {
Path tempDirectory = null;
try {
tempDirectory = Files.createTempDirectory("jaipilot-cfr-");
ExtractedClass extractedClass = extractClassFromJar(jarPath, classEntryPath, tempDirectory).orElse(null);
if (extractedClass == null) {
return Optional.empty();
}
return decompileClassFile(extractedClass.classFilePath());
} catch (IOException exception) {
LOGGER.log(System.Logger.Level.DEBUG, "cfr extraction failed for {0}: {1}", jarPath, exception.getMessage());
return Optional.empty();
} finally {
deleteRecursively(tempDirectory);
}
}
private Optional<ExtractedClass> extractClassFromJar(Path jarPath, String classEntryPath, Path tempDirectory) throws IOException {
String normalizedEntryPath = normalizeEntryPath(classEntryPath);
if (normalizedEntryPath.isBlank()) {
return Optional.empty();
}
String outerEntryPath = outerClassEntryPath(normalizedEntryPath);
try (ZipFile zipFile = new ZipFile(jarPath.toFile())) {
ZipEntry primaryEntry = findPrimaryEntry(zipFile, normalizedEntryPath, outerEntryPath);
if (primaryEntry == null) {
return Optional.empty();
}
String outerPrefix = outerEntryPath.substring(0, outerEntryPath.length() - ".class".length());
Set<String> entriesToExtract = new LinkedHashSet<>();
entriesToExtract.add(primaryEntry.getName());
entriesToExtract.add(outerEntryPath);
for (ZipEntry entry : List.copyOf(zipFile.stream().toList())) {
if (entry.isDirectory()) {
continue;
}
String name = entry.getName();
if (name.startsWith(outerPrefix + "$") && name.endsWith(".class")) {
entriesToExtract.add(name);
}
}
Path primaryPath = null;
for (String entryName : entriesToExtract) {
ZipEntry entry = zipFile.getEntry(entryName);
if (entry == null || entry.isDirectory()) {
continue;
}
Path extractedPath = extractEntry(zipFile, entry, tempDirectory);
if (entry.getName().equals(primaryEntry.getName())) {
primaryPath = extractedPath;
}
}
return Optional.ofNullable(primaryPath).map(ExtractedClass::new);
}
}
private ZipEntry findPrimaryEntry(ZipFile zipFile, String normalizedEntryPath, String outerEntryPath) {
ZipEntry outer = zipFile.getEntry(outerEntryPath);
if (outer != null && !outer.isDirectory()) {
return outer;
}
ZipEntry requested = zipFile.getEntry(normalizedEntryPath);
if (requested != null && !requested.isDirectory()) {
return requested;
}
return null;
}
private Path extractEntry(ZipFile zipFile, ZipEntry entry, Path outputRoot) throws IOException {
Path outputPath = outputRoot.resolve(entry.getName()).toAbsolutePath().normalize();
Path parent = outputPath.getParent();
if (parent != null) {
Files.createDirectories(parent);
}
try (InputStream inputStream = zipFile.getInputStream(entry)) {
Files.copy(inputStream, outputPath, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
return outputPath;
}
private Optional<String> decompileClassFile(Path classFilePath) {
List<String> decompiledSource = new ArrayList<>();
List<String> exceptions = new ArrayList<>();
try {
CfrDriver cfrDriver = new CfrDriver.Builder()
.withOptions(Map.of(
"showversion", "false",
"silent", "true"
))
.withOutputSink(new CfrOutputSink(decompiledSource, exceptions))
.build();
cfrDriver.analyse(List.of(classFilePath.toString()));
} catch (Exception exception) {
LOGGER.log(System.Logger.Level.DEBUG, "cfr decompilation failed for {0}: {1}", classFilePath, exception.getMessage());
return Optional.empty();
}
if (decompiledSource.isEmpty()) {
if (!exceptions.isEmpty()) {
LOGGER.log(System.Logger.Level.DEBUG, "cfr did not produce Java source for {0}: {1}", classFilePath, exceptions.get(0));
}
return Optional.empty();
}
return decompiledSource.stream()
.filter(source -> source != null && !source.isBlank())
.findFirst()
.map(this::normalizeLineEndings);
}
private String normalizeEntryPath(String classEntryPath) {
String normalized = classEntryPath.replace('\\', '/');
while (normalized.startsWith("/")) {
normalized = normalized.substring(1);
}
return normalized;
}
private String outerClassEntryPath(String classEntryPath) {
int firstDollar = classEntryPath.indexOf('$');
if (firstDollar < 0) {
return classEntryPath;
}
int classSuffix = classEntryPath.lastIndexOf(".class");
if (classSuffix < 0) {
return classEntryPath.substring(0, firstDollar);
}
return classEntryPath.substring(0, firstDollar) + ".class";
}
private String normalizeLineEndings(String source) {
return source.replace("\r\n", "\n").replace('\r', '\n');
}
private void deleteRecursively(Path path) {
if (path == null || !Files.exists(path)) {
return;
}
try (var paths = Files.walk(path)) {
paths.sorted(Comparator.reverseOrder()).forEach(candidate -> {
try {
Files.deleteIfExists(candidate);
} catch (IOException ignored) {
// Best-effort cleanup for temporary decompiler files.
}
});
} catch (IOException ignored) {
// Best-effort cleanup for temporary decompiler files.
}
}
private record ExtractedClass(Path classFilePath) {
}
private static final class CfrOutputSink implements OutputSinkFactory {
private final List<String> decompiledSource;
private final List<String> exceptions;
CfrOutputSink(List<String> decompiledSource, List<String> exceptions) {
this.decompiledSource = decompiledSource;
this.exceptions = exceptions;
}
@Override
public List<SinkClass> getSupportedSinks(SinkType sinkType, Collection<SinkClass> available) {
if (sinkType == SinkType.JAVA) {
if (available.contains(SinkClass.DECOMPILED)) {
return List.of(SinkClass.DECOMPILED);
}
if (available.contains(SinkClass.STRING)) {
return List.of(SinkClass.STRING);
}
return List.of();
}
if (sinkType == SinkType.EXCEPTION && available.contains(SinkClass.EXCEPTION_MESSAGE)) {
return List.of(SinkClass.EXCEPTION_MESSAGE);
}
if (sinkType == SinkType.EXCEPTION && available.contains(SinkClass.STRING)) {
return List.of(SinkClass.STRING);
}
return List.of();
}
@Override
@SuppressWarnings("unchecked")
public <T> Sink<T> getSink(SinkType sinkType, SinkClass sinkClass) {
if (sinkType == SinkType.JAVA && sinkClass == SinkClass.DECOMPILED) {
return sinkable -> decompiledSource.add(((SinkReturns.Decompiled) sinkable).getJava());
}
if (sinkType == SinkType.JAVA && sinkClass == SinkClass.STRING) {
return sinkable -> decompiledSource.add(String.valueOf(sinkable));
}
if (sinkType == SinkType.EXCEPTION && sinkClass == SinkClass.EXCEPTION_MESSAGE) {
return sinkable -> exceptions.add(((SinkReturns.ExceptionMessage) sinkable).getMessage());
}
if (sinkType == SinkType.EXCEPTION && sinkClass == SinkClass.STRING) {
return sinkable -> exceptions.add(String.valueOf(sinkable));
}
return sinkable -> {
};
}
}
}