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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
|
/*
* This file is part of fabric-loom, licensed under the MIT License (MIT).
*
* Copyright (c) 2020-2021 FabricMC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.fabricmc.loom.util.srg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
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.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.base.MoreObjects;
import com.google.common.base.Stopwatch;
import org.apache.commons.io.IOUtils;
import org.gradle.api.logging.Logger;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.loom.util.function.CollectionUtil;
import net.fabricmc.mappingio.FlatMappingVisitor;
import net.fabricmc.mappingio.MappingReader;
import net.fabricmc.mappingio.adapter.RegularAsFlatMappingVisitor;
import net.fabricmc.mappingio.format.Tiny2Writer;
import net.fabricmc.mappingio.format.TsrgReader;
import net.fabricmc.mappingio.tree.MappingTree;
import net.fabricmc.mappingio.tree.MappingTreeView;
import net.fabricmc.mappingio.tree.MemoryMappingTree;
/**
* Utilities for merging SRG mappings.
*
* @author Juuz
*/
public final class SrgMerger {
private final Logger logger;
private final Map<String, List<MappingTreeView.MemberMappingView>> addRegardlessSrg = new HashMap<>();
private final MemoryMappingTree srg;
private final MemoryMappingTree src;
private final MemoryMappingTree output;
private final FlatMappingVisitor flatOutput;
private final List<Runnable> postProcesses = new ArrayList<>();
private final boolean lenient;
private final Set<String> methodSrgNames = new HashSet<>();
public SrgMerger(Logger logger, Path srg, @Nullable Supplier<Path> mojmap, Path tiny, boolean lenient) throws IOException {
this.logger = logger;
this.srg = readSrg(srg, mojmap);
this.src = new MemoryMappingTree();
this.output = new MemoryMappingTree();
this.flatOutput = new RegularAsFlatMappingVisitor(output);
this.lenient = lenient;
MappingReader.read(tiny, this.src);
if (!"official".equals(this.src.getSrcNamespace())) {
throw new MappingException("Mapping file " + tiny + " does not have the 'official' namespace as the default!");
}
this.output.visitNamespaces(this.src.getSrcNamespace(), Stream.concat(Stream.of("srg"), this.src.getDstNamespaces().stream()).collect(Collectors.toList()));
}
public MemoryMappingTree merge() throws IOException {
for (MappingTree.ClassMapping klass : this.srg.getClasses()) {
classToTiny(klass);
}
try {
for (Runnable process : postProcesses) {
process.run();
}
} catch (UncheckedIOException e) {
throw e.getCause();
}
return output;
}
/**
* Merges SRG mappings with a tiny mappings tree through the obf names.
*
* @param srg the SRG file in .tsrg format
* @param mojmap the path to the mojmap file used for generating mojmap+srg names, may be null
* @param tiny the tiny file
* @param out the output file, will be in tiny v2
* @param lenient whether to ignore missing tiny mapping
* @throws IOException if an IO error occurs while reading or writing the mappings
* @throws MappingException if the input tiny tree's default namespace is not 'official'
* or if an element mentioned in the SRG file does not have tiny mappings
*/
public static void mergeSrg(Logger logger, @Nullable Supplier<Path> mojmap, Path srg, Path tiny, Path out, boolean lenient)
throws IOException, MappingException {
Stopwatch stopwatch = Stopwatch.createStarted();
MemoryMappingTree tree = mergeSrg(logger, mojmap, srg, tiny, lenient);
try (Tiny2Writer writer = new Tiny2Writer(Files.newBufferedWriter(out), false)) {
tree.accept(writer);
} catch (IOException e) {
e.printStackTrace();
}
logger.info(":merged srg mappings in " + stopwatch.stop());
}
/**
* Merges SRG mappings with a tiny mappings tree through the obf names.
*
* @param srg the SRG file in .tsrg format
* @param mojmap the path to the mojmap file used for generating mojmap+srg names, may be null
* @param tiny the tiny file
* @param lenient whether to ignore missing tiny mapping
* @return the created mapping tree
* @throws IOException if an IO error occurs while reading or writing the mappings
* @throws MappingException if the input tiny tree's default namespace is not 'official'
* or if an element mentioned in the SRG file does not have tiny mappings
*/
public static MemoryMappingTree mergeSrg(Logger logger, @Nullable Supplier<Path> mojmap, Path srg, Path tiny, boolean lenient)
throws IOException, MappingException {
return new SrgMerger(logger, srg, mojmap, tiny, lenient).merge();
}
private MemoryMappingTree readSrg(Path srg, @Nullable Supplier<Path> mojmap) throws IOException {
try (BufferedReader reader = Files.newBufferedReader(srg)) {
String content = IOUtils.toString(reader);
if (content.startsWith("tsrg2") && mojmap != null) {
addRegardlessSrgs(mojmap);
}
MemoryMappingTree tsrg = new MemoryMappingTree();
TsrgReader.read(new StringReader(content), tsrg);
return tsrg;
}
}
private void addRegardlessSrgs(Supplier<Path> mojmap) throws IOException {
MemoryMappingTree mojmapTree = readTsrg2ToTinyTree(mojmap.get());
for (MappingTree.ClassMapping classDef : mojmapTree.getClasses()) {
for (MappingTree.MethodMapping methodDef : classDef.getMethods()) {
String name = methodDef.getSrcName();
if (name.indexOf('<') != 0 && name.equals(methodDef.getDstName(0))) {
addRegardlessSrg.computeIfAbsent(classDef.getSrcName(), $ -> new ArrayList<>()).add(methodDef);
}
}
for (MappingTree.FieldMapping fieldDef : classDef.getFields()) {
if (fieldDef.getSrcName().equals(fieldDef.getDstName(0))) {
addRegardlessSrg.computeIfAbsent(classDef.getSrcName(), $ -> new ArrayList<>()).add(fieldDef);
}
}
}
}
private static MemoryMappingTree readTsrg2ToTinyTree(Path path) throws IOException {
MemoryMappingTree tree = new MemoryMappingTree();
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
MappingReader.read(reader, tree);
}
return tree;
}
private void classToTiny(MappingTree.ClassMapping klass) throws IOException {
String obf = klass.getSrcName();
String srg = klass.getDstName(0);
MappingTree.ClassMapping classDef = this.src.getClass(obf);
if (classDef == null) {
if (lenient) {
return;
} else {
throw new MappingException("Missing class: " + obf + " (srg: " + srg + ")");
}
}
List<String> classNames = CollectionUtil.map(
output.getDstNamespaces(),
namespace -> "srg".equals(namespace) ? srg : classDef.getName(namespace)
);
flatOutput.visitClass(obf, classNames.toArray(new String[0]));
if (classDef.getComment() != null) {
flatOutput.visitClassComment(obf, classDef.getComment());
}
for (MappingTree.MethodMapping method : klass.getMethods()) {
MappingTree.MethodMapping def = CollectionUtil.find(
classDef.getMethods(),
m -> m.getName("official").equals(method.getSrcName()) && m.getDesc("official").equals(method.getSrcDesc())
).orElse(null);
String methodSrgName = method.getDstName(0);
if (def == null) {
if (lenient) {
// TODO Big Hack!
// We are checking if there are methods with the same srg name that are already added, if it is, then we would not fill in these names
// This is especially troublesome with methods annotated with @DontObfuscate (e.g. m_129629_)
// with environments like yarn where methods with the same srg name may not inherit the same names due to parameter mappings and inheritance
// This requires further testing!
postProcesses.add(() -> {
if (!methodSrgNames.contains(methodSrgName)) {
List<String> methodNames = CollectionUtil.map(
output.getDstNamespaces(),
namespace -> "srg".equals(namespace) ? methodSrgName : method.getSrcName()
);
try {
flatOutput.visitMethod(obf, method.getSrcName(), method.getSrcDesc(), methodNames.toArray(new String[0]));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
});
} else {
throw new MappingException("Missing method: " + method.getSrcName() + " (srg: " + methodSrgName + ")");
}
continue;
}
methodToTiny(obf, method, methodSrgName, def);
if (methodSrgName.startsWith("func_") || methodSrgName.startsWith("m_")) {
methodSrgNames.add(methodSrgName);
}
}
postProcesses.add(() -> {
// TODO: This second iteration seems a bit wasteful.
// Is it possible to just iterate this and leave SRG out?
for (MappingTree.MethodMapping def : classDef.getMethods()) {
// If obf = some other name: some special name that srg might not contain.
// This includes constructors and overridden JDK methods.
if (!def.getSrcName().equals(def.getDstName(0))) {
continue;
}
MappingTree.MethodMapping method = CollectionUtil.find(
klass.getMethods(),
m -> m.getSrcName().equals(def.getName("official")) && m.getSrcDesc().equals(def.getDesc("official"))
).orElse(null);
if (method == null) {
try {
methodToTiny(obf, null, def.getSrcName(), def);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
});
for (MappingTree.FieldMapping field : klass.getFields()) {
MappingTree.FieldMapping def = CollectionUtil.find(
classDef.getFields(),
f -> f.getName("official").equals(field.getSrcName())
).orElse(nullOrThrow(() -> new MappingException("Missing field: " + field.getSrcName() + " (srg: " + field.getDstName(0) + ")")));
if (def == null) {
if (tryMatchRegardlessSrgsField(obf, field)) {
List<String> fieldNames = CollectionUtil.map(
output.getDstNamespaces(),
namespace -> "srg".equals(namespace) ? field.getDstName(0) : field.getSrcName()
);
flatOutput.visitField(obf, field.getSrcName(), field.getSrcDesc(), fieldNames.toArray(new String[0]));
}
continue;
}
List<String> fieldNames = CollectionUtil.map(
output.getDstNamespaces(),
namespace -> "srg".equals(namespace) ? field.getDstName(0) : def.getName(namespace)
);
flatOutput.visitField(obf, def.getName("official"), def.getDesc("official"), fieldNames.toArray(new String[0]));
if (def.getComment() != null) {
flatOutput.visitFieldComment(obf, def.getName("official"), def.getDesc("official"), def.getComment());
}
}
}
private void methodToTiny(String obfClassName, @Nullable MappingTree.MethodMapping srgMethod, @Nullable String srgMethodName, MappingTree.MethodMapping actualMethod)
throws IOException {
if (srgMethod != null && srgMethodName != null) {
srgMethodName = srgMethod.getDstName(0);
}
String finalSrgMethodName = srgMethodName;
List<String> methodNames = CollectionUtil.map(
output.getDstNamespaces(),
namespace -> "srg".equals(namespace) ? finalSrgMethodName : actualMethod.getName(namespace)
);
flatOutput.visitMethod(obfClassName, actualMethod.getName("official"), actualMethod.getDesc("official"), methodNames.toArray(new String[0]));
if (actualMethod.getComment() != null) {
flatOutput.visitMethodComment(obfClassName, actualMethod.getName("official"), actualMethod.getDesc("official"), actualMethod.getComment());
}
for (MappingTree.MethodArgMapping arg : actualMethod.getArgs()) {
MappingTree.MethodArgMapping srgArg = srgMethod != null ? srgMethod.getArg(arg.getArgPosition(), arg.getLvIndex(), arg.getName("official")) : null;
String srgName = srgArg != null ? srgArg.getDstName(0) : null;
List<String> argNames = CollectionUtil.map(
output.getDstNamespaces(),
namespace -> "srg".equals(namespace) ? srgName : arg.getName(namespace)
);
flatOutput.visitMethodArg(obfClassName, actualMethod.getName("official"), actualMethod.getDesc("official"), arg.getArgPosition(), arg.getLvIndex(), arg.getName("official"), argNames.toArray(new String[0]));
if (arg.getComment() != null) {
flatOutput.visitMethodArgComment(obfClassName, actualMethod.getName("official"), actualMethod.getDesc("official"), arg.getArgPosition(), arg.getLvIndex(), arg.getName("official"), arg.getComment());
}
}
for (MappingTree.MethodVarMapping var : actualMethod.getVars()) {
MappingTree.MethodVarMapping srgVar = srgMethod != null ? srgMethod.getVar(var.getLvtRowIndex(), var.getLvIndex(), var.getStartOpIdx(), var.getName("official")) : null;
String srgName = srgVar != null ? srgVar.getDstName(0) : null;
List<String> varNames = CollectionUtil.map(
output.getDstNamespaces(),
namespace -> "srg".equals(namespace) ? srgName : var.getName(namespace)
);
flatOutput.visitMethodVar(obfClassName, actualMethod.getName("official"), actualMethod.getDesc("official"), var.getLvtRowIndex(), var.getLvIndex(), var.getStartOpIdx(), var.getName("official"), varNames.toArray(new String[0]));
if (var.getComment() != null) {
flatOutput.visitMethodVarComment(obfClassName, actualMethod.getName("official"), actualMethod.getDesc("official"), var.getLvtRowIndex(), var.getLvIndex(), var.getStartOpIdx(), var.getName("official"), var.getComment());
}
}
}
private boolean tryMatchRegardlessSrgsMethod(String obf, MappingTree.MethodMapping method) {
List<MappingTreeView.MemberMappingView> mutableDescriptoredList = addRegardlessSrg.get(obf);
if (!method.getDstName(0).equals(method.getSrcName())) {
for (MappingTreeView.MemberMappingView descriptored : MoreObjects.firstNonNull(mutableDescriptoredList, Collections.<MappingTreeView.MemberMappingView>emptyList())) {
if (descriptored instanceof MappingTree.MethodMapping && descriptored.getSrcName().equals(method.getSrcName()) && descriptored.getSrcDesc().equals(method.getSrcDesc())) {
return true;
}
}
}
return false;
}
private boolean tryMatchRegardlessSrgsField(String obf, MappingTree.FieldMapping field) {
List<MappingTreeView.MemberMappingView> mutableDescriptoredList = addRegardlessSrg.get(obf);
if (!field.getDstName(0).equals(field.getSrcName())) {
for (MappingTreeView.MemberMappingView descriptored : MoreObjects.firstNonNull(mutableDescriptoredList, Collections.<MappingTreeView.MemberMappingView>emptyList())) {
if (descriptored instanceof MappingTree.FieldMapping && descriptored.getSrcName().equals(field.getSrcName())) {
return true;
}
}
}
return false;
}
@Nullable
private <T, X extends Exception> T nullOrThrow(Supplier<X> exception) throws X {
if (lenient) {
return null;
} else {
throw exception.get();
}
}
}
|