aboutsummaryrefslogtreecommitdiff
path: root/spark-fabric/src/main/java/me/lucko/spark/fabric/FabricClassSourceLookup.java
blob: 51834fc85a71fd10aee674feb50d334d3a9b1d41 (plain)
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
/*
 * This file is part of spark.
 *
 *  Copyright (c) lucko (Luck) <luck@lucko.me>
 *  Copyright (c) contributors
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package me.lucko.spark.fabric;

import com.google.common.collect.ImmutableMap;

import me.lucko.spark.common.sampler.source.ClassSourceLookup;
import me.lucko.spark.common.util.ClassFinder;
import me.lucko.spark.fabric.smap.MixinUtils;
import me.lucko.spark.fabric.smap.SourceMap;
import me.lucko.spark.fabric.smap.SourceMapProvider;

import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;

import org.checkerframework.checker.nullness.qual.Nullable;
import org.objectweb.asm.Type;
import org.spongepowered.asm.mixin.FabricUtil;
import org.spongepowered.asm.mixin.extensibility.IMixinConfig;
import org.spongepowered.asm.mixin.transformer.Config;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;

import java.lang.reflect.Method;
import java.net.URI;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Map;

public class FabricClassSourceLookup extends ClassSourceLookup.ByCodeSource {

    private final ClassFinder classFinder = new ClassFinder();
    private final SourceMapProvider smapProvider = new SourceMapProvider();

    private final Path modsDirectory;
    private final Map<String, String> pathToModMap;

    public FabricClassSourceLookup() {
        FabricLoader loader = FabricLoader.getInstance();
        this.modsDirectory = loader.getGameDir().resolve("mods").toAbsolutePath().normalize();
        this.pathToModMap = constructPathToModIdMap(loader.getAllMods());
    }

    @Override
    public String identifyFile(Path path) {
        String id = this.pathToModMap.get(path.toAbsolutePath().normalize().toString());
        if (id != null) {
            return id;
        }

        if (!path.startsWith(this.modsDirectory)) {
            return null;
        }

        return super.identifyFileName(this.modsDirectory.relativize(path).toString());
    }

    @Override
    public @Nullable String identify(MethodCall methodCall) throws Exception {
        String className = methodCall.getClassName();
        String methodName = methodCall.getMethodName();
        String methodDesc = methodCall.getMethodDescriptor();

        if (className.equals("native") || methodName.equals("<init>") || methodName.equals("<clinit>")) {
            return null;
        }

        Class<?> clazz = this.classFinder.findClass(className);
        if (clazz == null) {
            return null;
        }

        Class<?>[] params = getParameterTypesForMethodDesc(methodDesc);
        Method reflectMethod = clazz.getDeclaredMethod(methodName, params);

        MixinMerged mixinMarker = reflectMethod.getDeclaredAnnotation(MixinMerged.class);
        if (mixinMarker == null) {
            return null;
        }

        return modIdFromMixinClass(mixinMarker.mixin());
    }

    @Override
    public @Nullable String identify(MethodCallByLine methodCall) throws Exception {
        String className = methodCall.getClassName();
        String methodName = methodCall.getMethodName();
        int lineNumber = methodCall.getLineNumber();

        if (className.equals("native") || methodName.equals("<init>") || methodName.equals("<clinit>")) {
            return null;
        }

        SourceMap smap = this.smapProvider.getSourceMap(className);
        if (smap == null) {
            return null;
        }

        int[] inputLineInfo = smap.getReverseLineMapping().get(lineNumber);
        if (inputLineInfo == null || inputLineInfo.length == 0) {
            return null;
        }

        for (int fileInfoIds : inputLineInfo) {
            SourceMap.FileInfo inputFileInfo = smap.getFileInfo().get(fileInfoIds);
            if (inputFileInfo == null) {
                continue;
            }

            String path = inputFileInfo.path();
            if (path.endsWith(".java")) {
                path = path.substring(0, path.length() - 5);
            }

            String possibleMixinClassName = path.replace('/', '.');
            if (possibleMixinClassName.equals(className)) {
                continue;
            }

            return modIdFromMixinClass(possibleMixinClassName);
        }

        return null;
    }

    private static String modIdFromMixinClass(String mixinClassName) {
        for (Config config : MixinUtils.getMixinConfigs().values()) {
            IMixinConfig mixinConfig = config.getConfig();
            if (mixinClassName.startsWith(mixinConfig.getMixinPackage())) {
                return mixinConfig.getDecoration(FabricUtil.KEY_MOD_ID);
            }
        }
        return null;
    }

    private Class<?>[] getParameterTypesForMethodDesc(String methodDesc) {
        Type methodType = Type.getMethodType(methodDesc);
        Class<?>[] params = new Class[methodType.getArgumentTypes().length];
        Type[] argumentTypes = methodType.getArgumentTypes();

        for (int i = 0, argumentTypesLength = argumentTypes.length; i < argumentTypesLength; i++) {
            Type argumentType = argumentTypes[i];
            params[i] = getClassFromType(argumentType);
        }

        return params;
    }

    private Class<?> getClassFromType(Type type) {
        return switch (type.getSort()) {
            case Type.VOID -> void.class;
            case Type.BOOLEAN -> boolean.class;
            case Type.CHAR -> char.class;
            case Type.BYTE -> byte.class;
            case Type.SHORT -> short.class;
            case Type.INT -> int.class;
            case Type.FLOAT -> float.class;
            case Type.LONG -> long.class;
            case Type.DOUBLE -> double.class;
            case Type.ARRAY -> {
                final Class<?> classFromType = getClassFromType(type.getElementType());
                Class<?> result = classFromType;
                if (classFromType != null) {
                    for (int i = 0; i < type.getDimensions(); i++) {
                        result = result.arrayType();
                    }
                }
                yield result;
            }
            case Type.OBJECT -> this.classFinder.findClass(type.getClassName());
            default -> null;
        };
    }

    private static Map<String, String> constructPathToModIdMap(Collection<ModContainer> mods) {
        ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
        for (ModContainer mod : mods) {
            String modId = mod.getMetadata().getId();
            if (modId.equals("java")) {
                continue;
            }

            for (Path path : mod.getRootPaths()) {
                URI uri = path.toUri();
                if (uri.getScheme().equals("jar") && path.toString().equals("/")) { // ZipFileSystem
                    String zipFilePath = path.getFileSystem().toString();
                    builder.put(zipFilePath, modId);
                } else {
                    builder.put(path.toAbsolutePath().normalize().toString(), modId);
                }

            }
        }
        return builder.build();
    }
}