JNA does not have a function from the Windows API - java

I am in charge of porting Windows JNI code to Java, and have gone with JNA. Using the library is simple enough, as apparently it attempts to follow the structure and style of Windows' API (I do not know the API well, I follow the original JNI code).
I was able to find the JNA equivalent of most Windows API functions, but not EnableWindow.
This function is defined in winuser.h and logically, one should find it under com.sun.jna.platform.win32.WinUser, right? However there is no such function, and the only mention of EnableWindow is in the documentation of com.sun.jna.platform.win32.WinUser.WS_DISABLED:
[...] To change this after a window has been created, use the EnableWindow function.
That's it, no other reference, mention or indication towards the function. The rest of the documentation is equally terse and not very helpful when one does not know exactly what and where to look.
So where is JNA's EnableWindow, if it exists? And if it doesn't, what can be used in replacement?

There are two parts to JNA: the core functionality (in the jna artifact) and user-contributed platform mappings (in the jna-platform artifact). When users contribute mappings for functions and constants, they usually copy the Windows API documentation directly into the javadocs, so there are frequent references to values which have not (yet) been mapped.
As you have observed, no user has (yet) contributed a mapping for the EnableWindow function. That user could be you!
The JNA FAQ includes this tidbit:
JNA is missing function XXX in its platform library mappings
No, it's not, it's just waiting for you to add it :)
public interface MyUser32 extends User32 {
// DEFAULT_OPTIONS is critical for W32 API functions to simplify ASCII/UNICODE details
MyUser32 INSTANCE = (MyUser32)Native.load("user32", W32APIOptions.DEFAULT_OPTIONS);
void ThatFunctionYouReallyNeed();
}
That's basically the template for adding a function on your own: extend the existing library (if it's partially mapped) or create a new library if it hasn't been mapped (in which case, extend Library), then add the function you need.
WinUser is slightly different than most mappings; it doesn't include the library loading statement as it's just the header file, and in JNA, the DLL-loading library extends WinUser.
So you need to do a little bit more research to see which DLL to load to access the function natively. The docs indicate it's the user32.dll, just like the JNA FAQ example!
So the template is above, you just need the function mapping. Windows BOOL maps to Java's boolean so you just need to do this in your own codebase:
public interface MyUser32 extends User32 {
MyUser32 INSTANCE = (MyUser32) Native.load("user32", W32APIOptions.DEFAULT_OPTIONS);
boolean EnableWindow(HWND hWnd, boolean bEnable);
}
That will solve your immediate needs in your own project.
JNA is a user-maintained project. Please consider contributing your mapping to JNA so the next person can use your mapping and won't need to create it themselves!

Related

Where are SetCommMask and WaitCommEvent in JNA? [duplicate]

I am in charge of porting Windows JNI code to Java, and have gone with JNA. Using the library is simple enough, as apparently it attempts to follow the structure and style of Windows' API (I do not know the API well, I follow the original JNI code).
I was able to find the JNA equivalent of most Windows API functions, but not EnableWindow.
This function is defined in winuser.h and logically, one should find it under com.sun.jna.platform.win32.WinUser, right? However there is no such function, and the only mention of EnableWindow is in the documentation of com.sun.jna.platform.win32.WinUser.WS_DISABLED:
[...] To change this after a window has been created, use the EnableWindow function.
That's it, no other reference, mention or indication towards the function. The rest of the documentation is equally terse and not very helpful when one does not know exactly what and where to look.
So where is JNA's EnableWindow, if it exists? And if it doesn't, what can be used in replacement?
There are two parts to JNA: the core functionality (in the jna artifact) and user-contributed platform mappings (in the jna-platform artifact). When users contribute mappings for functions and constants, they usually copy the Windows API documentation directly into the javadocs, so there are frequent references to values which have not (yet) been mapped.
As you have observed, no user has (yet) contributed a mapping for the EnableWindow function. That user could be you!
The JNA FAQ includes this tidbit:
JNA is missing function XXX in its platform library mappings
No, it's not, it's just waiting for you to add it :)
public interface MyUser32 extends User32 {
// DEFAULT_OPTIONS is critical for W32 API functions to simplify ASCII/UNICODE details
MyUser32 INSTANCE = (MyUser32)Native.load("user32", W32APIOptions.DEFAULT_OPTIONS);
void ThatFunctionYouReallyNeed();
}
That's basically the template for adding a function on your own: extend the existing library (if it's partially mapped) or create a new library if it hasn't been mapped (in which case, extend Library), then add the function you need.
WinUser is slightly different than most mappings; it doesn't include the library loading statement as it's just the header file, and in JNA, the DLL-loading library extends WinUser.
So you need to do a little bit more research to see which DLL to load to access the function natively. The docs indicate it's the user32.dll, just like the JNA FAQ example!
So the template is above, you just need the function mapping. Windows BOOL maps to Java's boolean so you just need to do this in your own codebase:
public interface MyUser32 extends User32 {
MyUser32 INSTANCE = (MyUser32) Native.load("user32", W32APIOptions.DEFAULT_OPTIONS);
boolean EnableWindow(HWND hWnd, boolean bEnable);
}
That will solve your immediate needs in your own project.
JNA is a user-maintained project. Please consider contributing your mapping to JNA so the next person can use your mapping and won't need to create it themselves!

