jnr / jnr-ffi

Java Abstracted Foreign Function Layer
Other
1.26k stars 157 forks source link

call to getenv(String) does not terminate the string return value #27

Open seanmceligot opened 10 years ago

seanmceligot commented 10 years ago

The following code returns not just the USERNAME environment variable, but also every environment after that. myusername USERPROFILE=C:\Users\myusername ...

Similar code used to work with jna. This is on Windows 7.

import jnr.ffi.provider.FFIProvider;
import jnr.posix.util.Platform;

public class NativeCallsTest {
   public interface CLibrary  {
         public int system(String cmd);
         public String getenv(String name);
}
public static void main(String[] args) {
  CLibrary _libc;

    jnr.ffi.LibraryLoader<CLibrary> loader = FFIProvider.getSystemProvider().createLibraryLoader(CLibrary.class);
    _libc = loader.load(Platform.IS_WINDOWS ? "msvcrt" : "c");
    System.out.println(_libc.getenv("USERNAME"));
  }
}
headius commented 10 years ago

Well that is indeed peculiar! It is especially strange because I would not expect USERNAME passed to getenv to return anything but the value bound to USERNAME. Perhaps there's some pecular behavioral difference in the Windows implementation of getenv that we're not handling right?

headius commented 8 years ago

A theory: getenv on Windows returns a pointer into an existing ENV string that has nulls in it; C would see a null before the next env var and not include it in the string.

Does the bad string contain null characters? I can't tell from your example.