Improve decompiler options by moving them away from the task.

Done because the split jar changes required registering the decompiler task after evaluation.
As there may be more than one decompile task, the options are set per decompiler and not per task.
This should also make easier to add new decompilers without requiring a plugin.
dev/0.11
modmuss50 2022-01-05 09:49:11 +00:00
parent 19143fc5a8
commit 240a23f52d
13 changed files with 160 additions and 121 deletions

View File

@ -25,7 +25,6 @@
package net.fabricmc.loom.api; package net.fabricmc.loom.api;
import org.gradle.api.Action; import org.gradle.api.Action;
import org.gradle.api.DomainObjectCollection;
import org.gradle.api.NamedDomainObjectContainer; import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.artifacts.Dependency; import org.gradle.api.artifacts.Dependency;
import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.file.ConfigurableFileCollection;
@ -35,7 +34,7 @@ import org.gradle.api.provider.Property;
import org.gradle.api.publish.maven.MavenPublication; import org.gradle.api.publish.maven.MavenPublication;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import net.fabricmc.loom.api.decompilers.LoomDecompiler; import net.fabricmc.loom.api.decompilers.DecompilerOptions;
import net.fabricmc.loom.api.mappings.layered.spec.LayeredMappingSpecBuilder; import net.fabricmc.loom.api.mappings.layered.spec.LayeredMappingSpecBuilder;
import net.fabricmc.loom.configuration.ide.RunConfigSettings; import net.fabricmc.loom.configuration.ide.RunConfigSettings;
import net.fabricmc.loom.configuration.processors.JarProcessor; import net.fabricmc.loom.configuration.processors.JarProcessor;
@ -56,11 +55,9 @@ public interface LoomGradleExtensionAPI {
getShareRemapCaches().set(true); getShareRemapCaches().set(true);
} }
DomainObjectCollection<LoomDecompiler> getGameDecompilers(); NamedDomainObjectContainer<DecompilerOptions> getDecompilerOptions();
default void addDecompiler(LoomDecompiler decompiler) { void decompilers(Action<NamedDomainObjectContainer<DecompilerOptions>> action);
getGameDecompilers().add(decompiler);
}
ListProperty<JarProcessor> getGameJarProcessors(); ListProperty<JarProcessor> getGameJarProcessors();

View File

@ -0,0 +1,81 @@
/*
* This file is part of fabric-loom, licensed under the MIT License (MIT).
*
* Copyright (c) 2022 FabricMC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.fabricmc.loom.api.decompilers;
import java.io.Serializable;
import java.util.Map;
import com.google.common.base.Preconditions;
import org.gradle.api.Named;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.provider.MapProperty;
import org.gradle.api.provider.Property;
public abstract class DecompilerOptions implements Named {
/**
* Class name for to the {@link LoomDecompiler}.
*/
public abstract Property<String> getDecompilerClassname();
/**
* Additional classpath entries for the decompiler jvm.
*/
public abstract ConfigurableFileCollection getClasspath();
/**
* Additional options to be passed to the decompiler.
*/
public abstract MapProperty<String, String> getOptions();
/**
* Memory used for forked JVM in megabytes.
*/
public abstract Property<Long> getMemory();
/**
* Maximum number of threads the decompiler is allowed to use.
*/
public abstract Property<Integer> getMaxThreads();
public DecompilerOptions() {
getDecompilerClassname().finalizeValueOnRead();
getClasspath().finalizeValueOnRead();
getOptions().finalizeValueOnRead();
getMemory().convention(4096L).finalizeValueOnRead();
getMaxThreads().convention(Runtime.getRuntime().availableProcessors()).finalizeValueOnRead();
}
// Done to work around weird issues with the workers, possibly https://github.com/gradle/gradle/issues/13422
public record Dto(String className, Map<String, String> options, int maxThreads) implements Serializable { }
public Dto toDto() {
Preconditions.checkArgument(getDecompilerClassname().isPresent(), "No decompiler classname specified for decompiler: " + getName());
return new Dto(
getDecompilerClassname().get(),
getOptions().get(),
getMaxThreads().get()
);
}
}

View File

