CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-net-bytebuddy--byte-buddy-agent

Byte Buddy Agent is a Java instrumentation agent library that provides convenient APIs for attaching Java agents to local or remote virtual machines.

Pending
Overview
Eval results
Files

cross-platform.mddocs/

Cross-Platform Support

Platform-specific implementations and attachment providers enabling cross-JVM and cross-OS compatibility. Includes support for different attachment mechanisms, process management, and native integrations for maximum compatibility across Java environments.

Capabilities

Attachment Provider System

Pluggable attachment provider architecture supporting multiple JVM attachment mechanisms with automatic fallback strategies.

/**
 * An attachment provider is responsible for making the Java attachment API available.
 */
public interface AttachmentProvider {
    /**
     * Attempts the creation of an accessor for a specific JVM's attachment API.
     * @return The accessor this attachment provider can supply for the currently running JVM
     */
    Accessor attempt();
    
    /**
     * The default attachment provider to be used.
     */
    AttachmentProvider DEFAULT = new Compound(
        ForModularizedVm.INSTANCE,
        ForJ9Vm.INSTANCE,
        ForStandardToolsJarVm.JVM_ROOT,
        ForStandardToolsJarVm.JDK_ROOT,
        ForStandardToolsJarVm.MACINTOSH,
        ForUserDefinedToolsJar.INSTANCE,
        ForEmulatedAttachment.INSTANCE
    );
}

Attachment Provider Implementations

Individual attachment providers for different JVM types and attachment mechanisms.

/**
 * An attachment provider that locates the attach API directly from the system class loader,
 * as possible since introducing the Java module system via the jdk.attach module.
 */
enum ForModularizedVm implements AttachmentProvider;

/**
 * An attachment provider that locates the attach API directly from the system class loader
 * expecting an IBM J9 VM.
 */
enum ForJ9Vm implements AttachmentProvider;

/**
 * An attachment provider that is dependant on the existence of a tools.jar file on the local file system.
 */
enum ForStandardToolsJarVm implements AttachmentProvider {
    JVM_ROOT("../lib/tools.jar"),
    JDK_ROOT("lib/tools.jar"), 
    MACINTOSH("../Classes/classes.jar");
}

/**
 * An attachment provider that attempts to locate a tools.jar from a custom location set via a system property.
 */
enum ForUserDefinedToolsJar implements AttachmentProvider;

/**
 * An attachment provider that uses Byte Buddy's attachment API emulation. To use this feature, JNA is required.
 */
enum ForEmulatedAttachment implements AttachmentProvider;

/**
 * A compound attachment provider that attempts the attachment by delegation to other providers.
 */
class Compound implements AttachmentProvider;

Process Provider System

Process identification and management system for resolving JVM process IDs across different Java versions and platforms.

/**
 * A process provider is responsible for providing the process id of the current VM.
 */
public interface ProcessProvider {
    /**
     * Resolves a process id for the current JVM.
     * @return The resolved process id
     */
    String resolve();
}

/**
 * Supplies the current VM's process id.
 */
enum ForCurrentVm implements ProcessProvider {
    INSTANCE;
}

Process Provider Implementations

Platform and Java version specific process ID resolution mechanisms.

/**
 * A process provider for a legacy VM that reads the process id from its JMX properties.
 * This strategy is only used prior to Java 9.
 */
protected enum ForLegacyVm implements ProcessProvider {
    INSTANCE;
}

/**
 * A process provider for a Java 9 capable VM with access to the introduced process API.
 */
protected static class ForJava9CapableVm implements ProcessProvider {
    /**
     * Attempts to create a dispatcher for a Java 9 VM and falls back to a legacy dispatcher
     * if this is not possible.
     */
    public static ProcessProvider make();
}

Attachment Type Evaluation

System for determining whether external process attachment is required based on JVM configuration and version.

/**
 * An attachment evaluator is responsible for deciding if an agent can be attached from the current process.
 */
protected interface AttachmentTypeEvaluator {
    /**
     * Checks if the current VM requires external attachment for the supplied process id.
     * @param processId The process id of the process to which to attach
     * @return true if the current VM requires external attachment for the supplied process
     */
    boolean requiresExternalAttachment(String processId);
}

Platform-Specific Dispatchers

Cross-platform system integration for process management, file operations, and inter-process communication.

