-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
PatchManager.java
336 lines (317 loc) · 13.1 KB
/
PatchManager.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
package me.nallar.tickthreading.patcher;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.NotFoundException;
import me.nallar.tickthreading.Log;
import me.nallar.tickthreading.mappings.ClassDescription;
import me.nallar.tickthreading.mappings.FieldDescription;
import me.nallar.tickthreading.mappings.Mappings;
import me.nallar.tickthreading.mappings.MethodDescription;
import me.nallar.tickthreading.util.CollectionsUtil;
import me.nallar.tickthreading.util.DomUtil;
import me.nallar.tickthreading.util.LocationUtil;
import me.nallar.tickthreading.util.VersionUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class PatchManager {
private Document configDocument;
private Object patchTypes;
// Patch name -> patch method descriptor
private final Map<String, PatchMethodDescriptor> patches = new HashMap<String, PatchMethodDescriptor>();
public final ClassRegistry classRegistry = new ClassRegistry();
public File backupDirectory;
public String patchEnvironment = "forge";
public Map<String, CtClass> patchingClasses;
public PatchManager(InputStream configStream, Class<? extends Patches> patchClass) throws IOException, SAXException {
this(configStream, patchClass, new File(LocationUtil.directoryOf(patchClass).getAbsoluteFile().getParentFile(), "TickThreadingBackups"));
}
public PatchManager(InputStream configStream, Class<? extends Patches> patchClass, File backupDirectory) throws IOException, SAXException {
loadPatches(patchClass);
loadConfig(configStream);
this.backupDirectory = backupDirectory;
}
public void loadBackups(Iterable<File> filesToLoad) {
try {
classRegistry.disableJavassistLoading = true;
classRegistry.loadFiles(filesToLoad);
classRegistry.loadPatchHashes(this);
classRegistry.restoreBackups(backupDirectory);
classRegistry.clearClassInfo();
classRegistry.disableJavassistLoading = false;
} catch (IOException e) {
Log.severe("Failed to load jars for backup restore");
}
}
public void loadPatches(Class<? extends Patches> patchClass) {
try {
patchTypes = patchClass.getDeclaredConstructors()[0].newInstance(this, classRegistry);
} catch (Exception e) {
Log.severe("Failed to instantiate patch class", e);
}
for (Method method : patchClass.getDeclaredMethods()) {
for (Annotation annotation : method.getDeclaredAnnotations()) {
if (annotation instanceof Patch) {
PatchMethodDescriptor patchMethodDescriptor = new PatchMethodDescriptor(method, (Patch) annotation);
patches.put(patchMethodDescriptor.name, patchMethodDescriptor);
}
}
}
}
public void loadConfig(InputStream configInputStream) throws IOException, SAXException {
configDocument = DomUtil.readDocumentFromInputStream(configInputStream);
}
public void obfuscate(Mappings mappings) {
NodeList minecraftClassNodes = ((Element) configDocument.getElementsByTagName("minecraftCommon").item(0)).getElementsByTagName("class");
for (Element classElement : DomUtil.elementList(minecraftClassNodes)) {
String className = classElement.getAttribute("id");
ClassDescription deobfuscatedClass = new ClassDescription(className);
ClassDescription obfuscatedClass = mappings.map(deobfuscatedClass);
if (obfuscatedClass != null) {
classElement.setAttribute("id", obfuscatedClass.name);
}
NodeList patchElements = classElement.getChildNodes();
for (Element patchElement : DomUtil.elementList(patchElements)) {
String textContent = patchElement.getTextContent().trim();
List<MethodDescription> methodDescriptionList = MethodDescription.fromListString(deobfuscatedClass.name, textContent);
if (!textContent.isEmpty()) {
patchElement.setAttribute("deobf", methodDescriptionList.get(0).getShortName());
//noinspection unchecked
patchElement.setTextContent(MethodDescription.toListString((List<MethodDescription>) mappings.map(methodDescriptionList)));
}
String field = patchElement.getAttribute("field"), prefix = "";
if (!field.isEmpty()) {
if (field.startsWith("this.")) {
field = field.substring("this.".length());
prefix = "this.";
}
String after = "", type = className;
if (field.indexOf('.') != -1) {
after = field.substring(field.indexOf('.'));
field = field.substring(0, field.indexOf('.'));
if (!field.isEmpty() && (field.charAt(0) == '$') && prefix.isEmpty()) {
Set<String> parameters = new HashSet<String>();
for (MethodDescription methodDescription : methodDescriptionList) {
parameters.add(methodDescription.getParameters());
}
if (parameters.size() == 1) {
MethodDescription methodDescription = mappings.rmap(mappings.map(methodDescriptionList.get(0)));
methodDescription = methodDescription == null ? methodDescriptionList.get(0) : methodDescription;
type = methodDescription.getParameterList().get(Integer.valueOf(field.substring(1)) - 1);
prefix = field + '.';
field = after.substring(1);
after = "";
}
}
}
FieldDescription obfuscatedField = mappings.map(new FieldDescription(type, field));
if (obfuscatedField != null) {
patchElement.setAttribute("field", prefix + obfuscatedField.name + after);
}
}
String clazz = patchElement.getAttribute("class");
if (!clazz.isEmpty()) {
ClassDescription obfuscatedClazz = mappings.map(new ClassDescription(clazz));
if (obfuscatedClazz != null) {
patchElement.setAttribute("class", obfuscatedClazz.name);
}
}
}
}
for (Element classElement : DomUtil.getElementsByTag(configDocument.getDocumentElement(), "class")) {
for (Element patchElement : DomUtil.elementList(classElement.getChildNodes())) {
String code = patchElement.getAttribute("code");
if (!code.isEmpty()) {
String obfuscatedCode = mappings.obfuscate(code);
if (!code.equals(obfuscatedCode)) {
patchElement.setAttribute("code", obfuscatedCode);
Log.info("Obfuscated " + code + " to " + obfuscatedCode);
}
}
}
}
}
public Map<String, Integer> getHashes() {
Map<String, Integer> hashes = new TreeMap<String, Integer>();
List<Element> modElements = DomUtil.elementList(configDocument.getDocumentElement().getChildNodes());
for (Element modElement : modElements) {
for (Element classElement : DomUtil.getElementsByTag(modElement, "class")) {
hashes.put(classElement.getAttribute("id"), DomUtil.getHash(classElement) + VersionUtil.TTVersionString().hashCode() * 31);
}
}
return hashes;
}
public void runPatches() {
List<Element> modElements = DomUtil.elementList(configDocument.getDocumentElement().getChildNodes());
patchingClasses = new HashMap<String, CtClass>();
for (Element modElement : modElements) {
for (Element classElement : DomUtil.getElementsByTag(modElement, "class")) {
String className = classElement.getAttribute("id");
if (!classRegistry.shouldPatch(className)) {
Log.info(className + " is already patched, skipping.");
continue;
}
String environment = classElement.getAttribute("env");
if (!environment.isEmpty() && !environment.equals(patchEnvironment)) {
Log.info(className + " requires " + environment + ", not patched as we are using " + patchEnvironment);
continue;
}
CtClass ctClass;
try {
ctClass = classRegistry.getClass(className);
} catch (NotFoundException e) {
Log.info("Not patching " + className + ", not found.");
continue;
}
List<Element> patchElements = DomUtil.elementList(classElement.getChildNodes());
boolean patched = false;
for (Element patchElement : patchElements) {
PatchMethodDescriptor patch = patches.get(patchElement.getTagName());
if (patch == null) {
Log.severe("Patch " + patchElement.getTagName() + " was not found.");
continue;
}
try {
Object result = patch.run(patchElement, ctClass);
patched = true;
if (result instanceof CtClass) {
ctClass = (CtClass) result;
}
} catch (Exception e) {
Log.severe("Failed to patch " + ctClass.getName() + " with " + patch.name, e);
}
}
if (patched) {
patchingClasses.put(className, ctClass);
}
}
}
for (Map.Entry<String, CtClass> entry : patchingClasses.entrySet()) {
String className = entry.getKey();
CtClass ctClass = entry.getValue();
try {
classRegistry.update(className, ctClass.toBytecode());
} catch (Exception e) {
Log.severe("Javassist failed to save " + className, e);
}
}
patchingClasses = null;
}
public void save(File file) throws TransformerException {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(file);
Source input = new DOMSource(configDocument);
transformer.transform(input, output);
}
public class PatchMethodDescriptor {
public final String name;
public final List<String> requiredAttributes;
public final Method patchMethod;
public final boolean isClassPatch;
public final boolean emptyConstructor;
public PatchMethodDescriptor(Method method, Patch patch) {
String name = patch.name();
if (Arrays.asList(method.getParameterTypes()).contains(Map.class)) {
this.requiredAttributes = CollectionsUtil.split(patch.requiredAttributes());
} else {
this.requiredAttributes = null;
}
if (name == null || name.isEmpty()) {
name = method.getName();
}
this.name = name;
emptyConstructor = patch.emptyConstructor();
isClassPatch = method.getParameterTypes()[0].equals(CtClass.class);
patchMethod = method;
}
public Object run(Element patchElement, CtClass ctClass) {
Map<String, String> attributes = DomUtil.getAttributes(patchElement);
Log.fine("Patching " + ctClass.getName() + " with " + this.name + '(' + CollectionsUtil.joinMap(attributes) + ')');
if (requiredAttributes != null && !attributes.keySet().containsAll(requiredAttributes)) {
Log.severe("Missing required attributes " + requiredAttributes.toString() + " when patching " + ctClass.getName());
return null;
}
String textContent = patchElement.getTextContent().trim();
if (attributes.containsKey("runAll")) {
List<CtBehavior> ctBehaviors = new ArrayList<CtBehavior>();
Collections.addAll(ctBehaviors, ctClass.getDeclaredMethods());
Collections.addAll(ctBehaviors, ctClass.getDeclaredConstructors());
CtBehavior initializer = ctClass.getClassInitializer();
if (initializer != null) {
ctBehaviors.add(initializer);
}
for (CtBehavior ctBehavior : ctBehaviors) {
run(ctBehavior, attributes);
}
} else if (isClassPatch || (!emptyConstructor && textContent.isEmpty())) {
return run(ctClass, attributes);
} else if (textContent.isEmpty()) {
run(ctClass.getConstructors()[0], attributes);
} else {
List<MethodDescription> methodDescriptions = MethodDescription.fromListString(ctClass.getName(), textContent);
Log.fine("Patching methods " + methodDescriptions.toString());
for (MethodDescription methodDescription : methodDescriptions) {
run(methodDescription.inClass(ctClass), attributes);
}
}
return null;
}
private Object run(CtClass ctClass, Map<String, String> attributes) {
try {
if (requiredAttributes == null) {
return patchMethod.invoke(patchTypes, ctClass);
} else {
return patchMethod.invoke(patchTypes, ctClass, attributes);
}
} catch (Exception e) {
if (e instanceof InvocationTargetException) {
e = (Exception) e.getCause();
}
Log.severe("Error patching " + ctClass.getName() + " with " + toString(), e);
return null;
}
}
private Object run(CtBehavior ctBehavior, Map<String, String> attributes) {
try {
if (requiredAttributes == null) {
return patchMethod.invoke(patchTypes, ctBehavior);
} else {
return patchMethod.invoke(patchTypes, ctBehavior, attributes);
}
} catch (Exception e) {
if (e instanceof InvocationTargetException) {
e = (Exception) e.getCause();
}
Log.severe("Error patching " + ctBehavior.getName() + " in " + ctBehavior.getDeclaringClass().getName() + " with " + toString(), e);
return null;
}
}
@Override
public String toString() {
return name;
}
}
}