3

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?

Luke
  • 884
  • 8
  • 21

1 Answers1

1

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.

Luke
  • 884
  • 8
  • 21
  • see also https://stackoverflow.com/questions/50502023/how-to-start-a-command-in-windows-under-java-that-is-completely-detached/50522759#50522759 – Luke May 25 '18 at 06:32