@ -26,13 +26,7 @@ package net.fabricmc.loom.api.decompilers;
import java.nio.file.Path; import java.nio.file.Path;
import org.gradle.api.Project;
import org.gradle.api.file.FileCollection;
import org.jetbrains.annotations.Nullable;
public interface LoomDecompiler { public interface LoomDecompiler {
String name();
/** /**
* @param sourcesDestination Decompiled sources jar * @param sourcesDestination Decompiled sources jar
* @param linemapDestination A byproduct of decompilation that lines up the compiled jar's line numbers with the decompiled * @param linemapDestination A byproduct of decompilation that lines up the compiled jar's line numbers with the decompiled
@ -41,12 +35,4 @@ public interface LoomDecompiler {
* @param metaData Additional information that may or may not be needed while decompiling * @param metaData Additional information that may or may not be needed while decompiling
*/ */
void decompile(Path compiledJar, Path sourcesDestination, Path linemapDestination, DecompilationMetadata metaData); void decompile(Path compiledJar, Path sourcesDestination, Path linemapDestination, DecompilationMetadata metaData);
/**
* Add additional classpath entries to the decompiler classpath, can return a configuration.
*/
@Nullable
default FileCollection getBootstrapClasspath(Project project) {
return null;
}
} }

View File

@ -42,7 +42,7 @@ public interface LayeredMappingSpecBuilder {
LayeredMappingSpecBuilder addLayer(MappingsSpec<?> mappingSpec); LayeredMappingSpecBuilder addLayer(MappingsSpec<?> mappingSpec);
/** /**
* Add a layer that uses the official mappings provided by Mojang with the default options. * Add a layer that uses the official mappings provided by Mojang with the default decompilerOptions.
*/ */
default LayeredMappingSpecBuilder officialMojangMappings() { default LayeredMappingSpecBuilder officialMojangMappings() {
return officialMojangMappings(builder -> { }); return officialMojangMappings(builder -> { });

View File

@ -65,15 +65,16 @@ public final class MergedDecompileConfiguration {
final File inputJar = mappedJar; final File inputJar = mappedJar;
LoomGradleExtension.get(project).getGameDecompilers().forEach(decompiler -> { LoomGradleExtension.get(project).getDecompilerOptions().forEach(options -> {
String taskName = "genSourcesWith" + decompiler.name(); final String decompilerName = options.getName().substring(0, 1).toUpperCase() + options.getName().substring(1);
String taskName = "genSourcesWith" + decompilerName;
// Decompiler will be passed to the constructor of GenerateSourcesTask // Decompiler will be passed to the constructor of GenerateSourcesTask
project.getTasks().register(taskName, GenerateSourcesTask.class, decompiler).configure(task -> { project.getTasks().register(taskName, GenerateSourcesTask.class, options).configure(task -> {
task.getInputJar().set(inputJar); task.getInputJar().set(inputJar);
task.getRuntimeJar().set(minecraftProvider.getMergedJar().toFile()); task.getRuntimeJar().set(minecraftProvider.getMergedJar().toFile());
task.dependsOn(project.getTasks().named("validateAccessWidener")); task.dependsOn(project.getTasks().named("validateAccessWidener"));
task.setDescription("Decompile minecraft using %s.".formatted(decompiler.name())); task.setDescription("Decompile minecraft using %s.".formatted(decompilerName));
task.setGroup(Constants.TaskGroup.FABRIC); task.setGroup(Constants.TaskGroup.FABRIC);
if (mappingsProvider.hasUnpickDefinitions()) { if (mappingsProvider.hasUnpickDefinitions()) {

View File

@ -111,13 +111,14 @@ public final class SplitDecompileConfiguration {
} }
private TaskProvider<Task> createDecompileTasks(String name, Action<GenerateSourcesTask> configureAction) { private TaskProvider<Task> createDecompileTasks(String name, Action<GenerateSourcesTask> configureAction) {
extension.getGameDecompilers().forEach(decompiler -> { extension.getDecompilerOptions().forEach(options -> {
final String taskName = "gen%sSourcesWith%s".formatted(name, decompiler.name()); final String decompilerName = options.getName().substring(0, 1).toUpperCase() + options.getName().substring(1);
final String taskName = "gen%sSourcesWith%s".formatted(decompilerName, options.getName());
project.getTasks().register(taskName, GenerateSourcesTask.class, decompiler).configure(task -> { project.getTasks().register(taskName, GenerateSourcesTask.class, options).configure(task -> {
configureAction.execute(task); configureAction.execute(task);
task.dependsOn(project.getTasks().named("validateAccessWidener")); task.dependsOn(project.getTasks().named("validateAccessWidener"));
task.setDescription("Decompile minecraft using %s.".formatted(decompiler.name())); task.setDescription("Decompile minecraft using %s.".formatted(decompilerName));
task.setGroup(Constants.TaskGroup.FABRIC); task.setGroup(Constants.TaskGroup.FABRIC);
}); });
}); });

View File

@ -27,6 +27,7 @@ package net.fabricmc.loom.decompilers;
import org.gradle.api.Project; import org.gradle.api.Project;
import net.fabricmc.loom.LoomGradleExtension; import net.fabricmc.loom.LoomGradleExtension;
import net.fabricmc.loom.api.decompilers.LoomDecompiler;
import net.fabricmc.loom.decompilers.cfr.LoomCFRDecompiler; import net.fabricmc.loom.decompilers.cfr.LoomCFRDecompiler;
import net.fabricmc.loom.decompilers.fernflower.FabricFernFlowerDecompiler; import net.fabricmc.loom.decompilers.fernflower.FabricFernFlowerDecompiler;
@ -35,8 +36,11 @@ public final class DecompilerConfiguration {
} }
public static void setup(Project project) { public static void setup(Project project) {
LoomGradleExtension extension = LoomGradleExtension.get(project); registerDecompiler(project, "fernFlower", FabricFernFlowerDecompiler.class);
extension.getGameDecompilers().add(new FabricFernFlowerDecompiler()); registerDecompiler(project, "cfr", LoomCFRDecompiler.class);
extension.getGameDecompilers().add(new LoomCFRDecompiler()); }
private static void registerDecompiler(Project project, String name, Class<? extends LoomDecompiler> decompilerClass) {
LoomGradleExtension.get(project).getDecompilerOptions().register(name, options -> options.getDecompilerClassname().set(decompilerClass.getName()));
} }
} }

View File

@ -30,8 +30,6 @@ import java.io.Writer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.jar.Attributes; import java.util.jar.Attributes;
@ -48,20 +46,14 @@ import org.benf.cfr.reader.util.output.SinkDumperFactory;
import net.fabricmc.loom.api.decompilers.DecompilationMetadata; import net.fabricmc.loom.api.decompilers.DecompilationMetadata;
import net.fabricmc.loom.api.decompilers.LoomDecompiler; import net.fabricmc.loom.api.decompilers.LoomDecompiler;
import net.fabricmc.loom.decompilers.LineNumberRemapper;
public class LoomCFRDecompiler implements LoomDecompiler { public final class LoomCFRDecompiler implements LoomDecompiler {
private static final Map<String, String> DECOMPILE_OPTIONS = Map.of( private static final Map<String, String> DECOMPILE_OPTIONS = Map.of(
"renameillegalidents", "true", "renameillegalidents", "true",
"trackbytecodeloc", "true", "trackbytecodeloc", "true",
"comments", "false" "comments", "false"
); );
@Override
public String name() {
return "Cfr";
}
@Override @Override
public void decompile(Path compiledJar, Path sourcesDestination, Path linemapDestination, DecompilationMetadata metaData) { public void decompile(Path compiledJar, Path sourcesDestination, Path linemapDestination, DecompilationMetadata metaData) {
final String path = compiledJar.toAbsolutePath().toString(); final String path = compiledJar.toAbsolutePath().toString();
@ -132,21 +124,4 @@ public class LoomCFRDecompiler implements LoomDecompiler {
throw new UncheckedIOException("Failed to write line map", e); throw new UncheckedIOException("Failed to write line map", e);
} }
} }
// A test main class to make it quicker/easier to debug with minimal jars
public static void main(String[] args) throws IOException {
LoomCFRDecompiler decompiler = new LoomCFRDecompiler();
Path lineMap = Paths.get("linemap.txt");
decompiler.decompile(Paths.get("input.jar"),
Paths.get("output-sources.jar"),
lineMap,
new DecompilationMetadata(4, null, Collections.emptyList(), null, Collections.emptyMap())
);
LineNumberRemapper lineNumberRemapper = new LineNumberRemapper();
lineNumberRemapper.readMappings(lineMap.toFile());
lineNumberRemapper.process(null, Paths.get("input.jar"), Paths.get("output.jar"));
}
} }

View File

@ -37,11 +37,6 @@ import net.fabricmc.loom.api.decompilers.DecompilationMetadata;
import net.fabricmc.loom.api.decompilers.LoomDecompiler; import net.fabricmc.loom.api.decompilers.LoomDecompiler;
public final class FabricFernFlowerDecompiler implements LoomDecompiler { public final class FabricFernFlowerDecompiler implements LoomDecompiler {
@Override
public String name() {
return "FernFlower";
}
@Override @Override
public void decompile(Path compiledJar, Path sourcesDestination, Path linemapDestination, DecompilationMetadata metaData) { public void decompile(Path compiledJar, Path sourcesDestination, Path linemapDestination, DecompilationMetadata metaData) {
final Map<String, Object> options = new HashMap<>( final Map<String, Object> options = new HashMap<>(

View File

@ -25,7 +25,6 @@
package net.fabricmc.loom.extension; package net.fabricmc.loom.extension;
import org.gradle.api.Action; import org.gradle.api.Action;
import org.gradle.api.DomainObjectCollection;
import org.gradle.api.NamedDomainObjectContainer; import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.Project; import org.gradle.api.Project;
import org.gradle.api.artifacts.Dependency; import org.gradle.api.artifacts.Dependency;
@ -37,7 +36,7 @@ import org.gradle.api.publish.maven.MavenPublication;
import net.fabricmc.loom.api.LoomGradleExtensionAPI; import net.fabricmc.loom.api.LoomGradleExtensionAPI;
import net.fabricmc.loom.api.MixinExtensionAPI; import net.fabricmc.loom.api.MixinExtensionAPI;
import net.fabricmc.loom.api.decompilers.LoomDecompiler; import net.fabricmc.loom.api.decompilers.DecompilerOptions;
import net.fabricmc.loom.api.mappings.layered.spec.LayeredMappingSpecBuilder; import net.fabricmc.loom.api.mappings.layered.spec.LayeredMappingSpecBuilder;
import net.fabricmc.loom.configuration.ide.RunConfigSettings; import net.fabricmc.loom.configuration.ide.RunConfigSettings;
import net.fabricmc.loom.configuration.mods.ModVersionParser; import net.fabricmc.loom.configuration.mods.ModVersionParser;
@ -53,7 +52,6 @@ import net.fabricmc.loom.util.DeprecationHelper;
*/ */
public abstract class LoomGradleExtensionApiImpl implements LoomGradleExtensionAPI { public abstract class LoomGradleExtensionApiImpl implements LoomGradleExtensionAPI {
protected final DeprecationHelper deprecationHelper; protected final DeprecationHelper deprecationHelper;
protected final DomainObjectCollection<LoomDecompiler> decompilers;
protected final ListProperty<JarProcessor> jarProcessors; protected final ListProperty<JarProcessor> jarProcessors;
protected final ConfigurableFileCollection log4jConfigs; protected final ConfigurableFileCollection log4jConfigs;
protected final RegularFileProperty accessWidener; protected final RegularFileProperty accessWidener;
@ -67,12 +65,10 @@ public abstract class LoomGradleExtensionApiImpl implements LoomGradleExtensionA
private final ModVersionParser versionParser; private final ModVersionParser versionParser;
private NamedDomainObjectContainer<RunConfigSettings> runConfigs; private final NamedDomainObjectContainer<RunConfigSettings> runConfigs;
private final NamedDomainObjectContainer<DecompilerOptions> decompilers;
protected LoomGradleExtensionApiImpl(Project project, LoomFiles directories) { protected LoomGradleExtensionApiImpl(Project project, LoomFiles directories) {
this.runConfigs = project.container(RunConfigSettings.class,
baseName -> new RunConfigSettings(project, baseName));
this.decompilers = project.getObjects().domainObjectSet(LoomDecompiler.class);
this.jarProcessors = project.getObjects().listProperty(JarProcessor.class) this.jarProcessors = project.getObjects().listProperty(JarProcessor.class)
.empty(); .empty();
this.log4jConfigs = project.files(directories.getDefaultLog4jConfigFile()); this.log4jConfigs = project.files(directories.getDefaultLog4jConfigFile());
@ -97,6 +93,10 @@ public abstract class LoomGradleExtensionApiImpl implements LoomGradleExtensionA
this.deprecationHelper = new DeprecationHelper.ProjectBased(project); this.deprecationHelper = new DeprecationHelper.ProjectBased(project);
this.runConfigs = project.container(RunConfigSettings.class,
baseName -> new RunConfigSettings(project, baseName));
this.decompilers = project.getObjects().domainObjectContainer(DecompilerOptions.class);
this.accessWidener.finalizeValueOnRead(); this.accessWidener.finalizeValueOnRead();
this.getGameJarProcessors().finalizeValueOnRead(); this.getGameJarProcessors().finalizeValueOnRead();
} }
@ -117,10 +117,15 @@ public abstract class LoomGradleExtensionApiImpl implements LoomGradleExtensionA
} }
@Override @Override
public DomainObjectCollection<LoomDecompiler> getGameDecompilers() { public NamedDomainObjectContainer<DecompilerOptions> getDecompilerOptions() {
return decompilers; return decompilers;
} }
@Override
public void decompilers(Action<NamedDomainObjectContainer<DecompilerOptions>> action) {
action.execute(decompilers);
}
@Override @Override
public ListProperty<JarProcessor> getGameJarProcessors() { public ListProperty<JarProcessor> getGameJarProcessors() {
return jarProcessors; return jarProcessors;

View File

@ -42,13 +42,9 @@ import java.util.stream.Collectors;
import javax.inject.Inject; import javax.inject.Inject;
import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.RegularFileProperty; import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.MapProperty;
import org.gradle.api.provider.Property; import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile; import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.TaskAction;
import org.gradle.workers.WorkAction; import org.gradle.workers.WorkAction;
import org.gradle.workers.WorkParameters; import org.gradle.workers.WorkParameters;
@ -58,6 +54,7 @@ import org.gradle.workers.internal.WorkerDaemonClientsManager;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import net.fabricmc.loom.api.decompilers.DecompilationMetadata; import net.fabricmc.loom.api.decompilers.DecompilationMetadata;
import net.fabricmc.loom.api.decompilers.DecompilerOptions;
import net.fabricmc.loom.api.decompilers.LoomDecompiler; import net.fabricmc.loom.api.decompilers.LoomDecompiler;
import net.fabricmc.loom.configuration.accesswidener.AccessWidenerFile; import net.fabricmc.loom.configuration.accesswidener.AccessWidenerFile;
import net.fabricmc.loom.configuration.accesswidener.TransitiveAccessWidenerMappingsProcessor; import net.fabricmc.loom.configuration.accesswidener.TransitiveAccessWidenerMappingsProcessor;
@ -73,7 +70,7 @@ import net.fabricmc.loom.util.ipc.IPCClient;
import net.fabricmc.loom.util.ipc.IPCServer; import net.fabricmc.loom.util.ipc.IPCServer;
public abstract class GenerateSourcesTask extends AbstractLoomTask { public abstract class GenerateSourcesTask extends AbstractLoomTask {
public final LoomDecompiler decompiler; private final DecompilerOptions decompilerOptions;
/** /**
* The jar to decompile, can be the unpick jar. * The jar to decompile, can be the unpick jar.
@ -87,18 +84,6 @@ public abstract class GenerateSourcesTask extends AbstractLoomTask {
@InputFile @InputFile
public abstract RegularFileProperty getRuntimeJar(); public abstract RegularFileProperty getRuntimeJar();
/**
* Max memory for forked JVM in megabytes.
*/
@Input
public abstract Property<Long> getMaxMemory();
@Input
public abstract MapProperty<String, String> getOptions();
@InputFiles
public abstract ConfigurableFileCollection getClasspath();
@Inject @Inject
public abstract WorkerExecutor getWorkerExecutor(); public abstract WorkerExecutor getWorkerExecutor();
@ -106,21 +91,10 @@ public abstract class GenerateSourcesTask extends AbstractLoomTask {
public abstract WorkerDaemonClientsManager getWorkerDaemonClientsManager(); public abstract WorkerDaemonClientsManager getWorkerDaemonClientsManager();
@Inject @Inject
public GenerateSourcesTask(LoomDecompiler decompiler) { public GenerateSourcesTask(DecompilerOptions decompilerOptions) {
this.decompiler = decompiler; this.decompilerOptions = decompilerOptions;
Objects.requireNonNull(getDecompilerConstructor(this.decompiler.getClass().getCanonicalName()),
"%s must have a no args constructor".formatted(this.decompiler.getClass().getCanonicalName()));
FileCollection decompilerClasspath = decompiler.getBootstrapClasspath(getProject());
if (decompilerClasspath != null) {
getClasspath().from(decompilerClasspath);
}
getOutputs().upToDateWhen((o) -> false); getOutputs().upToDateWhen((o) -> false);
getMaxMemory().convention(4096L).finalizeValueOnRead();
getOptions().finalizeValueOnRead();
} }
@TaskAction @TaskAction
@ -140,9 +114,9 @@ public abstract class GenerateSourcesTask extends AbstractLoomTask {
final Path ipcPath = Files.createTempFile("loom", "ipc"); final Path ipcPath = Files.createTempFile("loom", "ipc");
Files.deleteIfExists(ipcPath); Files.deleteIfExists(ipcPath);
try (ThreadedProgressLoggerConsumer loggerConsumer = new ThreadedProgressLoggerConsumer(getProject(), decompiler.name(), "Decompiling minecraft sources"); try (ThreadedProgressLoggerConsumer loggerConsumer = new ThreadedProgressLoggerConsumer(getProject(), decompilerOptions.getName(), "Decompiling minecraft sources");
IPCServer logReceiver = new IPCServer(ipcPath, loggerConsumer)) { IPCServer logReceiver = new IPCServer(ipcPath, loggerConsumer)) {
doWork(ipcPath); doWork(logReceiver);
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new RuntimeException("Failed to shutdown log receiver", e); throw new RuntimeException("Failed to shutdown log receiver", e);
} finally { } finally {
@ -150,14 +124,12 @@ public abstract class GenerateSourcesTask extends AbstractLoomTask {
} }
} }
private void doWork(@Nullable Path ipcPath) { private void doWork(@Nullable IPCServer ipcServer) {
final String jvmMarkerValue = UUID.randomUUID().toString(); final String jvmMarkerValue = UUID.randomUUID().toString();
final WorkQueue workQueue = createWorkQueue(jvmMarkerValue); final WorkQueue workQueue = createWorkQueue(jvmMarkerValue);
workQueue.submit(DecompileAction.class, params -> { workQueue.submit(DecompileAction.class, params -> {
params.getDecompilerClass().set(decompiler.getClass().getCanonicalName()); params.getDecompilerOptions().set(decompilerOptions.toDto());
params.getOptions().set(getOptions());
params.getInputJar().set(getInputJar()); params.getInputJar().set(getInputJar());
params.getRuntimeJar().set(getRuntimeJar()); params.getRuntimeJar().set(getRuntimeJar());
@ -166,8 +138,8 @@ public abstract class GenerateSourcesTask extends AbstractLoomTask {
params.getLinemapJar().set(getMappedJarFileWithSuffix("-linemapped.jar")); params.getLinemapJar().set(getMappedJarFileWithSuffix("-linemapped.jar"));
params.getMappings().set(getMappings().toFile()); params.getMappings().set(getMappings().toFile());
if (ipcPath != null) { if (ipcServer != null) {
params.getIPCPath().set(ipcPath.toFile()); params.getIPCPath().set(ipcServer.getPath().toFile());
} }
params.getClassPath().setFrom(getProject().getConfigurations().getByName(Constants.Configurations.MINECRAFT_DEPENDENCIES)); params.getClassPath().setFrom(getProject().getConfigurations().getByName(Constants.Configurations.MINECRAFT_DEPENDENCIES));
@ -176,10 +148,10 @@ public abstract class GenerateSourcesTask extends AbstractLoomTask {
try { try {
workQueue.await(); workQueue.await();
} finally { } finally {
if (useProcessIsolation()) { if (ipcServer != null) {
boolean stopped = WorkerDaemonClientsManagerHelper.stopIdleJVM(getWorkerDaemonClientsManager(), jvmMarkerValue); boolean stopped = WorkerDaemonClientsManagerHelper.stopIdleJVM(getWorkerDaemonClientsManager(), jvmMarkerValue);
if (!stopped) { if (!stopped && ipcServer.hasReceivedMessage()) {
throw new RuntimeException("Failed to stop decompile worker JVM"); throw new RuntimeException("Failed to stop decompile worker JVM");
} }
} }
@ -193,9 +165,9 @@ public abstract class GenerateSourcesTask extends AbstractLoomTask {
return getWorkerExecutor().processIsolation(spec -> { return getWorkerExecutor().processIsolation(spec -> {
spec.forkOptions(forkOptions -> { spec.forkOptions(forkOptions -> {
forkOptions.setMaxHeapSize("%dm".formatted(getMaxMemory().get())); forkOptions.setMaxHeapSize("%dm".formatted(decompilerOptions.getMemory().get()));
forkOptions.systemProperty(WorkerDaemonClientsManagerHelper.MARKER_PROP, jvmMarkerValue); forkOptions.systemProperty(WorkerDaemonClientsManagerHelper.MARKER_PROP, jvmMarkerValue);
forkOptions.bootstrapClasspath(getClasspath()); forkOptions.bootstrapClasspath(decompilerOptions.getClasspath());
}); });
}); });
} }
@ -206,9 +178,7 @@ public abstract class GenerateSourcesTask extends AbstractLoomTask {
} }
public interface DecompileParams extends WorkParameters { public interface DecompileParams extends WorkParameters {
Property<String> getDecompilerClass(); Property<DecompilerOptions.Dto> getDecompilerOptions();
MapProperty<String, String> getOptions();
RegularFileProperty getInputJar(); RegularFileProperty getInputJar();
RegularFileProperty getRuntimeJar(); RegularFileProperty getRuntimeJar();
@ -247,20 +217,26 @@ public abstract class GenerateSourcesTask extends AbstractLoomTask {
final Path linemapJar = getParameters().getLinemapJar().get().getAsFile().toPath(); final Path linemapJar = getParameters().getLinemapJar().get().getAsFile().toPath();
final Path runtimeJar = getParameters().getRuntimeJar().get().getAsFile().toPath(); final Path runtimeJar = getParameters().getRuntimeJar().get().getAsFile().toPath();
final DecompilerOptions.Dto decompilerOptions = getParameters().getDecompilerOptions().get();
final LoomDecompiler decompiler; final LoomDecompiler decompiler;
try { try {
decompiler = getDecompilerConstructor(getParameters().getDecompilerClass().get()).newInstance(); final String className = decompilerOptions.className();
final Constructor<LoomDecompiler> decompilerConstructor = getDecompilerConstructor(className);
Objects.requireNonNull(decompilerConstructor, "%s must have a no args constructor".formatted(className));
decompiler = decompilerConstructor.newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Failed to create decompiler", e); throw new RuntimeException("Failed to create decompiler", e);
} }
DecompilationMetadata metadata = new DecompilationMetadata( DecompilationMetadata metadata = new DecompilationMetadata(
Runtime.getRuntime().availableProcessors(), decompilerOptions.maxThreads(),
getParameters().getMappings().get().getAsFile().toPath(), getParameters().getMappings().get().getAsFile().toPath(),
getLibraries(), getLibraries(),
logger, logger,
getParameters().getOptions().get() decompilerOptions.options()
); );
decompiler.decompile( decompiler.decompile(

View File

@ -46,6 +46,8 @@ public class IPCServer implements AutoCloseable {
private final CountDownLatch startupLock = new CountDownLatch(1); private final CountDownLatch startupLock = new CountDownLatch(1);
private boolean receivedMessage = false;
public IPCServer(Path path, Consumer<String> consumer) { public IPCServer(Path path, Consumer<String> consumer) {
this.path = path; this.path = path;
this.consumer = consumer; this.consumer = consumer;
@ -71,6 +73,7 @@ public class IPCServer implements AutoCloseable {
Scanner scanner = new Scanner(clientChannel, StandardCharsets.UTF_8)) { Scanner scanner = new Scanner(clientChannel, StandardCharsets.UTF_8)) {
while (!Thread.currentThread().isInterrupted()) { while (!Thread.currentThread().isInterrupted()) {
if (scanner.hasNextLine()) { if (scanner.hasNextLine()) {
receivedMessage = true;
this.consumer.accept(scanner.nextLine()); this.consumer.accept(scanner.nextLine());
} }
} }
@ -85,4 +88,12 @@ public class IPCServer implements AutoCloseable {
loggerReceiverService.shutdownNow(); loggerReceiverService.shutdownNow();
loggerReceiverService.awaitTermination(10, TimeUnit.SECONDS); loggerReceiverService.awaitTermination(10, TimeUnit.SECONDS);
} }
public boolean hasReceivedMessage() {
return receivedMessage;
}
public Path getPath() {
return path;
}
} }

View File

@ -8,6 +8,13 @@ dependencies {
modImplementation "net.fabricmc:fabric-loader:0.11.7" modImplementation "net.fabricmc:fabric-loader:0.11.7"
} }
tasks.named("genSourcesWithCfr") { loom {
decompilers {
cfr {
options.put("test", "value") options.put("test", "value")
}
fernflower {
options.put("test", "value")
}
}
} }