/**
 * A dispatcher for native operations being used for communication with an OpenJ9 virtual machine.
 */
public interface Dispatcher {
    String getTemporaryFolder(String processId);
    int pid();
    int userId();
    boolean isExistingProcess(int processId);
    int getOwnerIdOf(File file);
    void setPermissions(File file, int permissions);
    void incrementSemaphore(File directory, String name, boolean global, int count);
    void decrementSemaphore(File directory, String name, boolean global, int count);
    void chownFileToUser(File file, long userId);
}

/**
 * A connector implementation for a POSIX environment using JNA.
 */
class ForJnaPosixEnvironment implements Dispatcher;

/**
 * A connector implementation for a Windows environment using JNA.
 */
class ForJnaWindowsEnvironment implements Dispatcher;

Usage Examples

Custom Attachment Provider Strategy

import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.ByteBuddyAgent.AttachmentProvider;

// Create custom attachment strategy prioritizing specific mechanisms
AttachmentProvider customProvider = new AttachmentProvider.Compound(
    AttachmentProvider.ForModularizedVm.INSTANCE,    // Java 9+ modules first
    AttachmentProvider.ForJ9Vm.INSTANCE,             // IBM J9 support
    AttachmentProvider.ForEmulatedAttachment.INSTANCE // JNA fallback
);

// Use custom provider for installation
Instrumentation instrumentation = ByteBuddyAgent.install(customProvider);

// Use custom provider for attachment
File agentJar = new File("my-agent.jar");
ByteBuddyAgent.attach(agentJar, "1234", customProvider);

Tools.jar Based Attachment

import net.bytebuddy.agent.ByteBuddyAgent.AttachmentProvider;

// Try different tools.jar locations
AttachmentProvider toolsJarProvider = new AttachmentProvider.Compound(
    AttachmentProvider.ForStandardToolsJarVm.JDK_ROOT,    // Standard JDK location
    AttachmentProvider.ForStandardToolsJarVm.JVM_ROOT,    // JRE location
    AttachmentProvider.ForStandardToolsJarVm.MACINTOSH    // macOS location
);

// Set custom tools.jar location
System.setProperty("net.bytebuddy.agent.toolsjar", "/custom/path/tools.jar");
AttachmentProvider customToolsJar = AttachmentProvider.ForUserDefinedToolsJar.INSTANCE;

// Use tools.jar provider
Instrumentation instrumentation = ByteBuddyAgent.install(toolsJarProvider);

JNA-Based Attachment

import net.bytebuddy.agent.ByteBuddyAgent.AttachmentProvider;

// Force JNA-based attachment (requires JNA on classpath)
AttachmentProvider jnaProvider = AttachmentProvider.ForEmulatedAttachment.INSTANCE;

try {
    Instrumentation instrumentation = ByteBuddyAgent.install(jnaProvider);
    System.out.println("JNA attachment successful");
} catch (IllegalStateException e) {
    if (e.getMessage().contains("JNA dependency")) {
        System.err.println("JNA library not available");
    } else {
        System.err.println("JNA attachment failed: " + e.getMessage());
    }
}

Process Provider Configuration

import net.bytebuddy.agent.ByteBuddyAgent.ProcessProvider;

// Use current VM process provider
ProcessProvider currentVM = ProcessProvider.ForCurrentVm.INSTANCE;
String currentPid = currentVM.resolve();
System.out.println("Current process ID: " + currentPid);

// Custom process provider implementation
ProcessProvider customProvider = new ProcessProvider() {
    @Override
    public String resolve() {
        // Custom logic for process resolution
        return System.getProperty("my.app.pid", "1234");
    }
};

// Use custom provider for installation
Instrumentation instrumentation = ByteBuddyAgent.install(customProvider);

Platform Detection and Adaptation

import net.bytebuddy.agent.VirtualMachine;
import com.sun.jna.Platform;