How to automate Java bindings for Rust code?

I want to call Rust code from Java / Android, and I've found 3 variants to do so:
JNI
JNA
JNR FFI
JNI looks good and powerful enough, but you have to
write too much code by hand.
JNA, if not taking into consideration that it crashes on my machine, requires writing Rust struct data type description in Java by hand,
the same problem with JNR FFI.
So I wonder how difficult will be generate JNI code
for traits and struct with macros or a compiler plugin?
This compiler should match traits implementations for concrete struct,
and also struct
#[JNI]
struct Foo {
a: i32,
}
trait Boo {
fn f(&self, b: f64) -> f64;
}
#[JNI]
impl Boo for Foo {
fn f(&self, b: f64) -> f64 {
0f64
}
}
and create Java classes for struct and Java classes with native functions, plus generate pub no_mangle functions that wrap traits functions.
In order to provide #[jni] annotations that work like that you'd need to use a compiler plugin. It would be an awesome tool, but it doesn't exist yet, as far as I know.
There are bits and pieces of tooling lying around that might be helpful, if you want to create a project that does this.
Plugins are currently unstable, and don't work on non-nightly rust; you would probably want to use syntex, which provides a stable interface to compiler plugins. You could also write a raw plugin (see here for the API for those), but most people won't be able to use it.
There's rusty-cheddar, which generates c header files; you could take a look at that to see how it works. The author of that also seems to be working on a more general bindings-generation framework, but I don't know if it's active. You might be able to hook the output of cheddar up to something like JNAerator, but it probably won't create the prettiest interfaces on the java side.
There's also rust-bindgen and corrode, which work in the other direction; they translate c headers and arbitrary c code to rust respectively. I don't know if that's actually helpful.
JNI-sys provides low-level JNI bindings; rust-on-mobile is a small project that uses it. Also see First steps with Rust and Java, a blog post that shows some rudiments of getting things hooked up.
Finally, there's cbox, which lets you work around awkwardness with ownership and FFI.
Finally I created such project (link to github repository) to automate
binding creation.
You can use jnaerator to auto-generate your structure mappings for JNA.
Alternatively, if you want to use JNI (and compile some more native code) you should go with SWIG.

How to use JNI, but only when available for current platform?

