DEV Community

Query Filter
Query Filter

Posted on

bridge44

package comet.agent;

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.utility.JavaModule;
import java.lang.instrument.Instrumentation;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.LongAdder;
import java.text.SimpleDateFormat;
import java.util.jar.JarFile;

public class ProfilerAgent {
    public static final ConcurrentHashMap<String, Stats> metrics = new ConcurrentHashMap<>();
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void agentmain(String agentArgs, Instrumentation inst) {
        System.out.println("PROFILER: Dynamic Attach Initiated.");
        // CRITICAL: For dynamic attach, we MUST inject into Bootstrap to avoid ClassNotFound
        try {
            File agentJar = new File(ProfilerAgent.class.getProtectionDomain().getCodeSource().getLocation().toURI());
            inst.appendToBootstrapClassLoaderSearch(new JarFile(agentJar));
            System.out.println("PROFILER: Bootstrap Injection Complete.");
        } catch (Exception e) {
            System.err.println("PROFILER: Injection failed: " + e.getMessage());
        }

        premain(agentArgs, inst);
    }

    public static void premain(String agentArgs, Instrumentation inst) {
        // Use a simple local directory to avoid permission issues
        String outputDir = "profiler_logs";
        new File(outputDir).mkdirs();

        List<String> targetClasses = loadClasses("profiler_targets.txt");
        System.out.println("PROFILER: Targets Loaded: " + targetClasses.size());

        startReporter(30, outputDir);

        new AgentBuilder.Default()
            // 1. FORCED RETRANSFORMATION: This is what triggers on already-running classes
            .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
            .with(AgentBuilder.TypeStrategy.Default.REDEFINE) 
            .ignore(ElementMatchers.none()) // Don't skip Bootstrap classes
            .type(builder -> {
                String name = builder.getName();
                if (name.startsWith("comet.agent.") || name.startsWith("net.bytebuddy.")) return false;
                return targetClasses.contains(name.trim());
            })
            .transform((builder, typeDescription, classLoader, module) ->
                builder.method(ElementMatchers.any()
                        .and(ElementMatchers.not(ElementMatchers.isAbstract()))
                        .and(ElementMatchers.not(ElementMatchers.isNative())))
                        .intercept(Advice.to(ProfilerAdvice.class))
            )
            .with(new AgentBuilder.Listener.Adapter() {
                @Override
                public void onTransformation(TypeDescription td, ClassLoader cl, JavaModule m, boolean loaded, DynamicType dt) {
                    System.out.println("PROFILER: [HOOKED] " + td.getName());
                    System.out.flush();
                }
            })
            .installOn(inst);
    }

    private static List<String> loadClasses(String path) {
        try { return Files.readAllLines(Paths.get(path)); }
        catch (Exception e) { 
            System.err.println("PROFILER: Could not find " + path);
            return Collections.emptyList(); 
        }
    }

    public static class ProfilerAdvice {
        @Advice.OnMethodEnter
        static long enter() { return System.nanoTime(); }

        @Advice.OnMethodExit(onThrowable = Throwable.class)
        static void exit(@Advice.Enter long start, @Advice.Origin("#t.#m") String methodName) {
            if (start == 0L) return;
            long duration = System.nanoTime() - start;

            // Reaching back to the main metrics map
            Stats s = comet.agent.ProfilerAgent.metrics.get(methodName);
            if (s == null) {
                comet.agent.ProfilerAgent.metrics.putIfAbsent(methodName, new comet.agent.ProfilerAgent.Stats());
                s = comet.agent.ProfilerAgent.metrics.get(methodName);
            }
            s.record(duration);
        }
    }

    public static class Stats {
        public final LongAdder count = new LongAdder();
        public final LongAdder totalTime = new LongAdder();
        public void record(long nanos) {
            count.increment();
            totalTime.add(nanos);
        }
    }

    private static void startReporter(int seconds, String outputDir) {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            File csvFile = new File(outputDir, "report.csv");
            try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(csvFile, true)))) {
                String ts = sdf.format(new Date());
                final int[] activeCount = {0};

                metrics.forEach((method, stats) -> {
                    long c = stats.count.sumThenReset();
                    long t = stats.totalTime.sumThenReset();
                    if (c > 0) {
                        activeCount[0]++;
                        pw.printf("%s,%s,%d,%.4f,%.2f%n", ts, method, c, (t/(double)c)/1000000.0, t/1000000.0);
                    }
                });
                pw.flush();
                System.out.println("PROFILER: " + ts + " - Methods with data: " + activeCount[0]);
                System.out.flush();
            } catch (Exception e) { e.printStackTrace(); }
        }, seconds, seconds, TimeUnit.SECONDS);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)