if (Platform.isWindows()) {
    // Windows-specific attachment using named pipes
    VirtualMachine vm = VirtualMachine.ForHotSpot.attach("1234", 
        new VirtualMachine.ForHotSpot.Connection.ForJnaWindowsNamedPipe.Factory());
    
} else if (Platform.isSolaris()) {
    // Solaris-specific attachment using doors
    VirtualMachine vm = VirtualMachine.ForHotSpot.attach("1234",
        new VirtualMachine.ForHotSpot.Connection.ForJnaSolarisDoor.Factory(15, 100, TimeUnit.MILLISECONDS));
    
} else {
    // POSIX-based systems (Linux, macOS) using sockets
    VirtualMachine vm = VirtualMachine.ForHotSpot.attach("1234",
        VirtualMachine.ForHotSpot.Connection.ForJnaPosixSocket.Factory.withDefaultTemporaryFolder(15, 100, TimeUnit.MILLISECONDS));
}

JVM Type Detection

import java.util.Locale;

// Detect JVM type for appropriate provider selection
String vmName = System.getProperty("java.vm.name", "").toUpperCase(Locale.US);

if (vmName.contains("J9")) {
    // Use OpenJ9-specific attachment
    VirtualMachine vm = VirtualMachine.ForOpenJ9.attach("1234");
} else {
    // Use HotSpot-compatible attachment
    VirtualMachine vm = VirtualMachine.ForHotSpot.attach("1234");
}

Error Handling and Diagnostics

import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.ByteBuddyAgent.AttachmentProvider;

// Try multiple providers with detailed error reporting
AttachmentProvider[] providers = {
    AttachmentProvider.ForModularizedVm.INSTANCE,
    AttachmentProvider.ForJ9Vm.INSTANCE,
    AttachmentProvider.ForStandardToolsJarVm.JDK_ROOT,
    AttachmentProvider.ForEmulatedAttachment.INSTANCE
};

Instrumentation instrumentation = null;
for (AttachmentProvider provider : providers) {
    try {
        instrumentation = ByteBuddyAgent.install(provider);
        System.out.println("Success with provider: " + provider.getClass().getSimpleName());
        break;
    } catch (IllegalStateException e) {
        System.out.println("Failed with provider " + provider.getClass().getSimpleName() + ": " + e.getMessage());
    }
}

if (instrumentation == null) {
    System.err.println("All attachment providers failed");
}

Platform-Specific Features

Windows Support

  • Named pipe communication: Efficient inter-process communication using Windows named pipes
  • Native extensions: Pre-compiled DLLs for enhanced attachment capabilities
  • Security descriptors: Proper Windows security handling for cross-user attachment
  • Process management: Windows-specific process enumeration and control

Linux Support

  • POSIX socket communication: Unix domain socket-based VM communication
  • Process namespace support: Container and namespace-aware process handling
  • File permission management: POSIX file permission and ownership control
  • Semaphore operations: System V semaphore-based synchronization

macOS Support

  • Darwin-specific paths: macOS-specific temporary directory resolution
  • Framework integration: Integration with macOS system frameworks
  • Code signing compatibility: Support for signed JVM processes
  • Unified memory management: macOS-specific memory and process management

Solaris Support

  • Door communication: Solaris door-based high-performance IPC
  • Zone awareness: Solaris container/zone-aware process operations
  • Extended attributes: Solaris-specific file system features
  • Privilege management: Solaris privilege escalation and management

Compatibility Matrix

FeatureWindowsLinuxmacOSSolarisAIX
JNA Attachment
Tools.jar
Module System
Native Extensions----
Socket Emulation--
Door Communication----

Configuration Properties

System properties for customizing cross-platform behavior:

  • net.bytebuddy.agent.toolsjar: Custom tools.jar location
  • net.bytebuddy.agent.latent: Disable self-resolution for attachment
  • net.bytebuddy.agent.attacher.dump: Enable diagnostic dumping
  • net.bytebuddy.library.name: Custom native library name for Windows
  • jdk.attach.allowAttachSelf: Control self-attachment (Java 9+)

Example configuration:

// Configure custom tools.jar location
System.setProperty("net.bytebuddy.agent.toolsjar", "/opt/jdk/lib/tools.jar");

// Enable diagnostic output
System.setProperty("net.bytebuddy.agent.attacher.dump", "/tmp/attachment.log");

// Allow self-attachment on Java 9+
System.setProperty("jdk.attach.allowAttachSelf", "true");

Install with Tessl CLI

npx tessl i tessl/maven-net-bytebuddy--byte-buddy-agent

docs

agent-attachment.md

agent-installation.md

cross-platform.md

index.md

vm-operations.md

tile.json