I have an .so file with a simple function returning a number * 2. That .so file is inside a .zip archive. From a python script, I'm trying to extract the .so file to a temporary location, and execute the function from it. The trouble is that the second time I am trying to do that, I get a segmentation fault.
It's probably clearer from code, so here are the cases I've tried:
Case I - failing
import ctypes
import zipfile
import tempfile
def foo():
archive = zipfile.ZipFile("test.zip")
lib_path = archive.extract("secret.so", tempfile.gettempdir())
archive.close()
secret = ctypes.CDLL(lib_path)
print(secret.secret_calculation(3))
foo()
foo() # <--- SegFault when calling secret.secret_calculation
Case II - working (extract to different folders every time)
import ctypes
import zipfile
import tempfile
def foo():
archive = zipfile.ZipFile("test.zip")
lib_path = archive.extract("secret.so", tempfile.mkdtemp()) # <--- mkdtemp creates a new folder every time
archive.close()
secret = ctypes.CDLL(lib_path)
print(secret.secret_calculation(3))
foo()
foo() # <--- NO SegFault
Case III - working (loading the so without calling into it)
import ctypes
import zipfile
import tempfile
def foo():
archive = zipfile.ZipFile("test.zip")
lib_path = archive.extract("secret.so", tempfile.gettempdir())
archive.close()
secret = ctypes.CDLL(lib_path)
# print(secret.secret_calculation(3))
foo()
foo() # <--- NO SegFault
Case IV - working (calling into the .so twice, without extracting it first)
import ctypes
import zipfile
import tempfile
def foo():
# archive = zipfile.ZipFile("test.zip")
# lib_path = archive.extract("secret.so", tempfile.gettempdir())
# archive.close()
secret = ctypes.CDLL("/tmp/secret.so")
print(secret.secret_calculation(3))
foo()
foo() # <--- NO SegFault
Python version: 2.7.12
Any ideas why do I get this behavior?