What is the common way (or best practice) to optionally use JNI?
E.g. I have a Java class and this class is 100% pure Java, so it can run on all platforms. However, on some platforms I'd like to speed up some heavy calculations using JNI - which works fine. Unfortunately I cannot support any existing Java platform in the world. So I guess it is fine to initially only support the big three: Linux, Windows, Mac OS X.
So what I'd like to do is to use JNI on those three platforms and use the 100% pure Java version on all other platforms. Now I can think of various ways how to do that (loading class dynamically for example and either loading the JNI class or the pure Java one), but thinking that this is a common issue that thousands of projects had to solve in the past for sure, I'm really surprised to not find any documentation or references to the question how to solve this most elegantly or effectively.
If it really makes sense to supply two different versions you could do the following:
Create an interface for the class
Implement the interface in a class in pure Java
Implement the interface in a class that uses JNI
Then you can write a factory method that instantiates the correct class:
public static SomeInterface getInterface()
{
SomeInterface res = new JavaSomeInterfaceImpl();
if (System.getProperty("os.name").matches(".*Windows.*"))
{
File library = new File("mylibrary.dll");
System.load(library.getAbsolutePath());
res = new NativeSomeInterfaceImpl();
}
return res;
}
Your platform dependant code should be in a platform dependant class ;-)
Suppose you have a main "Algorithm" class (or better, interface).
This interface is implemented by a WindowsAlgorithm using JNI and a HaikuAlgorithm not doing so (it's only for the sake of example). The only thing you have to do now is to load the right one depending upon your client OS, which I think is rather mundane to do.

How to determine which classes are referenced in a compiled .Net or Java application?

I wonder if there's an easy way to determine which classes from a library are "used" by a compiled .NET or Java application, and I need to write a simple utility to do that (so using any of the available decompilers won't do the job).
I don't need to analyze different inputs to figure out if a class is actually created for this or that input set - I'm only concerned whether or not the class is referenced in the application. Most likely the application would subclass from the class I look for and use the subclass.
I've looked through a bunch of .Net .exe's and Java .classes with a hex editor and it appears that the referenced classes are spelled out in plaintext, but I am not sure if it will always be the case - my knowledge of MSIL/Java bytecode is not enough for that. I assume that even though the application itself can be obfuscated, it'll still have to call the library classes by the original name?
Extending what overslacked said.
EDIT: For some reason I thought you asked about methods, not types.
Types
Like finding methods, this doesn't cover access through the Reflection API.
You have to locate the following in a Reflector plugin to identify referenced types and perform a transitive closure:
Method parameters
Method return types
Custom attributes
Base types and interface implementations
Local variable declarations
Evaluated sub-expression types
Field, property, and event types
If you parse the IL yourself, all you have to do is process from the main assembly is the TypeRef and TypeSpec metadata, which is pretty easy (of course I'm speaking from parsing the entire byte code here). However, the transitive closure would still require you process the full byte code of each referenced method in the referenced assembly (to get the subexpression types).
Methods
If you can write a plugin for Reflector to handle the task, it will definitely be the easiest way. Parsing the IL is non-trivial, though I've done it now so I would just use that code if I had to (just saying it's not impossible). :D
Keep in mind that you may have method dependencies you don't see on the first pass that neither method mentioned will catch. These are due to indirect dispatch via the callvirt (virtual and interface method calls) and calli (generally delegates) instructions. For each type T created with newobj and for each method M within the type, you'll have to check all callvirt, ldftn, and ldvirtftn instructions to see if the base definition for the target (if the target is a virtual method) is the same as the base method definition for M in T or M is in the type's interface map if the target is an interface method. This is not perfect, but it is about the best you can do for static analysis without a theorem prover. It is a superset of the actual methods that will be called outside of the Reflection API, and a subset of the full set of methods in the assembly(ies).
For .NET: it looks like there's an article on MSDN that should help you get started. For what it's worth, for .NET the magic Google words are ".net assembly references".
In Java, the best mechanism to find class dependencies (in a programmatic fashion) is through bytecode inspection. This can be done with libraries like BCEL or (preferably) ASM. If you wish to parse the class files with your own code, the class file structure is well documented in the Java VM specification.
Note that class inspection won't cover runtime dependencies (like classes loaded using the service API).

Is there a Java library of Unix functions?

I am looking for a Java library to interface with standard Unix functions, i.e. stat(), getpwuid(), readlink().
This used to exist, and was called javaunix. It was released back in 2000. See this announcement. But the project page is now gone.
Is there any modern replacement for these types of functions in Java today? One could make a system call to /bin/ls -l and parse the output, or write a custom JNI method, but these approaches are more work than simply using the old javaunix library.
Clarification -- In order to find out a file's owner, from a C program, it should call stat() which gives the UID of the owner, and then use getpwuid() to get the account's name from the UID. In Java this can be done through a custom JNI method, or the javaunix library which uses JNI.
I'm aware of two compelling projects:
posix for Java (based on JNI) [derived from Jython]
jna-posix (based on JNA) [derived from JRuby]
Personally I like very much JNA. Take a look at this example of mine, mapping link(2):
import com.sun.jna.Library;
import com.sun.jna.Native;
class Link {
private static final C c =
(C) Native.loadLibrary("c", C.class);
private static interface C extends Library {
/** see man 2 link */
public int link(String oldpath, String newpath);
}
#Override
protected void hardLink(String from, String to) {
c.link(to, from);
}
}
JNA-POSIX is stagnant currently, as far as I know.
The developers went on to create JNR-POSIX
I would be surprised to see one, considering it would almost necessarily be platform-specific. Java is not the best tool for that job. But you could certainly hook in via JNI or calls out to external programs if you insist. Or perhaps look into Groovy, which I understand is reasonably good for shell scripting, though I have no personal experience with it.
I don't know any library with the Unix functions.
for most of the functions, I believe, you can use the standard Java API to do what you want. for example, there's no need to use the command ls to read the files of some directory. but in some specific cases, like stat (to find out if a file is a link) you have to use JNI.

Categories