Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a Environment Pointer to Windows CreateProcess in Java (using jna)

I am calling Kernel32.Instance.CreateProcess to start a detached process. One issue I am facing is attempting to pass a environment block to CreateProcess each time I do the process does not start.

I first used

Advapi32Util.getEnvironmentBlock(environment)

to create the block, then to make a Pointer (needed by CreateProcess( I used:

public static Pointer asPointer(String string) {
    byte[] data;
    try {
        data = Native.toByteArray(string, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    Pointer pointer = new Memory(data.length + 1);
    pointer.write(0, data, 0, data.length);
    pointer.setByte(data.length, (byte) 0);
    return pointer;
}

That I think results in the double null needed at the end. I did actually set CREATE_UNICODE_ENVIRONMENT so I tried add two extra nulls to the end of the Memory. That still resulted in CreateProcess returning false and not starting the command.

I don't understand what I am doing wrong. Should I be checking a log file that might hint at the problem?

like image 872
Luke Avatar asked Jun 21 '26 11:06

Luke


1 Answers

Ah So it seems while using CREATE_UNICODE_ENVIRONMENT it needs to take UTF-16LE byte[]. Ensure that each key=value is followed by two nulls aka (byte) 0). Finally add two more null bytes. The pointer can be made as above.

like image 188
Luke Avatar answered Jun 23 '26 00:06

Luke