From f9c898caf921c47f9c6d94f9c1e7d19905b55c07 Mon Sep 17 00:00:00 2001 From: Paint_Ninja Date: Sun, 7 Aug 2022 19:03:02 +0100 Subject: Support getting the CPU model name on Windows (#237) --- .../me/lucko/spark/common/monitor/cpu/CpuInfo.java | 27 ++++++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/spark-common/src/main/java/me/lucko/spark/common/monitor/cpu/CpuInfo.java b/spark-common/src/main/java/me/lucko/spark/common/monitor/cpu/CpuInfo.java index 9bbe0f8..fcb70c0 100644 --- a/spark-common/src/main/java/me/lucko/spark/common/monitor/cpu/CpuInfo.java +++ b/spark-common/src/main/java/me/lucko/spark/common/monitor/cpu/CpuInfo.java @@ -22,10 +22,13 @@ package me.lucko.spark.common.monitor.cpu; import me.lucko.spark.common.util.LinuxProc; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; import java.util.regex.Pattern; /** - * Small utility to query the CPU model on Linux systems. + * Small utility to query the CPU model on Linux and Windows systems. */ public enum CpuInfo { ; @@ -38,11 +41,25 @@ public enum CpuInfo { * @return the cpu model */ public static String queryCpuModel() { - for (String line : LinuxProc.CPUINFO.read()) { - String[] splitLine = SPACE_COLON_SPACE_PATTERN.split(line); + if (System.getProperty("os.name").startsWith("Windows")) { + final String[] args = { "wmic", "cpu", "get", "name", "/FORMAT:list" }; + try (final BufferedReader buf = new BufferedReader(new InputStreamReader(new ProcessBuilder(args).redirectErrorStream(true).start().getInputStream()))) { + String line; + while ((line = buf.readLine()) != null) { + if (line.startsWith("Name")) { + return line.substring(5).trim(); + } + } + } catch (final IOException e) { + return ""; + } + } else { + for (String line : LinuxProc.CPUINFO.read()) { + String[] splitLine = SPACE_COLON_SPACE_PATTERN.split(line); - if (splitLine[0].equals("model name") || splitLine[0].equals("Processor")) { - return splitLine[1]; + if (splitLine[0].equals("model name") || splitLine[0].equals("Processor")) { + return splitLine[1]; + } } } return ""; -- cgit From 0d3b71f3163d34a35506668066f94fcad8d5c6f8 Mon Sep 17 00:00:00 2001 From: Paint_Ninja Date: Sun, 7 Aug 2022 19:04:33 +0100 Subject: Improve operating system info (#238) --- .../common/monitor/os/OperatingSystemInfo.java | 78 ++++++++++++++++++++++ .../platform/PlatformStatisticsProvider.java | 5 +- .../java/me/lucko/spark/common/util/LinuxProc.java | 7 +- 3 files changed, 87 insertions(+), 3 deletions(-) create mode 100644 spark-common/src/main/java/me/lucko/spark/common/monitor/os/OperatingSystemInfo.java diff --git a/spark-common/src/main/java/me/lucko/spark/common/monitor/os/OperatingSystemInfo.java b/spark-common/src/main/java/me/lucko/spark/common/monitor/os/OperatingSystemInfo.java new file mode 100644 index 0000000..4eeebd1 --- /dev/null +++ b/spark-common/src/main/java/me/lucko/spark/common/monitor/os/OperatingSystemInfo.java @@ -0,0 +1,78 @@ +/* + * This file is part of spark. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package me.lucko.spark.common.monitor.os; + +import me.lucko.spark.common.util.LinuxProc; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public enum OperatingSystemInfo { + ; + + private static String name = null; + private static String version = null; + + static { + final String osNameJavaProp = System.getProperty("os.name"); + + if (osNameJavaProp.startsWith("Windows")) { + final String[] args = { "wmic", "os", "get", "caption,version", "/FORMAT:list" }; + try (final BufferedReader buf = new BufferedReader(new InputStreamReader(new ProcessBuilder(args).redirectErrorStream(true).start().getInputStream()))) { + String line; + while ((line = buf.readLine()) != null) { + if (line.startsWith("Caption")) { + name = line.substring(18).trim(); + } else if (line.startsWith("Version")) { + version = line.substring(8).trim(); + } + } + } catch (final IOException | IndexOutOfBoundsException e) { + // ignore + } + } else { + for (final String line : LinuxProc.OSINFO.read()) { + if (line.startsWith("PRETTY_NAME")) { + try { + name = line.substring(13).replace('"', ' ').trim(); + } catch (final IndexOutOfBoundsException e) { + // ignore + } + } + } + } + + if (name == null) + name = osNameJavaProp; + + if (version == null) + version = System.getProperty("os.version"); + } + + public static String getName() { + return name; + } + + public static String getVersion() { + return version; + } +} diff --git a/spark-common/src/main/java/me/lucko/spark/common/platform/PlatformStatisticsProvider.java b/spark-common/src/main/java/me/lucko/spark/common/platform/PlatformStatisticsProvider.java index 49cfed5..e5be647 100644 --- a/spark-common/src/main/java/me/lucko/spark/common/platform/PlatformStatisticsProvider.java +++ b/spark-common/src/main/java/me/lucko/spark/common/platform/PlatformStatisticsProvider.java @@ -28,6 +28,7 @@ import me.lucko.spark.common.monitor.memory.GarbageCollectorStatistics; import me.lucko.spark.common.monitor.memory.MemoryInfo; import me.lucko.spark.common.monitor.net.NetworkInterfaceAverages; import me.lucko.spark.common.monitor.net.NetworkMonitor; +import me.lucko.spark.common.monitor.os.OperatingSystemInfo; import me.lucko.spark.common.monitor.ping.PingStatistics; import me.lucko.spark.common.monitor.tick.TickStatistics; import me.lucko.spark.common.platform.world.WorldInfoProvider; @@ -87,8 +88,8 @@ public class PlatformStatisticsProvider { ) .setOs(SystemStatistics.Os.newBuilder() .setArch(System.getProperty("os.arch")) - .setName(System.getProperty("os.name")) - .setVersion(System.getProperty("os.version")) + .setName(OperatingSystemInfo.getName()) + .setVersion(OperatingSystemInfo.getVersion()) .build() ) .setJava(SystemStatistics.Java.newBuilder() diff --git a/spark-common/src/main/java/me/lucko/spark/common/util/LinuxProc.java b/spark-common/src/main/java/me/lucko/spark/common/util/LinuxProc.java index 7d688d7..44fd3f9 100644 --- a/spark-common/src/main/java/me/lucko/spark/common/util/LinuxProc.java +++ b/spark-common/src/main/java/me/lucko/spark/common/util/LinuxProc.java @@ -49,7 +49,12 @@ public enum LinuxProc { /** * Information about the system network usage. */ - NET_DEV("/proc/net/dev"); + NET_DEV("/proc/net/dev"), + + /** + * Information about the operating system distro. + */ + OSINFO("/etc/os-release"); private final Path path; -- cgit From 1ebcc65460e85afd10b7e276892f2eb2f236701f Mon Sep 17 00:00:00 2001 From: Luck Date: Sun, 7 Aug 2022 21:25:39 +0100 Subject: Update forge/fabric to 1.19.2 --- spark-fabric/build.gradle | 8 ++++---- spark-forge/build.gradle | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/spark-fabric/build.gradle b/spark-fabric/build.gradle index 35b7a86..30b1ff6 100644 --- a/spark-fabric/build.gradle +++ b/spark-fabric/build.gradle @@ -28,9 +28,9 @@ configurations { dependencies { // https://modmuss50.me/fabric.html - minecraft 'com.mojang:minecraft:1.19' - mappings 'net.fabricmc:yarn:1.19+build.1:v2' - modImplementation 'net.fabricmc:fabric-loader:0.14.7' + minecraft 'com.mojang:minecraft:1.19.2' + mappings 'net.fabricmc:yarn:1.19.2+build.1:v2' + modImplementation 'net.fabricmc:fabric-loader:0.14.9' Set apiModules = [ "fabric-api-base", @@ -40,7 +40,7 @@ dependencies { // Add each module as a dependency apiModules.forEach { - modImplementation(fabricApi.module(it, '0.55.3+1.19')) + modImplementation(fabricApi.module(it, '0.59.0+1.19.2')) } include(modImplementation('me.lucko:fabric-permissions-api:0.1-SNAPSHOT')) diff --git a/spark-forge/build.gradle b/spark-forge/build.gradle index 46ac08c..5d6f2dc 100644 --- a/spark-forge/build.gradle +++ b/spark-forge/build.gradle @@ -20,7 +20,7 @@ tasks.withType(JavaCompile) { } minecraft { - mappings channel: 'official', version: '1.19' + mappings channel: 'official', version: '1.19.2' accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') } @@ -30,7 +30,7 @@ configurations { } dependencies { - minecraft 'net.minecraftforge:forge:1.19-41.0.11' + minecraft 'net.minecraftforge:forge:1.19.2-43.0.0' shade project(':spark-common') } -- cgit From c96f88f7c125109edcae382b8d10011e87125102 Mon Sep 17 00:00:00 2001 From: Luck Date: Sun, 7 Aug 2022 21:53:11 +0100 Subject: Refactor Windows wmic utility --- .../me/lucko/spark/common/monitor/LinuxProc.java | 89 +++++++++++++++++++++ .../me/lucko/spark/common/monitor/WindowsWmic.java | 74 ++++++++++++++++++ .../me/lucko/spark/common/monitor/cpu/CpuInfo.java | 32 +++----- .../spark/common/monitor/memory/MemoryInfo.java | 2 +- .../common/monitor/net/NetworkInterfaceInfo.java | 2 +- .../common/monitor/os/OperatingSystemInfo.java | 90 ++++++++++++---------- .../platform/PlatformStatisticsProvider.java | 7 +- .../java/me/lucko/spark/common/util/LinuxProc.java | 89 --------------------- 8 files changed, 229 insertions(+), 156 deletions(-) create mode 100644 spark-common/src/main/java/me/lucko/spark/common/monitor/LinuxProc.java create mode 100644 spark-common/src/main/java/me/lucko/spark/common/monitor/WindowsWmic.java delete mode 100644 spark-common/src/main/java/me/lucko/spark/common/util/LinuxProc.java diff --git a/spark-common/src/main/java/me/lucko/spark/common/monitor/LinuxProc.java b/spark-common/src/main/java/me/lucko/spark/common/monitor/LinuxProc.java new file mode 100644 index 0000000..563e247 --- /dev/null +++ b/spark-common/src/main/java/me/lucko/spark/common/monitor/LinuxProc.java @@ -0,0 +1,89 @@ +/* + * This file is part of spark. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package me.lucko.spark.common.monitor; + +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collections; +import java.util.List; + +/** + * Utility for reading from /proc/ on Linux systems. + */ +public enum LinuxProc { + + /** + * Information about the system CPU. + */ + CPUINFO("/proc/cpuinfo"), + + /** + * Information about the system memory. + */ + MEMINFO("/proc/meminfo"), + + /** + * Information about the system network usage. + */ + NET_DEV("/proc/net/dev"), + + /** + * Information about the operating system distro. + */ + OSINFO("/etc/os-release"); + + private final Path path; + + LinuxProc(String path) { + this.path = resolvePath(path); + } + + private static @Nullable Path resolvePath(String path) { + try { + Path p = Paths.get(path); + if (Files.isReadable(p)) { + return p; + } + } catch (Exception e) { + // ignore + } + return null; + } + + public @NonNull List read() { + if (this.path != null) { + try { + return Files.readAllLines(this.path, StandardCharsets.UTF_8); + } catch (IOException e) { + // ignore + } + } + + return Collections.emptyList(); + } + +} diff --git a/spark-common/src/main/java/me/lucko/spark/common/monitor/WindowsWmic.java b/spark-common/src/main/java/me/lucko/spark/common/monitor/WindowsWmic.java new file mode 100644 index 0000000..6b602d9 --- /dev/null +++ b/spark-common/src/main/java/me/lucko/spark/common/monitor/WindowsWmic.java @@ -0,0 +1,74 @@ +/* + * This file is part of spark. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package me.lucko.spark.common.monitor; + +import org.checkerframework.checker.nullness.qual.NonNull; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Utility for reading from wmic (Windows Management Instrumentation Commandline) on Windows systems. + */ +public enum WindowsWmic { + + /** + * Gets the CPU name + */ + CPU_GET_NAME("wmic", "cpu", "get", "name", "/FORMAT:list"), + + /** + * Gets the operating system name (caption) and version. + */ + OS_GET_CAPTION_AND_VERSION("wmic", "os", "get", "caption,version", "/FORMAT:list"); + + private static final boolean SUPPORTED = System.getProperty("os.name").startsWith("Windows"); + + private final String[] cmdArgs; + + WindowsWmic(String... cmdArgs) { + this.cmdArgs = cmdArgs; + } + + public @NonNull List read() { + if (SUPPORTED) { + ProcessBuilder process = new ProcessBuilder(this.cmdArgs).redirectErrorStream(true); + try (BufferedReader buf = new BufferedReader(new InputStreamReader(process.start().getInputStream()))) { + List lines = new ArrayList<>(); + + String line; + while ((line = buf.readLine()) != null) { + lines.add(line); + } + + return lines; + } catch (Exception e) { + // ignore + } + } + + return Collections.emptyList(); + } +} + diff --git a/spark-common/src/main/java/me/lucko/spark/common/monitor/cpu/CpuInfo.java b/spark-common/src/main/java/me/lucko/spark/common/monitor/cpu/CpuInfo.java index fcb70c0..9954bd5 100644 --- a/spark-common/src/main/java/me/lucko/spark/common/monitor/cpu/CpuInfo.java +++ b/spark-common/src/main/java/me/lucko/spark/common/monitor/cpu/CpuInfo.java @@ -20,11 +20,9 @@ package me.lucko.spark.common.monitor.cpu; -import me.lucko.spark.common.util.LinuxProc; +import me.lucko.spark.common.monitor.LinuxProc; +import me.lucko.spark.common.monitor.WindowsWmic; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; import java.util.regex.Pattern; /** @@ -41,27 +39,19 @@ public enum CpuInfo { * @return the cpu model */ public static String queryCpuModel() { - if (System.getProperty("os.name").startsWith("Windows")) { - final String[] args = { "wmic", "cpu", "get", "name", "/FORMAT:list" }; - try (final BufferedReader buf = new BufferedReader(new InputStreamReader(new ProcessBuilder(args).redirectErrorStream(true).start().getInputStream()))) { - String line; - while ((line = buf.readLine()) != null) { - if (line.startsWith("Name")) { - return line.substring(5).trim(); - } - } - } catch (final IOException e) { - return ""; + for (String line : LinuxProc.CPUINFO.read()) { + String[] splitLine = SPACE_COLON_SPACE_PATTERN.split(line); + if (splitLine[0].equals("model name") || splitLine[0].equals("Processor")) { + return splitLine[1]; } - } else { - for (String line : LinuxProc.CPUINFO.read()) { - String[] splitLine = SPACE_COLON_SPACE_PATTERN.split(line); + } - if (splitLine[0].equals("model name") || splitLine[0].equals("Processor")) { - return splitLine[1]; - } + for (String line : WindowsWmic.CPU_GET_NAME.read()) { + if (line.startsWith("Name")) { + return line.substring(5).trim(); } } + return ""; } diff --git a/spark-common/src/main/java/me/lucko/spark/common/monitor/memory/MemoryInfo.java b/spark-common/src/main/java/me/lucko/spark/common/monitor/memory/MemoryInfo.java index 226f75b..8f63f71 100644 --- a/spark-common/src/main/java/me/lucko/spark/common/monitor/memory/MemoryInfo.java +++ b/spark-common/src/main/java/me/lucko/spark/common/monitor/memory/MemoryInfo.java @@ -20,7 +20,7 @@ package me.lucko.spark.common.monitor.memory; -import me.lucko.spark.common.util.LinuxProc; +import me.lucko.spark.common.monitor.LinuxProc; import java.lang.management.ManagementFactory; import java.util.regex.Matcher; diff --git a/spark-common/src/main/java/me/lucko/spark/common/monitor/net/NetworkInterfaceInfo.java b/spark-common/src/main/java/me/lucko/spark/common/monitor/net/NetworkInterfaceInfo.java index bd9e187..332077a 100644 --- a/spark-common/src/main/java/me/lucko/spark/common/monitor/net/NetworkInterfaceInfo.java +++ b/spark-common/src/main/java/me/lucko/spark/common/monitor/net/NetworkInterfaceInfo.java @@ -22,7 +22,7 @@ package me.lucko.spark.common.monitor.net; import com.google.common.collect.ImmutableMap; -import me.lucko.spark.common.util.LinuxProc; +import me.lucko.spark.common.monitor.LinuxProc; import org.checkerframework.checker.nullness.qual.NonNull; diff --git a/spark-common/src/main/java/me/lucko/spark/common/monitor/os/OperatingSystemInfo.java b/spark-common/src/main/java/me/lucko/spark/common/monitor/os/OperatingSystemInfo.java index 4eeebd1..1c2732c 100644 --- a/spark-common/src/main/java/me/lucko/spark/common/monitor/os/OperatingSystemInfo.java +++ b/spark-common/src/main/java/me/lucko/spark/common/monitor/os/OperatingSystemInfo.java @@ -20,59 +20,67 @@ package me.lucko.spark.common.monitor.os; -import me.lucko.spark.common.util.LinuxProc; +import me.lucko.spark.common.monitor.LinuxProc; +import me.lucko.spark.common.monitor.WindowsWmic; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; +/** + * Small utility to query the operating system name & version. + */ +public final class OperatingSystemInfo { + private final String name; + private final String version; + private final String arch; + + public OperatingSystemInfo(String name, String version, String arch) { + this.name = name; + this.version = version; + this.arch = arch; + } -public enum OperatingSystemInfo { - ; + public String name() { + return this.name; + } - private static String name = null; - private static String version = null; + public String version() { + return this.version; + } + + public String arch() { + return this.arch; + } - static { - final String osNameJavaProp = System.getProperty("os.name"); + public static OperatingSystemInfo poll() { + String name = null; + String version = null; - if (osNameJavaProp.startsWith("Windows")) { - final String[] args = { "wmic", "os", "get", "caption,version", "/FORMAT:list" }; - try (final BufferedReader buf = new BufferedReader(new InputStreamReader(new ProcessBuilder(args).redirectErrorStream(true).start().getInputStream()))) { - String line; - while ((line = buf.readLine()) != null) { - if (line.startsWith("Caption")) { - name = line.substring(18).trim(); - } else if (line.startsWith("Version")) { - version = line.substring(8).trim(); - } - } - } catch (final IOException | IndexOutOfBoundsException e) { - // ignore + for (String line : LinuxProc.OSINFO.read()) { + if (line.startsWith("PRETTY_NAME") && line.length() > 13) { + name = line.substring(13).replace('"', ' ').trim(); } - } else { - for (final String line : LinuxProc.OSINFO.read()) { - if (line.startsWith("PRETTY_NAME")) { - try { - name = line.substring(13).replace('"', ' ').trim(); - } catch (final IndexOutOfBoundsException e) { - // ignore - } - } + } + + for (String line : WindowsWmic.OS_GET_CAPTION_AND_VERSION.read()) { + if (line.startsWith("Caption") && line.length() > 18) { + // Caption=Microsoft Windows something + // \----------------/ = 18 chars + name = line.substring(18).trim(); + } else if (line.startsWith("Version")) { + // Version=10.0.something + // \------/ = 8 chars + version = line.substring(8).trim(); } } - if (name == null) - name = osNameJavaProp; + if (name == null) { + name = System.getProperty("os.name"); + } - if (version == null) + if (version == null) { version = System.getProperty("os.version"); - } + } - public static String getName() { - return name; - } + String arch = System.getProperty("os.arch"); - public static String getVersion() { - return version; + return new OperatingSystemInfo(name, version, arch); } } diff --git a/spark-common/src/main/java/me/lucko/spark/common/platform/PlatformStatisticsProvider.java b/spark-common/src/main/java/me/lucko/spark/common/platform/PlatformStatisticsProvider.java index e5be647..1eb9753 100644 --- a/spark-common/src/main/java/me/lucko/spark/common/platform/PlatformStatisticsProvider.java +++ b/spark-common/src/main/java/me/lucko/spark/common/platform/PlatformStatisticsProvider.java @@ -51,6 +51,7 @@ public class PlatformStatisticsProvider { public SystemStatistics getSystemStatistics() { RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); + OperatingSystemInfo osInfo = OperatingSystemInfo.poll(); SystemStatistics.Builder builder = SystemStatistics.newBuilder() .setCpu(SystemStatistics.Cpu.newBuilder() @@ -87,9 +88,9 @@ public class PlatformStatisticsProvider { .build() ) .setOs(SystemStatistics.Os.newBuilder() - .setArch(System.getProperty("os.arch")) - .setName(OperatingSystemInfo.getName()) - .setVersion(OperatingSystemInfo.getVersion()) + .setArch(osInfo.arch()) + .setName(osInfo.name()) + .setVersion(osInfo.version()) .build() ) .setJava(SystemStatistics.Java.newBuilder() diff --git a/spark-common/src/main/java/me/lucko/spark/common/util/LinuxProc.java b/spark-common/src/main/java/me/lucko/spark/common/util/LinuxProc.java deleted file mode 100644 index 44fd3f9..0000000 --- a/spark-common/src/main/java/me/lucko/spark/common/util/LinuxProc.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * This file is part of spark. - * - * Copyright (c) lucko (Luck) - * Copyright (c) contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package me.lucko.spark.common.util; - -import org.checkerframework.checker.nullness.qual.NonNull; -import org.checkerframework.checker.nullness.qual.Nullable; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.List; - -/** - * Utility for reading from /proc/ on Linux systems. - */ -public enum LinuxProc { - - /** - * Information about the system CPU. - */ - CPUINFO("/proc/cpuinfo"), - - /** - * Information about the system memory. - */ - MEMINFO("/proc/meminfo"), - - /** - * Information about the system network usage. - */ - NET_DEV("/proc/net/dev"), - - /** - * Information about the operating system distro. - */ - OSINFO("/etc/os-release"); - - private final Path path; - - LinuxProc(String path) { - this.path = resolvePath(path); - } - - private static @Nullable Path resolvePath(String path) { - try { - Path p = Paths.get(path); - if (Files.isReadable(p)) { - return p; - } - } catch (Exception e) { - // ignore - } - return null; - } - - public @NonNull List read() { - if (this.path != null) { - try { - return Files.readAllLines(this.path, StandardCharsets.UTF_8); - } catch (IOException e) { - // ignore - } - } - - return Collections.emptyList(); - } - -} -- cgit From 22e29390a12c3b8989355d18ec9e462a19008e3a Mon Sep 17 00:00:00 2001 From: Luck Date: Sun, 4 Sep 2022 10:21:23 +0100 Subject: Add extra null checks to BukkitWorldInfoProvider (#247) --- .../main/java/me/lucko/spark/bukkit/BukkitWorldInfoProvider.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/spark-bukkit/src/main/java/me/lucko/spark/bukkit/BukkitWorldInfoProvider.java b/spark-bukkit/src/main/java/me/lucko/spark/bukkit/BukkitWorldInfoProvider.java index 5d50eeb..79c2715 100644 --- a/spark-bukkit/src/main/java/me/lucko/spark/bukkit/BukkitWorldInfoProvider.java +++ b/spark-bukkit/src/main/java/me/lucko/spark/bukkit/BukkitWorldInfoProvider.java @@ -49,7 +49,9 @@ public class BukkitWorldInfoProvider implements WorldInfoProvider { List list = new ArrayList<>(chunks.length); for (Chunk chunk : chunks) { - list.add(new BukkitChunkInfo(chunk)); + if (chunk != null) { + list.add(new BukkitChunkInfo(chunk)); + } } data.put(world.getName(), list); @@ -66,7 +68,9 @@ public class BukkitWorldInfoProvider implements WorldInfoProvider { this.entityCounts = new CountMap.EnumKeyed<>(EntityType.class); for (Entity entity : chunk.getEntities()) { - this.entityCounts.increment(entity.getType()); + if (entity != null) { + this.entityCounts.increment(entity.getType()); + } } } -- cgit From 7dce92ac6f577e04b99a1da555edfbc801efa049 Mon Sep 17 00:00:00 2001 From: Luck Date: Sun, 4 Sep 2022 10:34:02 +0100 Subject: Update async-profiler --- spark-common/build.gradle | 2 +- .../spark/linux/aarch64/libasyncProfiler.so | Bin 333864 -> 334176 bytes .../spark/linux/amd64-musl/libasyncProfiler.so | Bin 304568 -> 308800 bytes .../spark/linux/amd64/libasyncProfiler.so | Bin 347712 -> 352112 bytes .../main/resources/spark/macos/libasyncProfiler.so | Bin 690128 -> 690208 bytes 5 files changed, 1 insertion(+), 1 deletion(-) diff --git a/spark-common/build.gradle b/spark-common/build.gradle index ce09d51..4a20142 100644 --- a/spark-common/build.gradle +++ b/spark-common/build.gradle @@ -8,7 +8,7 @@ license { dependencies { api project(':spark-api') - implementation 'com.github.jvm-profiling-tools:async-profiler:v2.8.1' + implementation 'com.github.jvm-profiling-tools:async-profiler:v2.8.3' implementation 'org.ow2.asm:asm:9.1' implementation 'com.google.protobuf:protobuf-javalite:3.15.6' implementation 'net.bytebuddy:byte-buddy-agent:1.11.0' diff --git a/spark-common/src/main/resources/spark/linux/aarch64/libasyncProfiler.so b/spark-common/src/main/resources/spark/linux/aarch64/libasyncProfiler.so index c3c2eb2..cf6c48b 100755 Binary files a/spark-common/src/main/resources/spark/linux/aarch64/libasyncProfiler.so and b/spark-common/src/main/resources/spark/linux/aarch64/libasyncProfiler.so differ diff --git a/spark-common/src/main/resources/spark/linux/amd64-musl/libasyncProfiler.so b/spark-common/src/main/resources/spark/linux/amd64-musl/libasyncProfiler.so index 4c69ab8..0a08f7c 100755 Binary files a/spark-common/src/main/resources/spark/linux/amd64-musl/libasyncProfiler.so and b/spark-common/src/main/resources/spark/linux/amd64-musl/libasyncProfiler.so differ diff --git a/spark-common/src/main/resources/spark/linux/amd64/libasyncProfiler.so b/spark-common/src/main/resources/spark/linux/amd64/libasyncProfiler.so index 5612ad9..0deb9e0 100755 Binary files a/spark-common/src/main/resources/spark/linux/amd64/libasyncProfiler.so and b/spark-common/src/main/resources/spark/linux/amd64/libasyncProfiler.so differ diff --git a/spark-common/src/main/resources/spark/macos/libasyncProfiler.so b/spark-common/src/main/resources/spark/macos/libasyncProfiler.so index 1fc6ba3..65b4aed 100755 Binary files a/spark-common/src/main/resources/spark/macos/libasyncProfiler.so and b/spark-common/src/main/resources/spark/macos/libasyncProfiler.so differ -- cgit From 618230b958d7822985e2702cd9528f1b4567e59c Mon Sep 17 00:00:00 2001 From: Luck Date: Sun, 4 Sep 2022 10:53:06 +0100 Subject: Improve debug output when JFR parsing fails --- .../spark/common/sampler/async/AsyncSampler.java | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/spark-common/src/main/java/me/lucko/spark/common/sampler/async/AsyncSampler.java b/spark-common/src/main/java/me/lucko/spark/common/sampler/async/AsyncSampler.java index d8288da..dae3852 100644 --- a/spark-common/src/main/java/me/lucko/spark/common/sampler/async/AsyncSampler.java +++ b/spark-common/src/main/java/me/lucko/spark/common/sampler/async/AsyncSampler.java @@ -185,8 +185,19 @@ public class AsyncSampler extends AbstractSampler { // read the jfr file produced by async-profiler try (JfrReader reader = new JfrReader(this.outputFile)) { readSegments(reader, threadFilter); - } catch (IOException e) { - throw new RuntimeException("Read error", e); + } catch (Exception e) { + boolean fileExists; + try { + fileExists = Files.exists(this.outputFile) && Files.size(this.outputFile) != 0; + } catch (IOException ex) { + fileExists = false; + } + + if (fileExists) { + throw new JfrParsingException("Error parsing JFR data from profiler output", e); + } else { + throw new JfrParsingException("Error parsing JFR data from profiler output - file " + this.outputFile + " does not exist!", e); + } } // delete the output file after reading @@ -268,4 +279,10 @@ public class AsyncSampler extends AbstractSampler { reader.stackFrames.put(methodId, result); return result; } + + private static final class JfrParsingException extends RuntimeException { + public JfrParsingException(String message, Throwable cause) { + super(message, cause); + } + } } -- cgit From 7ef9b6281135ce0a24f3c14c2255d9a2c2eca969 Mon Sep 17 00:00:00 2001 From: ishland Date: Mon, 19 Sep 2022 21:48:28 +0800 Subject: Display source info for mixin injected methods (#249) Co-authored-by: Luck --- .../spark/common/sampler/AbstractSampler.java | 12 +- .../lucko/spark/common/util/ClassSourceLookup.java | 257 +++++++++++++++++++-- .../src/main/proto/spark/spark_sampler.proto | 2 + spark-fabric/build.gradle | 10 +- .../spark/fabric/FabricClassSourceLookup.java | 159 ++++++++++++- .../fabric/plugin/FabricSparkMixinPlugin.java | 71 ++++++ .../me/lucko/spark/fabric/smap/MixinUtils.java | 52 +++++ .../lucko/spark/fabric/smap/SourceDebugCache.java | 87 +++++++ .../java/me/lucko/spark/fabric/smap/SourceMap.java | 133 +++++++++++ .../lucko/spark/fabric/smap/SourceMapProvider.java | 53 +++++ spark-fabric/src/main/resources/spark.mixins.json | 3 +- 11 files changed, 806 insertions(+), 33 deletions(-) create mode 100644 spark-fabric/src/main/java/me/lucko/spark/fabric/plugin/FabricSparkMixinPlugin.java create mode 100644 spark-fabric/src/main/java/me/lucko/spark/fabric/smap/MixinUtils.java create mode 100644 spark-fabric/src/main/java/me/lucko/spark/fabric/smap/SourceDebugCache.java create mode 100644 spark-fabric/src/main/java/me/lucko/spark/fabric/smap/SourceMap.java create mode 100644 spark-fabric/src/main/java/me/lucko/spark/fabric/smap/SourceMapProvider.java diff --git a/spark-common/src/main/java/me/lucko/spark/common/sampler/AbstractSampler.java b/spark-common/src/main/java/me/lucko/spark/common/sampler/AbstractSampler.java index 1c217db..3cfef0b 100644 --- a/spark-common/src/main/java/me/lucko/spark/common/sampler/AbstractSampler.java +++ b/spark-common/src/main/java/me/lucko/spark/common/sampler/AbstractSampler.java @@ -164,8 +164,16 @@ public abstract class AbstractSampler implements Sampler { classSourceVisitor.visit(entry); } - if (classSourceVisitor.hasMappings()) { - proto.putAllClassSources(classSourceVisitor.getMapping()); + if (classSourceVisitor.hasClassSourceMappings()) { + proto.putAllClassSources(classSourceVisitor.getClassSourceMapping()); + } + + if (classSourceVisitor.hasMethodSourceMappings()) { + proto.putAllMethodSources(classSourceVisitor.getMethodSourceMapping()); + } + + if (classSourceVisitor.hasLineSourceMappings()) { + proto.putAllLineSources(classSourceVisitor.getLineSourceMapping()); } } } diff --git a/spark-common/src/main/java/me/lucko/spark/common/util/ClassSourceLookup.java b/spark-common/src/main/java/me/lucko/spark/common/util/ClassSourceLookup.java index bd9ec37..668f31a 100644 --- a/spark-common/src/main/java/me/lucko/spark/common/util/ClassSourceLookup.java +++ b/spark-common/src/main/java/me/lucko/spark/common/util/ClassSourceLookup.java @@ -38,9 +38,11 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.function.Function; +import java.util.stream.Collectors; /** - * A function which defines the source of given {@link Class}es. + * A function which defines the source of given {@link Class}es or (Mixin) method calls. */ public interface ClassSourceLookup { @@ -52,6 +54,26 @@ public interface ClassSourceLookup { */ @Nullable String identify(Class clazz) throws Exception; + /** + * Identify the given method call. + * + * @param methodCall the method call info + * @return the source of the method call + */ + default @Nullable String identify(MethodCall methodCall) throws Exception { + return null; + } + + /** + * Identify the given method call. + * + * @param methodCall the method call info + * @return the source of the method call + */ + default @Nullable String identify(MethodCallByLine methodCall) throws Exception { + return null; + } + /** * A no-operation {@link ClassSourceLookup}. */ @@ -156,9 +178,17 @@ public interface ClassSourceLookup { interface Visitor { void visit(ThreadNode node); - boolean hasMappings(); + boolean hasClassSourceMappings(); + + Map getClassSourceMapping(); + + boolean hasMethodSourceMappings(); + + Map getMethodSourceMapping(); + + boolean hasLineSourceMappings(); - Map getMapping(); + Map getLineSourceMapping(); } static Visitor createVisitor(ClassSourceLookup lookup) { @@ -177,25 +207,46 @@ public interface ClassSourceLookup { } @Override - public boolean hasMappings() { + public boolean hasClassSourceMappings() { + return false; + } + + @Override + public Map getClassSourceMapping() { + return Collections.emptyMap(); + } + + @Override + public boolean hasMethodSourceMappings() { + return false; + } + + @Override + public Map getMethodSourceMapping() { + return Collections.emptyMap(); + } + + @Override + public boolean hasLineSourceMappings() { return false; } @Override - public Map getMapping() { + public Map getLineSourceMapping() { return Collections.emptyMap(); } } /** - * Visitor which scans {@link StackTraceNode}s and accumulates class identities. + * Visitor which scans {@link StackTraceNode}s and accumulates class/method call identities. */ class VisitorImpl implements Visitor { private final ClassSourceLookup lookup; private final ClassFinder classFinder = new ClassFinder(); - // class name --> identifier (plugin name) - private final Map map = new HashMap<>(); + private final SourcesMap classSources = new SourcesMap<>(Function.identity()); + private final SourcesMap methodSources = new SourcesMap<>(MethodCall::toString); + private final SourcesMap lineSources = new SourcesMap<>(MethodCallByLine::toString); VisitorImpl(ClassSourceLookup lookup) { this.lookup = lookup; @@ -208,34 +259,194 @@ public interface ClassSourceLookup { } } + private void visitStackNode(StackTraceNode node) { + this.classSources.computeIfAbsent( + node.getClassName(), + className -> { + Class clazz = this.classFinder.findClass(className); + if (clazz == null) { + return null; + } + return this.lookup.identify(clazz); + }); + + if (node.getMethodDescription() != null) { + MethodCall methodCall = new MethodCall(node.getClassName(), node.getMethodName(), node.getMethodDescription()); + this.methodSources.computeIfAbsent(methodCall, this.lookup::identify); + } else { + MethodCallByLine methodCall = new MethodCallByLine(node.getClassName(), node.getMethodName(), node.getLineNumber()); + this.lineSources.computeIfAbsent(methodCall, this.lookup::identify); + } + + // recursively + for (StackTraceNode child : node.getChildren()) { + visitStackNode(child); + } + } + @Override - public boolean hasMappings() { - return !this.map.isEmpty(); + public boolean hasClassSourceMappings() { + return this.classSources.hasMappings(); } @Override - public Map getMapping() { - this.map.values().removeIf(Objects::isNull); - return this.map; + public Map getClassSourceMapping() { + return this.classSources.export(); } - private void visitStackNode(StackTraceNode node) { - String className = node.getClassName(); - if (!this.map.containsKey(className)) { + @Override + public boolean hasMethodSourceMappings() { + return this.methodSources.hasMappings(); + } + + @Override + public Map getMethodSourceMapping() { + return this.methodSources.export(); + } + + @Override + public boolean hasLineSourceMappings() { + return this.lineSources.hasMappings(); + } + + @Override + public Map getLineSourceMapping() { + return this.lineSources.export(); + } + } + + final class SourcesMap { + // --> identifier (plugin name) + private final Map map = new HashMap<>(); + private final Function keyToStringFunction; + + private SourcesMap(Function keyToStringFunction) { + this.keyToStringFunction = keyToStringFunction; + } + + public void computeIfAbsent(T key, ComputeSourceFunction function) { + if (!this.map.containsKey(key)) { try { - Class clazz = this.classFinder.findClass(className); - Objects.requireNonNull(clazz); - this.map.put(className, this.lookup.identify(clazz)); + this.map.put(key, function.compute(key)); } catch (Throwable e) { - this.map.put(className, null); + this.map.put(key, null); } } + } - // recursively - for (StackTraceNode child : node.getChildren()) { - visitStackNode(child); + public boolean hasMappings() { + this.map.values().removeIf(Objects::isNull); + return !this.map.isEmpty(); + } + + public Map export() { + this.map.values().removeIf(Objects::isNull); + if (this.keyToStringFunction.equals(Function.identity())) { + //noinspection unchecked + return (Map) this.map; + } else { + return this.map.entrySet().stream().collect(Collectors.toMap( + e -> this.keyToStringFunction.apply(e.getKey()), + Map.Entry::getValue + )); } } + + private interface ComputeSourceFunction { + String compute(T key) throws Exception; + } + } + + /** + * Encapsulates information about a given method call using the name + method description. + */ + final class MethodCall { + private final String className; + private final String methodName; + private final String methodDescriptor; + + public MethodCall(String className, String methodName, String methodDescriptor) { + this.className = className; + this.methodName = methodName; + this.methodDescriptor = methodDescriptor; + } + + public String getClassName() { + return this.className; + } + + public String getMethodName() { + return this.methodName; + } + + public String getMethodDescriptor() { + return this.methodDescriptor; + } + + @Override + public String toString() { + return this.className + ";" + this.methodName + ";" + this.methodDescriptor; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof MethodCall)) return false; + MethodCall that = (MethodCall) o; + return this.className.equals(that.className) && + this.methodName.equals(that.methodName) && + this.methodDescriptor.equals(that.methodDescriptor); + } + + @Override + public int hashCode() { + return Objects.hash(this.className, this.methodName, this.methodDescriptor); + } + } + + /** + * Encapsulates information about a given method call using the name + line number. + */ + final class MethodCallByLine { + private final String className; + private final String methodName; + private final int lineNumber; + + public MethodCallByLine(String className, String methodName, int lineNumber) { + this.className = className; + this.methodName = methodName; + this.lineNumber = lineNumber; + } + + public String getClassName() { + return this.className; + } + + public String getMethodName() { + return this.methodName; + } + + public int getLineNumber() { + return this.lineNumber; + } + + @Override + public String toString() { + return this.className + ";" + this.lineNumber; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof MethodCallByLine)) return false; + MethodCallByLine that = (MethodCallByLine) o; + return this.lineNumber == that.lineNumber && this.className.equals(that.className); + } + + @Override + public int hashCode() { + return Objects.hash(this.className, this.lineNumber); + } } } diff --git a/spark-common/src/main/proto/spark/spark_sampler.proto b/spark-common/src/main/proto/spark/spark_sampler.proto index 8d9512a..f670ddf 100644 --- a/spark-common/src/main/proto/spark/spark_sampler.proto +++ b/spark-common/src/main/proto/spark/spark_sampler.proto @@ -11,6 +11,8 @@ message SamplerData { SamplerMetadata metadata = 1; repeated ThreadNode threads = 2; map class_sources = 3; // optional + map method_sources = 4; // optional + map line_sources = 5; // optional } message SamplerMetadata { diff --git a/spark-fabric/build.gradle b/spark-fabric/build.gradle index 30b1ff6..fce859a 100644 --- a/spark-fabric/build.gradle +++ b/spark-fabric/build.gradle @@ -66,6 +66,10 @@ processResources { } } +license { + exclude '**/smap/SourceMap.java' +} + shadowJar { archiveFileName = "spark-fabric-${project.pluginVersion}-dev.jar" configurations = [project.configurations.shade] @@ -74,12 +78,16 @@ shadowJar { relocate 'net.kyori.examination', 'me.lucko.spark.lib.adventure.examination' relocate 'net.bytebuddy', 'me.lucko.spark.lib.bytebuddy' relocate 'com.google.protobuf', 'me.lucko.spark.lib.protobuf' - relocate 'org.objectweb.asm', 'me.lucko.spark.lib.asm' +// relocate 'org.objectweb.asm', 'me.lucko.spark.lib.asm' relocate 'one.profiler', 'me.lucko.spark.lib.asyncprofiler' exclude 'module-info.class' exclude 'META-INF/maven/**' exclude 'META-INF/proguard/**' + + dependencies { + exclude(dependency('org.ow2.asm::')) + } } task remappedShadowJar(type: RemapJarTask) { diff --git a/spark-fabric/src/main/java/me/lucko/spark/fabric/FabricClassSourceLookup.java b/spark-fabric/src/main/java/me/lucko/spark/fabric/FabricClassSourceLookup.java index 7030680..9ffac18 100644 --- a/spark-fabric/src/main/java/me/lucko/spark/fabric/FabricClassSourceLookup.java +++ b/spark-fabric/src/main/java/me/lucko/spark/fabric/FabricClassSourceLookup.java @@ -22,18 +22,35 @@ package me.lucko.spark.fabric; import com.google.common.collect.ImmutableMap; +import me.lucko.spark.common.util.ClassFinder; import me.lucko.spark.common.util.ClassSourceLookup; +import me.lucko.spark.fabric.smap.MixinUtils; +import me.lucko.spark.fabric.smap.SourceMap; +import me.lucko.spark.fabric.smap.SourceMapProvider; import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.ModContainer; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.objectweb.asm.Type; +import org.spongepowered.asm.mixin.FabricUtil; +import org.spongepowered.asm.mixin.extensibility.IMixinConfig; +import org.spongepowered.asm.mixin.transformer.Config; +import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; + +import java.lang.reflect.Method; +import java.net.URI; import java.nio.file.Path; import java.util.Collection; import java.util.Map; public class FabricClassSourceLookup extends ClassSourceLookup.ByCodeSource { + + private final ClassFinder classFinder = new ClassFinder(); + private final SourceMapProvider smapProvider = new SourceMapProvider(); + private final Path modsDirectory; - private final Map pathToModMap; + private final Map pathToModMap; public FabricClassSourceLookup() { FabricLoader loader = FabricLoader.getInstance(); @@ -43,7 +60,7 @@ public class FabricClassSourceLookup extends ClassSourceLookup.ByCodeSource { @Override public String identifyFile(Path path) { - String id = this.pathToModMap.get(path); + String id = this.pathToModMap.get(path.toAbsolutePath().normalize().toString()); if (id != null) { return id; } @@ -55,11 +72,141 @@ public class FabricClassSourceLookup extends ClassSourceLookup.ByCodeSource { return super.identifyFileName(this.modsDirectory.relativize(path).toString()); } - private static Map constructPathToModIdMap(Collection mods) { - ImmutableMap.Builder builder = ImmutableMap.builder(); + @Override + public @Nullable String identify(MethodCall methodCall) throws Exception { + String className = methodCall.getClassName(); + String methodName = methodCall.getMethodName(); + String methodDesc = methodCall.getMethodDescriptor(); + + if (className.equals("native") || methodName.equals("") || methodName.equals("")) { + return null; + } + + Class clazz = this.classFinder.findClass(className); + if (clazz == null) { + return null; + } + + Class[] params = getParameterTypesForMethodDesc(methodDesc); + Method reflectMethod = clazz.getDeclaredMethod(methodName, params); + + MixinMerged mixinMarker = reflectMethod.getDeclaredAnnotation(MixinMerged.class); + if (mixinMarker == null) { + return null; + } + + return modIdFromMixinClass(mixinMarker.mixin()); + } + + @Override + public @Nullable String identify(MethodCallByLine methodCall) throws Exception { + String className = methodCall.getClassName(); + String methodName = methodCall.getMethodName(); + int lineNumber = methodCall.getLineNumber(); + + if (className.equals("native") || methodName.equals("") || methodName.equals("")) { + return null; + } + + SourceMap smap = this.smapProvider.getSourceMap(className); + if (smap == null) { + return null; + } + + int[] inputLineInfo = smap.getReverseLineMapping().get(lineNumber); + if (inputLineInfo == null || inputLineInfo.length == 0) { + return null; + } + + for (int fileInfoIds : inputLineInfo) { + SourceMap.FileInfo inputFileInfo = smap.getFileInfo().get(fileInfoIds); + if (inputFileInfo == null) { + continue; + } + + String path = inputFileInfo.path(); + if (path.endsWith(".java")) { + path = path.substring(0, path.length() - 5); + } + + String possibleMixinClassName = path.replace('/', '.'); + if (possibleMixinClassName.equals(className)) { + continue; + } + + return modIdFromMixinClass(possibleMixinClassName); + } + + return null; + } + + private static String modIdFromMixinClass(String mixinClassName) { + for (Config config : MixinUtils.getMixinConfigs().values()) { + IMixinConfig mixinConfig = config.getConfig(); + if (mixinClassName.startsWith(mixinConfig.getMixinPackage())) { + return mixinConfig.getDecoration(FabricUtil.KEY_MOD_ID); + } + } + return null; + } + + private Class[] getParameterTypesForMethodDesc(String methodDesc) { + Type methodType = Type.getMethodType(methodDesc); + Class[] params = new Class[methodType.getArgumentTypes().length]; + Type[] argumentTypes = methodType.getArgumentTypes(); + + for (int i = 0, argumentTypesLength = argumentTypes.length; i < argumentTypesLength; i++) { + Type argumentType = argumentTypes[i]; + params[i] = getClassFromType(argumentType); + } + + return params; + } + + private Class getClassFromType(Type type) { + return switch (type.getSort()) { + case Type.VOID -> void.class; + case Type.BOOLEAN -> boolean.class; + case Type.CHAR -> char.class; + case Type.BYTE -> byte.class; + case Type.SHORT -> short.class; + case Type.INT -> int.class; + case Type.FLOAT -> float.class; + case Type.LONG -> long.class; + case Type.DOUBLE -> double.class; + case Type.ARRAY -> { + final Class classFromType = getClassFromType(type.getElementType()); + Class result = classFromType; + if (classFromType != null) { + for (int i = 0; i < type.getDimensions(); i++) { + result = result.arrayType(); + } + } + yield result; + } + case Type.OBJECT -> this.classFinder.findClass(type.getClassName()); + default -> null; + }; + } + + private static Map constructPathToModIdMap(Collection mods) { + ImmutableMap.Builder builder = ImmutableMap.builder(); for (ModContainer mod : mods) { - Path path = mod.getRootPath().toAbsolutePath().normalize(); - builder.put(path, mod.getMetadata().getId()); + String modId = mod.getMetadata().getId(); + if (modId.equals("java")) { + continue; + } + + for (Path path : mod.getRootPaths()) { + URI uri = path.toUri(); + if (uri.getScheme().equals("jar") && path.toString().equals("/")) { // ZipFileSystem + String zipFilePath = path.getFileSystem().toString(); + builder.put(zipFilePath, modId); + } else { + builder.put(path.toAbsolutePath().normalize().toString(), modId); + } + + } } return builder.build(); } diff --git a/spark-fabric/src/main/java/me/lucko/spark/fabric/plugin/FabricSparkMixinPlugin.java b/spark-fabric/src/main/java/me/lucko/spark/fabric/plugin/FabricSparkMixinPlugin.java new file mode 100644 index 0000000..cfc8c95 --- /dev/null +++ b/spark-fabric/src/main/java/me/lucko/spark/fabric/plugin/FabricSparkMixinPlugin.java @@ -0,0 +1,71 @@ +/* + * This file is part of spark. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package me.lucko.spark.fabric.plugin; + +import me.lucko.spark.fabric.smap.SourceDebugCache; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.transformer.IMixinTransformer; +import org.spongepowered.asm.mixin.transformer.ext.Extensions; +import org.spongepowered.asm.mixin.transformer.ext.IExtension; +import org.spongepowered.asm.mixin.transformer.ext.ITargetClassContext; + +import java.util.List; +import java.util.Set; + +public class FabricSparkMixinPlugin implements IMixinConfigPlugin, IExtension { + + private static final Logger LOGGER = LogManager.getLogger("spark"); + + @Override + public void onLoad(String mixinPackage) { + Object activeTransformer = MixinEnvironment.getCurrentEnvironment().getActiveTransformer(); + if (activeTransformer instanceof IMixinTransformer transformer && transformer.getExtensions() instanceof Extensions extensions) { + extensions.add(this); + } else { + LOGGER.error( + "Failed to initialize SMAP parser for spark profiler. " + + "Mod information for mixin injected methods is now only available with the async-profiler engine." + ); + } + } + + @Override + public void export(MixinEnvironment env, String name, boolean force, ClassNode classNode) { + SourceDebugCache.put(name, classNode); + } + + // noop + @Override public String getRefMapperConfig() { return null; } + @Override public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { return true; } + @Override public void acceptTargets(Set myTargets, Set otherTargets) { } + @Override public List getMixins() { return null; } + @Override public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } + @Override public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } + @Override public boolean checkActive(MixinEnvironment environment) { return true; } + @Override public void preApply(ITargetClassContext context) { } + @Override public void postApply(ITargetClassContext context) { } + +} diff --git a/spark-fabric/src/main/java/me/lucko/spark/fabric/smap/MixinUtils.java b/spark-fabric/src/main/java/me/lucko/spark/fabric/smap/MixinUtils.java new file mode 100644 index 0000000..ebf2766 --- /dev/null +++ b/spark-fabric/src/main/java/me/lucko/spark/fabric/smap/MixinUtils.java @@ -0,0 +1,52 @@ +/* + * This file is part of spark. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package me.lucko.spark.fabric.smap; + +import org.spongepowered.asm.mixin.transformer.Config; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + +public enum MixinUtils { + ; + + private static final Map MIXIN_CONFIGS; + + static { + Map configs; + try { + Field allConfigsField = Config.class.getDeclaredField("allConfigs"); + allConfigsField.setAccessible(true); + + //noinspection unchecked + configs = (Map) allConfigsField.get(null); + } catch (Exception e) { + e.printStackTrace(); + configs = new HashMap<>(); + } + MIXIN_CONFIGS = configs; + } + + public static Map getMixinConfigs() { + return MIXIN_CONFIGS; + } +} diff --git a/spark-fabric/src/main/java/me/lucko/spark/fabric/smap/SourceDebugCache.java b/spark-fabric/src/main/java/me/lucko/spark/fabric/smap/SourceDebugCache.java new file mode 100644 index 0000000..88adae6 --- /dev/null +++ b/spark-fabric/src/main/java/me/lucko/spark/fabric/smap/SourceDebugCache.java @@ -0,0 +1,87 @@ +/* + * This file is part of spark. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package me.lucko.spark.fabric.smap; + +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.service.IClassBytecodeProvider; +import org.spongepowered.asm.service.MixinService; + +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Caches the lookup of class -> source debug info for classes loaded on the JVM. + * + * The {@li