GetLastError() (with and without debugger)

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Fri Aug 12 16:05:42 UTC 2022


On 12/08/2022 16:58, Pedro Lamarão wrote:
> Em sex., 12 de ago. de 2022 às 12:05, Pedro Lamarão 
> <pedro.lamarao at prodist.com.br> escreveu:
>
>
>     Em sex., 12 de ago. de 2022 às 12:01, Maurizio Cimadamore
>     <maurizio.cimadamore at oracle.com> escreveu:
>
>         As I said, I believe this should be visible in JNI too - but
>         perhaps nobody would write code like this using JNI. E.g. with
>         JNI, since it's painful enough to write one native method,
>         developers tend to "lump" multiple functionalities, e.g. error
>         checking, in the same native method implementation. Which,
>         coincidentally, bypasses some issues that might be visible
>         when using debuggers (so it is possible that this is a problem
>         that debuggers never had to worry too much about).
>
>
>     Something like this would happen in JNA and JNR based code.
>     I am familiar with these; I'll port the original poster program
>     and push to Github.
>
>
> Here: https://github.com/pedrolamarao/jvm-getlasterror 
> <https://urldefense.com/v3/__https://github.com/pedrolamarao/jvm-getlasterror__;!!ACWV5N9M2RV99hQ!PrCl-0peM-3VuLVa9b6nGGFTnO--4ZJkBXn_fCSvUCnwrceSTXMrlGc8ncp7mCmVpx8rJjH6XIEYny3qeeOPZ1RnFW51VJC7epE$>
>
> Intellij should be able to understand this with a JDK 19 EA build.
>
> Simply running the program in the IDE gives the expected result for 
> "panama" and "jna", but not "jnr", in my machine.
> Very interesting.

Interesting results :-)

In general, there's no silver bullet here. Some frameworks (JNA, and 
even JNR - although that didn't seem to work for you) save certain 
special values after a given native call (e.g. they save them in some 
external thread-local storage).

This of course works because any other components (JVM, debugger, 
whatever) can override the value, but will not touch the saved copy.

That said, the JNA strategy seems more of a workaround to me (perhaps 
one that is unavoidable).

For instance, let's say that your application does:

1) a JNA call to some Windows API
2) followed by a JNI call, which makes a bunch of Windows API calls

Then you ask JNA what's the "last error" and JNA will give you the error 
after (1), IIUC.

If this is a problem with the debugger accidentally overwriting 
LastError on some platforms, I think it would be perhaps better to fix 
it at that level (given that our JVM has some code to defend against 
similar accidental overwrites, I'm assuming that it is possible for the 
JVM code/debugger code to act in a "transparent" fashion).

Maurizio


>
> -- 
> Pedro Lamarão
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/panama-dev/attachments/20220812/65294190/attachment.htm>


More information about the panama-dev mailing list