-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
PrePatcher.java
373 lines (340 loc) · 14.2 KB
/
PrePatcher.java
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package nallar.nmsprepatcher;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import java.util.regex.*;
// The prepatcher adds method declarations in superclasses,
// so javac can compile the patch classes if they need to use a method/field they
// add on an instance other than this
class PrePatcher {
private static final Logger log = Logger.getLogger("PatchLogger");
private static final Pattern privatePattern = Pattern.compile("^(\\s+?)private", Pattern.MULTILINE);
private static final Pattern extendsPattern = Pattern.compile("^public.*?\\s+?extends\\s+?([\\S^<]+?)(?:<(\\S+)>)?[\\s]+?(?:implements [^}]+?)?\\{", Pattern.MULTILINE);
private static final Pattern genericMethodPattern = Pattern.compile("@Generic\\s+?(public\\s+?(\\S*?)?\\s+?(\\S*?)\\s*?\\S+?\\s*?\\()[^\\{]*\\)\\s*?\\{", Pattern.DOTALL | Pattern.MULTILINE);
private static final Pattern declareMethodPattern = Pattern.compile("@Declare\\s+?(public\\s+?(?:(?:synchronized|static) )*(\\S*?)?\\s+?(\\S*?)\\s*?\\S+?\\s*?\\([^\\{]*\\)\\s*?\\{)", Pattern.DOTALL | Pattern.MULTILINE);
private static final Pattern declareFieldPattern = Pattern.compile("@Declare\\s+?(public [^;\r\n]+?)_?( = [^;\r\n]+?)?;", Pattern.DOTALL | Pattern.MULTILINE);
private static final Pattern packageFieldPattern = Pattern.compile("\n ? ?([^ ]+ ? ?[^ ]+);");
private static final Pattern innerClassPattern = Pattern.compile("[^\n]public (?:static )?class ([^ \n]+)[ \n]", Pattern.MULTILINE);
private static final Splitter spaceSplitter = Splitter.on(' ').omitEmptyStrings();
private static final Splitter commaSplitter = Splitter.on(',').omitEmptyStrings().trimResults();
private static final Map<String, PatchInfo> patchClasses = new HashMap<String, PatchInfo>();
private static final Map<String, String> generics = new HashMap<String, String>();
public static void loadPatches(File patchDirectory) {
recursiveSearch(patchDirectory);
}
private static void recursiveSearch(File patchDirectory) {
for (File file : patchDirectory.listFiles()) {
if (!file.getName().equals("annotation") && file.isDirectory()) {
recursiveSearch(file);
continue;
}
if (!file.getName().endsWith(".java")) {
continue;
}
String contents = readFile(file);
if (contents == null) {
log.log(Level.SEVERE, "Failed to read " + file);
continue;
}
Matcher extendsMatcher = extendsPattern.matcher(contents);
if (!extendsMatcher.find()) {
if (contents.contains(" extends")) {
log.warning("Didn't match extends matcher for " + file);
}
continue;
}
String shortClassName = extendsMatcher.group(1);
String className = null;
for (String line : Splitter.on('\n').split(contents)) {
if (line.endsWith('.' + shortClassName + ';')) {
className = line.substring(7, line.length() - 1);
}
}
if (className == null) {
log.warning("Unable to find class " + shortClassName + " for " + file);
continue;
}
String generic = extendsMatcher.group(2);
if (generic != null) {
generics.put(className, generic);
}
addPatches(className, contents);
log.warning("Loaded patch for " + className);
}
}
//private static final Pattern methodInfoPattern = Pattern.compile("(?:(public|private|protected) )?(static )?(?:([^ ]+?) )([^\\( ]+?) ?\\((.*?)\\) ?\\{", Pattern.DOTALL);
private static final Pattern methodInfoPattern = Pattern.compile("^(.+) ?\\(([^\\(]*)\\) ?\\{", Pattern.DOTALL);
private static void addPatches(String className, String contents) {
PatchInfo patchInfo = patchClasses.get(className);
if (patchInfo == null) {
patchInfo = new PatchInfo();
patchClasses.put(className, patchInfo);
}
String shortClassName = className;
shortClassName = shortClassName.substring(shortClassName.lastIndexOf('/') + 1);
shortClassName = shortClassName.substring(0, shortClassName.indexOf('.'));
patchInfo.shortClassName = shortClassName;
Matcher matcher = declareMethodPattern.matcher(contents);
while (matcher.find()) {
Matcher methodInfoMatcher = methodInfoPattern.matcher(matcher.group(1));
if (!methodInfoMatcher.find()) {
log.warning("Failed to match method info matcher to method declaration " + matcher.group(1));
continue;
}
MethodInfo methodInfo = new MethodInfo();
patchInfo.methods.add(methodInfo);
String accessAndNameString = methodInfoMatcher.group(1);
String paramString = methodInfoMatcher.group(2);
for (String parameter : commaSplitter.split(paramString)) {
String parameterType = spaceSplitter.split(parameter).iterator().next();
methodInfo.parameterTypes.add(parameterType);
}
LinkedList<String> accessAndNames = Lists.newLinkedList(spaceSplitter.split(accessAndNameString));
methodInfo.name = accessAndNames.removeLast();
String type = methodInfo.returnType = accessAndNames.removeLast();
while (!accessAndNames.isEmpty()) {
String thing = accessAndNames.removeLast();
if (thing.equals("static")) {
methodInfo.static_ = true;
} else if (thing.equals("synchronized")) {
methodInfo.synchronized_ = true;
} else {
if (methodInfo.access != null) {
log.warning("overwriting access from " + methodInfo.access + " -> " + thing + " in " + matcher.group(1));
}
methodInfo.access = thing;
}
}
//methodInfo.parameterTypes.add();
String ret = "null";
if ("static".equals(type)) {
type = matcher.group(3);
}
if ("boolean".equals(type)) {
ret = "false";
} else if ("void".equals(type)) {
ret = "";
} else if ("long".equals(type)) {
ret = "0L";
} else if ("int".equals(type)) {
ret = "0";
} else if ("float".equals(type)) {
ret = "0f";
} else if ("double".equals(type)) {
ret = "0.0";
}
methodInfo.javaCode = matcher.group(1) + "return " + ret + ";}";
log.warning(methodInfo.toString());
}
Matcher FieldMatcher = declareFieldPattern.matcher(contents);
while (FieldMatcher.find()) {
String var = FieldMatcher.group(1);
FieldInfo FieldInfo = new FieldInfo();
patchInfo.Fields.add(FieldInfo);
LinkedList<String> typeAndName = Lists.newLinkedList(spaceSplitter.split(var));
FieldInfo.name = typeAndName.removeLast();
FieldInfo.type = typeAndName.removeLast();
while (!typeAndName.isEmpty()) {
String thing = typeAndName.removeLast();
if (thing.equals("static")) {
FieldInfo.static_ = true;
} else if (thing.equals("volatile")) {
FieldInfo.volatile_ = true;
} else {
if (FieldInfo.access != null) {
log.severe("overwriting access from " + FieldInfo.access + " -> " + thing + " in " + var);
}
FieldInfo.access = thing;
}
}
FieldInfo.javaCode = var + ';';
log.warning(FieldInfo.toString());
}
String generic = generics.get(className);
Matcher genericMatcher = genericMethodPattern.matcher(contents);
while (genericMatcher.find()) {
String original = genericMatcher.group(1);
String withoutGenerics = original.replace(' ' + generic + ' ', " Object ");
log.warning(original + " -> " + withoutGenerics);
}
if (contents.contains("\n@Public")) {
patchInfo.makeAllPublic = true;
}
}
private static class MethodInfo {
public String name;
public List<String> parameterTypes = new ArrayList<String>();
public String returnType;
public String access;
public boolean static_;
public boolean synchronized_;
public String javaCode;
private static final Joiner parameterJoiner = Joiner.on(", ");
public String toString() {
return "method: " + access + ' ' + (static_ ? "static " : "") + (synchronized_ ? "synchronized " : "") + returnType + ' ' + name + " (" + parameterJoiner.join(parameterTypes) + ')';
}
}
private static class FieldInfo {
public String name;
public String type;
public String access;
public boolean static_;
public boolean volatile_;
public String javaCode;
public String toString() {
return "field: " + access + ' ' + (static_ ? "static " : "") + (volatile_ ? "volatile " : "") + type + ' ' + name;
}
}
private static class PatchInfo {
List<MethodInfo> methods = new ArrayList<MethodInfo>();
List<FieldInfo> Fields = new ArrayList<FieldInfo>();
boolean makeAllPublic = false;
String shortClassName;
}
private static PatchInfo patchForClass(String className) {
return patchClasses.get(className.replace("/", ".").replace(".java", "").replace(".class", ""));
}
public static String patchSource(String inputSource, String inputClassName) {
PatchInfo patchInfo = patchForClass(inputClassName);
if (patchInfo == null) {
return inputSource;
}
log.warning("Prepatching source for " + inputClassName);
inputSource = inputSource.trim().replace("\t", " ");
String shortClassName = patchInfo.shortClassName;
StringBuilder sourceBuilder = new StringBuilder(inputSource.substring(0, inputSource.lastIndexOf('}')))
.append("\n// TT Patch Declarations\n");
for (MethodInfo methodInfo : patchInfo.methods) {
if (sourceBuilder.indexOf(methodInfo.javaCode) == -1) {
sourceBuilder.append(methodInfo.javaCode).append('\n');
}
}
for (FieldInfo FieldInfo : patchInfo.Fields) {
if (sourceBuilder.indexOf(FieldInfo.javaCode) == -1) {
sourceBuilder.append(FieldInfo.javaCode).append('\n');
}
}
sourceBuilder.append("\n}");
inputSource = sourceBuilder.toString();
String generic = generics.get(inputClassName);
if (generic != null) {
inputSource = inputSource.replaceAll("class " + shortClassName + "(<[^>]>)?", "class " + shortClassName + '<' + generic + '>');
}
/*Matcher genericMatcher = genericMethodPattern.matcher(contents);
while (genericMatcher.find()) {
String original = genericMatcher.group(1);
String withoutGenerics = original.replace(' ' + generic + ' ', " Object ");
int index = inputSource.indexOf(withoutGenerics);
if (index == -1) {
continue;
}
int endIndex = inputSource.indexOf("\n }", index);
String body = inputSource.substring(index, endIndex);
inputSource = inputSource.replace(body, body.replace(withoutGenerics, original).replace("return ", "return (" + generic + ") "));
}*/
inputSource = inputSource.replace("\nfinal ", " ");
inputSource = inputSource.replace(" final ", " ");
inputSource = inputSource.replace("\nclass", "\npublic class");
inputSource = inputSource.replace("\n " + shortClassName, "\n public " + shortClassName);
inputSource = inputSource.replace("\n protected " + shortClassName, "\n public " + shortClassName);
inputSource = inputSource.replace("private class", "public class");
inputSource = inputSource.replace("protected class", "public class");
inputSource = privatePattern.matcher(inputSource).replaceAll("$1protected");
if (patchInfo.makeAllPublic) {
inputSource = inputSource.replace("protected ", "public ");
}
inputSource = inputSource.replace("protected void save(", "public void save(");
Matcher packageMatcher = packageFieldPattern.matcher(inputSource);
StringBuffer sb = new StringBuffer();
while (packageMatcher.find()) {
packageMatcher.appendReplacement(sb, "\n public " + packageMatcher.group(1) + ';');
}
packageMatcher.appendTail(sb);
inputSource = sb.toString();
Matcher innerClassMatcher = innerClassPattern.matcher(inputSource);
while (innerClassMatcher.find()) {
String name = innerClassMatcher.group(1);
inputSource = inputSource.replace(" " + name + '(', " public " + name + '(');
}
return inputSource.replace(" ", "\t");
}
private static boolean hasFlag(int access, int flag) {
return (access & flag) != 0;
}
private static int replaceFlag(int in, int from, int to) {
if ((in & from) != 0) {
in &= ~from;
in |= to;
}
return in;
}
/**
* Changes access flags to be protected, unless already public.
* @return
*/
private static int makeAtLeastProtected(int access) {
if (hasFlag(access, Opcodes.ACC_PUBLIC) || hasFlag(access, Opcodes.ACC_PROTECTED)) {
// already protected or public
return access;
}
if (hasFlag(access, Opcodes.ACC_PRIVATE)) {
// private -> protected
return replaceFlag(access, Opcodes.ACC_PRIVATE, Opcodes.ACC_PROTECTED);
}
// not public, protected or private so must be package-local
// change to public - protected doesn't include package-local.
return access | Opcodes.ACC_PUBLIC;
}
public static byte[] patchCode(byte[] inputCode, String inputClassName) {
PatchInfo patchInfo = patchForClass(inputClassName);
if (patchInfo == null) {
return inputCode;
}
log.warning("Prepatching code for " + inputClassName);
ClassReader classReader = new ClassReader(inputCode);
ClassNode classNode = new ClassNode();
classReader.accept(classNode, 0);
classNode.access = classNode.access & ~Opcodes.ACC_FINAL;
for (FieldNode fieldNode : (Iterable<FieldNode>) classNode.fields) {
fieldNode.access = fieldNode.access & ~Opcodes.ACC_FINAL;
fieldNode.access = makeAtLeastProtected(fieldNode.access);
}
for (MethodNode methodNode : (Iterable<MethodNode>) classNode.methods) {
methodNode.access = methodNode.access & ~Opcodes.ACC_FINAL;
methodNode.access = makeAtLeastProtected(methodNode.access);
}
ClassWriter classWriter = new ClassWriter(classReader, 0);
classNode.accept(classWriter);
return classWriter.toByteArray();
}
private static String readFile(File file) {
Scanner fileReader = null;
try {
fileReader = new Scanner(file, "UTF-8").useDelimiter("\\A");
return fileReader.next().replace("\r\n", "\n");
} catch (FileNotFoundException ignored) {
} finally {
if (fileReader != null) {
fileReader.close();
}
}
return null;
}
private static void writeFile(File file, String contents) throws IOException {
FileWriter fileWriter = new FileWriter(file);
try {
fileWriter.write(contents);
} finally {
fileWriter.close();
}
}
}