Compare commits

..
3 Commits
Author SHA1 Message Date
ZekerZhayard 5830503dfc refactor: rebuild ASM transformation framework and support 26.3 (#399) 2026-10-01 08:30:39 +08:00
Copilotandxfl03 f334a61faa Remove Cosmetica from legacy defaults and documented load lists (#391)
* Remove Cosmetica from default profiles and docs

Co-authored-by: xfl03 <[email protected]>

* Remove deprecated LabyMod commented entry

Co-authored-by: xfl03 <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: xfl03 <[email protected]>
2026-08-12 20:27:30 +08:00
Steven QiuandZekerZhayard 873705c4fb feat: default user agent (#389)
* feat: default user agent

* fix: Fabric version detection

* refactor: remove junit test

* refactor: read mod loader info in bootstrap

* Optimize mod loader version retrieval

---------

Co-authored-by: ZekerZhayard <[email protected]>
2026-08-12 20:19:00 +08:00
52 changed files with 1307 additions and 1233 deletions

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@ outputs:
runs:
using: composite
steps:
- uses: actions/setup-java@v5
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: '25'
+3 -3
View File
@@ -11,7 +11,7 @@ jobs:
name: Build
runs-on: windows-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: ./.github/actions/build
with:
@@ -22,7 +22,7 @@ jobs:
needs: build
runs-on: windows-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
with:
@@ -54,7 +54,7 @@ jobs:
runs-on: windows-latest
environment: Build
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
with:
+1 -1
View File
@@ -9,7 +9,7 @@ jobs:
name: Build
runs-on: windows-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: ./.github/actions/build
with:
+6 -5
View File
@@ -18,7 +18,7 @@ jobs:
game_versions: ${{ steps.build.outputs.game_versions }}
java: ${{ steps.build.outputs.java }}
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: ./.github/actions/build
id: build
@@ -30,7 +30,7 @@ jobs:
needs: build
runs-on: windows-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
with:
@@ -51,7 +51,7 @@ jobs:
runs-on: windows-latest
environment: Build
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
with:
@@ -85,14 +85,14 @@ jobs:
runs-on: windows-latest
environment: Build
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
with:
name: CustomSkinLoader-Release-${{ github.run_number }}
path: artifact
- uses: Kir-Antipov/mc-publish@v3.3
- uses: Kir-Antipov/mc-publish@v3
with:
modrinth-id: idMHQ4n2
modrinth-featured: true
@@ -107,6 +107,7 @@ jobs:
${{ needs.build.outputs.loaders }}
game-versions: |
${{ needs.build.outputs.game_versions }}
environment: client
game-version-filter: releases
java: |
${{ needs.build.outputs.java }}
@@ -0,0 +1,22 @@
package customskinloader.bootstrap;
public final class ModLoaderInfo {
public static final String NAME_PROPERTY = "customskinloader.modLoader.name";
public static final String VERSION_PROPERTY = "customskinloader.modLoader.version";
private ModLoaderInfo() {
}
public static void publish(String name, String version) {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("Mod loader name must not be empty");
}
if (version == null || version.trim().isEmpty()) {
throw new IllegalArgumentException("Mod loader version must not be empty");
}
System.setProperty(NAME_PROPERTY, name);
System.setProperty(VERSION_PROPERTY, version);
BootstrapLogger.LOGGER.info("Detected mod loader " + name + " " + version);
}
}
@@ -68,10 +68,6 @@ public final class ClassTransformationContext {
return this.mappings.unmapMethodDescriptor(targetDescriptor);
}
public boolean isTarget(String canonicalName) {
return this.getInternalClassName().equals(this.remapClassName(canonicalName));
}
public MethodNode findMethod(String owner, String name, String desc) {
String mappedDesc = this.remapMethodDescriptor(desc);
String mappedName = "<init>".equals(name) ? name : this.remapMethodName(owner, name, desc);
@@ -7,40 +7,41 @@ import java.util.List;
import org.objectweb.asm.tree.ClassNode;
public final class ClassTransformationReport {
private final ClassTransformationContext context;
private final List<String> appliedTransformerNames;
private final String internalClassName;
private final ClassNode transformedClassNode;
private final byte[] originalBytecode;
private final List<String> appliedRuleNames;
private volatile byte[] transformedBytecode;
public ClassTransformationReport(ClassTransformationContext context, List<String> appliedTransformerNames) {
this.context = context;
this.appliedTransformerNames = Collections.unmodifiableList(new ArrayList<>(appliedTransformerNames));
}
public ClassTransformationContext getContext() {
return this.context;
ClassTransformationReport(String internalClassName, ClassNode transformedClassNode, byte[] originalBytecode, List<String> appliedRuleNames) {
this.internalClassName = internalClassName;
this.transformedClassNode = transformedClassNode;
this.originalBytecode = originalBytecode;
this.appliedRuleNames = Collections.unmodifiableList(new ArrayList<>(appliedRuleNames));
}
public byte[] getTransformedBytecode() {
if (this.transformedBytecode == null) {
if (this.getTransformedClassNode() == null) {
throw new IllegalStateException("Transformed bytecode is not available without a transformed ClassNode");
}
this.transformedBytecode = TransformerBootstrapSupport.toByteArray(this.getTransformedClassNode());
if (!this.isModified() && this.originalBytecode != null) {
return this.originalBytecode.clone();
}
if (this.transformedBytecode == null) {
if (this.transformedClassNode == null) {
throw new IllegalStateException("Transformed bytecode is not available without a ClassNode");
}
this.transformedBytecode = TransformerBootstrapSupport.toByteArray(this.transformedClassNode);
}
return this.transformedBytecode.clone();
}
public ClassNode getTransformedClassNode() {
return this.context.getCurrentClassNode();
return this.transformedClassNode;
}
public List<String> getAppliedTransformerNames() {
return this.appliedTransformerNames;
public List<String> getAppliedRuleNames() {
return this.appliedRuleNames;
}
public boolean isModified() {
return !this.appliedTransformerNames.isEmpty();
return !this.appliedRuleNames.isEmpty();
}
}
@@ -1,51 +0,0 @@
package customskinloader.bootstrap.transformer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import customskinloader.bootstrap.mapping.Mappings;
public final class ClassTransformerRegistry {
private static final Comparator<TargetedClassTransformer> TRANSFORMER_ORDER = (left, right) -> {
// Higher-priority transformers run first so low-priority patches can react to earlier changes.
int priorityOrder = Integer.compare(right.getPriority(), left.getPriority());
if (priorityOrder != 0) {
return priorityOrder;
}
return left.getName().compareTo(right.getName());
};
private final CopyOnWriteArrayList<TargetedClassTransformer> transformers = new CopyOnWriteArrayList<>();
public void register(TargetedClassTransformer transformer) {
this.transformers.add(transformer);
this.sortTransformers();
}
public List<TargetedClassTransformer> getTransformers() {
return Collections.unmodifiableList(new ArrayList<>(this.transformers));
}
public List<TargetedClassTransformer> getApplicableTransformers(String className, Mappings mappings) {
List<TargetedClassTransformer> applicableTransformers = new ArrayList<>();
for (TargetedClassTransformer transformer : this.transformers) {
if (transformer.supports(className, mappings)) {
applicableTransformers.add(transformer);
}
}
return Collections.unmodifiableList(applicableTransformers);
}
private void sortTransformers() {
List<TargetedClassTransformer> sortedTransformers = new ArrayList<>(this.transformers);
Collections.sort(sortedTransformers, TRANSFORMER_ORDER);
this.transformers.clear();
this.transformers.addAll(sortedTransformers);
}
}
@@ -1,46 +0,0 @@
package customskinloader.bootstrap.transformer;
import java.util.ArrayList;
import java.util.List;
import customskinloader.bootstrap.BootstrapLogger;
import org.apache.logging.log4j.Logger;
public final class RuntimeClassTransformerEngine {
private static final Logger LOGGER = BootstrapLogger.LOGGER;
private final ClassTransformerRegistry registry;
public RuntimeClassTransformerEngine(ClassTransformerRegistry registry) {
this.registry = registry;
}
public ClassTransformationReport transform(ClassTransformationContext context) {
List<String> appliedTransformers = new ArrayList<>();
for (TargetedClassTransformer transformer : this.registry.getApplicableTransformers(context.getInternalClassName(), context.getMappings())) {
if (!this.applyTransformer(transformer, context)) {
LOGGER.debug("Skipped transformer " + transformer.getName() + " for " + context.getInternalClassName());
continue;
}
appliedTransformers.add(transformer.getName());
LOGGER.debug("Applied transformer " + transformer.getName() + " to " + context.getInternalClassName());
}
if (!appliedTransformers.isEmpty()) {
LOGGER.info("Transformed " + context.getInternalClassName() + " with " + appliedTransformers);
}
return new ClassTransformationReport(context, appliedTransformers);
}
private boolean applyTransformer(TargetedClassTransformer transformer, ClassTransformationContext context) {
try {
return transformer.transform(context);
} catch (Exception exception) {
String message = "Failed to transform " + context.getInternalClassName() + " with " + transformer.getName();
LOGGER.error(message, exception);
throw new IllegalStateException(message, exception);
}
}
}
@@ -0,0 +1,24 @@
package customskinloader.bootstrap.transformer;
public final class RuntimeVersion {
private final int protocolVersion;
private final int worldVersion;
public RuntimeVersion(int protocolVersion, int worldVersion) {
this.protocolVersion = protocolVersion;
this.worldVersion = worldVersion;
}
public int getProtocolVersion() {
return this.protocolVersion;
}
public int getWorldVersion() {
return this.worldVersion;
}
@Override
public String toString() {
return "protocol=" + this.protocolVersion + ", world=" + this.worldVersion;
}
}
@@ -1,46 +0,0 @@
package customskinloader.bootstrap.transformer;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
public abstract class TargetedClassTransformer {
private final String name;
private final int priority;
private final Set<String> targetClassNames;
protected TargetedClassTransformer(String name, int priority, String... targetClassNames) {
this.name = name;
this.priority = priority;
this.targetClassNames = Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(targetClassNames)));
}
public final String getName() {
return this.name;
}
public final int getPriority() {
return this.priority;
}
public boolean supports(String className, customskinloader.bootstrap.mapping.Mappings mappings) {
if (this.targetClassNames.isEmpty()) {
return false;
}
for (String targetClassName : this.targetClassNames) {
if (className.equals(mappings.remapClassName(targetClassName))) {
return true;
}
}
return false;
}
public Set<String> getTargetClassNames() {
return this.targetClassNames;
}
public abstract boolean transform(ClassTransformationContext context) throws Exception;
}
@@ -0,0 +1,9 @@
package customskinloader.bootstrap.transformer;
public interface TransformationObserver {
void ruleApplied(String ruleId, String internalClassName);
void optionalRuleSkipped(String message);
void classTransformed(String internalClassName, Iterable<String> ruleIds);
}
@@ -0,0 +1,175 @@
package customskinloader.bootstrap.transformer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import customskinloader.bootstrap.mapping.Mappings;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
public final class TransformationPlan {
private static final String IGNORE_PATCH_FAILURE_PROPERTY = "customskinloader.ignorePatchFailure";
private static final Comparator<TransformationRule> RULE_ORDER = (left, right) -> {
// Higher-priority transformers run first so low-priority patches can react to earlier changes.
int priorityOrder = Integer.compare(right.getPriority(), left.getPriority());
if (priorityOrder != 0) {
return priorityOrder;
}
int groupOrder = left.getGroupName().compareTo(right.getGroupName());
if (groupOrder != 0) {
return groupOrder;
}
int declarationOrder = Integer.compare(left.getDeclarationOrder(), right.getDeclarationOrder());
return declarationOrder != 0 ? declarationOrder : left.getId().compareTo(right.getId());
};
private final RuntimeVersion runtimeVersion;
private final Mappings mappings;
private final TransformationObserver observer;
private final Map<String, List<TransformationRule>> rulesByTargetClass;
private final Set<String> targetClassNames;
private final int declaredRuleCount;
private final int activeRuleCount;
public TransformationPlan(Iterable<TransformationRuleProvider> providers, RuntimeVersion runtimeVersion, Mappings mappings, TransformationObserver observer) {
if (providers == null || runtimeVersion == null || mappings == null || observer == null) {
throw new IllegalArgumentException("Transformation plan inputs must not be null");
}
this.runtimeVersion = runtimeVersion;
this.mappings = mappings;
this.observer = observer;
Map<String, List<TransformationRule>> mutableRulesByTarget = new LinkedHashMap<>();
Set<String> ruleIds = new HashSet<>();
Set<String> activeVariants = new HashSet<>();
int declaredRules = 0;
int activeRules = 0;
for (TransformationRuleProvider provider : providers) {
if (provider == null) {
throw new IllegalStateException("Transformation rule provider must not be null");
}
List<TransformationRule> rules = provider.getTransformationRules();
if (rules == null) {
throw new IllegalStateException("Transformation rule provider " + provider.getClass().getName() + " returned null");
}
for (TransformationRule rule : rules) {
declaredRules++;
if (rule == null) {
throw new IllegalStateException("Transformation rule provider " + provider.getClass().getName() + " returned a null rule");
}
if (!ruleIds.add(rule.getId())) {
throw new IllegalStateException("Duplicate transformation rule id: " + rule.getId());
}
if (!rule.getVersionSelector().matches(runtimeVersion)) {
continue;
}
String mappedTargetClassName = mappings.remapClassName(rule.getTargetClassName()).replace('.', '/');
if (rule.getVariantGroup() != null && !activeVariants.add(mappedTargetClassName + "@" + rule.getVariantGroup())) {
throw new IllegalStateException("Multiple variants from transformation rule group " + rule.getVariantGroup()
+ " are active for " + mappedTargetClassName + " at " + runtimeVersion);
}
mutableRulesByTarget.computeIfAbsent(mappedTargetClassName, ignored -> new ArrayList<>()).add(rule);
activeRules++;
}
}
Map<String, List<TransformationRule>> compiledRulesByTarget = new LinkedHashMap<>();
for (Map.Entry<String, List<TransformationRule>> entry : mutableRulesByTarget.entrySet()) {
List<TransformationRule> sortedRules = new ArrayList<>(entry.getValue());
Collections.sort(sortedRules, RULE_ORDER);
compiledRulesByTarget.put(entry.getKey(), Collections.unmodifiableList(sortedRules));
}
this.rulesByTargetClass = Collections.unmodifiableMap(compiledRulesByTarget);
this.targetClassNames = Collections.unmodifiableSet(new LinkedHashSet<>(compiledRulesByTarget.keySet()));
this.declaredRuleCount = declaredRules;
this.activeRuleCount = activeRules;
}
public Set<String> getTargetClassNames() {
return this.targetClassNames;
}
public int getDeclaredRuleCount() {
return this.declaredRuleCount;
}
public int getActiveRuleCount() {
return this.activeRuleCount;
}
public ClassTransformationReport transform(String className, byte[] classBytecode) {
if (classBytecode == null) {
throw new IllegalArgumentException("Class bytecode must not be null");
}
String internalClassName = className == null ? "" : className.replace('.', '/');
List<TransformationRule> rules = this.rulesByTargetClass.get(internalClassName);
if (rules == null) {
return new ClassTransformationReport(internalClassName, null, classBytecode, Collections.emptyList());
}
ClassNode classNode = new ClassNode();
// Expanded frames are required to derive the stack map frames of inserted branch targets
// without loading any class (see FrameCapture). The writer compresses them again.
new ClassReader(classBytecode).accept(classNode, ClassReader.EXPAND_FRAMES);
return this.transform(internalClassName, classNode, classBytecode, rules);
}
public ClassTransformationReport transform(String className, ClassNode classNode) {
if (classNode == null) {
throw new IllegalArgumentException("Class node must not be null");
}
String internalClassName = className == null || className.trim().isEmpty() ? classNode.name : className.replace('.', '/');
List<TransformationRule> rules = this.rulesByTargetClass.get(internalClassName);
if (rules == null) {
return new ClassTransformationReport(internalClassName, classNode, null, Collections.emptyList());
}
return this.transform(internalClassName, classNode, null, rules);
}
private ClassTransformationReport transform(String internalClassName, ClassNode classNode, byte[] originalBytecode, List<TransformationRule> rules) {
ClassTransformationContext context = ClassTransformationContext.create(internalClassName, classNode, this.mappings);
List<String> appliedRules = new ArrayList<>();
for (TransformationRule rule : rules) {
boolean modified;
try {
modified = rule.getOperation().apply(context);
} catch (Exception exception) {
String message = "Failed to apply transformation rule " + rule.getId() + " to " + internalClassName;
throw new IllegalStateException(message, exception);
}
if (!modified) {
String message = "Transformation rule '" + rule.getId() + "' selected " + internalClassName + " for "
+ this.runtimeVersion + " but did not modify any bytecode. If you want to force CustomSkinLoader to ignore this patch failure, add -D"
+ IGNORE_PATCH_FAILURE_PROPERTY + "=true to the JVM arguments.";
String failureSetting = System.getProperty(IGNORE_PATCH_FAILURE_PROPERTY);
if ("false".equalsIgnoreCase(failureSetting) || (rule.isRequired() && !Boolean.getBoolean(IGNORE_PATCH_FAILURE_PROPERTY))) {
throw new IllegalStateException(message);
}
this.observer.optionalRuleSkipped(message);
continue;
}
appliedRules.add(rule.getId());
this.observer.ruleApplied(rule.getId(), internalClassName);
}
if (!appliedRules.isEmpty()) {
this.observer.classTransformed(internalClassName, appliedRules);
}
return new ClassTransformationReport(internalClassName, classNode, originalBytecode, appliedRules);
}
}
@@ -0,0 +1,84 @@
package customskinloader.bootstrap.transformer;
public final class TransformationRule {
@FunctionalInterface
public interface Operation {
boolean apply(ClassTransformationContext context) throws Exception;
}
private final String groupName;
private final String name;
private final int priority;
private final int declarationOrder;
private final String variantGroup;
private final String targetClassName;
private final VersionSelector versionSelector;
private final boolean required;
private final Operation operation;
public TransformationRule(String groupName, String name, int priority, int declarationOrder, String targetClassName, String versionExpression, boolean required, Operation operation) {
if (groupName == null || groupName.trim().isEmpty()) {
throw new IllegalArgumentException("Transformation rule group name must not be empty");
}
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("Transformation rule name must not be empty");
}
if (targetClassName == null || targetClassName.trim().isEmpty()) {
throw new IllegalArgumentException("Transformation rule target class must not be empty");
}
if (operation == null) {
throw new IllegalArgumentException("Transformation rule operation must not be null");
}
this.groupName = groupName;
this.name = name;
this.priority = priority;
this.declarationOrder = declarationOrder;
int variantMarker = name.lastIndexOf(".v");
boolean numberedVariant = variantMarker > 0 && variantMarker + 2 < name.length();
for (int index = variantMarker + 2; numberedVariant && index < name.length(); index++) {
numberedVariant = Character.isDigit(name.charAt(index));
}
this.variantGroup = numberedVariant ? groupName + "/" + name.substring(0, variantMarker) : null;
this.targetClassName = targetClassName.replace('.', '/');
this.versionSelector = new VersionSelector(versionExpression);
this.required = required;
this.operation = operation;
}
public String getId() {
return this.groupName + "/" + this.name;
}
public int getPriority() {
return this.priority;
}
public String getGroupName() {
return this.groupName;
}
public int getDeclarationOrder() {
return this.declarationOrder;
}
public String getVariantGroup() {
return this.variantGroup;
}
public String getTargetClassName() {
return this.targetClassName;
}
public VersionSelector getVersionSelector() {
return this.versionSelector;
}
public boolean isRequired() {
return this.required;
}
public Operation getOperation() {
return this.operation;
}
}
@@ -0,0 +1,7 @@
package customskinloader.bootstrap.transformer;
import java.util.List;
public interface TransformationRuleProvider {
List<TransformationRule> getTransformationRules();
}
@@ -1,111 +1,85 @@
package customskinloader.bootstrap.transformer;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import customskinloader.bootstrap.BootstrapLogger;
import customskinloader.bootstrap.mapping.Loader;
import customskinloader.bootstrap.mapping.Mappings;
import customskinloader.bootstrap.mapping.VersionMetadataReader;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
public final class TransformerBootstrapSupport {
private static final Field[] CLASS_NODE_FIELDS = ClassNode.class.getFields();
private static final Logger LOGGER = BootstrapLogger.LOGGER;
private final Object lock = new Object();
private final Class<?> serviceLoaderAnchor;
private final String mappingType;
private final ClassTransformerRegistry registry = new ClassTransformerRegistry();
private final RuntimeClassTransformerEngine transformerEngine = new RuntimeClassTransformerEngine(this.registry);
private volatile boolean transformersLoaded;
private volatile Mappings mappings;
private volatile TransformationPlan transformationPlan;
public TransformerBootstrapSupport(Class<?> serviceLoaderAnchor, String mappingType) {
if (serviceLoaderAnchor == null) {
throw new IllegalArgumentException("Service loader anchor must not be null");
}
this.serviceLoaderAnchor = serviceLoaderAnchor;
this.mappingType = mappingType;
}
public void ensureTransformersLoaded() {
if (this.transformersLoaded) {
return;
public Set<String> getTargetClassNames() {
return this.getTransformationPlan().getTargetClassNames();
}
public ClassTransformationReport transform(String internalClassName, byte[] classBytecode) {
return this.getTransformationPlan().transform(internalClassName, classBytecode);
}
public ClassTransformationReport transform(String internalClassName, ClassNode inputClassNode) {
return this.getTransformationPlan().transform(internalClassName, inputClassNode);
}
private TransformationPlan getTransformationPlan() {
TransformationPlan loadedPlan = this.transformationPlan;
if (loadedPlan != null) {
return loadedPlan;
}
synchronized (this.lock) {
if (this.transformersLoaded) {
return;
}
loadedPlan = this.transformationPlan;
if (loadedPlan == null) {
LOGGER.info("Compiling CustomSkinLoader transformation plan for " + this.mappingType + " mappings");
Mappings mappings = Loader.load(this.serviceLoaderAnchor.getClassLoader(), this.mappingType);
// Discover platform-contributed targeted transformers lazily through the shared service contract.
ServiceLoader<TransformationRuleProvider> providers = ServiceLoader.load(
TransformationRuleProvider.class, this.serviceLoaderAnchor.getClassLoader());
loadedPlan = new TransformationPlan(
providers,
new RuntimeVersion(VersionMetadataReader.PROTOCOL_VERSION, VersionMetadataReader.WORLD_VERSION),
mappings,
new TransformationObserver() {
@Override
public void ruleApplied(String ruleId, String internalClassName) {
LOGGER.debug("Applied transformation rule " + ruleId + " to " + internalClassName);
}
// Discover platform-contributed targeted transformers lazily through the shared service contract.
ServiceLoader<TargetedClassTransformer> serviceLoader = ServiceLoader.load(TargetedClassTransformer.class, this.serviceLoaderAnchor.getClassLoader());
int transformerCount = 0;
for (TargetedClassTransformer transformer : serviceLoader) {
this.registry.register(transformer);
transformerCount++;
LOGGER.debug("Registered transformer " + transformer.getName()
+ " with priority " + transformer.getPriority()
+ " and targets " + transformer.getTargetClassNames());
}
@Override
public void optionalRuleSkipped(String message) {
LOGGER.warn(message);
}
this.transformersLoaded = true;
LOGGER.info("Loaded " + transformerCount + " CustomSkinLoader bootstrap transformer(s) for " + this.mappingType + " mappings");
}
}
public Set<String> collectTargetClassNames() {
this.ensureTransformersLoaded();
Mappings loadedMappings = this.getMappings();
Set<String> targetClassNames = new LinkedHashSet<>();
for (TargetedClassTransformer transformer : this.registry.getTransformers()) {
for (String targetClassName : transformer.getTargetClassNames()) {
targetClassNames.add(loadedMappings.remapClassName(targetClassName));
@Override
public void classTransformed(String internalClassName, Iterable<String> ruleIds) {
LOGGER.info("Transformed " + internalClassName + " with " + ruleIds);
}
}
);
this.transformationPlan = loadedPlan;
LOGGER.info("Compiled " + loadedPlan.getActiveRuleCount() + " of " + loadedPlan.getDeclaredRuleCount()
+ " transformation rule(s) for " + loadedPlan.getTargetClassNames().size() + " target class(es)");
}
}
LOGGER.info("Collected " + targetClassNames.size() + " CustomSkinLoader bootstrap target class(es) for " + this.mappingType + " mappings");
return Collections.unmodifiableSet(targetClassNames);
}
public boolean hasApplicableTransformers(String internalClassName) {
this.ensureTransformersLoaded();
return !this.registry.getApplicableTransformers(internalClassName, this.getMappings()).isEmpty();
}
public ClassTransformationReport transformClassNode(String internalClassName, ClassNode inputClassNode) {
this.ensureTransformersLoaded();
ClassTransformationContext context = ClassTransformationContext.create(internalClassName, inputClassNode, this.getMappings());
return this.transformerEngine.transform(context);
}
public Mappings getMappings() {
Mappings loadedMappings = this.mappings;
if (loadedMappings != null) {
return loadedMappings;
}
synchronized (this.lock) {
loadedMappings = this.mappings;
if (loadedMappings == null) {
LOGGER.info("Loading CustomSkinLoader bootstrap mappings for " + this.mappingType);
loadedMappings = Loader.load(this.serviceLoaderAnchor.getClassLoader(), this.mappingType);
this.mappings = loadedMappings;
LOGGER.info("Loaded " + loadedMappings.getClassMappings().size() + " CustomSkinLoader bootstrap class mapping(s) for " + this.mappingType);
}
}
return loadedMappings;
return loadedPlan;
}
public static byte[] toByteArray(ClassNode classNode) {
@@ -114,22 +88,4 @@ public final class TransformerBootstrapSupport {
return classWriter.toByteArray();
}
public static ClassNode toClassNode(byte[] classBytecode) {
ClassReader classReader = new ClassReader(classBytecode);
ClassNode classNode = new ClassNode();
classReader.accept(classNode, 0);
return classNode;
}
public static void copyClassNode(ClassNode source, ClassNode target) {
try {
for (Field field : CLASS_NODE_FIELDS) {
if (!Modifier.isStatic(field.getModifiers())) {
field.set(target, field.get(source));
}
}
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Failed to copy transformed ClassNode state", exception);
}
}
}
@@ -0,0 +1,20 @@
package customskinloader.bootstrap.transformer;
import customskinloader.bootstrap.util.RangeMatcher;
public final class VersionSelector {
private final String expression;
public VersionSelector(String expression) {
this.expression = expression == null ? "" : expression.trim();
}
public boolean matches(RuntimeVersion version) {
return RangeMatcher.matches(this.expression, version.getProtocolVersion(), version.getWorldVersion());
}
@Override
public String toString() {
return this.expression.isEmpty() ? "*" : this.expression;
}
}
@@ -0,0 +1,97 @@
package customskinloader.bootstrap.transformer.patch;
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.AnalyzerAdapter;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FrameNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Computes the operand stack / local variable state around a given instruction without loading any
* class. Only usable when the method already carries expanded (F_NEW) stack map frames, which is
* the case for the byte array based transformation paths. Platforms that recompute frames (e.g.
* ModLauncher) hand over compressed frames; callers must then fall back to letting the platform
* compute the frames.
*/
final class FrameCapture {
final Object[] localsBefore;
final Object[] stackBefore;
final Object[] localsAfter;
final Object[] stackAfter;
private FrameCapture(Object[] localsBefore, Object[] stackBefore, Object[] localsAfter, Object[] stackAfter) {
this.localsBefore = localsBefore;
this.stackBefore = stackBefore;
this.localsAfter = localsAfter;
this.stackAfter = stackAfter;
}
static FrameCapture capture(String owner, MethodNode methodNode, AbstractInsnNode target) {
if (!hasExpandedFrames(methodNode)) {
return null;
}
AnalyzerAdapter analyzer = new AnalyzerAdapter(owner, methodNode.access, methodNode.name, methodNode.desc, null);
for (AbstractInsnNode instruction = methodNode.instructions.getFirst(); instruction != null; instruction = instruction.getNext()) {
if (instruction == target) {
Object[] localsBefore = toFrameTypes(analyzer.locals);
Object[] stackBefore = toFrameTypes(analyzer.stack);
if (localsBefore == null || stackBefore == null) {
return null;
}
instruction.accept(analyzer);
Object[] localsAfter = toFrameTypes(analyzer.locals);
Object[] stackAfter = toFrameTypes(analyzer.stack);
if (localsAfter == null || stackAfter == null) {
return null;
}
return new FrameCapture(localsBefore, stackBefore, localsAfter, stackAfter);
}
instruction.accept(analyzer);
}
return null;
}
private static boolean hasExpandedFrames(MethodNode methodNode) {
for (AbstractInsnNode instruction : methodNode.instructions) {
if (instruction instanceof FrameNode && ((FrameNode) instruction).type != Opcodes.F_NEW) {
return false;
}
}
return true;
}
/**
* Converts the slot based lists maintained by {@link AnalyzerAdapter} into the expanded frame
* format expected by {@link FrameNode}. Long and double values occupy two slots but only one
* frame entry, so the implicit {@code TOP} following them must be dropped.
*/
private static Object[] toFrameTypes(List<Object> slots) {
if (slots == null) {
return null;
}
List<Object> types = new ArrayList<>(slots.size());
for (int index = 0; index < slots.size(); index++) {
Object slot = slots.get(index);
if (!(slot instanceof String) && !(slot instanceof Integer)) {
// Uninitialized types are represented by analyzer owned labels that cannot be mapped
// back to labels of the method being transformed.
return null;
}
types.add(slot);
if (slot instanceof Integer && (slot.equals(Opcodes.LONG) || slot.equals(Opcodes.DOUBLE))) {
index++;
}
}
return types.toArray();
}
}
@@ -1,47 +1,24 @@
package customskinloader.bootstrap.transformer.patch;
import customskinloader.bootstrap.transformer.ClassTransformationContext;
public final class InterfacePatch extends PatchSupport {
public InterfacePatch() {
super(
"customskinloader:interface-patch", 1000,
targets(
HTTP_TEXTURE_PROCESSOR, "[,553]", // 19w37a- (1.14.4-)
RESOURCE, "",
RESOURCE_MANAGER, "",
NATIVE_IMAGE, "[404,]", // 1.13.2+
IDENTIFIER, ""
)
);
}
super("customskinloader:interface-patch", 1000);
@Override
public boolean transform(ClassTransformationContext context) {
boolean modified = false;
// 19w37a- (1.14.4-)
this.rule("http-texture-processor.interface", HTTP_TEXTURE_PROCESSOR, "[,553]", context ->
this.addInterface(context.getCurrentClassNode(), FAKE_HTTP_TEXTURE_PROCESSOR));
if (context.isTarget(HTTP_TEXTURE_PROCESSOR)) {
modified |= this.requireModified("http-texture-processor.interface", this.addInterface(context.getCurrentClassNode(), FAKE_HTTP_TEXTURE_PROCESSOR));
}
if (context.isTarget(RESOURCE)) {
boolean resourceModified = false;
resourceModified |= this.addInterface(context.getCurrentClassNode(), FAKE_I_RESOURCE_V1);
resourceModified |= this.addInterface(context.getCurrentClassNode(), FAKE_I_RESOURCE_V2);
modified |= this.requireModified("resource.interfaces", resourceModified);
}
if (context.isTarget(RESOURCE_MANAGER)) {
boolean resourceManagerModified = false;
resourceManagerModified |= this.addInterface(context.getCurrentClassNode(), FAKE_I_RESOURCE_MANAGER_V1);
resourceManagerModified |= this.addInterface(context.getCurrentClassNode(), FAKE_I_RESOURCE_MANAGER_V2);
modified |= this.requireModified("resource-manager.interfaces", resourceManagerModified);
}
if (context.isTarget(NATIVE_IMAGE)) {
modified |= this.requireModified("native-image.interface", this.addInterface(context.getCurrentClassNode(), FAKE_NATIVE_IMAGE));
}
if (context.isTarget(IDENTIFIER)) {
modified |= this.requireModified("identifier.patch", this.makeMethodPublicNonFinal(context.findMethod(IDENTIFIER, "<init>", "(" + objectDesc(STRING) + objectDesc(STRING) + ")V")));
}
this.rule("resource.interfaces", RESOURCE, "", context ->
this.addInterface(context.getCurrentClassNode(), FAKE_I_RESOURCE_V1) | this.addInterface(context.getCurrentClassNode(), FAKE_I_RESOURCE_V2));
return modified;
this.rule("resource-manager.interfaces", RESOURCE_MANAGER, "", context ->
this.addInterface(context.getCurrentClassNode(), FAKE_I_RESOURCE_MANAGER_V1) | this.addInterface(context.getCurrentClassNode(), FAKE_I_RESOURCE_MANAGER_V2));
// 1.13.2+
this.rule("native-image.interface", NATIVE_IMAGE, "[404,]", context ->
this.addInterface(context.getCurrentClassNode(), FAKE_NATIVE_IMAGE));
this.rule("identifier.constructor", IDENTIFIER, "", context ->
this.makeMethodPublicNonFinal(context.findMethod(IDENTIFIER, "<init>", "(" + objectDesc(STRING) + objectDesc(STRING) + ")V")));
}
}
@@ -2,31 +2,31 @@ package customskinloader.bootstrap.transformer.patch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BooleanSupplier;
import customskinloader.bootstrap.BootstrapLogger;
import customskinloader.bootstrap.mapping.VersionMetadataReader;
import customskinloader.bootstrap.transformer.TargetedClassTransformer;
import customskinloader.bootstrap.util.RangeMatcher;
import org.apache.logging.log4j.Logger;
import customskinloader.bootstrap.transformer.ClassTransformationContext;
import customskinloader.bootstrap.transformer.TransformationRule;
import customskinloader.bootstrap.transformer.TransformationRuleProvider;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.FrameNode;
import org.objectweb.asm.tree.InnerClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
abstract class PatchSupport extends TargetedClassTransformer implements Opcodes {
private static final String IGNORE_PATCH_FAILURE_PROPERTY = "customskinloader.ignorePatchFailure";
private static final Logger LOGGER = BootstrapLogger.LOGGER;
abstract class PatchSupport implements TransformationRuleProvider, Opcodes {
protected static final String BOOLEAN = "java/lang/Boolean";
protected static final String OBJECT = "java/lang/Object";
protected static final String RUNNABLE = "java/lang/Runnable";
protected static final String STRING = "java/lang/String";
protected static final String CALL_SITE = "java/lang/invoke/CallSite";
protected static final String LAMBDA_METAFACTORY = "java/lang/invoke/LambdaMetafactory";
@@ -36,8 +36,8 @@ abstract class PatchSupport extends TargetedClassTransformer implements Opcodes
protected static final String FILE = "java/io/File";
protected static final String INPUT_STREAM = "java/io/InputStream";
protected static final String PATH = "java/nio/file/Path";
protected static final String RUNNABLE = "java/lang/Runnable";
protected static final String MAP = "java/util/Map";
protected static final String OBJECTS = "java/util/Objects";
protected static final String UUID = "java/util/UUID";
protected static final String COMPLETABLE_FUTURE = "java/util/concurrent/CompletableFuture";
protected static final String EXECUTOR = "java/util/concurrent/Executor";
@@ -101,6 +101,7 @@ abstract class PatchSupport extends TargetedClassTransformer implements Opcodes
protected static final String MINECRAFT_PROFILE_TEXTURE_TYPE = "com/mojang/authlib/minecraft/MinecraftProfileTexture$Type";
protected static final String MINECRAFT_SESSION_SERVICE = "com/mojang/authlib/minecraft/MinecraftSessionService";
protected static final String MINECRAFT_PROFILE_TEXTURES = "com/mojang/authlib/minecraft/MinecraftProfileTextures";
protected static final String SESSION_SERVICE = "com/mojang/authlib/minecraft/SessionService";
protected static final String GAME_PROFILE = "com/mojang/authlib/GameProfile";
protected static final String PROPERTY = "com/mojang/authlib/properties/Property";
@@ -108,39 +109,26 @@ abstract class PatchSupport extends TargetedClassTransformer implements Opcodes
return "L" + internalName + ";";
}
private final int protocolVersion;
private final int worldVersion;
private final String groupName;
private final int priority;
private final List<TransformationRule> rules = new ArrayList<>();
protected PatchSupport(String name, int priority, Map<String, String> targetClassNames) {
this(name, priority, VersionMetadataReader.PROTOCOL_VERSION, VersionMetadataReader.WORLD_VERSION, targetClassNames);
protected PatchSupport(String groupName, int priority) {
this.groupName = groupName;
this.priority = priority;
}
private PatchSupport(String name, int priority, int protocolVersion, int worldVersion, Map<String, String> targetClassNames) {
super(name, priority, filterTargetClassNames(targetClassNames, protocolVersion, worldVersion));
this.protocolVersion = protocolVersion;
this.worldVersion = worldVersion;
protected final void rule(String name, String targetClassName, String versionExpression, TransformationRule.Operation operation) {
this.rules.add(new TransformationRule(this.groupName, name, this.priority, this.rules.size(), targetClassName, versionExpression, true, operation));
}
protected static Map<String, String> targets(String... targetClassNameProtocolRanges) {
if (targetClassNameProtocolRanges.length % 2 != 0) {
throw new IllegalArgumentException("Target class names must be paired with protocol ranges");
}
Map<String, String> targets = new LinkedHashMap<>();
for (int index = 0; index < targetClassNameProtocolRanges.length; index += 2) {
targets.put(targetClassNameProtocolRanges[index], targetClassNameProtocolRanges[index + 1]);
}
return Collections.unmodifiableMap(targets);
protected final void optionalRule(String name, String targetClassName, String versionExpression, TransformationRule.Operation operation) {
this.rules.add(new TransformationRule(this.groupName, name, this.priority, this.rules.size(), targetClassName, versionExpression, false, operation));
}
private static String[] filterTargetClassNames(Map<String, String> targetClassNames, int protocolVersion, int worldVersion) {
List<String> filteredTargetClassNames = new ArrayList<>();
for (Map.Entry<String, String> entry : targetClassNames.entrySet()) {
if (RangeMatcher.matches(entry.getValue(), protocolVersion, worldVersion)) {
filteredTargetClassNames.add(entry.getKey());
}
}
return filteredTargetClassNames.toArray(new String[0]);
@Override
public final List<TransformationRule> getTransformationRules() {
return Collections.unmodifiableList(new ArrayList<>(this.rules));
}
protected boolean addInterface(ClassNode classNode, String interfaceName) {
@@ -194,46 +182,6 @@ abstract class PatchSupport extends TargetedClassTransformer implements Opcodes
return (access & ~(ACC_PRIVATE | ACC_PROTECTED | ACC_FINAL)) | ACC_PUBLIC;
}
protected boolean matches(String range) {
return RangeMatcher.matches(range, this.protocolVersion, this.worldVersion);
}
protected boolean applyIfMatches(String range, String label, BooleanSupplier operation) {
return applyIfMatches(range, label, operation, true);
}
protected boolean applyIfMatches(String range, String label, BooleanSupplier operation, boolean required) {
if (!this.matches(range)) {
return false;
}
return this.requireModified(label, operation.getAsBoolean(), required);
}
protected boolean requireModified(String label, boolean modified) {
return this.requireModified(label, modified, true);
}
protected boolean requireModified(String label, boolean modified, boolean required) {
if (modified) {
return true;
}
String message = "Patch '" + this.getName() + ":" + label + "' matched protocol " + this.protocolVersion
+ " but did not modify any bytecode. If you want to force CustomSkinLoader to ignore this patch failure, add -D"
+ IGNORE_PATCH_FAILURE_PROPERTY + "=true to the JVM arguments.";
if ("false".equalsIgnoreCase(System.getProperty(IGNORE_PATCH_FAILURE_PROPERTY))) {
throw new IllegalStateException(message);
}
if (!required || Boolean.getBoolean(IGNORE_PATCH_FAILURE_PROPERTY)) {
LOGGER.warn(message);
return false;
}
throw new IllegalStateException(message);
}
protected InsnList clone(InsnList source) {
InsnList copy = new InsnList();
for (AbstractInsnNode abstractInsnNode : source) {
@@ -261,7 +209,43 @@ abstract class PatchSupport extends TargetedClassTransformer implements Opcodes
return current;
}
protected static void methodNodeSet(MethodNode methodNode, AbstractInsnNode oldInstruction, AbstractInsnNode newInstruction) {
methodNode.instructions.set(oldInstruction, newInstruction);
protected void replaceInstructionSafely(ClassTransformationContext context, MethodNode methodNode, AbstractInsnNode original, AbstractInsnNode replacement) {
this.replaceInstructionSafely(context, methodNode, new InsnNode(ICONST_1), IFNE, original, replacement);
}
protected void replaceInstructionSafely(ClassTransformationContext context, MethodNode methodNode, AbstractInsnNode condition, int jumpOpcode, AbstractInsnNode original, AbstractInsnNode replacement) {
LabelNode label0 = new LabelNode();
LabelNode label1 = new LabelNode();
InsnList before = new InsnList();
before.add(condition);
before.add(new JumpInsnNode(jumpOpcode, label0));
before.add(new LdcInsnNode("Modified by CustomSkinLoader."));
before.add(new InsnNode(POP));
methodNode.instructions.insertBefore(original, before);
// The original instruction is kept as dead code so later Mixin / coremod transformations
// can still locate it. Both branch targets therefore need a real stack map frame: the
// replacement starts with the state the original instruction would have seen, and the
// merge point continues with the state the original instruction would have produced.
FrameCapture frames = FrameCapture.capture(context.getInternalClassName(), methodNode, original);
if (frames == null) {
BootstrapLogger.LOGGER.debug("Could not derive stack map frames for " + methodNode.name + methodNode.desc + "; the inserted branch targets carry no frame");
}
InsnList after = new InsnList();
after.add(new JumpInsnNode(GOTO, label1));
after.add(label0);
if (frames != null) {
after.add(new FrameNode(F_NEW, frames.localsBefore.length, frames.localsBefore, frames.stackBefore.length, frames.stackBefore));
}
after.add(replacement);
after.add(label1);
if (frames != null) {
after.add(new FrameNode(F_NEW, frames.localsAfter.length, frames.localsAfter, frames.stackAfter.length, frames.stackAfter));
}
methodNode.instructions.insert(original, after);
}
}
@@ -2,66 +2,78 @@ package customskinloader.bootstrap.transformer.patch;
import customskinloader.bootstrap.transformer.ClassTransformationContext;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
public final class RenderPatch extends PatchSupport {
public RenderPatch() {
super(
"customskinloader:render-patch", 1000,
targets(
PLAYER_TAB_OVERLAY, "",
CAPE_LAYER, "[556,]", // 19w39a+ (1.15+)
PLAYER_RENDERER, "[556,767],[801,803],[0x40000001,0x400000CC]" // 19w39a ~ 1.21.1 (1.15 ~ 1.21.1)
)
);
}
super("customskinloader:render-patch", 1000);
@Override
public boolean transform(ClassTransformationContext context) {
boolean modified = false;
if (context.isTarget(PLAYER_TAB_OVERLAY)) {
modified |= this.requireModified("player-tab-overlay", this.patchPlayerTabOverlay(context));
}
if (context.isTarget(CAPE_LAYER)) {
modified |= this.requireModified("cape-layer", this.patchCapeLayer(context), false);
}
if (context.isTarget(PLAYER_RENDERER)) {
modified |= this.requireModified("player-renderer", this.patchPlayerRenderer(context), false);
}
return modified;
}
private boolean patchPlayerTabOverlay(ClassTransformationContext context) {
boolean modified = false;
// 20w16a- (1.15.2-)
modified |= this.applyIfMatches("[,712]", "player-tab-overlay.render.v1", () -> replaceMinecraftLocalServerCheck(
context, context.findMethod(PLAYER_TAB_OVERLAY, "render", "(I" + objectDesc(SCOREBOARD) + objectDesc(OBJECTIVE) + ")V"), MINECRAFT, "isLocalServer"
));
this.rule("player-tab-overlay.render.v1", PLAYER_TAB_OVERLAY, "[,712]", context ->
this.replaceLocalServerCheck(
context, context.findMethod(PLAYER_TAB_OVERLAY, "render", "(I" + objectDesc(SCOREBOARD) + objectDesc(OBJECTIVE) + ")V"),
MINECRAFT, "isLocalServer"));
// 20w17a ~ 23w14a (1.16 ~ 1.19.4)
modified |= this.applyIfMatches("[713,762],[801,803],[0x40000001,0x40000082]", "player-tab-overlay.render.v2", () -> replaceMinecraftLocalServerCheck(
context, context.findMethod(PLAYER_TAB_OVERLAY, "render", "(" + objectDesc(POSE_STACK) + "I" + objectDesc(SCOREBOARD) + objectDesc(OBJECTIVE) + ")V"), MINECRAFT, "isLocalServer"
));
this.rule("player-tab-overlay.render.v2", PLAYER_TAB_OVERLAY, "[713,762],[801,803],[0x40000001,0x40000082]", context ->
this.replaceLocalServerCheck(
context, context.findMethod(PLAYER_TAB_OVERLAY, "render", "(" + objectDesc(POSE_STACK) + "I" + objectDesc(SCOREBOARD) + objectDesc(OBJECTIVE) + ")V"),
MINECRAFT, "isLocalServer"));
// 23w16a ~ 26.1-snapshot-11 (1.20 ~ 1.21.11)
modified |= this.applyIfMatches("[763,774],[0x40000083,0x40000129]", "player-tab-overlay.render.v3", () -> replaceMinecraftLocalServerCheck(
context, context.findMethod(PLAYER_TAB_OVERLAY, "render", "(" + objectDesc(GUI_GRAPHICS) + "I" + objectDesc(SCOREBOARD) + objectDesc(OBJECTIVE) + ")V"), MINECRAFT, "isLocalServer"
));
this.rule("player-tab-overlay.render.v3", PLAYER_TAB_OVERLAY, "[763,774],[0x40000083,0x40000129]", context ->
this.replaceLocalServerCheck(
context, context.findMethod(PLAYER_TAB_OVERLAY, "render", "(" + objectDesc(GUI_GRAPHICS) + "I" + objectDesc(SCOREBOARD) + objectDesc(OBJECTIVE) + ")V"),
MINECRAFT, "isLocalServer"));
// 26.1-pre-1 ~ 26.2-snapshot-6 (26.1 ~ 26.1.2)
modified |= this.applyIfMatches("775,[0x4000012A,0x40000138]", "player-tab-overlay.extract-render-state.v1", () -> replaceMinecraftLocalServerCheck(
context, context.findMethod(PLAYER_TAB_OVERLAY, "extractRenderState", "(" + objectDesc(GUI_GRAPHICS_EXTRACTOR) + "I" + objectDesc(SCOREBOARD) + objectDesc(OBJECTIVE) + ")V"), MINECRAFT, "isLocalServer"
));
this.rule("player-tab-overlay.extract-render-state.v1", PLAYER_TAB_OVERLAY, "775,[0x4000012A,0x40000138]", context ->
this.replaceLocalServerCheck(
context, context.findMethod(PLAYER_TAB_OVERLAY, "extractRenderState", "(" + objectDesc(GUI_GRAPHICS_EXTRACTOR) + "I" + objectDesc(SCOREBOARD) + objectDesc(OBJECTIVE) + ")V"),
MINECRAFT, "isLocalServer"));
// 26.2-snapshot-7+ (26.2+)
modified |= this.applyIfMatches("[776,800],[804,0x40000000],[0x40000139,]", "player-tab-overlay.extract-render-state.v2", () -> replaceMinecraftLocalServerCheck(
context, context.findMethod(PLAYER_TAB_OVERLAY, "extractRenderState", "(" + objectDesc(GUI_GRAPHICS_EXTRACTOR) + "I" + objectDesc(SCOREBOARD) + objectDesc(OBJECTIVE) + ")V"), CLIENT_PACKET_LISTENER, "onlineMode"
));
return modified;
this.rule("player-tab-overlay.extract-render-state.v2", PLAYER_TAB_OVERLAY, "[776,800],[804,0x40000000],[0x40000139,]", context ->
this.replaceLocalServerCheck(
context, context.findMethod(PLAYER_TAB_OVERLAY, "extractRenderState", "(" + objectDesc(GUI_GRAPHICS_EXTRACTOR) + "I" + objectDesc(SCOREBOARD) + objectDesc(OBJECTIVE) + ")V"),
CLIENT_PACKET_LISTENER, "onlineMode"));
// 19w39a ~ 19w44a
this.optionalRule("cape-layer.render.v1", CAPE_LAYER, "[556,560]", context ->
this.replaceEntitySolidWithTranslucent(
context, context.findMethod(CAPE_LAYER, "render", "(" + objectDesc(POSE_STACK) + objectDesc(MULTI_BUFFER_SOURCE) + "I" + objectDesc(ABSTRACT_CLIENT_PLAYER) + "FFFFFFF)V"),
RENDER_TYPE));
// 19w45a ~ 1.21.1 (1.15 ~ 1.21.1)
this.optionalRule("cape-layer.render.v2", CAPE_LAYER, "[561,767],[801,803],[0x40000001,0x400000CC]", context ->
this.replaceEntitySolidWithTranslucent(
context, context.findMethod(CAPE_LAYER, "render", "(" + objectDesc(POSE_STACK) + objectDesc(MULTI_BUFFER_SOURCE) + "I" + objectDesc(ABSTRACT_CLIENT_PLAYER) + "FFFFFF)V"),
RENDER_TYPE));
// 24w33a ~ 1.21.8 (1.21.2 ~ 1.21.8)
this.optionalRule("cape-layer.render.v3", CAPE_LAYER, "[768,772],[0x400000CD,0x40000103]", context ->
this.replaceEntitySolidWithTranslucent(
context, context.findMethod(CAPE_LAYER, "render", "(" + objectDesc(POSE_STACK) + objectDesc(MULTI_BUFFER_SOURCE) + "I" + objectDesc(PLAYER_RENDER_STATE) + "FF)V"),
RENDER_TYPE));
// 25w31a ~ 25w42a (1.21.9 ~ 1.21.10)
this.optionalRule("cape-layer.submit.v1", CAPE_LAYER, "773,[0x40000104,0x40000112]", context ->
this.replaceEntitySolidWithTranslucent(
context, context.findMethod(CAPE_LAYER, "submit", "(" + objectDesc(POSE_STACK) + objectDesc(SUBMIT_NODE_COLLECTOR) + "I" + objectDesc(AVATAR_RENDER_STATE) + "FF)V"),
RENDER_TYPE));
// 25w43a+ (1.21.11+)
this.optionalRule("cape-layer.submit.v2", CAPE_LAYER, "[774,800],[804,0x40000000],[0x40000113,]", context ->
this.replaceEntitySolidWithTranslucent(
context, context.findMethod(CAPE_LAYER, "submit", "(" + objectDesc(POSE_STACK) + objectDesc(SUBMIT_NODE_COLLECTOR) + "I" + objectDesc(AVATAR_RENDER_STATE) + "FF)V"),
RENDER_TYPES));
// 19w39a ~ 19w44a
this.optionalRule("player-renderer.render-hand.v1", PLAYER_RENDERER, "[556,560]", context ->
this.replaceEntitySolidWithTranslucent(
context, context.findMethod(PLAYER_RENDERER, "renderHand", "(" + objectDesc(POSE_STACK) + objectDesc(MULTI_BUFFER_SOURCE) + objectDesc(ABSTRACT_CLIENT_PLAYER) + objectDesc(MODEL_PART) + objectDesc(MODEL_PART) + ")V"),
RENDER_TYPE));
// 19w45a ~ 1.21.1 (1.15 ~ 1.21.1)
this.optionalRule("player-renderer.render-hand.v2", PLAYER_RENDERER, "[561,767],[801,803],[0x40000001,0x400000CC]", context ->
this.replaceEntitySolidWithTranslucent(
context, context.findMethod(PLAYER_RENDERER, "renderHand", "(" + objectDesc(POSE_STACK) + objectDesc(MULTI_BUFFER_SOURCE) + "I" + objectDesc(ABSTRACT_CLIENT_PLAYER) + objectDesc(MODEL_PART) + objectDesc(MODEL_PART) + ")V"),
RENDER_TYPE));
}
private boolean replaceMinecraftLocalServerCheck(ClassTransformationContext context, MethodNode methodNode, String owner, String name) {
private boolean replaceLocalServerCheck(ClassTransformationContext context, MethodNode methodNode, String owner, String name) {
if (methodNode == null) {
return false;
}
@@ -75,64 +87,11 @@ public final class RenderPatch extends PatchSupport {
}
MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
if (!remappedOwner.equals(methodInsnNode.owner) || !remappedName.equals(methodInsnNode.name) || !"()Z".equals(methodInsnNode.desc)) {
continue;
if (remappedOwner.equals(methodInsnNode.owner) && remappedName.equals(methodInsnNode.name) && "()Z".equals(methodInsnNode.desc)) {
this.replaceInstructionSafely(context, methodNode, instruction, new MethodInsnNode(INVOKESTATIC, OBJECTS, "nonNull", "(" + objectDesc(OBJECT) + ")Z"));
modified = true;
}
InsnList replacement = new InsnList();
replacement.add(new InsnNode(POP));
replacement.add(new InsnNode(ICONST_1));
methodNode.instructions.insertBefore(instruction, replacement);
methodNode.instructions.remove(instruction);
modified = true;
}
return modified;
}
private boolean patchCapeLayer(ClassTransformationContext context) {
boolean modified = false;
// 19w39a ~ 19w44a
modified |= this.applyIfMatches("[556,560]", "cape-layer.render.v1", () -> replaceEntitySolidWithTranslucent(
context, context.findMethod(CAPE_LAYER, "render", "(" + objectDesc(POSE_STACK) + objectDesc(MULTI_BUFFER_SOURCE) + "I" + objectDesc(ABSTRACT_CLIENT_PLAYER) + "FFFFFFF)V"),
RENDER_TYPE
), false);
// 19w45a ~ 1.21.1 (1.15 ~ 1.21.1)
modified |= this.applyIfMatches("[561,767],[801,803],[0x40000001,0x400000CC]", "cape-layer.render.v2", () -> replaceEntitySolidWithTranslucent(
context, context.findMethod(CAPE_LAYER, "render", "(" + objectDesc(POSE_STACK) + objectDesc(MULTI_BUFFER_SOURCE) + "I" + objectDesc(ABSTRACT_CLIENT_PLAYER) + "FFFFFF)V"),
RENDER_TYPE
), false);
// 24w33a ~ 1.21.8 (1.21.2 ~ 1.21.8)
modified |= this.applyIfMatches("[768,772],[0x400000CD,0x40000103]", "cape-layer.render.v3", () -> replaceEntitySolidWithTranslucent(
context, context.findMethod(CAPE_LAYER, "render", "(" + objectDesc(POSE_STACK) + objectDesc(MULTI_BUFFER_SOURCE) + "I" + objectDesc(PLAYER_RENDER_STATE) + "FF)V"),
RENDER_TYPE
), false);
// 25w31a ~ 25w42a (1.21.9 ~ 1.21.10)
modified |= this.applyIfMatches("773,[0x40000104,0x40000112]", "cape-layer.submit.v1", () -> replaceEntitySolidWithTranslucent(
context, context.findMethod(CAPE_LAYER, "submit", "(" + objectDesc(POSE_STACK) + objectDesc(SUBMIT_NODE_COLLECTOR) + "I" + objectDesc(AVATAR_RENDER_STATE) + "FF)V"),
RENDER_TYPE
), false);
// 25w43a+ (1.21.11+)
modified |= this.applyIfMatches("[774,800],[804,0x40000000],[0x40000113,]", "cape-layer.submit.v2", () -> replaceEntitySolidWithTranslucent(
context, context.findMethod(CAPE_LAYER, "submit", "(" + objectDesc(POSE_STACK) + objectDesc(SUBMIT_NODE_COLLECTOR) + "I" + objectDesc(AVATAR_RENDER_STATE) + "FF)V"),
RENDER_TYPES
), false);
return modified;
}
private boolean patchPlayerRenderer(ClassTransformationContext context) {
boolean modified = false;
// 19w39a ~ 19w44a
modified |= this.applyIfMatches("[556,560]", "player-renderer.render-hand.v1", () -> replaceEntitySolidWithTranslucent(
context, context.findMethod(PLAYER_RENDERER, "renderHand", "(" + objectDesc(POSE_STACK) + objectDesc(MULTI_BUFFER_SOURCE) + objectDesc(ABSTRACT_CLIENT_PLAYER) + objectDesc(MODEL_PART) + objectDesc(MODEL_PART) + ")V"),
RENDER_TYPE
), false);
// 19w45a ~ 1.21.1 (1.15 ~ 1.21.1)
modified |= this.applyIfMatches("[561,767],[801,803],[0x40000001,0x400000CC]", "player-renderer.render-hand.v2", () -> replaceEntitySolidWithTranslucent(
context, context.findMethod(PLAYER_RENDERER, "renderHand", "(" + objectDesc(POSE_STACK) + objectDesc(MULTI_BUFFER_SOURCE) + "I" + objectDesc(ABSTRACT_CLIENT_PLAYER) + objectDesc(MODEL_PART) + objectDesc(MODEL_PART) + ")V"),
RENDER_TYPE
), false);
return modified;
}
@@ -153,16 +112,11 @@ public final class RenderPatch extends PatchSupport {
}
MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
if (!remappedOwner.equals(methodInsnNode.owner) || !originalName.equals(methodInsnNode.name) || !remappedDesc.equals(methodInsnNode.desc)) {
continue;
if (remappedOwner.equals(methodInsnNode.owner) && originalName.equals(methodInsnNode.name) && remappedDesc.equals(methodInsnNode.desc)) {
this.replaceInstructionSafely(context, methodNode, instruction, new MethodInsnNode(INVOKESTATIC, remappedOwner, replacementName, remappedDesc, false));
modified = true;
}
methodNode.instructions.insertBefore(instruction, new InsnNode(DUP));
methodNode.instructions.insert(instruction, new MethodInsnNode(INVOKESTATIC, remappedOwner, replacementName, remappedDesc, false));
methodNode.instructions.insert(instruction, new InsnNode(POP));
modified = true;
}
return modified;
}
}
@@ -7,6 +7,7 @@ import org.objectweb.asm.Handle;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FrameNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
@@ -17,83 +18,182 @@ import org.objectweb.asm.tree.VarInsnNode;
public final class SkinManagerPatch extends PatchSupport {
public SkinManagerPatch() {
super(
"customskinloader:skin-manager-patch", 1000,
targets(
SKIN_MANAGER, "",
SKIN_MANAGER_1, "[764,800],[804,0x40000000],[0x40000090,]", // 23w31a+ (1.20.2+)
SKIN_MANAGER_3, "[,340]", // 1.12.2-
SKIN_MANAGER_CACHE_KEY, "[764,800],[804,0x40000000],[0x40000090,]", // 23w31a+ (1.20.2+)
SKIN_MANAGER_TEXTURE_CACHE, "[764,800],[804,0x40000000],[0x40000090,]" // 23w31a+ (1.20.2+)
)
);
}
super("customskinloader:skin-manager-patch", 1000);
@Override
public boolean transform(ClassTransformationContext context) {
boolean modified = false;
// 23w31a+ (1.20.2+)
this.rule("skin-manager.cache-key-inner-class", SKIN_MANAGER, "[764,800],[804,0x40000000],[0x40000090,]", context ->
this.makeInnerClassPublicNonFinal(context.getCurrentClassNode(), context.remapClassName(SKIN_MANAGER_CACHE_KEY)));
if (context.isTarget(SKIN_MANAGER)) {
// 23w31a+ (1.20.2+)
modified |= this.applyIfMatches("[764,800],[804,0x40000000],[0x40000090,]", "skin-manager.cache-key-inner-class", () -> makeInnerClassPublicNonFinal(context.getCurrentClassNode(), context.remapClassName(SKIN_MANAGER_CACHE_KEY)));
modified |= this.requireModified("skin-manager", this.patchSkinManager(context));
}
if (context.isTarget(SKIN_MANAGER_1)) {
modified |= this.requireModified("skin-manager-1", this.patchSkinManagerLoader(context));
}
if (context.isTarget(SKIN_MANAGER_3)) {
MethodNode getUserProfile = context.findMethod(SKIN_MANAGER_3, "run", "()V");
modified |= this.requireModified("skin-manager-3", getUserProfile != null && this.replaceGetTexturesWithFakeUserProfile(getUserProfile));
}
if (context.isTarget(SKIN_MANAGER_CACHE_KEY)) {
modified |= this.requireModified("skin-manager-cache-key", this.patchSkinManagerCacheKeyClass(context));
}
if (context.isTarget(SKIN_MANAGER_TEXTURE_CACHE)) {
modified |= this.requireModified("skin-manager-texture-cache", this.patchSkinManagerTextureCache(context));
}
return modified;
}
private boolean patchSkinManager(ClassTransformationContext context) {
boolean modified = false;
modified |= this.injectSkinManagerConstructors(context);
// 1.20.1-
modified |= this.applyIfMatches("[,763],[801,803],[0x40000001,0x4000008E]", "skin-manager.v1", () -> patchLegacySkinManager(context));
// 23w42a+ (1.20.3+)
modified |= this.applyIfMatches("[765,800],[804,0x40000000],[0x4000009D,]", "skin-manager.v2", () -> patchSkinManagerCacheKey(context));
return modified;
}
private boolean patchSkinManagerCacheKeyClass(ClassTransformationContext context) {
boolean modified = this.makeClassPublicNonFinal(context.getCurrentClassNode());
modified |= this.makeMethodPublicNonFinal(context.findMethod(SKIN_MANAGER_CACHE_KEY, "<init>", "(" + objectDesc(UUID) + objectDesc(PROPERTY) + ")V"));
return modified;
}
private boolean injectSkinManagerConstructors(ClassTransformationContext context) {
boolean modified = false;
// 1.20.1-
modified |= this.applyIfMatches("[,763],[801,803],[0x40000001,0x4000008E]", "skin-manager.<init>.v1", () -> injectSetSkinCacheDir(
context, "(" + objectDesc(TEXTURE_MANAGER) + objectDesc(FILE) + objectDesc(MINECRAFT_SESSION_SERVICE) + ")V", 2, objectDesc(FILE)
));
this.rule("skin-manager.constructor.v1", SKIN_MANAGER, "[,763],[801,803],[0x40000001,0x4000008E]", context ->
this.injectSetSkinCacheDir(context, "(" + objectDesc(TEXTURE_MANAGER) + objectDesc(FILE) + objectDesc(MINECRAFT_SESSION_SERVICE) + ")V", 2, objectDesc(FILE)));
// 23w31a ~ 24w45a (1.20.2 ~ 1.21.3)
modified |= this.applyIfMatches("[764,768],[0x40000090,0x400000DD]", "skin-manager.<init>.v2", () -> injectSetSkinCacheDir(
context, "(" + objectDesc(TEXTURE_MANAGER) + objectDesc(PATH) + objectDesc(MINECRAFT_SESSION_SERVICE) + objectDesc(EXECUTOR) + ")V", 2, objectDesc(PATH)
));
this.rule("skin-manager.constructor.v2", SKIN_MANAGER, "[764,768],[0x40000090,0x400000DD]", context ->
this.injectSetSkinCacheDir(context, "(" + objectDesc(TEXTURE_MANAGER) + objectDesc(PATH) + objectDesc(MINECRAFT_SESSION_SERVICE) + objectDesc(EXECUTOR) + ")V", 2, objectDesc(PATH)));
// 24w46a ~ 25w33a (1.21.4 ~ 1.21.8)
modified |= this.applyIfMatches("[769,772],[0x400000DE,0x40000106]", "skin-manager.<init>.v3", () -> injectSetSkinCacheDir(
context, "(" + objectDesc(PATH) + objectDesc(MINECRAFT_SESSION_SERVICE) + objectDesc(EXECUTOR) + ")V", 1, objectDesc(PATH)
));
this.rule("skin-manager.constructor.v3", SKIN_MANAGER, "[769,772],[0x400000DE,0x40000106]", context ->
this.injectSetSkinCacheDir(context, "(" + objectDesc(PATH) + objectDesc(MINECRAFT_SESSION_SERVICE) + objectDesc(EXECUTOR) + ")V", 1, objectDesc(PATH)));
// 25w34a ~ 25w34b
modified |= this.applyIfMatches("[0x40000107,0x40000108]", "skin-manager.<init>.v4", () -> injectSetSkinCacheDir(
context, "(" + objectDesc(PATH) + objectDesc(SERVICES) + objectDesc(EXECUTOR) + ")V", 1, objectDesc(PATH)
));
this.rule("skin-manager.constructor.v4", SKIN_MANAGER, "[0x40000107,0x40000108]", context ->
this.injectSetSkinCacheDir(context, "(" + objectDesc(PATH) + objectDesc(SERVICES) + objectDesc(EXECUTOR) + ")V", 1, objectDesc(PATH)));
// 25w35a+ (1.21.9+)
modified |= this.applyIfMatches("[773,800],[804,0x40000000],[0x40000109,]", "skin-manager.<init>.v5", () -> injectSetSkinCacheDir(
context, "(" + objectDesc(PATH) + objectDesc(SERVICES) + objectDesc(SKIN_TEXTURE_DOWNLOADER) + objectDesc(EXECUTOR) + ")V", 1, objectDesc(PATH)
));
return modified;
this.rule("skin-manager.constructor.v5", SKIN_MANAGER, "[773,800],[804,0x40000000],[0x40000109,]", context ->
this.injectSetSkinCacheDir(context, "(" + objectDesc(PATH) + objectDesc(SERVICES) + objectDesc(SKIN_TEXTURE_DOWNLOADER) + objectDesc(EXECUTOR) + ")V", 1, objectDesc(PATH)));
// 19w37a- (1.14.4-)
this.rule("skin-manager.register-texture.v1", SKIN_MANAGER, "[,553]", context -> {
InsnList loadTextureType = new InsnList();
loadTextureType.add(new VarInsnNode(ALOAD, 2));
return this.redirectHttpTextureConstructorToFake(
context,
context.findMethod(SKIN_MANAGER, "registerTexture", "(" + objectDesc(MINECRAFT_PROFILE_TEXTURE) + objectDesc(MINECRAFT_PROFILE_TEXTURE_TYPE) + objectDesc(SKIN_MANAGER_SKIN_TEXTURE_CALLBACK) + ")" + objectDesc(IDENTIFIER)),
context.remapMethodDescriptor("(" + objectDesc(FILE) + objectDesc(STRING) + objectDesc(IDENTIFIER) + objectDesc(HTTP_TEXTURE_PROCESSOR) + ")V"),
context.remapMethodDescriptor("(" + objectDesc(FILE) + objectDesc(STRING) + objectDesc(IDENTIFIER) + objectDesc(HTTP_TEXTURE_PROCESSOR) + objectDesc(MINECRAFT_PROFILE_TEXTURE) + objectDesc(MINECRAFT_PROFILE_TEXTURE_TYPE) + ")V"),
loadTextureType
);
});
// 19w38a ~ 1.20.1 (1.15 ~ 1.20.1)
this.rule("skin-manager.register-texture.v2", SKIN_MANAGER, "[554,763],[801,803],[0x40000001,0x4000008E]", context -> {
InsnList loadTextureType = new InsnList();
loadTextureType.add(new VarInsnNode(ALOAD, 2));
return this.redirectHttpTextureConstructorToFake(
context,
context.findMethod(SKIN_MANAGER, "registerTexture", "(" + objectDesc(MINECRAFT_PROFILE_TEXTURE) + objectDesc(MINECRAFT_PROFILE_TEXTURE_TYPE) + objectDesc(SKIN_MANAGER_SKIN_TEXTURE_CALLBACK) + ")" + objectDesc(IDENTIFIER)),
context.remapMethodDescriptor("(" + objectDesc(FILE) + objectDesc(STRING) + objectDesc(IDENTIFIER) + "Z" + objectDesc(RUNNABLE) + ")V"),
context.remapMethodDescriptor("(" + objectDesc(FILE) + objectDesc(STRING) + objectDesc(IDENTIFIER) + "Z" + objectDesc(RUNNABLE) + objectDesc(MINECRAFT_PROFILE_TEXTURE) + objectDesc(MINECRAFT_PROFILE_TEXTURE_TYPE) + ")V"),
loadTextureType
);
});
// 19w37a- (1.14.4-)
this.rule("skin-manager.register-skins.v1", SKIN_MANAGER, "[,553]", context ->
this.replaceExecutorProfileLoadAtInvocation(
context, context.findMethod(SKIN_MANAGER, "registerSkins", "(" + objectDesc(GAME_PROFILE) + objectDesc(SKIN_MANAGER_SKIN_TEXTURE_CALLBACK) + "Z)V"),
EXECUTOR_SERVICE, "submit", "(" + objectDesc(RUNNABLE) + ")" + objectDesc(FUTURE)));
// 19w38a ~ 1.18-exp7 (1.15 ~ 1.17.1)
this.rule("skin-manager.register-skins.v2", SKIN_MANAGER, "[554,756],[801,803],[0x40000001,0x4000002F]+[2205,2831]", context ->
this.replaceExecutorProfileLoadAtInvocation(
context, context.findMethod(SKIN_MANAGER, "registerSkins", "(" + objectDesc(GAME_PROFILE) + objectDesc(SKIN_MANAGER_SKIN_TEXTURE_CALLBACK) + "Z)V"),
EXECUTOR, "execute", "(" + objectDesc(RUNNABLE) + ")V"));
// 21w37a ~ 1.20.1 (1.18 ~ 1.20.1)
this.rule("skin-manager.register-skins.v3", SKIN_MANAGER, "[757,763],[0x40000029,0x4000008E]+[2834,3465]", context ->
this.replaceExecutorProfileLoadAtInvocation(
context, context.findMethod(SKIN_MANAGER, "registerSkins", "(" + objectDesc(GAME_PROFILE) + objectDesc(SKIN_MANAGER_SKIN_TEXTURE_CALLBACK) + "Z)V"),
EXECUTOR_SERVICE, "execute", "(" + objectDesc(RUNNABLE) + ")V"));
this.rule("skin-manager.get-insecure-skin-information", SKIN_MANAGER, "[,763],[801,803],[0x40000001,0x4000008E]", context -> {
MethodNode methodNode = context.findMethod(SKIN_MANAGER, "getInsecureSkinInformation", "(" + objectDesc(GAME_PROFILE) + ")" + objectDesc(MAP));
if (methodNode == null) {
return false;
}
InsnList injection = new InsnList();
injection.add(new VarInsnNode(ALOAD, 1));
injection.add(new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_MANAGER, "loadSkinFromCache", "(" + objectDesc(GAME_PROFILE) + ")" + objectDesc(MAP), false));
injection.add(new InsnNode(ARETURN));
injection.add(new FrameNode(F_SAME, 0, null, 0, null));
methodNode.instructions.insert(injection);
return true;
});
// 1.13.2 ~ 1.20.1
this.rule("skin-manager.lambda-register-skins-4", SKIN_MANAGER, "[404,763],[801,803],[0x40000001,0x4000008E]", context ->
this.replaceGetTexturesWithFakeUserProfile(context, context.findMethod(SKIN_MANAGER, "lambda$registerSkins$4",
"(" + objectDesc(GAME_PROFILE) + "Z" + objectDesc(SKIN_MANAGER_SKIN_TEXTURE_CALLBACK) + ")V")));
// 23w42a ~ 25w33a (1.20.3 ~ 1.21.8)
this.rule("skin-manager.cache-key.v1", SKIN_MANAGER, "[765,772],[0x4000009D,0x40000106]", context ->
this.redirectCacheKeyConstruction(context, context.findMethod(SKIN_MANAGER, "getOrLoad", "(" + objectDesc(GAME_PROFILE) + ")" + objectDesc(COMPLETABLE_FUTURE))));
// 25w34a+ (1.21.9+)
this.rule("skin-manager.cache-key.v2", SKIN_MANAGER, "[773,800],[804,0x40000000],[0x40000107,]", context ->
this.redirectCacheKeyConstruction(context, context.findMethod(SKIN_MANAGER, "get", "(" + objectDesc(GAME_PROFILE) + ")" + objectDesc(COMPLETABLE_FUTURE))));
// 23w31a+ (1.20.2+)
this.rule("skin-manager-1.executor", SKIN_MANAGER_1, "[764,800],[804,0x40000000],[0x40000090,]", context -> {
MethodNode methodNode = context.findMethod(SKIN_MANAGER_1, "load", "(" + objectDesc(SKIN_MANAGER_CACHE_KEY) + ")" + objectDesc(COMPLETABLE_FUTURE));
if (methodNode == null) {
return false;
}
boolean modified = false;
for (AbstractInsnNode instruction : methodNode.instructions.toArray()) {
if (!(instruction instanceof MethodInsnNode)) {
continue;
}
MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
if (COMPLETABLE_FUTURE.equals(methodInsnNode.owner)
&& (("supplyAsync".equals(methodInsnNode.name) && ("(" + objectDesc(SUPPLIER) + objectDesc(EXECUTOR) + ")" + objectDesc(COMPLETABLE_FUTURE)).equals(methodInsnNode.desc))
|| ("thenComposeAsync".equals(methodInsnNode.name) && ("(" + objectDesc(FUNCTION) + objectDesc(EXECUTOR) + ")" + objectDesc(COMPLETABLE_FUTURE)).equals(methodInsnNode.desc)))) {
methodNode.instructions.insertBefore(instruction, new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_MANAGER, "loadProfileTextures", "(" + objectDesc(EXECUTOR) + ")" + objectDesc(EXECUTOR), false));
modified = true;
}
}
return modified;
});
// 23w31a ~ 23w41a (1.20.2)
this.rule("skin-manager-1.lambda-load-0.v1", SKIN_MANAGER_1, "764,[0x40000090,0x4000009C]", context -> {
MethodNode methodNode = context.findMethod(SKIN_MANAGER_1, "lambda$load$0", "(" + objectDesc(MINECRAFT_SESSION_SERVICE) + objectDesc(GAME_PROFILE) + ")" + objectDesc(SKIN_MANAGER_TEXTURE_INFO));
if (methodNode == null) {
return false;
}
boolean modified = false;
for (AbstractInsnNode instruction : methodNode.instructions.toArray()) {
if (!(instruction instanceof MethodInsnNode)) {
continue;
}
MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
if (MINECRAFT_SESSION_SERVICE.equals(methodInsnNode.owner) && "getTextures".equals(methodInsnNode.name)
&& ("(" + objectDesc(GAME_PROFILE) + "Z)" + objectDesc(MAP)).equals(methodInsnNode.desc)) {
this.replaceInstructionSafely(context, methodNode, instruction, new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_MANAGER, "loadSkinFromCache", "(" + objectDesc(OBJECT) + objectDesc(GAME_PROFILE) + "Z)" + objectDesc(MAP), false));
modified = true;
}
}
return modified;
});
// 23w42a ~ 25w33a (1.20.3 ~ 1.21.8)
this.rule("skin-manager-1.lambda-load-0.v2", SKIN_MANAGER_1, "[765,772],[0x4000009D,0x40000106]", context ->
this.replaceUnpackTexturesWithFakeSkinCache(context, context.findMethod(SKIN_MANAGER_1, "lambda$load$0",
"(" + objectDesc(SKIN_MANAGER_CACHE_KEY) + objectDesc(MINECRAFT_SESSION_SERVICE) + ")" + objectDesc(MINECRAFT_PROFILE_TEXTURES)), MINECRAFT_SESSION_SERVICE));
// 25w34a ~ 26.3-snapshot-1 (1.21.9 ~ 26.2)
this.rule("skin-manager-1.lambda-load-0.v3", SKIN_MANAGER_1, "[773,776],[0x40000107,0x40000143]", context ->
this.replaceUnpackTexturesWithFakeSkinCache(context, context.findMethod(SKIN_MANAGER_1, "lambda$load$0",
"(" + objectDesc(SKIN_MANAGER_CACHE_KEY) + objectDesc(SERVICES) + ")" + objectDesc(MINECRAFT_PROFILE_TEXTURES)), MINECRAFT_SESSION_SERVICE));
// 26.3-snapshot-2+ (26.3+)
this.rule("skin-manager-1.lambda-load-0.v4", SKIN_MANAGER_1, "[777,800],[804,0x40000000],[0x40000144,]", context ->
this.replaceUnpackTexturesWithFakeSkinCache(context, context.findMethod(SKIN_MANAGER_1, "lambda$load$0",
"(" + objectDesc(SKIN_MANAGER_CACHE_KEY) + objectDesc(SERVICES) + ")" + objectDesc(MINECRAFT_PROFILE_TEXTURES)), SESSION_SERVICE));
// 1.12.2-
this.rule("skin-manager-3.get-user-profile", SKIN_MANAGER_3, "[,340]", context ->
this.replaceGetTexturesWithFakeUserProfile(context, context.findMethod(SKIN_MANAGER_3, "run", "()V")));
// 23w31a+ (1.20.2+)
this.rule("skin-manager-cache-key.access", SKIN_MANAGER_CACHE_KEY, "[764,800],[804,0x40000000],[0x40000090,]", context -> {
boolean modified = this.makeClassPublicNonFinal(context.getCurrentClassNode());
modified |= this.makeMethodPublicNonFinal(context.findMethod(SKIN_MANAGER_CACHE_KEY, "<init>", "(" + objectDesc(UUID) + objectDesc(PROPERTY) + ")V"));
return modified;
});
// 23w31a ~ 24w45a (1.20.2 ~ 1.21.3)
this.rule("skin-manager-texture-cache.http-texture", SKIN_MANAGER_TEXTURE_CACHE, "[764,768],[0x40000090,0x400000DD]", context -> {
InsnList loadType = new InsnList();
loadType.add(new VarInsnNode(ALOAD, 0));
loadType.add(new FieldInsnNode(GETFIELD, context.remapClassName(SKIN_MANAGER_TEXTURE_CACHE), context.remapFieldName(SKIN_MANAGER_TEXTURE_CACHE, "type"), objectDesc(MINECRAFT_PROFILE_TEXTURE_TYPE)));
return this.redirectHttpTextureConstructorToFake(
context,
context.findMethod(SKIN_MANAGER_TEXTURE_CACHE, "registerTexture", "(" + objectDesc(MINECRAFT_PROFILE_TEXTURE) + ")" + objectDesc(COMPLETABLE_FUTURE)),
context.remapMethodDescriptor("(" + objectDesc(FILE) + objectDesc(STRING) + objectDesc(IDENTIFIER) + "Z" + objectDesc(RUNNABLE) + ")V"),
context.remapMethodDescriptor("(" + objectDesc(FILE) + objectDesc(STRING) + objectDesc(IDENTIFIER) + "Z" + objectDesc(RUNNABLE) + objectDesc(MINECRAFT_PROFILE_TEXTURE) + objectDesc(MINECRAFT_PROFILE_TEXTURE_TYPE) + ")V"),
loadType
);
});
// 24w46a ~ 25w34b (1.21.4 ~ 1.21.8)
this.rule("skin-manager-texture-cache.skin-texture-downloader.v1", SKIN_MANAGER_TEXTURE_CACHE, "[769,772],[0x400000DE,0x40000108]", context ->
this.redirectSkinTextureDownloaderToFake(context, context.findMethod(SKIN_MANAGER_TEXTURE_CACHE, "registerTexture",
"(" + objectDesc(MINECRAFT_PROFILE_TEXTURE) + ")" + objectDesc(COMPLETABLE_FUTURE)), INVOKESTATIC));
// 25w35a+ (1.21.9+)
this.rule("skin-manager-texture-cache.skin-texture-downloader.v2", SKIN_MANAGER_TEXTURE_CACHE, "[773,800],[804,0x40000000],[0x40000109,]", context ->
this.redirectSkinTextureDownloaderToFake(context, context.findMethod(SKIN_MANAGER_TEXTURE_CACHE, "registerTexture",
"(" + objectDesc(MINECRAFT_PROFILE_TEXTURE) + ")" + objectDesc(COMPLETABLE_FUTURE)), INVOKEVIRTUAL));
}
private boolean injectSetSkinCacheDir(ClassTransformationContext context, String constructorDesc, int localIndex, String argumentDesc) {
@@ -118,153 +218,6 @@ public final class SkinManagerPatch extends PatchSupport {
return modified;
}
private boolean patchLegacySkinManager(ClassTransformationContext context) {
boolean modified = false;
modified |= this.requireModified("skin-manager.v1.register-texture", this.patchLegacySkinManagerRegisterTexture(context));
modified |= this.requireModified("skin-manager.v1.register-skins", this.patchLegacySkinManagerRegisterSkins(context));
modified |= this.requireModified("skin-manager.v1.get-insecure-skin-information", this.patchLegacySkinManagerGetInsecureSkinInformation(context));
// 1.13.2 ~ 1.20.1
modified |= this.applyIfMatches("[404,763],[801,803],[0x40000001,0x4000008E]", "skin-manager.v1.lambda-register-skins-4", () -> patchLegacySkinManagerGetUserProfile(context));
return modified;
}
private boolean patchLegacySkinManagerRegisterTexture(ClassTransformationContext context) {
MethodNode registerTexture = context.findMethod(SKIN_MANAGER, "registerTexture", "(" + objectDesc(MINECRAFT_PROFILE_TEXTURE) + objectDesc(MINECRAFT_PROFILE_TEXTURE_TYPE) + objectDesc(SKIN_MANAGER_SKIN_TEXTURE_CALLBACK) + ")" + objectDesc(IDENTIFIER));
if (registerTexture == null) {
return false;
}
InsnList insnList = new InsnList();
insnList.add(new VarInsnNode(ALOAD, 2));
return this.patchCreateThreadDownloadImageData(context, registerTexture, insnList);
}
private boolean patchLegacySkinManagerRegisterSkins(ClassTransformationContext context) {
MethodNode registerSkins = context.findMethod(SKIN_MANAGER, "registerSkins", "(" + objectDesc(GAME_PROFILE) + objectDesc(SKIN_MANAGER_SKIN_TEXTURE_CALLBACK) + "Z)V");
if (registerSkins == null) {
return false;
}
boolean modified = false;
// 19w37a- (1.14.4-)
modified |= this.applyIfMatches("[,553]", "skin-manager.register-skins.v1", () -> replaceExecutorProfileLoadAtInvocation(registerSkins, EXECUTOR_SERVICE, "submit", "(" + objectDesc(RUNNABLE) + ")" + objectDesc(FUTURE), true));
// 19w38a ~ 1.18-exp7 (1.15 ~ 1.17.1)
modified |= this.applyIfMatches("[554,756],[801,803],[0x40000001,0x4000002F]+[2205,2831]", "skin-manager.register-skins.v2", () -> replaceExecutorProfileLoadAtInvocation(registerSkins, EXECUTOR, "execute", "(" + objectDesc(RUNNABLE) + ")V", false));
// 21w37a ~ 1.20.1 (1.18 ~ 1.20.1)
modified |= this.applyIfMatches("[757,763],[0x40000029,0x4000008E]+[2834,3465]", "skin-manager.register-skins.v3", () -> replaceExecutorProfileLoadAtInvocation(registerSkins, EXECUTOR_SERVICE, "execute", "(" + objectDesc(RUNNABLE) + ")V", false));
return modified;
}
private boolean patchLegacySkinManagerGetInsecureSkinInformation(ClassTransformationContext context) {
MethodNode loadSkinFromCache = context.findMethod(SKIN_MANAGER, "getInsecureSkinInformation", "(" + objectDesc(GAME_PROFILE) + ")" + objectDesc(MAP));
if (loadSkinFromCache == null) {
return false;
}
return this.replaceLoadSkinFromCacheMethod(loadSkinFromCache);
}
private boolean patchLegacySkinManagerGetUserProfile(ClassTransformationContext context) {
MethodNode getUserProfile = context.findMethod(SKIN_MANAGER, "lambda$registerSkins$4", "(" + objectDesc(GAME_PROFILE) + "Z" + objectDesc(SKIN_MANAGER_SKIN_TEXTURE_CALLBACK) + ")V");
if (getUserProfile == null) {
return false;
}
return this.replaceGetTexturesWithFakeUserProfile(getUserProfile);
}
private boolean patchSkinManagerCacheKey(ClassTransformationContext context) {
boolean modified = false;
// 23w42a ~ 25w33a (1.20.3 ~ 1.21.8)
modified |= this.applyIfMatches("[765,772],[0x4000009D,0x40000106]", "skin-manager.cache-key.v1", () -> {
MethodNode getOrLoad = context.findMethod(SKIN_MANAGER, "getOrLoad", "(" + objectDesc(GAME_PROFILE) + ")" + objectDesc(COMPLETABLE_FUTURE));
return getOrLoad != null && redirectCacheKeyConstruction(context, getOrLoad);
});
// 25w34a+ (1.21.9+)
modified |= this.applyIfMatches("[773,800],[804,0x40000000],[0x40000107,]", "skin-manager.cache-key.v2", () -> {
MethodNode get = context.findMethod(SKIN_MANAGER, "get", "(" + objectDesc(GAME_PROFILE) + ")" + objectDesc(COMPLETABLE_FUTURE));
return get != null && redirectCacheKeyConstruction(context, get);
});
return modified;
}
private boolean patchSkinManagerLoader(ClassTransformationContext context) {
boolean modified = false;
MethodNode load = context.findMethod(SKIN_MANAGER_1, "load", "(" + objectDesc(SKIN_MANAGER_CACHE_KEY) + ")" + objectDesc(COMPLETABLE_FUTURE));
modified |= this.requireModified("skin-manager-1.executor", load != null && this.replaceCompletableFutureExecutor(load));
modified |= this.patchSkinManagerLoaderLambda(context);
return modified;
}
private boolean patchSkinManagerLoaderLambda(ClassTransformationContext context) {
boolean modified = false;
// 23w31a ~ 23w41a (1.20.2)
modified |= this.applyIfMatches("764,[0x40000090,0x4000009C]", "skin-manager-1.lambda-load-0.v1", () -> {
MethodNode oldLambda = context.findMethod(SKIN_MANAGER_1, "lambda$load$0", "(" + objectDesc(MINECRAFT_SESSION_SERVICE) + objectDesc(GAME_PROFILE) + ")" + objectDesc(SKIN_MANAGER_TEXTURE_INFO));
return oldLambda != null && replaceGetTexturesWithFakeSkinCache(oldLambda);
});
// 23w42a ~ 25w33a (1.20.3 ~ 1.21.8)
modified |= this.applyIfMatches("[765,772],[0x4000009D,0x40000106]", "skin-manager-1.lambda-load-0.v2", () -> {
MethodNode lambdaWithSession = context.findMethod(SKIN_MANAGER_1, "lambda$load$0", "(" + objectDesc(SKIN_MANAGER_CACHE_KEY) + objectDesc(MINECRAFT_SESSION_SERVICE) + ")" + objectDesc(MINECRAFT_PROFILE_TEXTURES));
return lambdaWithSession != null && replaceUnpackTexturesWithFakeSkinCache(context, lambdaWithSession);
});
// 25w34a+ (1.21.9+)
modified |= this.applyIfMatches("[773,800],[804,0x40000000],[0x40000107,]", "skin-manager-1.lambda-load-0.v3", () -> {
MethodNode lambdaWithServices = context.findMethod(SKIN_MANAGER_1, "lambda$load$0", "(" + objectDesc(SKIN_MANAGER_CACHE_KEY) + objectDesc(SERVICES) + ")" + objectDesc(MINECRAFT_PROFILE_TEXTURES));
return lambdaWithServices != null && replaceUnpackTexturesWithFakeSkinCache(context, lambdaWithServices);
});
return modified;
}
private boolean patchSkinManagerTextureCache(ClassTransformationContext context) {
MethodNode registerTexture = context.findMethod(SKIN_MANAGER_TEXTURE_CACHE, "registerTexture", "(" + objectDesc(MINECRAFT_PROFILE_TEXTURE) + ")" + objectDesc(COMPLETABLE_FUTURE));
if (registerTexture == null) {
return false;
}
String fieldName = context.remapFieldName(SKIN_MANAGER_TEXTURE_CACHE, "type");
InsnList loadType = new InsnList();
loadType.add(new VarInsnNode(ALOAD, 0));
loadType.add(new FieldInsnNode(GETFIELD, context.remapClassName(SKIN_MANAGER_TEXTURE_CACHE), fieldName, objectDesc(MINECRAFT_PROFILE_TEXTURE_TYPE)));
boolean modified = false;
// 23w31a ~ 24w45a (1.20.2 ~ 1.21.3)
modified |= this.applyIfMatches("[764,768],[0x40000090,0x400000DD]", "skin-manager-texture-cache.http-texture", () -> redirectHttpTextureConstructorToFake(
context, registerTexture, context.remapMethodDescriptor("(" + objectDesc(FILE) + objectDesc(STRING) + objectDesc(IDENTIFIER) + "Z" + objectDesc(RUNNABLE) + ")V"),
context.remapMethodDescriptor("(" + objectDesc(FILE) + objectDesc(STRING) + objectDesc(IDENTIFIER) + "Z" + objectDesc(RUNNABLE) + objectDesc(MINECRAFT_PROFILE_TEXTURE) + objectDesc(MINECRAFT_PROFILE_TEXTURE_TYPE) + ")V"),
loadType
));
// 24w46a ~ 25w34b (1.21.4 ~ 1.21.8)
modified |= this.applyIfMatches("[769,772],[0x400000DE,0x40000108]", "skin-manager-texture-cache.skin-texture-downloader.v1", () -> redirectSkinTextureDownloaderToFake(
context, registerTexture, INVOKESTATIC
));
// 25w35a+ (1.21.9+)
modified |= this.applyIfMatches("[773,800],[804,0x40000000],[0x40000109,]", "skin-manager-texture-cache.skin-texture-downloader.v2", () -> redirectSkinTextureDownloaderToFake(
context, registerTexture, INVOKEVIRTUAL
));
return modified;
}
private boolean patchCreateThreadDownloadImageData(ClassTransformationContext context, MethodNode methodNode, InsnList loadTextureType) {
boolean modified = false;
// 19w37a- (1.14.4-)
modified |= this.applyIfMatches("[,553]", "skin-manager.http-texture.v1", () -> redirectHttpTextureConstructorToFake(
context, methodNode, context.remapMethodDescriptor("(" + objectDesc(FILE) + objectDesc(STRING) + objectDesc(IDENTIFIER) + objectDesc(HTTP_TEXTURE_PROCESSOR) + ")V"),
context.remapMethodDescriptor("(" + objectDesc(FILE) + objectDesc(STRING) + objectDesc(IDENTIFIER) + objectDesc(HTTP_TEXTURE_PROCESSOR) + objectDesc(MINECRAFT_PROFILE_TEXTURE) + objectDesc(MINECRAFT_PROFILE_TEXTURE_TYPE) + ")V"),
loadTextureType
));
// 19w38a ~ 1.20.1 (1.15 ~ 1.20.1)
modified |= this.applyIfMatches("[554,763],[801,803],[0x40000001,0x4000008E]", "skin-manager.http-texture.v2", () -> redirectHttpTextureConstructorToFake(
context, methodNode, context.remapMethodDescriptor("(" + objectDesc(FILE) + objectDesc(STRING) + objectDesc(IDENTIFIER) + "Z" + objectDesc(RUNNABLE) + ")V"),
context.remapMethodDescriptor("(" + objectDesc(FILE) + objectDesc(STRING) + objectDesc(IDENTIFIER) + "Z" + objectDesc(RUNNABLE) + objectDesc(MINECRAFT_PROFILE_TEXTURE) + objectDesc(MINECRAFT_PROFILE_TEXTURE_TYPE) + ")V"),
loadTextureType
));
return modified;
}
private boolean redirectHttpTextureConstructorToFake(ClassTransformationContext context, MethodNode methodNode, String originalDesc, String replacementDesc, InsnList loadTextureType) {
if (methodNode == null) {
return false;
@@ -341,7 +294,7 @@ public final class SkinManagerPatch extends PatchSupport {
}
injection.add(new VarInsnNode(ALOAD, 1));
methodNode.instructions.insertBefore(methodInsnNode, injection);
methodNodeSet(methodNode, methodInsnNode, new MethodInsnNode(INVOKESTATIC, FAKE_HTTP_TEXTURE_V2, "downloadAndRegisterSkin", replacementDesc, false));
methodNode.instructions.set(methodInsnNode, new MethodInsnNode(INVOKESTATIC, FAKE_HTTP_TEXTURE_V2, "downloadAndRegisterSkin", replacementDesc, false));
modified = true;
}
return modified;
@@ -365,7 +318,11 @@ public final class SkinManagerPatch extends PatchSupport {
return false;
}
private boolean replaceExecutorProfileLoadAtInvocation(MethodNode methodNode, String owner, String name, String desc, boolean pushNullReturn) {
private boolean replaceExecutorProfileLoadAtInvocation(ClassTransformationContext context, MethodNode methodNode, String owner, String name, String desc) {
if (methodNode == null) {
return false;
}
boolean modified = false;
for (AbstractInsnNode instruction : methodNode.instructions.toArray()) {
if (!(instruction instanceof MethodInsnNode)) {
@@ -377,31 +334,21 @@ public final class SkinManagerPatch extends PatchSupport {
continue;
}
InsnList replacement = new InsnList();
replacement.add(new InsnNode(SWAP));
replacement.add(new InsnNode(POP));
replacement.add(new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_MANAGER, "loadProfileTextures", "(" + objectDesc(RUNNABLE) + ")V", false));
if (pushNullReturn) {
replacement.add(new InsnNode(ACONST_NULL));
this.replaceInstructionSafely(context, methodNode, instruction, methodInsnNode = new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_MANAGER, "loadProfileTextures", "(" + objectDesc(OBJECT) + objectDesc(RUNNABLE) + ")V", false));
if (!desc.endsWith("V")) {
methodNode.instructions.insert(methodInsnNode, new InsnNode(ACONST_NULL));
}
methodNode.instructions.insertBefore(instruction, replacement);
methodNode.instructions.remove(instruction);
modified = true;
break;
}
return modified;
}
private boolean replaceLoadSkinFromCacheMethod(MethodNode methodNode) {
methodNode.instructions.clear();
methodNode.tryCatchBlocks.clear();
methodNode.instructions.add(new VarInsnNode(ALOAD, 1));
methodNode.instructions.add(new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_MANAGER, "loadSkinFromCache", "(" + objectDesc(GAME_PROFILE) + ")" + objectDesc(MAP), false));
methodNode.instructions.add(new InsnNode(ARETURN));
methodNode.maxLocals = Math.max(methodNode.maxLocals, 2);
return true;
}
private boolean replaceGetTexturesWithFakeUserProfile(ClassTransformationContext context, MethodNode methodNode) {
if (methodNode == null) {
return false;
}
private boolean replaceGetTexturesWithFakeUserProfile(MethodNode methodNode) {
boolean modified = false;
for (AbstractInsnNode instruction : methodNode.instructions.toArray()) {
if (!(instruction instanceof MethodInsnNode)) {
@@ -413,13 +360,17 @@ public final class SkinManagerPatch extends PatchSupport {
continue;
}
methodNode.instructions.set(instruction, new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_MANAGER, "getUserProfile", "(" + objectDesc(MINECRAFT_SESSION_SERVICE) + objectDesc(GAME_PROFILE) + "Z)" + objectDesc(MAP), false));
this.replaceInstructionSafely(context, methodNode, instruction, new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_MANAGER, "getUserProfile", "(" + objectDesc(OBJECT) + objectDesc(GAME_PROFILE) + "Z)" + objectDesc(MAP), false));
modified = true;
}
return modified;
}
private boolean redirectCacheKeyConstruction(ClassTransformationContext context, MethodNode methodNode) {
if (methodNode == null) {
return false;
}
boolean modified = false;
String owner = context.remapClassName(SKIN_MANAGER_CACHE_KEY);
String desc = context.remapMethodDescriptor("(" + objectDesc(UUID) + objectDesc(PROPERTY) + ")V");
@@ -455,49 +406,13 @@ public final class SkinManagerPatch extends PatchSupport {
return modified;
}
private boolean replaceCompletableFutureExecutor(MethodNode methodNode) {
boolean modified = false;
for (AbstractInsnNode instruction : methodNode.instructions.toArray()) {
if (!(instruction instanceof MethodInsnNode)) {
continue;
}
MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
if (!COMPLETABLE_FUTURE.equals(methodInsnNode.owner)) {
continue;
}
if (("supplyAsync".equals(methodInsnNode.name) && ("(" + objectDesc(SUPPLIER) + objectDesc(EXECUTOR) + ")" + objectDesc(COMPLETABLE_FUTURE)).equals(methodInsnNode.desc))
|| ("thenComposeAsync".equals(methodInsnNode.name) && ("(" + objectDesc(FUNCTION) + objectDesc(EXECUTOR) + ")" + objectDesc(COMPLETABLE_FUTURE)).equals(methodInsnNode.desc))) {
InsnList replacement = new InsnList();
replacement.add(new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_MANAGER, "loadProfileTextures", "(" + objectDesc(EXECUTOR) + ")" + objectDesc(EXECUTOR), false));
methodNode.instructions.insertBefore(instruction, replacement);
modified = true;
}
private boolean replaceUnpackTexturesWithFakeSkinCache(ClassTransformationContext context, MethodNode methodNode, String owner) {
if (methodNode == null) {
return false;
}
return modified;
}
private boolean replaceGetTexturesWithFakeSkinCache(MethodNode methodNode) {
boolean modified = false;
for (AbstractInsnNode instruction : methodNode.instructions.toArray()) {
if (!(instruction instanceof MethodInsnNode)) {
continue;
}
MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
if (!MINECRAFT_SESSION_SERVICE.equals(methodInsnNode.owner) || !"getTextures".equals(methodInsnNode.name) || !("(" + objectDesc(GAME_PROFILE) + "Z)" + objectDesc(MAP)).equals(methodInsnNode.desc)) {
continue;
}
methodNode.instructions.set(instruction, new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_MANAGER, "loadSkinFromCache", "(" + objectDesc(MINECRAFT_SESSION_SERVICE) + objectDesc(GAME_PROFILE) + "Z)" + objectDesc(MAP), false));
modified = true;
}
return modified;
}
private boolean replaceUnpackTexturesWithFakeSkinCache(ClassTransformationContext context, MethodNode methodNode) {
boolean modified = false;
String desc = context.remapMethodDescriptor("(" + objectDesc(MINECRAFT_SESSION_SERVICE) + objectDesc(PROPERTY) + objectDesc(SKIN_MANAGER_CACHE_KEY) + ")" + objectDesc(OBJECT));
String desc = context.remapMethodDescriptor("(" + objectDesc(OBJECT) + objectDesc(SKIN_MANAGER_CACHE_KEY) + ")" + objectDesc(OBJECT));
String returnType = context.remapClassName(MINECRAFT_PROFILE_TEXTURES);
for (AbstractInsnNode instruction : methodNode.instructions.toArray()) {
@@ -506,16 +421,15 @@ public final class SkinManagerPatch extends PatchSupport {
}
MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
if (!MINECRAFT_SESSION_SERVICE.equals(methodInsnNode.owner) || !"unpackTextures".equals(methodInsnNode.name) || !("(" + objectDesc(PROPERTY) + ")" + objectDesc(MINECRAFT_PROFILE_TEXTURES)).equals(methodInsnNode.desc)) {
if (!owner.equals(methodInsnNode.owner) || !"unpackTextures".equals(methodInsnNode.name) || !("(" + objectDesc(PROPERTY) + ")" + objectDesc(MINECRAFT_PROFILE_TEXTURES)).equals(methodInsnNode.desc)) {
continue;
}
InsnList replacement = new InsnList();
replacement.add(new VarInsnNode(ALOAD, 0));
replacement.add(new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_MANAGER, "loadSkinFromCache", desc, false));
replacement.add(new TypeInsnNode(CHECKCAST, returnType));
methodNode.instructions.insertBefore(instruction, replacement);
methodNode.instructions.remove(instruction);
InsnList insnList = new InsnList();
insnList.add(new VarInsnNode(ALOAD, 0));
insnList.add(new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_MANAGER, "loadSkinFromCache", desc, false));
insnList.add(new TypeInsnNode(CHECKCAST, returnType));
methodNode.instructions.insert(instruction, insnList);
modified = true;
}
return modified;
@@ -1,101 +1,107 @@
package customskinloader.bootstrap.transformer.patch;
import customskinloader.bootstrap.transformer.ClassTransformationContext;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
public final class SkinTexturePatch extends PatchSupport {
public SkinTexturePatch() {
super(
"customskinloader:skin-texture-patch", 1000,
targets(
HTTP_TEXTURE, "[,768],[801,803],[0x40000001,0x400000DD]", // 24w45a- (1.21.3-)
SKIN_TEXTURE_DOWNLOADER, "[769,800],[804,0x40000000],[0x400000DE,]" // 24w46a+ (1.21.4+)
)
);
}
super("customskinloader:skin-texture-patch", 1000);
@Override
public boolean transform(ClassTransformationContext context) {
boolean modified = false;
// 24w45a- (1.21.3-)
this.rule("http-texture.uploaded", HTTP_TEXTURE, "[,768],[801,803],[0x40000001,0x400000DD]", context ->
this.makeFieldPublicNonFinal(context.findField(HTTP_TEXTURE, "uploaded")));
if (context.isTarget(HTTP_TEXTURE)) {
// 24w45a- (1.21.3-)
modified |= this.applyIfMatches("[,768],[801,803],[0x40000001,0x400000DD]", "http-texture.uploaded", () -> this.makeFieldPublicNonFinal(context.findField(HTTP_TEXTURE, "uploaded")));
// 19w38a ~ 24w45a (1.15 ~ 1.21.3)
modified |= this.applyIfMatches("[554,768],[801,803],[0x40000001,0x400000DD]", "http-texture.patch", () -> this.patchHttpTexture(context));
}
if (context.isTarget(SKIN_TEXTURE_DOWNLOADER)) {
modified |= this.requireModified("skin-texture-downloader.patch", this.patchSkinTextureDownloader(context));
}
// 19w38a ~ 24w45a (1.15 ~ 1.21.3)
this.rule("http-texture.process-legacy-skin", HTTP_TEXTURE, "[554,768],[801,803],[0x40000001,0x400000DD]", context -> {
MethodNode load = context.findMethod(HTTP_TEXTURE, "load", "(" + objectDesc(INPUT_STREAM) + ")" + objectDesc(NATIVE_IMAGE));
if (load == null) {
return false;
}
return modified;
}
boolean modified = false;
String owner = context.remapClassName(HTTP_TEXTURE);
String originalName = context.remapMethodName(HTTP_TEXTURE, "processLegacySkin", "(" + objectDesc(NATIVE_IMAGE) + ")" + objectDesc(NATIVE_IMAGE));
String imageDesc = context.remapMethodDescriptor("(" + objectDesc(NATIVE_IMAGE) + ")" + objectDesc(NATIVE_IMAGE));
String conditionDesc = context.remapMethodDescriptor("(" + objectDesc(RUNNABLE) + ")Z");
String replacementDesc = context.remapMethodDescriptor("(" + objectDesc(NATIVE_IMAGE) + objectDesc(RUNNABLE) + ")" + objectDesc(NATIVE_IMAGE));
String processTaskField = context.remapFieldName(HTTP_TEXTURE, "onDownloaded");
for (AbstractInsnNode instruction : load.instructions.toArray()) {
if (!(instruction instanceof MethodInsnNode)) {
continue;
}
private boolean patchHttpTexture(ClassTransformationContext context) {
return this.replaceHttpTextureProcessLegacySkin(
context, context.findMethod(HTTP_TEXTURE, "load", "(" + objectDesc(INPUT_STREAM) + ")" + objectDesc(NATIVE_IMAGE))
);
}
MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
if (!owner.equals(methodInsnNode.owner) || !originalName.equals(methodInsnNode.name) || !imageDesc.equals(methodInsnNode.desc)) {
continue;
}
load.instructions.insertBefore(instruction, new VarInsnNode(ALOAD, 0));
load.instructions.insertBefore(instruction, new FieldInsnNode(GETFIELD, owner, processTaskField, objectDesc(RUNNABLE)));
MethodInsnNode processLegacySkin = new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_BUFFER, "processLegacySkin", replacementDesc, false);
this.replaceInstructionSafely(context, load, new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_BUFFER, "shouldProcessLegacySkin", conditionDesc, false), IFNE, instruction, processLegacySkin);
InsnList injection = new InsnList();
if (methodInsnNode.getOpcode() == INVOKESTATIC) {
injection.add(new VarInsnNode(ALOAD, 0));
} else {
injection.add(new InsnNode(SWAP));
}
injection.add(new FieldInsnNode(GETFIELD, owner, processTaskField, objectDesc(RUNNABLE)));
load.instructions.insertBefore(processLegacySkin, injection);
modified = true;
}
return modified;
});
private boolean patchSkinTextureDownloader(ClassTransformationContext context) {
boolean modified = false;
modified |= this.requireModified("skin-texture-downloader.then-compose", this.replaceThenComposeTextureFunction(
context, context.findMethod(SKIN_TEXTURE_DOWNLOADER, "downloadAndRegisterSkin", "(" + objectDesc(IDENTIFIER) + objectDesc(PATH) + objectDesc(STRING) + "Z)" + objectDesc(COMPLETABLE_FUTURE))
));
// 24w46a+ (1.21.4+)
modified |= this.applyIfMatches("[769,800],[804,0x40000000],[0x400000DE,]", "skin-texture-downloader.process-legacy-skin", () -> replaceSkinTextureDownloaderProcessLegacySkin(context));
return modified;
}
private boolean replaceThenComposeTextureFunction(ClassTransformationContext context, MethodNode methodNode) {
if (methodNode == null) {
return false;
}
boolean modified = false;
int locationLocal = (methodNode.access & ACC_STATIC) == 0 ? 1 : 0;
int booleanLocal = locationLocal + 3;
String remappedHookDesc = context.remapMethodDescriptor("(" + objectDesc(FUNCTION) + objectDesc(IDENTIFIER) + "Z)" + objectDesc(FUNCTION));
for (AbstractInsnNode instruction : methodNode.instructions.toArray()) {
if (!(instruction instanceof MethodInsnNode)) {
continue;
this.rule("skin-texture-downloader.then-compose", SKIN_TEXTURE_DOWNLOADER, "[769,800],[804,0x40000000],[0x400000DE,]", context -> {
MethodNode methodNode = context.findMethod(SKIN_TEXTURE_DOWNLOADER, "downloadAndRegisterSkin",
"(" + objectDesc(IDENTIFIER) + objectDesc(PATH) + objectDesc(STRING) + "Z)" + objectDesc(COMPLETABLE_FUTURE));
if (methodNode == null) {
return false;
}
MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
if (!COMPLETABLE_FUTURE.equals(methodInsnNode.owner) || !"thenCompose".equals(methodInsnNode.name) || !("(" + objectDesc(FUNCTION) + ")" + objectDesc(COMPLETABLE_FUTURE)).equals(methodInsnNode.desc)) {
continue;
boolean modified = false;
int locationLocal = (methodNode.access & ACC_STATIC) == 0 ? 1 : 0;
int booleanLocal = locationLocal + 3;
String remappedHookDesc = context.remapMethodDescriptor("(" + objectDesc(FUNCTION) + objectDesc(IDENTIFIER) + "Z)" + objectDesc(FUNCTION));
for (AbstractInsnNode instruction : methodNode.instructions.toArray()) {
if (!(instruction instanceof MethodInsnNode)) {
continue;
}
MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
if (!COMPLETABLE_FUTURE.equals(methodInsnNode.owner) || !"thenCompose".equals(methodInsnNode.name)
|| !("(" + objectDesc(FUNCTION) + ")" + objectDesc(COMPLETABLE_FUTURE)).equals(methodInsnNode.desc)) {
continue;
}
InsnList injection = new InsnList();
injection.add(new VarInsnNode(ALOAD, locationLocal));
injection.add(new VarInsnNode(ILOAD, booleanLocal));
injection.add(new MethodInsnNode(INVOKESTATIC, FAKE_HTTP_TEXTURE_V2, "createTexture", remappedHookDesc, false));
methodNode.instructions.insertBefore(instruction, injection);
modified = true;
}
return modified;
});
InsnList injection = new InsnList();
injection.add(new VarInsnNode(ALOAD, locationLocal));
injection.add(new VarInsnNode(ILOAD, booleanLocal));
injection.add(new MethodInsnNode(INVOKESTATIC, FAKE_HTTP_TEXTURE_V2, "createTexture", remappedHookDesc, false));
methodNode.instructions.insertBefore(instruction, injection);
modified = true;
}
return modified;
}
private boolean replaceSkinTextureDownloaderProcessLegacySkin(ClassTransformationContext context) {
boolean modified = false;
// 24w46a ~ 25w37a (1.21.4 ~ 1.21.8)
modified |= this.applyIfMatches("[769,772],[0x400000DE,0x4000010C]", "skin-texture-downloader.process-legacy-skin.v1", () -> replaceSkinTextureDownloaderProcessLegacySkin(
context, context.findMethod(SKIN_TEXTURE_DOWNLOADER, "lambda$downloadAndRegisterSkin$0", "(" + objectDesc(PATH) + objectDesc(STRING) + "Z)" + objectDesc(NATIVE_IMAGE))
));
this.rule("skin-texture-downloader.process-legacy-skin.v1", SKIN_TEXTURE_DOWNLOADER, "[769,772],[0x400000DE,0x4000010C]", context ->
this.replaceSkinTextureDownloaderProcessLegacySkin(
context, context.findMethod(SKIN_TEXTURE_DOWNLOADER, "lambda$downloadAndRegisterSkin$0",
"(" + objectDesc(PATH) + objectDesc(STRING) + "Z)" + objectDesc(NATIVE_IMAGE))));
// 1.21.9-pre1+ (1.21.9+)
modified |= this.applyIfMatches("[773,800],[804,0x40000000],[0x4000010D,]", "skin-texture-downloader.process-legacy-skin.v2", () -> replaceSkinTextureDownloaderProcessLegacySkin(
context, context.findMethod(SKIN_TEXTURE_DOWNLOADER, "lambda$downloadAndRegisterSkin$0", "(" + objectDesc(PATH) + objectDesc(CLIENT_ASSET_DOWNLOADED_TEXTURE) + "Z)" + objectDesc(NATIVE_IMAGE))
));
return modified;
this.rule("skin-texture-downloader.process-legacy-skin.v2", SKIN_TEXTURE_DOWNLOADER, "[773,800],[804,0x40000000],[0x4000010D,]", context ->
this.replaceSkinTextureDownloaderProcessLegacySkin(
context, context.findMethod(SKIN_TEXTURE_DOWNLOADER, "lambda$downloadAndRegisterSkin$0",
"(" + objectDesc(PATH) + objectDesc(CLIENT_ASSET_DOWNLOADED_TEXTURE) + "Z)" + objectDesc(NATIVE_IMAGE))));
}
private boolean replaceSkinTextureDownloaderProcessLegacySkin(ClassTransformationContext context, MethodNode methodNode) {
@@ -113,64 +119,10 @@ public final class SkinTexturePatch extends PatchSupport {
}
MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
if (methodInsnNode.getOpcode() != INVOKESTATIC || !owner.equals(methodInsnNode.owner) || !originalName.equals(methodInsnNode.name) || !originalDesc.equals(methodInsnNode.desc)) {
continue;
if (methodInsnNode.getOpcode() == INVOKESTATIC && owner.equals(methodInsnNode.owner) && originalName.equals(methodInsnNode.name) && originalDesc.equals(methodInsnNode.desc)) {
this.replaceInstructionSafely(context, methodNode, instruction, new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_BUFFER, "processLegacySkin", originalDesc, false));
modified = true;
}
methodNodeSet(methodNode, instruction, new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_BUFFER, "processLegacySkin", originalDesc, false));
modified = true;
}
return modified;
}
private boolean replaceHttpTextureProcessLegacySkin(ClassTransformationContext context, MethodNode load) {
if (load == null) {
return false;
}
boolean modified = false;
String owner = context.remapClassName(HTTP_TEXTURE);
String originalName = context.remapMethodName(HTTP_TEXTURE, "processLegacySkin", "(" + objectDesc(NATIVE_IMAGE) + ")" + objectDesc(NATIVE_IMAGE));
String imageDesc = context.remapMethodDescriptor("(" + objectDesc(NATIVE_IMAGE) + ")" + objectDesc(NATIVE_IMAGE));
String replacementDesc = context.remapMethodDescriptor("(" + objectDesc(NATIVE_IMAGE) + objectDesc(RUNNABLE) + objectDesc(FUNCTION) + ")" + objectDesc(NATIVE_IMAGE));
String processTaskField = context.remapFieldName(HTTP_TEXTURE, "onDownloaded");
for (AbstractInsnNode instruction : load.instructions.toArray()) {
if (!(instruction instanceof MethodInsnNode)) {
continue;
}
MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
if (!owner.equals(methodInsnNode.owner) || !originalName.equals(methodInsnNode.name) || !imageDesc.equals(methodInsnNode.desc)) {
continue;
}
boolean staticProcessLegacySkin = methodInsnNode.getOpcode() == INVOKESTATIC;
InsnList injection = new InsnList();
int implementationHandleTag;
String functionFactoryDesc;
if (staticProcessLegacySkin) {
injection.add(new VarInsnNode(ALOAD, 0));
injection.add(new FieldInsnNode(GETFIELD, owner, processTaskField, objectDesc(RUNNABLE)));
implementationHandleTag = H_INVOKESTATIC;
functionFactoryDesc = "()" + objectDesc(FUNCTION);
} else {
injection.add(new InsnNode(SWAP));
injection.add(new FieldInsnNode(GETFIELD, owner, processTaskField, objectDesc(RUNNABLE)));
injection.add(new VarInsnNode(ALOAD, 0));
implementationHandleTag = H_INVOKEVIRTUAL;
functionFactoryDesc = "(" + objectDesc(owner) + ")" + objectDesc(FUNCTION);
}
injection.add(new InvokeDynamicInsnNode(
"apply", functionFactoryDesc,
new Handle(H_INVOKESTATIC, LAMBDA_METAFACTORY, "metafactory", "(" + objectDesc(METHOD_HANDLES_LOOKUP) + objectDesc(STRING) + objectDesc(METHOD_TYPE) + objectDesc(METHOD_TYPE) + objectDesc(METHOD_HANDLE) + objectDesc(METHOD_TYPE) + ")" + objectDesc(CALL_SITE), false),
Type.getType("(" + objectDesc(OBJECT) + ")" + objectDesc(OBJECT)),
new Handle(implementationHandleTag, owner, originalName, imageDesc, false),
Type.getType(imageDesc)
));
load.instructions.insertBefore(instruction, injection);
methodNodeSet(load, instruction, new MethodInsnNode(INVOKESTATIC, FAKE_SKIN_BUFFER, "processLegacySkin", replacementDesc, false));
modified = true;
}
return modified;
}
@@ -0,0 +1,51 @@
package customskinloader.bootstrap.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
public class ReflectionUtils {
private static final Map<String, Class<?>> CLASSES = new ConcurrentHashMap<>();
private static final Map<Pair<Class<?>, String>, Field> FIELDS = new ConcurrentHashMap<>();
private static final Map<Triple<Class<?>, String, List<Class<?>>>, Method> METHODS = new ConcurrentHashMap<>();
public static Class<?> findClass(String className) {
return CLASSES.computeIfAbsent(className, k -> {
try {
return Class.forName(k);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
});
}
public static Field findField(Class<?> clazz, String fieldName) {
return FIELDS.computeIfAbsent(Pair.of(clazz, fieldName), k -> {
try {
Field f = k.getLeft().getDeclaredField(k.getRight());
f.setAccessible(true);
return f;
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
});
}
public static Method findMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
return METHODS.computeIfAbsent(Triple.of(clazz, methodName, Arrays.asList(parameterTypes)), k -> {
try {
Method m = k.getLeft().getDeclaredMethod(k.getMiddle(), k.getRight().toArray(new Class<?>[0]));
m.setAccessible(true);
return m;
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
});
}
}
@@ -9,8 +9,11 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
public final class MixinConfigPlugin implements IMixinConfigPlugin {
private String mixinPackage;
@Override
public void onLoad(String mixinPackage) {
this.mixinPackage = mixinPackage + ".";
TransformerBootstrap.initialize();
}
@@ -27,7 +30,7 @@ public final class MixinConfigPlugin implements IMixinConfigPlugin {
@Override
public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) {
// This is the last stable point before postInitialise/validation, so reflected target injection is still visible downstream.
TransformerBootstrap.applyPendingMixinTargets(this);
TransformerBootstrap.applyMixinTargets(this.mixinPackage);
}
@Override
@@ -37,11 +40,11 @@ public final class MixinConfigPlugin implements IMixinConfigPlugin {
@Override
public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
TransformerBootstrap.transformTargetClass(targetClassName, targetClass);
}
@Override
public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
TransformerBootstrap.transformTargetClass(targetClassName, targetClass);
}
}
@@ -4,21 +4,21 @@ import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import customskinloader.bootstrap.BootstrapLogger;
import customskinloader.bootstrap.ModLoaderInfo;
import customskinloader.bootstrap.installer.CommonJarInstaller;
import customskinloader.bootstrap.transformer.ClassTransformationReport;
import customskinloader.bootstrap.transformer.TransformerBootstrapSupport;
import customskinloader.bootstrap.util.ReflectionUtils;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.impl.launch.FabricLauncherBase;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.extensibility.IMixinConfig;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.transformer.ClassInfo;
import org.spongepowered.asm.mixin.transformer.Config;
@@ -26,8 +26,6 @@ import org.spongepowered.asm.mixin.transformer.Config;
final class TransformerBootstrap {
private static final Logger LOGGER = BootstrapLogger.LOGGER;
private static final TransformerBootstrapSupport SUPPORT = new TransformerBootstrapSupport(TransformerBootstrap.class, "intermediary");
private static final Object LOCK = new Object();
private static final List<PendingMixinTarget> PENDING_MIXIN_TARGETS = new ArrayList<>();
private static final String DUMMY_MIXIN = "customskinloader.bootstrap.fabric.v1.mixin.DummyMixin";
private TransformerBootstrap() {
@@ -35,16 +33,8 @@ final class TransformerBootstrap {
public static void initialize() {
LOGGER.info("Initializing CustomSkinLoader Bootstrap for Fabric");
releaseRuntimeArtifacts();
int targetCount = 0;
for (String targetClassName : SUPPORT.collectTargetClassNames()) {
registerMixinTarget(DUMMY_MIXIN, targetClassName.replace('/', '.'));
targetCount++;
}
LOGGER.info("Initialized CustomSkinLoader Bootstrap for Fabric with " + targetCount + " reflected Mixin target(s)");
}
ModLoaderInfo.publish("Fabric", FabricLoader.getInstance().getModContainer("fabricloader").map(m -> m.getMetadata().getVersion().getFriendlyString()).orElse("unknown"));
private static void releaseRuntimeArtifacts() {
try {
Path commonJar = CommonJarInstaller.releaseCommonJar(FabricLoader.getInstance().getGameDir(), "intermediary");
FabricLauncherBase.getLauncher().addToClassPath(commonJar, "customskinloader.");
@@ -55,133 +45,88 @@ final class TransformerBootstrap {
}
}
public static void registerMixinTarget(String mixinClassName, String targetClassName) {
synchronized (LOCK) {
PENDING_MIXIN_TARGETS.add(new PendingMixinTarget(mixinClassName, targetClassName));
LOGGER.debug("Queued Fabric Mixin target " + targetClassName + " for " + mixinClassName);
}
}
public static void applyPendingMixinTargets(IMixinConfigPlugin plugin) {
synchronized (LOCK) {
if (PENDING_MIXIN_TARGETS.isEmpty()) {
return;
}
try {
IMixinConfig mixinConfig = findOwningMixinConfig(plugin);
int appliedTargetCount = 0;
Iterator<PendingMixinTarget> iterator = PENDING_MIXIN_TARGETS.iterator();
while (iterator.hasNext()) {
PendingMixinTarget pendingTarget = iterator.next();
applyMixinTarget(mixinConfig, pendingTarget.mixinClassName, pendingTarget.targetClassName);
iterator.remove();
appliedTargetCount++;
@SuppressWarnings("unchecked")
public static void applyMixinTargets(String mixinPackage) {
try {
IMixinConfig mixinConfig = null;
Field allConfigsField = ReflectionUtils.findField(Config.class, "allConfigs");
for (Object configHandle : ((Map<?, ?>) allConfigsField.get(null)).values()) {
IMixinConfig mixinConfig0 = ((Config) configHandle).getConfig();
if (mixinPackage.equals(mixinConfig0.getMixinPackage())) {
mixinConfig = mixinConfig0;
break;
}
LOGGER.info("Applied " + appliedTargetCount + " reflected Fabric Mixin target(s)");
} catch (ReflectiveOperationException exception) {
LOGGER.error("Failed to append reflected targets to the current Fabric mixin config", exception);
throw new IllegalStateException("Failed to append reflected targets to the current Fabric mixin config", exception);
}
if (mixinConfig == null) {
throw new IllegalStateException("Could not find the owning MixinConfig for " + mixinPackage);
}
int appliedTargetCount = 0;
Class<?> mixinConfigClass = ReflectionUtils.findClass("org.spongepowered.asm.mixin.transformer.MixinConfig");
Class<?> mixinInfoClass = ReflectionUtils.findClass("org.spongepowered.asm.mixin.transformer.MixinInfo");
Field mixinsField = ReflectionUtils.findField(mixinConfigClass, "mixins");
Field targetClassNamesField = ReflectionUtils.findField(mixinInfoClass, "targetClassNames");
Field targetClassesField = ReflectionUtils.findField(mixinInfoClass, "targetClasses");
Field mixinMappingField = ReflectionUtils.findField(mixinConfigClass, "mixinMapping");
Field unhandledTargetsField = ReflectionUtils.findField(mixinConfigClass, "unhandledTargets");
Method addMixinMethod = ReflectionUtils.findMethod(ClassInfo.class, "addMixin", mixinInfoClass);
for (String targetClassName : SUPPORT.getTargetClassNames()) {
boolean applied = false;
for (Object mixinInfo : (List<?>) mixinsField.get(mixinConfig)) {
String currentMixinName = ((IMixinInfo) mixinInfo).getClassName();
if (DUMMY_MIXIN.equals(currentMixinName)) {
String targetBinaryName = targetClassName.replace('/', '.');
String targetInternalName = targetClassName.replace('.', '/');
List<String> targetClassNames = (List<String>) targetClassNamesField.get(mixinInfo);
if (targetClassNames.contains(targetInternalName)) {
applied = true;
break;
}
ClassInfo targetClassInfo = ClassInfo.forName(targetInternalName);
if (targetClassInfo == null) {
throw new IllegalStateException("Could not resolve target ClassInfo for " + targetInternalName);
}
addMixinMethod.invoke(targetClassInfo, mixinInfo);
List<ClassInfo> targetClasses = (List<ClassInfo>) targetClassesField.get(mixinInfo);
targetClasses.add(targetClassInfo);
targetClassNames.add(targetInternalName);
Map<String, List<Object>> mixinMapping = (Map<String, List<Object>>) mixinMappingField.get(mixinConfig);
List<Object> mappedMixins = mixinMapping.computeIfAbsent(targetBinaryName, k -> new ArrayList<>());
if (!mappedMixins.contains(mixinInfo)) {
mappedMixins.add(mixinInfo);
}
((Set<String>) unhandledTargetsField.get(mixinConfig)).add(targetBinaryName);
applied = true;
break;
}
}
if (!applied) {
throw new IllegalStateException("Could not find mixin " + DUMMY_MIXIN + " in the current config");
}
LOGGER.debug("Applied Fabric Mixin target " + targetClassName);
appliedTargetCount++;
}
LOGGER.info("Applied " + appliedTargetCount + " reflected Fabric Mixin target(s)");
} catch (ReflectiveOperationException exception) {
LOGGER.error("Failed to append reflected targets to the current Fabric mixin config", exception);
throw new IllegalStateException("Failed to append reflected targets to the current Fabric mixin config", exception);
}
}
public static void transformTargetClass(String targetClassName, ClassNode targetClass) {
ClassTransformationReport report = SUPPORT.transformClassNode(targetClassName, targetClass);
ClassNode transformedNode = report.getTransformedClassNode();
if (transformedNode != targetClass) {
TransformerBootstrapSupport.copyClassNode(transformedNode, targetClass);
}
ClassTransformationReport report = SUPPORT.transform(targetClassName, targetClass);
if (report.isModified()) {
LOGGER.info("Transformed Fabric target " + targetClassName + " with " + report.getAppliedTransformerNames());
}
}
private static IMixinConfig findOwningMixinConfig(IMixinConfigPlugin plugin) throws ReflectiveOperationException {
Field allConfigsField = Config.class.getDeclaredField("allConfigs");
allConfigsField.setAccessible(true);
for (Object configHandle : ((Map<?, ?>) allConfigsField.get(null)).values()) {
IMixinConfig mixinConfig = ((Config) configHandle).getConfig();
if (mixinConfig.getPlugin() == plugin) {
return mixinConfig;
}
}
throw new IllegalStateException("Could not find the owning MixinConfig for " + plugin.getClass().getName());
}
@SuppressWarnings("unchecked")
private static void applyMixinTarget(IMixinConfig mixinConfig, String mixinClassName, String targetClassName) throws ReflectiveOperationException {
IMixinInfo mixinInfo = findMixinInfo(mixinConfig, mixinClassName);
String targetBinaryName = targetClassName.replace('/', '.');
String targetInternalName = targetClassName.replace('.', '/');
List<String> targetClassNames = (List<String>) getField(mixinInfo, "targetClassNames");
if (targetClassNames.contains(targetInternalName)) {
return;
}
ClassInfo targetClassInfo = ClassInfo.forName(targetInternalName);
if (targetClassInfo == null) {
throw new IllegalStateException("Could not resolve target ClassInfo for " + targetInternalName);
}
Method addMixin = ClassInfo.class.getDeclaredMethod("addMixin", Class.forName("org.spongepowered.asm.mixin.transformer.MixinInfo"));
addMixin.setAccessible(true);
addMixin.invoke(targetClassInfo, mixinInfo);
List<ClassInfo> targetClasses = (List<ClassInfo>) getField(mixinInfo, "targetClasses");
targetClasses.add(targetClassInfo);
targetClassNames.add(targetInternalName);
Map<String, List<Object>> mixinMapping = (Map<String, List<Object>>) getField(mixinConfig, "mixinMapping");
List<Object> mappedMixins = mixinMapping.computeIfAbsent(targetBinaryName, k -> new ArrayList<>());
if (!mappedMixins.contains(mixinInfo)) {
mappedMixins.add(mixinInfo);
}
((Set<String>) getField(mixinConfig, "unhandledTargets")).add(targetBinaryName);
}
@SuppressWarnings("unchecked")
private static IMixinInfo findMixinInfo(IMixinConfig mixinConfig, String mixinClassName) throws ReflectiveOperationException {
for (IMixinInfo mixinInfo : (List<IMixinInfo>) getField(mixinConfig, "mixins")) {
String currentMixinName = mixinInfo.getClassName();
if (mixinClassName.equals(currentMixinName)) {
return mixinInfo;
}
}
throw new IllegalStateException("Could not find mixin " + mixinClassName + " in the current config");
}
private static Object getField(Object instance, String fieldName) throws ReflectiveOperationException {
Field field = findField(instance.getClass(), fieldName);
field.setAccessible(true);
return field.get(instance);
}
private static Field findField(Class<?> type, String fieldName) throws NoSuchFieldException {
Class<?> currentType = type;
while (currentType != null) {
try {
return currentType.getDeclaredField(fieldName);
} catch (NoSuchFieldException exception) {
currentType = currentType.getSuperclass();
}
}
throw new NoSuchFieldException(fieldName);
}
private static final class PendingMixinTarget {
private final String mixinClassName;
private final String targetClassName;
private PendingMixinTarget(String mixinClassName, String targetClassName) {
this.mixinClassName = mixinClassName;
this.targetClassName = targetClassName;
LOGGER.info("Transformed Fabric target " + targetClassName + " with " + report.getAppliedRuleNames());
}
}
}
@@ -6,12 +6,13 @@ import java.nio.file.Paths;
import java.util.Map;
import customskinloader.bootstrap.BootstrapLogger;
import customskinloader.bootstrap.ModLoaderInfo;
import customskinloader.bootstrap.installer.CommonJarInstaller;
import customskinloader.bootstrap.transformer.ClassTransformationReport;
import customskinloader.bootstrap.transformer.TransformerBootstrapSupport;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.relauncher.FMLInjectionData;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.tree.ClassNode;
final class TransformerBootstrap {
private static final Logger LOGGER = BootstrapLogger.LOGGER;
@@ -22,6 +23,9 @@ final class TransformerBootstrap {
public static void injectData(Map<String, Object> data) {
try {
Object[] version = FMLInjectionData.data();
ModLoaderInfo.publish("Forge", version[0] + "." + version[1] + "." + version[2] + "." + version[3]);
Path runtimeDirectory = resolveRuntimeDirectory(data);
LOGGER.info("Initializing CustomSkinLoader Bootstrap for Forge v1 in " + BootstrapLogger.formatPath(runtimeDirectory));
Path commonJar = CommonJarInstaller.releaseCommonJar(runtimeDirectory, "srg");
@@ -34,16 +38,9 @@ final class TransformerBootstrap {
}
public static byte[] transform(String className, byte[] classBytecode) {
SUPPORT.ensureTransformersLoaded();
if (!SUPPORT.hasApplicableTransformers(className)) {
return classBytecode;
}
ClassNode classNode = TransformerBootstrapSupport.toClassNode(classBytecode);
ClassTransformationReport report = SUPPORT.transformClassNode(className, classNode);
ClassTransformationReport report = SUPPORT.transform(className, classBytecode);
if (report.isModified()) {
LOGGER.info("Transformed Forge v1 target " + className + " with " + report.getAppliedTransformerNames());
LOGGER.info("Transformed Forge v1 target " + className + " with " + report.getAppliedRuleNames());
}
return report.isModified() ? report.getTransformedBytecode() : classBytecode;
}
@@ -1,10 +1,9 @@
package customskinloader.bootstrap.forge.v2;
import customskinloader.bootstrap.util.ModLocatorUtils;
import net.minecraftforge.fml.loading.FMLPaths;
import net.minecraftforge.fml.loading.moddiscovery.ModsFolderLocator;
import customskinloader.bootstrap.util.ModLocatorUtils;
public final class CommonModLocator extends ModsFolderLocator {
public CommonModLocator() {
ModLocatorUtils.initialize(this, ModsFolderLocator.class, FMLPaths.GAMEDIR.get(), "srg");
@@ -3,6 +3,7 @@ package customskinloader.bootstrap.forge.v2;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@@ -24,6 +25,7 @@ public final class TransformationService implements ITransformationService {
@Override
public void initialize(IEnvironment environment) {
LOGGER.info("Initializing CustomSkinLoader Bootstrap transformation service");
TransformerBootstrap.publishModLoaderInfo();
try {
List<Path> extraLocators = ModDirTransformerDiscoverer.getExtraLocators();
Path servicePath = Paths.get(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).toAbsolutePath().normalize();
@@ -54,8 +56,7 @@ public final class TransformationService implements ITransformationService {
@Override
public List<ITransformer> transformers() {
List<ITransformer> transformers = TransformerBootstrap.buildTransformers();
LOGGER.info("Provided " + transformers.size() + " CustomSkinLoader ModLauncher transformer(s)");
return transformers;
LOGGER.info("Providing CustomSkinLoader ModLauncher transformer");
return Collections.singletonList(new TransformerBootstrap());
}
}
@@ -1,85 +1,95 @@
package customskinloader.bootstrap.forge.v2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import cpw.mods.modlauncher.ArgumentHandler;
import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.ITransformer;
import cpw.mods.modlauncher.api.ITransformerVotingContext;
import cpw.mods.modlauncher.api.TransformerVoteResult;
import customskinloader.bootstrap.BootstrapLogger;
import customskinloader.bootstrap.ModLoaderInfo;
import customskinloader.bootstrap.transformer.ClassTransformationReport;
import customskinloader.bootstrap.transformer.TransformerBootstrapSupport;
import customskinloader.bootstrap.util.ReflectionUtils;
import net.minecraftforge.fml.loading.FMLLoader;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.tree.ClassNode;
final class TransformerBootstrap {
final class TransformerBootstrap implements ITransformer<ClassNode> {
private static final Logger LOGGER = BootstrapLogger.LOGGER;
private static final TransformerBootstrapSupport SUPPORT = new TransformerBootstrapSupport(TransformerBootstrap.class,
// official: neoforge 1.20.2-20.2.3 ~ 1.21.3-21.3.97
// srg: forge *, neoforge 1.21.4-21.4.0 ~ 1.21.9-21.9.13
Launcher.INSTANCE.environment().findLaunchHandler("forgeclient")
.map(handle -> handle.getClass().getName().startsWith("net.neoforged.")).orElse(false) ? "official" : "srg");
private TransformerBootstrap() {
public static void publishModLoaderInfo() {
try {
Object argumentHandler = ReflectionUtils.findField(Launcher.class, "argumentHandler").get(Launcher.INSTANCE);
String[] args = (String[]) ReflectionUtils.findField(ArgumentHandler.class, "args").get(argumentHandler);
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (Objects.equals(arg, "--fml.forgeVersion")) {
// forge 1.13.2-25.0.216 ~ 1.20.2-48.1.0
ModLoaderInfo.publish("Forge", args[i + 1]);
return;
} else if (Objects.equals(arg, "--fml.neoForgeVersion")) {
// neoforge 1.20.2-20.2.3 ~ 1.21.9-21.9.13
ModLoaderInfo.publish("NeoForge", args[i + 1]);
return;
}
}
// forge 1.20.3-49.0.1+
ModLoaderInfo.publish("Forge", FMLLoader.class.getPackage().getImplementationVersion());
} catch (Exception e) {
LOGGER.warn("Could not determine mod loader", e);
ModLoaderInfo.publish("Forge", "unknown");
}
}
public static List<ITransformer> buildTransformers() {
List<ITransformer> transformers = new ArrayList<>();
for (String targetClassName : SUPPORT.collectTargetClassNames()) {
transformers.add(new ModLauncherClassTransformer(targetClassName));
LOGGER.debug("Created ModLauncher transformer for " + targetClassName);
}
private final Set<ITransformer.Target> targets;
return Collections.unmodifiableList(transformers);
TransformerBootstrap() {
Set<ITransformer.Target> transformerTargets = new LinkedHashSet<>();
for (String targetClassName : SUPPORT.getTargetClassNames()) {
transformerTargets.add(ITransformer.Target.targetClass(targetClassName));
}
this.targets = Collections.unmodifiableSet(transformerTargets);
LOGGER.info("Created one ModLauncher transformer for " + this.targets.size() + " target class(es)");
}
private static ClassNode transformClassNode(String internalClassName, ClassNode inputClassNode) {
ClassTransformationReport report = SUPPORT.transformClassNode(internalClassName, inputClassNode);
if (!report.isModified() || report.getTransformedClassNode() == null) {
return inputClassNode;
@Override
public ClassNode transform(ClassNode input, ITransformerVotingContext context) {
String internalClassName = input.name;
ClassTransformationReport report = SUPPORT.transform(internalClassName, input);
if (report.isModified()) {
LOGGER.info("Transformed ModLauncher target " + internalClassName + " with " + report.getAppliedRuleNames());
}
LOGGER.info("Transformed ModLauncher target " + internalClassName + " with " + report.getAppliedTransformerNames());
return report.getTransformedClassNode();
}
private static final class ModLauncherClassTransformer implements ITransformer<ClassNode> {
private final String targetClassName;
private final Set<ITransformer.Target> targets;
@Override
public TransformerVoteResult castVote(ITransformerVotingContext context) {
return TransformerVoteResult.YES;
}
private ModLauncherClassTransformer(String targetClassName) {
this.targetClassName = targetClassName;
@Override
public Set<ITransformer.Target> targets() {
return this.targets;
}
Set<ITransformer.Target> transformerTargets = new LinkedHashSet<>();
transformerTargets.add(ITransformer.Target.targetClass(targetClassName));
this.targets = Collections.unmodifiableSet(transformerTargets);
}
// NeoForge
public cpw.mods.modlauncher.api.TargetType getTargetType() {
return cpw.mods.modlauncher.api.TargetType.CLASS;
}
@Override
public ClassNode transform(ClassNode input, ITransformerVotingContext context) {
return transformClassNode(this.targetClassName, input);
}
@Override
public TransformerVoteResult castVote(ITransformerVotingContext context) {
return TransformerVoteResult.YES;
}
@Override
public Set<ITransformer.Target> targets() {
return this.targets;
}
// NeoForge
public cpw.mods.modlauncher.api.TargetType getTargetType() {
return cpw.mods.modlauncher.api.TargetType.CLASS;
}
@Override
public String[] labels() {
return new String[] {"customskinloader:" + this.targetClassName.replace('/', '.')};
}
@Override
public String[] labels() {
return new String[] {"customskinloader:bootstrap"};
}
}
@@ -9,6 +9,7 @@ public final class CommonModLocator extends ModsFolderLocator {
ModLocatorUtils.initialize(this, ModsFolderLocator.class, FMLPaths.GAMEDIR.get(), "official");
}
@Override
public String name() {
return ModLocatorUtils.LOCATOR_NAME;
}
@@ -1,9 +1,12 @@
package customskinloader.bootstrap.neoforge.v2;
import customskinloader.bootstrap.BootstrapLogger;
import customskinloader.bootstrap.ModLoaderInfo;
import net.neoforged.fml.loading.FMLLoader;
import net.neoforged.neoforgespi.transformation.ClassProcessorProvider;
import org.apache.logging.log4j.Logger;
// NeoForge 21.9.14+
public final class ClassProcessorProviderImpl implements ClassProcessorProvider {
private static final Logger LOGGER = BootstrapLogger.LOGGER;
@@ -11,6 +14,7 @@ public final class ClassProcessorProviderImpl implements ClassProcessorProvider
public void createProcessors(Context context, Collector collector) {
// Always register the bridge processor so late transformer registrations can still be observed.
LOGGER.info("Registering CustomSkinLoader Bootstrap NeoForge class processor");
collector.add(TransformerBootstrap.createProcessor());
ModLoaderInfo.publish("NeoForge", FMLLoader.getCurrent().getVersionInfo().neoForgeVersion());
collector.add(new TransformerBootstrap());
}
}
@@ -4,6 +4,7 @@ import customskinloader.bootstrap.util.ModLocatorUtils;
import net.neoforged.fml.loading.FMLPaths;
import net.neoforged.fml.loading.moddiscovery.locators.ModsFolderLocator;
// NeoForge 20.6.14+
public final class CommonModLocator extends ModsFolderLocator {
public CommonModLocator() {
ModLocatorUtils.initialize(this, ModsFolderLocator.class, FMLPaths.GAMEDIR.get(), "official");
@@ -10,63 +10,49 @@ import net.neoforged.neoforgespi.transformation.ClassProcessor;
import net.neoforged.neoforgespi.transformation.ClassProcessorIds;
import net.neoforged.neoforgespi.transformation.ProcessorName;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.tree.ClassNode;
final class TransformerBootstrap {
final class TransformerBootstrap implements ClassProcessor {
private static final Logger LOGGER = BootstrapLogger.LOGGER;
private static final TransformerBootstrapSupport SUPPORT = new TransformerBootstrapSupport(TransformerBootstrap.class, "official");
private static final ProcessorName PROCESSOR_NAME = new ProcessorName("customskinloader", "bootstrap");
private TransformerBootstrap() {
}
public static ClassProcessor createProcessor() {
SUPPORT.ensureTransformersLoaded();
TransformerBootstrap() {
SUPPORT.getTargetClassNames();
LOGGER.info("Created CustomSkinLoader Bootstrap NeoForge class processor");
return new BootstrapClassProcessor();
}
private static ClassTransformationReport transformClassNode(String internalClassName, ClassNode inputClassNode) {
return SUPPORT.transformClassNode(internalClassName, inputClassNode);
@Override
public ProcessorName name() {
return PROCESSOR_NAME;
}
private static final class BootstrapClassProcessor implements ClassProcessor {
@Override
public ProcessorName name() {
return PROCESSOR_NAME;
@Override
public Set<ProcessorName> runsBefore() {
return Collections.singleton(ClassProcessorIds.MIXIN);
}
@Override
public boolean handlesClass(SelectionContext context) {
// The shared framework currently targets concrete classes only, so we skip synthetic empty definitions.
return !context.empty() && SUPPORT.getTargetClassNames().contains(context.type().getInternalName());
}
@Override
public ComputeFlags processClass(TransformationContext context) {
ClassTransformationReport report = SUPPORT.transform(context.type().getInternalName(), context.node());
if (!report.isModified()) {
return ComputeFlags.NO_REWRITE;
}
@Override
public Set<ProcessorName> runsAfter() {
// Run after the default simple-processor group so the shared framework sees post-Mixin bytecode.
return Collections.singleton(ClassProcessorIds.SIMPLE_PROCESSORS_GROUP);
for (String ruleName : report.getAppliedRuleNames()) {
context.audit("customskinloader.bootstrap", ruleName);
}
LOGGER.info("Transformed NeoForge target " + context.type().getInternalName() + " with " + report.getAppliedRuleNames());
return ComputeFlags.COMPUTE_FRAMES;
}
@Override
public boolean handlesClass(SelectionContext context) {
// The shared framework currently targets concrete classes only, so we skip synthetic empty definitions.
return !context.empty() && SUPPORT.hasApplicableTransformers(context.type().getInternalName());
}
@Override
public ComputeFlags processClass(TransformationContext context) {
ClassTransformationReport report = transformClassNode(context.type().getInternalName(), context.node());
if (!report.isModified()) {
return ComputeFlags.NO_REWRITE;
}
TransformerBootstrapSupport.copyClassNode(report.getTransformedClassNode(), context.node());
for (String transformerName : report.getAppliedTransformerNames()) {
context.audit("customskinloader.bootstrap", transformerName);
}
LOGGER.info("Transformed NeoForge target " + context.type().getInternalName() + " with " + report.getAppliedTransformerNames());
return ComputeFlags.COMPUTE_FRAMES;
}
@Override
public OrderingHint orderingHint() {
return OrderingHint.LATE;
}
@Override
public OrderingHint orderingHint() {
return OrderingHint.EARLY;
}
}
@@ -218,7 +218,7 @@ public class CustomSkinLoader {
logger.info("Operating System: " + System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") version " + System.getProperty("os.version"));
logger.info("Java Version: " + System.getProperty("java.version") + ", " + System.getProperty("java.vendor"));
logger.info("Java VM Version: " + System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.info") + "), " + System.getProperty("java.vm.vendor"));
logger.info("Minecraft: " + MinecraftUtil.getMinecraftMainVersion());
logger.info("Minecraft: " + MinecraftUtil.getMinecraftMainVersion() + " (" + MinecraftUtil.getLoaderName() + " " + MinecraftUtil.getLoaderVersion() + ")");
return logger;
}
@@ -38,14 +38,16 @@ public class FakeSkinBuffer implements FakeHttpTextureProcessor {
* 19w38a ~ 24w45a
* Invoked from {@link HttpTexture#loadTexture(InputStream)}
*/
public static NativeImage processLegacySkin(NativeImage image, Runnable processTask, Function<NativeImage, NativeImage> processLegacySkin) {
if (processTask instanceof FakeHttpTextureProcessor) {
return ((FakeHttpTextureProcessor) processTask).process(image);
} else if (processLegacySkin != null) {
return processLegacySkin.apply(image);
} else {
return image;
}
public static boolean shouldProcessLegacySkin(Runnable processTask) {
return processTask instanceof FakeHttpTextureProcessor;
}
/**
* 19w38a ~ 24w45a
* Invoked from {@link HttpTexture#loadTexture(InputStream)}
*/
public static NativeImage processLegacySkin(NativeImage image, Runnable processTask) {
return ((FakeHttpTextureProcessor) processTask).process(image);
}
//parseUserSkin for 1.13+
@@ -1,18 +1,9 @@
package customskinloader.fake;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.SignatureState;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftProfileTextures;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.properties.Property;
import com.mojang.blaze3d.platform.NativeImage;
import customskinloader.CustomSkinLoader;
@@ -24,6 +15,14 @@ import net.minecraft.client.resources.SkinManager;
import net.minecraft.client.resources.SkinManager$CacheKey;
import net.minecraft.server.Services;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
public class FakeSkinManager {
/**
* 1.20.1-
@@ -51,7 +50,7 @@ public class FakeSkinManager {
* 1.20.1-
* Invoked from {@link SkinManager#registerSkins(GameProfile, SkinManager$SkinTextureCallback, boolean)}
*/
public static void loadProfileTextures(Runnable runnable) {
public static void loadProfileTextures(Object executor, Runnable runnable) {
CustomSkinLoader.loadProfileTextures(runnable);
}
@@ -67,7 +66,7 @@ public class FakeSkinManager {
* 1.20.1-
* Invoked from {@link SkinManager#lambda$registerSkins$4(GameProfile, boolean, SkinManager$SkinTextureCallback)}
*/
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> getUserProfile(MinecraftSessionService sessionService, GameProfile profile, boolean requireSecure) {
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> getUserProfile(Object sessionService, GameProfile profile, boolean requireSecure) {
return ModelManager0.fromUserProfile(CustomSkinLoader.loadProfile(profile));
}
@@ -83,7 +82,7 @@ public class FakeSkinManager {
* 23w31a ~ 23w41a
* Invoked from {@link SkinManager$1#lambda$load$0(MinecraftSessionService, GameProfile)}
*/
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadSkinFromCache(MinecraftSessionService sessionService, GameProfile profile, boolean requireSecure) {
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadSkinFromCache(Object sessionService, GameProfile profile, boolean requireSecure) {
return getUserProfile(sessionService, profile, requireSecure);
}
@@ -94,11 +93,11 @@ public class FakeSkinManager {
* 25w34a+
* Invoked from {@link SkinManager$1#lambda$load$0(SkinManager$CacheKey, Services)}
*/
public static Object loadSkinFromCache(MinecraftSessionService sessionService, Property property, SkinManager$CacheKey cacheKey) {
public static Object loadSkinFromCache(Object textures, SkinManager$CacheKey cacheKey) {
if (cacheKey instanceof FakeCacheKey) {
return FakeCacheKey.createMinecraftProfileTextures(loadSkinFromCache(sessionService, ((FakeCacheKey) cacheKey).profile(), false));
return FakeCacheKey.createMinecraftProfileTextures(loadSkinFromCache(null, ((FakeCacheKey) cacheKey).profile(), false));
}
return sessionService.unpackTextures(property);
return textures;
}
public static class BaseBuffer implements FakeHttpTextureProcessor {
@@ -173,7 +172,7 @@ public class FakeSkinManager {
* Invoked from {@link SkinManager#get(GameProfile)}
*/
public static SkinManager$CacheKey createFakeCacheKey(UUID uuid, Property property, GameProfile profile) {
return new FakeCacheKey(uuid, property == null ? new Property(null, null) : property, profile);
return new FakeCacheKey(uuid, property == null ? new Property("", "") : property, profile);
}
public static Object createMinecraftProfileTextures(Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> textures) {
@@ -14,7 +14,6 @@ import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.authlib.yggdrasil.response.MinecraftTexturesPayload;
import com.mojang.util.UUIDTypeAdapter;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
@@ -101,10 +100,14 @@ public class GameProfileLoader implements ICustomSkinLoaderPlugin, ProfileLoader
if (result == null) {
return Maps.newHashMap();
}
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> textures = TextureUtil.AuthlibField.MINECRAFT_TEXTURES_PAYLOAD_TEXTURES.get(result);
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> textures = result.textures;
if (textures == null) {
return Maps.newHashMap();
}
return textures;
}
public static class MinecraftTexturesPayload {
public Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> textures;
}
}
@@ -27,9 +27,7 @@ public class LegacyLoader implements ICustomSkinLoaderPlugin, ProfileLoader.IPro
public List<IDefaultProfile> getDefaultProfiles() {
return Lists.newArrayList(new LocalSkin(this),
getCapeProfile(this, "OptiFine", "https://optifine.net/capes/{USERNAME}.png", 810),
getCapeProfile(this, "CloakPlus", "http://161.35.130.99/capes/{USERNAME}.png", 840),
//getCapeProfile(this, "LabyMod", "https://dl.labymod.net/capes/{STANDARD_UUID}", 850),
getCapeProfile(this, "Cosmetica", "https://api.cosmetica.cc/get/cloak?username={USERNAME}&uuid={STANDARD_UUID}&nothirdparty", 860)
getCapeProfile(this, "CloakPlus", "http://161.35.130.99/capes/{USERNAME}.png", 840)
);
}
@@ -6,12 +6,10 @@ import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.authlib.yggdrasil.response.MinecraftProfilePropertiesResponse;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
@@ -86,7 +84,7 @@ public class MojangAPILoader implements ICustomSkinLoaderPlugin, ProfileLoader.I
CustomSkinLoader.logger.info("Profile not found.(" + username + "'s profile not found.)");
return null;
}
PropertyMap propertyMap = TextureUtil.AuthlibField.MINECRAFT_PROFILE_PROPERTIES_RESPONSE_PROPERTIES.get(fillProfile(ssp.sessionRoot, newProfile));
PropertyMap propertyMap = fillProfile(ssp.sessionRoot, newProfile).properties;
if (propertyMap != null) {
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map = GameProfileLoader.getTextures(propertyMap);
if (!map.isEmpty()) {
@@ -116,7 +114,7 @@ public class MojangAPILoader implements ICustomSkinLoaderPlugin, ProfileLoader.I
return null;
}
UUID id = TextureUtil.AuthlibField.MINECRAFT_PROFILE_PROPERTIES_RESPONSE_ID.get(profiles[0]);
UUID id = profiles[0].id;
if (id == null) {
return null;
}
@@ -135,14 +133,14 @@ public class MojangAPILoader implements ICustomSkinLoaderPlugin, ProfileLoader.I
if (profile == null) {
return null;
}
UUID id = TextureUtil.AuthlibField.MINECRAFT_PROFILE_PROPERTIES_RESPONSE_ID.get(profile);
UUID id = profile.id;
return standard ? id.toString() : TextureUtil.fromUUID(id);
}
//UUID -> Profile
public static MinecraftProfilePropertiesResponse fillProfile(String sessionRoot, MinecraftProfilePropertiesResponse profile) {
//Doc (https://minecraft.wiki/w/Mojang_API#Query_player's_skin_and_cape)
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequestUtil.HttpRequest(sessionRoot + "session/minecraft/profile/" + TextureUtil.fromUUID(TextureUtil.AuthlibField.MINECRAFT_PROFILE_PROPERTIES_RESPONSE_ID.get(profile))).setCacheTime(90));
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequestUtil.HttpRequest(sessionRoot + "session/minecraft/profile/" + TextureUtil.fromUUID(profile.id)).setCacheTime(90));
if (StringUtils.isEmpty(responce.content)) {
return profile;
}
@@ -179,4 +177,9 @@ public class MojangAPILoader implements ICustomSkinLoaderPlugin, ProfileLoader.I
public static String getMojangSessionRoot() {
return MOJANG_SESSION_ROOT.replace("{DO_NOT_MODIFY}", "");
}
public static class MinecraftProfilePropertiesResponse {
public UUID id;
public PropertyMap properties;
}
}
@@ -97,7 +97,8 @@ public class HttpRequestUtil {
CustomSkinLoader.logger.debug("Try to read cache '" + request.cacheFile + "'.");
return loadFromCache(request, new HttpResponce());
}
CustomSkinLoader.logger.debug("Try to request '" + request.url + (request.userAgent == null ? "'." : "' with user agent '" + request.userAgent + "'."));
String userAgent = UserAgentUtil.expandUserAgent(request.userAgent);
CustomSkinLoader.logger.debug("Try to request '" + request.url + "' with user agent '" + userAgent + "'.");
//Check Cache
if (StringUtils.isNotEmpty(request.payload) || CustomSkinLoader.config.forceDisableCache) {
request.cacheTime = -1;//No Cache
@@ -156,9 +157,7 @@ public class HttpRequestUtil {
c.setRequestProperty("If-None-Match", cacheInfo.etag);
}
c.setRequestProperty("Accept-Encoding", "gzip");
if (request.userAgent != null) {
c.setRequestProperty("User-Agent", request.userAgent);
}
c.setRequestProperty("User-Agent", userAgent);
if (StringUtils.isNotEmpty(request.payload)) {
CustomSkinLoader.logger.info("Payload: " + request.payload);
c.setRequestMethod("POST");
@@ -12,8 +12,6 @@ import com.google.gson.JsonParser;
import com.mojang.authlib.GameProfile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.SkinManager;
/**
* @author Alexander Xia
@@ -24,13 +22,6 @@ public class MinecraftUtil {
return Minecraft.getInstance().gameDirectory;
}
public static TextureManager getTextureManager() {
return Minecraft.getInstance().getTextureManager();
}
public static SkinManager getSkinManager() {
return Minecraft.getInstance().getSkinManager();
}
private static String minecraftMainVersion = null;
public static String getMinecraftMainVersion() {
@@ -67,6 +58,17 @@ public class MinecraftUtil {
return "unknown";
}
private static final String MOD_LOADER_NAME_PROPERTY = "customskinloader.modLoader.name";
private static final String MOD_LOADER_VERSION_PROPERTY = "customskinloader.modLoader.version";
public static String getLoaderName() {
return System.getProperty(MOD_LOADER_NAME_PROPERTY, "unknown");
}
public static String getLoaderVersion() {
return System.getProperty(MOD_LOADER_VERSION_PROPERTY, "unknown");
}
// (domain|ip)(:port)
public static String getServerAddress() {
ServerData data = Minecraft.getInstance().getCurrentServer();
@@ -6,8 +6,6 @@ import java.util.UUID;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.yggdrasil.response.MinecraftProfilePropertiesResponse;
import com.mojang.authlib.yggdrasil.response.MinecraftTexturesPayload;
import customskinloader.CustomSkinLoader;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
@@ -43,10 +41,7 @@ public class TextureUtil {
GAME_PROFILE_ID(GameProfile.class, "id"),
GAME_PROFILE_NAME(GameProfile.class, "name"),
GAME_PROFILE_PROPERTIES(GameProfile.class, "properties"),
PROPERTY_VALUE(Property.class, "value"),
MINECRAFT_PROFILE_PROPERTIES_RESPONSE_ID(MinecraftProfilePropertiesResponse.class, "id"),
MINECRAFT_PROFILE_PROPERTIES_RESPONSE_PROPERTIES(MinecraftProfilePropertiesResponse.class, "properties"),
MINECRAFT_TEXTURES_PAYLOAD_TEXTURES(MinecraftTexturesPayload.class, "textures");
PROPERTY_VALUE(Property.class, "value");
private final Field field;
@@ -67,14 +62,6 @@ public class TextureUtil {
throw new RuntimeException(t);
}
}
public void set(Object o, Object value) {
try {
this.field.set(o, value);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
}
public static String fromUUID(UUID value) {
@@ -0,0 +1,55 @@
package customskinloader.utils;
import customskinloader.CustomSkinLoader;
public final class UserAgentUtil {
public static final String DEFAULT_USER_AGENT_PLACEHOLDER = "{DEFAULT_USER_AGENT}";
public static final String CSL_VERSION_PLACEHOLDER = "{CSL_VERSION}";
public static final String MINECRAFT_VERSION_PLACEHOLDER = "{MINECRAFT_VERSION}";
public static final String MOD_LOADER_NAME_PLACEHOLDER = "{MOD_LOADER_NAME}";
public static final String MOD_LOADER_VERSION_PLACEHOLDER = "{MOD_LOADER_VERSION}";
public static final String JAVA_VERSION_PLACEHOLDER = "{JAVA_VERSION}";
private UserAgentUtil() {
}
public static String expandUserAgent(String userAgent) {
String modVersion = sanitizeComponent(CustomSkinLoader.CustomSkinLoader_FULL_VERSION);
String minecraftVersion = sanitizeComponent(MinecraftUtil.getMinecraftMainVersion());
String loaderName = sanitizeComponent(MinecraftUtil.getLoaderName());
String loaderVersion = sanitizeComponent(MinecraftUtil.getLoaderVersion());
String javaVersion = sanitizeComponent(System.getProperty("java.version", "unknown"));
String defaultUserAgent = "CustomSkinLoader/" + modVersion
+ " (Minecraft/" + minecraftVersion
+ "; " + loaderName + "/" + loaderVersion
+ "; Java/" + javaVersion + ")";
if (userAgent == null) {
return defaultUserAgent;
}
return userAgent
.replace(DEFAULT_USER_AGENT_PLACEHOLDER, defaultUserAgent)
.replace(CSL_VERSION_PLACEHOLDER, modVersion)
.replace(MINECRAFT_VERSION_PLACEHOLDER, minecraftVersion)
.replace(MOD_LOADER_NAME_PLACEHOLDER, loaderName)
.replace(MOD_LOADER_VERSION_PLACEHOLDER, loaderVersion)
.replace(JAVA_VERSION_PLACEHOLDER, javaVersion);
}
private static String sanitizeComponent(String value) {
if (value == null || value.trim().isEmpty()) {
return "unknown";
}
String component = value.trim();
StringBuilder sanitized = new StringBuilder(component.length());
for (int i = 0; i < component.length(); i++) {
char c = component.charAt(i);
sanitized.append(c >= '0' && c <= '9'
|| c >= 'A' && c <= 'Z'
|| c >= 'a' && c <= 'z'
|| "!#$%&'*+-.^_`|~".indexOf(c) >= 0 ? c : '_');
}
return sanitized.toString();
}
}
-2
View File
@@ -69,7 +69,6 @@ Supported special skin sites and profiles:
- [MinecraftCapes](https://minecraftcapes.net/)
- [OptiFineCape](https://optifine.net/home)
- [Cloaks+](https://cloaksplus.com/)
- [Cosmetica](https://cosmetica.cc/)
- [Wynntils](https://wynntils.com/) compatible profile support
You can customize the skin load list and load textures from any compatible skin server. Skin server owners can also use ExtraList files to help users add their server.
@@ -131,7 +130,6 @@ GitHub Actions intentionally runs on Windows with PowerShell, but local project
- [MinecraftCapes](https://minecraftcapes.net/)
- [OptiFineCape](https://optifine.net/home)
- [Cloaks+](https://cloaksplus.com/)
- [Cosmetica](https://cosmetica.cc/)
If you want to add another skin server to the default list, please open an [issue](https://github.com/xfl03/MCCustomSkinLoader/issues).
+2 -2
View File
@@ -1,7 +1,7 @@
{
"mod_group": "customskinloader",
"mod_name": "CustomSkinLoader",
"mod_version": "15.0.1",
"mod_version": "15.1",
"edition": "Universal",
"loaders": [
@@ -22,7 +22,7 @@
"1.19", "1.19.1", "1.19.2", "1.19.3", "1.19.4",
"1.20", "1.20.1", "1.20.2", "1.20.3", "1.20.4", "1.20.5", "1.20.6",
"1.21", "1.21.1", "1.21.2", "1.21.3", "1.21.4", "1.21.5", "1.21.6", "1.21.7", "1.21.8", "1.21.9", "1.21.10", "1.21.11",
"26.1", "26.1.1", "26.1.2", "26.2"
"26.1", "26.1.1", "26.1.2", "26.2", "26.3"
],
"java": [
8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 25
+3 -3
View File
@@ -1,8 +1,8 @@
build_type=beta
minecraft_version=26.2
fabric_v1_version=0.19.3
minecraft_version=26.3
fabric_v1_version=0.19.5
forge_v1_version=14.23.5.2864
forge_v2_version=36.2.42
neoforge_v1_version=20.6.13-beta
neoforge_v2_version=26.2.0.1-beta
neoforge_v2_version=26.3.0.1-beta
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
Vendored
+2 -2
View File
@@ -20,7 +20,7 @@
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
# gradlew start up script for POSIX generated by Gradle.
#
# Important for running:
#
@@ -29,7 +29,7 @@
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
# ksh gradlew
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
Vendored
+2 -2
View File
@@ -19,7 +19,7 @@
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem gradlew startup script for Windows
@rem
@rem ##########################################################################
@@ -72,7 +72,7 @@ echo location of your Java installation. 1>&2
@rem Execute Gradle
@rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel