How to load AttachProvider (attach.dll) dynamically

I am using com.sun.tools.attach from jdk tools.jar and it needs to specify java.library.path env pointing to attach.dll at startup in order to install the provider correctly, for example WindowsAttachProvider . For some reason, I need to dynamically load one of the attach.dll packages. I am trying to use several of these:

 public static void main(String[] args) throws Exception { Path bin = Paths.get(System.getProperty("user.dir"),"bin").toAbsolutePath(); switch (System.getProperty("os.arch")) { case "amd64": bin = bin.resolve("win64"); break; default: bin = bin.resolve("win32"); } // Dynamic setting of java.library.path only seems not sufficient System.setProperty("java.library.path", System.getProperty("java.library.path") + File.pathSeparator + bin.toString()); // So I try to manual loading attach.dll. This is not sufficient too. System.load(bin.resolve("attach.dll").toString()); // I'm using com.sun.tools.attach in my app new myApp(); } 

If I run this from jdk (in normall jre), it will tell me:

 java.util.ServiceConfigurationError: com.sun.tools.attach.spi.AttachProvider: Provider sun.tools.attach.WindowsAttachProvider could not be instantiated: java.lang.UnsatisfiedLinkError: no attach in java.library.path Exception in thread "main" com.sun.tools.attach.AttachNotSupportedException: no providers installed at com.sun.tools.attach.VirtualMachine.attach(... 

How to install a connection provider without specifying -Djava.library.path to the attach.dll item at startup?

+4
source share
1 answer

The API you are using uses loadLibrary (String) . It seems you cannot successfully preempt (make it succeed) by first invoking a more explicit load (String) .

So you must specify the path in java.library.path .

This System property is set at the beginning of the JVM life cycle and is not modified by standard tools.

Thus, the usual solution would be to pass the appropriate java.library.path when starting the JVM.

Alternatively, you can learn hacks to change this property after starting the JVM using reflection. I have not tried any of them.

For example, see here :

 System.setProperty( "java.library.path", "/path/to/libs" ); Field fieldSysPath = ClassLoader.class.getDeclaredField( "sys_paths" ); fieldSysPath.setAccessible( true ); fieldSysPath.set( null, null ); 

By the way, I would recommend providing your own path to an existing path, rather than replacing it.

+5
source

All Articles