Odin icon indicating copy to clipboard operation
Odin copied to clipboard

Implement os.environ() on Linux

Open greenm01 opened this issue 1 year ago • 6 comments

Please implement this function on Linux.

Right now it only works on Windows?

greenm01 avatar Jan 31 '24 03:01 greenm01

If that is a libc function, you can foreign link to it. Otherwise, if you just need access to the environment, this will get it for you:

#no_bounds_check env: [^]cstring = &runtime.args__[len(runtime.args__) + 1]

jasonKercher avatar Jan 31 '24 11:01 jasonKercher

#no_bounds_check env: [^]cstring = &runtime.args__[len(runtime.args__) + 1]

Thanks for this tip. I was binding to C to get the same functionality.

os.environ() is listed in the core package documentation and was a bit confusing at first as to why it was not working.

Cheers!

greenm01 avatar Jan 31 '24 14:01 greenm01

One other question:

What's the smartest way to convert a [^]cstring to a []string?

greenm01 avatar Jan 31 '24 15:01 greenm01

This is what I would do:

#no_bounds_check env: [^]cstring = &runtime.args__[len(runtime.args__) + 1]

length: int
for ; env[length] != nil; length += 1 {}

env_strs := make([]string, length)
for &env_str, i in env_strs {
	env_str = string(env[i])
}

laytan avatar Jan 31 '24 15:01 laytan

This is what I would do:

Awesome, it works with no segfault. Thanks!

greenm01 avatar Jan 31 '24 15:01 greenm01

Just to be clear, this method will not see modifications to the environment if done via libc. I believe setenv/putenv (whatever its called) will copy the entire thing to a fresh buffer on the first modification. What that little trick does is just access the environment that was passed to execve when your process was first launched.

jasonKercher avatar Jan 31 '24 17:01 jasonKercher