Why is Python segfault trying to invoke an environment using ctypes in libc?

Tested this on both Ubuntu and ArchLinux, I get

from ctypes import * libc = CDLL('libc.so.6') libc.environ() Segmentation fault 

Why?

+6
source share
2 answers

If I read the man page correctly, environ is a char** , not a function. If you want to get var var, according to this post , you can do:

 from ctypes import * libc = CDLL('libc.so.6') environ = c_char_p.in_dll(libc, 'environ') 

But it returns 'c_void_p (None)' for me, I don’t know why this happens (I know that I declared only as char * , but since it returns None, they are not for dereference).

In any case, you still have the python method:

 import os print os.environ 

Or, if you are looking for a specific string in an environment using ctypes, for some function you need to override the standard repeat type:

 from ctypes import * libc = CDLL('libc.so.6') getenv = libc.getenv getenv.restype = c_char_p print getenv('HOME') 
+7
source

Here you can print the C environ using ctypes in Ubuntu:

 #!/usr/bin/env python2 import ctypes libc = ctypes.CDLL(None) environ = ctypes.POINTER(ctypes.c_char_p).in_dll(libc, 'environ') for envvar in iter(iter(environ).next, None): print envvar 

Exit

 LC_PAPER=en_GB.UTF-8 LC_ADDRESS=en_GB.UTF-8 CLUTTER_IM_MODULE=xim LC_MONETARY=en_GB.UTF-8 VIRTUALENVWRAPPER_PROJECT_FILENAME=.project SESSION=ubuntu ... 
0
source

Source: https://habr.com/ru/post/907221/


All Articles