pytorch/caffe2/python/extension_loader.py
Xiaodong Wang 2630109727 always restore dlopen flag in dyndep (#22958)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/22958

When we use `extension_loader.DlopenGuard()` to dyndep or import modules, it sets a `RTLD_GLOBAL` flag, and restores the original flags after the `yield`. However, if the modules is not there, yield will fail, and the flags won't be restored, creating all kinds of symbol conflict problems.

Reviewed By: bddppq

Differential Revision: D16311949

fbshipit-source-id: 7b9ec6d60423ec5e78cae694b66c2f17493840b0
2019-07-17 10:26:25 -07:00

30 lines
889 B
Python

## @package extension_loader
# Module caffe2.python.extension_loader
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import contextlib
import ctypes
import sys
_set_global_flags = (
hasattr(sys, 'getdlopenflags') and hasattr(sys, 'setdlopenflags'))
@contextlib.contextmanager
def DlopenGuard(extra_flags=ctypes.RTLD_GLOBAL):
if _set_global_flags:
old_flags = sys.getdlopenflags()
sys.setdlopenflags(old_flags | extra_flags)
# in case we dlopen something that doesn't exist, yield will fail and throw;
# we need to remember reset the old flags to clean up, otherwise RTLD_GLOBAL
# flag will stick around and create symbol conflict problems
try:
yield
finally:
if _set_global_flags:
sys.setdlopenflags(old_flags)