diff options
author | Ori Bernstein <ori@eigenstate.org> | 2021-06-14 00:00:37 +0000 |
---|---|---|
committer | Ori Bernstein <ori@eigenstate.org> | 2021-06-14 00:00:37 +0000 |
commit | a73a964e51247ed169d322c725a3a18859f109a3 (patch) | |
tree | 3f752d117274d444bda44e85609aeac1acf313f3 /sys/lib/python/ctypes | |
parent | e64efe273fcb921a61bf27d33b230c4e64fcd425 (diff) |
python, hg: tow outside the environment.
they've served us well, and can ride off into the sunset.
Diffstat (limited to 'sys/lib/python/ctypes')
-rw-r--r-- | sys/lib/python/ctypes/__init__.py | 529 | ||||
-rw-r--r-- | sys/lib/python/ctypes/_endian.py | 60 | ||||
-rw-r--r-- | sys/lib/python/ctypes/macholib/README.ctypes | 7 | ||||
-rw-r--r-- | sys/lib/python/ctypes/macholib/__init__.py | 12 | ||||
-rw-r--r-- | sys/lib/python/ctypes/macholib/dyld.py | 169 | ||||
-rw-r--r-- | sys/lib/python/ctypes/macholib/dylib.py | 66 | ||||
-rwxr-xr-x | sys/lib/python/ctypes/macholib/fetch_macholib | 2 | ||||
-rw-r--r-- | sys/lib/python/ctypes/macholib/fetch_macholib.bat | 1 | ||||
-rw-r--r-- | sys/lib/python/ctypes/macholib/framework.py | 68 | ||||
-rw-r--r-- | sys/lib/python/ctypes/util.py | 154 | ||||
-rw-r--r-- | sys/lib/python/ctypes/wintypes.py | 172 |
11 files changed, 0 insertions, 1240 deletions
diff --git a/sys/lib/python/ctypes/__init__.py b/sys/lib/python/ctypes/__init__.py deleted file mode 100644 index 593730449..000000000 --- a/sys/lib/python/ctypes/__init__.py +++ /dev/null @@ -1,529 +0,0 @@ -###################################################################### -# This file should be kept compatible with Python 2.3, see PEP 291. # -###################################################################### -"""create and manipulate C data types in Python""" - -import os as _os, sys as _sys - -__version__ = "1.0.2" - -from _ctypes import Union, Structure, Array -from _ctypes import _Pointer -from _ctypes import CFuncPtr as _CFuncPtr -from _ctypes import __version__ as _ctypes_version -from _ctypes import RTLD_LOCAL, RTLD_GLOBAL -from _ctypes import ArgumentError - -from struct import calcsize as _calcsize - -if __version__ != _ctypes_version: - raise Exception, ("Version number mismatch", __version__, _ctypes_version) - -if _os.name in ("nt", "ce"): - from _ctypes import FormatError - -DEFAULT_MODE = RTLD_LOCAL -if _os.name == "posix" and _sys.platform == "darwin": - import gestalt - - # gestalt.gestalt("sysv") returns the version number of the - # currently active system file as BCD. - # On OS X 10.4.6 -> 0x1046 - # On OS X 10.2.8 -> 0x1028 - # See also http://www.rgaros.nl/gestalt/ - # - # On OS X 10.3, we use RTLD_GLOBAL as default mode - # because RTLD_LOCAL does not work at least on some - # libraries. - - if gestalt.gestalt("sysv") < 0x1040: - DEFAULT_MODE = RTLD_GLOBAL - -from _ctypes import FUNCFLAG_CDECL as _FUNCFLAG_CDECL, \ - FUNCFLAG_PYTHONAPI as _FUNCFLAG_PYTHONAPI - -""" -WINOLEAPI -> HRESULT -WINOLEAPI_(type) - -STDMETHODCALLTYPE - -STDMETHOD(name) -STDMETHOD_(type, name) - -STDAPICALLTYPE -""" - -def create_string_buffer(init, size=None): - """create_string_buffer(aString) -> character array - create_string_buffer(anInteger) -> character array - create_string_buffer(aString, anInteger) -> character array - """ - if isinstance(init, (str, unicode)): - if size is None: - size = len(init)+1 - buftype = c_char * size - buf = buftype() - buf.value = init - return buf - elif isinstance(init, (int, long)): - buftype = c_char * init - buf = buftype() - return buf - raise TypeError, init - -def c_buffer(init, size=None): -## "deprecated, use create_string_buffer instead" -## import warnings -## warnings.warn("c_buffer is deprecated, use create_string_buffer instead", -## DeprecationWarning, stacklevel=2) - return create_string_buffer(init, size) - -_c_functype_cache = {} -def CFUNCTYPE(restype, *argtypes): - """CFUNCTYPE(restype, *argtypes) -> function prototype. - - restype: the result type - argtypes: a sequence specifying the argument types - - The function prototype can be called in different ways to create a - callable object: - - prototype(integer address) -> foreign function - prototype(callable) -> create and return a C callable function from callable - prototype(integer index, method name[, paramflags]) -> foreign function calling a COM method - prototype((ordinal number, dll object)[, paramflags]) -> foreign function exported by ordinal - prototype((function name, dll object)[, paramflags]) -> foreign function exported by name - """ - try: - return _c_functype_cache[(restype, argtypes)] - except KeyError: - class CFunctionType(_CFuncPtr): - _argtypes_ = argtypes - _restype_ = restype - _flags_ = _FUNCFLAG_CDECL - _c_functype_cache[(restype, argtypes)] = CFunctionType - return CFunctionType - -if _os.name in ("nt", "ce"): - from _ctypes import LoadLibrary as _dlopen - from _ctypes import FUNCFLAG_STDCALL as _FUNCFLAG_STDCALL - if _os.name == "ce": - # 'ce' doesn't have the stdcall calling convention - _FUNCFLAG_STDCALL = _FUNCFLAG_CDECL - - _win_functype_cache = {} - def WINFUNCTYPE(restype, *argtypes): - # docstring set later (very similar to CFUNCTYPE.__doc__) - try: - return _win_functype_cache[(restype, argtypes)] - except KeyError: - class WinFunctionType(_CFuncPtr): - _argtypes_ = argtypes - _restype_ = restype - _flags_ = _FUNCFLAG_STDCALL - _win_functype_cache[(restype, argtypes)] = WinFunctionType - return WinFunctionType - if WINFUNCTYPE.__doc__: - WINFUNCTYPE.__doc__ = CFUNCTYPE.__doc__.replace("CFUNCTYPE", "WINFUNCTYPE") - -elif _os.name == "posix": - from _ctypes import dlopen as _dlopen - -from _ctypes import sizeof, byref, addressof, alignment, resize -from _ctypes import _SimpleCData - -def _check_size(typ, typecode=None): - # Check if sizeof(ctypes_type) against struct.calcsize. This - # should protect somewhat against a misconfigured libffi. - from struct import calcsize - if typecode is None: - # Most _type_ codes are the same as used in struct - typecode = typ._type_ - actual, required = sizeof(typ), calcsize(typecode) - if actual != required: - raise SystemError("sizeof(%s) wrong: %d instead of %d" % \ - (typ, actual, required)) - -class py_object(_SimpleCData): - _type_ = "O" - def __repr__(self): - try: - return super(py_object, self).__repr__() - except ValueError: - return "%s(<NULL>)" % type(self).__name__ -_check_size(py_object, "P") - -class c_short(_SimpleCData): - _type_ = "h" -_check_size(c_short) - -class c_ushort(_SimpleCData): - _type_ = "H" -_check_size(c_ushort) - -class c_long(_SimpleCData): - _type_ = "l" -_check_size(c_long) - -class c_ulong(_SimpleCData): - _type_ = "L" -_check_size(c_ulong) - -if _calcsize("i") == _calcsize("l"): - # if int and long have the same size, make c_int an alias for c_long - c_int = c_long - c_uint = c_ulong -else: - class c_int(_SimpleCData): - _type_ = "i" - _check_size(c_int) - - class c_uint(_SimpleCData): - _type_ = "I" - _check_size(c_uint) - -class c_float(_SimpleCData): - _type_ = "f" -_check_size(c_float) - -class c_double(_SimpleCData): - _type_ = "d" -_check_size(c_double) - -if _calcsize("l") == _calcsize("q"): - # if long and long long have the same size, make c_longlong an alias for c_long - c_longlong = c_long - c_ulonglong = c_ulong -else: - class c_longlong(_SimpleCData): - _type_ = "q" - _check_size(c_longlong) - - class c_ulonglong(_SimpleCData): - _type_ = "Q" - ## def from_param(cls, val): - ## return ('d', float(val), val) - ## from_param = classmethod(from_param) - _check_size(c_ulonglong) - -class c_ubyte(_SimpleCData): - _type_ = "B" -c_ubyte.__ctype_le__ = c_ubyte.__ctype_be__ = c_ubyte -# backward compatibility: -##c_uchar = c_ubyte -_check_size(c_ubyte) - -class c_byte(_SimpleCData): - _type_ = "b" -c_byte.__ctype_le__ = c_byte.__ctype_be__ = c_byte -_check_size(c_byte) - -class c_char(_SimpleCData): - _type_ = "c" -c_char.__ctype_le__ = c_char.__ctype_be__ = c_char -_check_size(c_char) - -class c_char_p(_SimpleCData): - _type_ = "z" -_check_size(c_char_p, "P") - -class c_void_p(_SimpleCData): - _type_ = "P" -c_voidp = c_void_p # backwards compatibility (to a bug) -_check_size(c_void_p) - -# This cache maps types to pointers to them. -_pointer_type_cache = {} - -def POINTER(cls): - try: - return _pointer_type_cache[cls] - except KeyError: - pass - if type(cls) is str: - klass = type(_Pointer)("LP_%s" % cls, - (_Pointer,), - {}) - _pointer_type_cache[id(klass)] = klass - return klass - else: - name = "LP_%s" % cls.__name__ - klass = type(_Pointer)(name, - (_Pointer,), - {'_type_': cls}) - _pointer_type_cache[cls] = klass - return klass - -try: - from _ctypes import set_conversion_mode -except ImportError: - pass -else: - if _os.name in ("nt", "ce"): - set_conversion_mode("mbcs", "ignore") - else: - set_conversion_mode("ascii", "strict") - - class c_wchar_p(_SimpleCData): - _type_ = "Z" - - class c_wchar(_SimpleCData): - _type_ = "u" - - POINTER(c_wchar).from_param = c_wchar_p.from_param #_SimpleCData.c_wchar_p_from_param - - def create_unicode_buffer(init, size=None): - """create_unicode_buffer(aString) -> character array - create_unicode_buffer(anInteger) -> character array - create_unicode_buffer(aString, anInteger) -> character array - """ - if isinstance(init, (str, unicode)): - if size is None: - size = len(init)+1 - buftype = c_wchar * size - buf = buftype() - buf.value = init - return buf - elif isinstance(init, (int, long)): - buftype = c_wchar * init - buf = buftype() - return buf - raise TypeError, init - -POINTER(c_char).from_param = c_char_p.from_param #_SimpleCData.c_char_p_from_param - -# XXX Deprecated -def SetPointerType(pointer, cls): - if _pointer_type_cache.get(cls, None) is not None: - raise RuntimeError, \ - "This type already exists in the cache" - if not _pointer_type_cache.has_key(id(pointer)): - raise RuntimeError, \ - "What's this???" - pointer.set_type(cls) - _pointer_type_cache[cls] = pointer - del _pointer_type_cache[id(pointer)] - - -def pointer(inst): - return POINTER(type(inst))(inst) - -# XXX Deprecated -def ARRAY(typ, len): - return typ * len - -################################################################ - - -class CDLL(object): - """An instance of this class represents a loaded dll/shared - library, exporting functions using the standard C calling - convention (named 'cdecl' on Windows). - - The exported functions can be accessed as attributes, or by - indexing with the function name. Examples: - - <obj>.qsort -> callable object - <obj>['qsort'] -> callable object - - Calling the functions releases the Python GIL during the call and - reaquires it afterwards. - """ - class _FuncPtr(_CFuncPtr): - _flags_ = _FUNCFLAG_CDECL - _restype_ = c_int # default, can be overridden in instances - - def __init__(self, name, mode=DEFAULT_MODE, handle=None): - self._name = name - if handle is None: - self._handle = _dlopen(self._name, mode) - else: - self._handle = handle - - def __repr__(self): - return "<%s '%s', handle %x at %x>" % \ - (self.__class__.__name__, self._name, - (self._handle & (_sys.maxint*2 + 1)), - id(self) & (_sys.maxint*2 + 1)) - - def __getattr__(self, name): - if name.startswith('__') and name.endswith('__'): - raise AttributeError, name - func = self.__getitem__(name) - setattr(self, name, func) - return func - - def __getitem__(self, name_or_ordinal): - func = self._FuncPtr((name_or_ordinal, self)) - if not isinstance(name_or_ordinal, (int, long)): - func.__name__ = name_or_ordinal - return func - -class PyDLL(CDLL): - """This class represents the Python library itself. It allows to - access Python API functions. The GIL is not released, and - Python exceptions are handled correctly. - """ - class _FuncPtr(_CFuncPtr): - _flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI - _restype_ = c_int # default, can be overridden in instances - -if _os.name in ("nt", "ce"): - - class WinDLL(CDLL): - """This class represents a dll exporting functions using the - Windows stdcall calling convention. - """ - class _FuncPtr(_CFuncPtr): - _flags_ = _FUNCFLAG_STDCALL - _restype_ = c_int # default, can be overridden in instances - - # XXX Hm, what about HRESULT as normal parameter? - # Mustn't it derive from c_long then? - from _ctypes import _check_HRESULT, _SimpleCData - class HRESULT(_SimpleCData): - _type_ = "l" - # _check_retval_ is called with the function's result when it - # is used as restype. It checks for the FAILED bit, and - # raises a WindowsError if it is set. - # - # The _check_retval_ method is implemented in C, so that the - # method definition itself is not included in the traceback - # when it raises an error - that is what we want (and Python - # doesn't have a way to raise an exception in the caller's - # frame). - _check_retval_ = _check_HRESULT - - class OleDLL(CDLL): - """This class represents a dll exporting functions using the - Windows stdcall calling convention, and returning HRESULT. - HRESULT error values are automatically raised as WindowsError - exceptions. - """ - class _FuncPtr(_CFuncPtr): - _flags_ = _FUNCFLAG_STDCALL - _restype_ = HRESULT - -class LibraryLoader(object): - def __init__(self, dlltype): - self._dlltype = dlltype - - def __getattr__(self, name): - if name[0] == '_': - raise AttributeError(name) - dll = self._dlltype(name) - setattr(self, name, dll) - return dll - - def __getitem__(self, name): - return getattr(self, name) - - def LoadLibrary(self, name): - return self._dlltype(name) - -cdll = LibraryLoader(CDLL) -pydll = LibraryLoader(PyDLL) - -if _os.name in ("nt", "ce"): - pythonapi = PyDLL("python dll", None, _sys.dllhandle) -elif _sys.platform == "cygwin": - pythonapi = PyDLL("libpython%d.%d.dll" % _sys.version_info[:2]) -else: - pythonapi = PyDLL(None) - - -if _os.name in ("nt", "ce"): - windll = LibraryLoader(WinDLL) - oledll = LibraryLoader(OleDLL) - - if _os.name == "nt": - GetLastError = windll.kernel32.GetLastError - else: - GetLastError = windll.coredll.GetLastError - - def WinError(code=None, descr=None): - if code is None: - code = GetLastError() - if descr is None: - descr = FormatError(code).strip() - return WindowsError(code, descr) - -_pointer_type_cache[None] = c_void_p - -if sizeof(c_uint) == sizeof(c_void_p): - c_size_t = c_uint -elif sizeof(c_ulong) == sizeof(c_void_p): - c_size_t = c_ulong - -# functions - -from _ctypes import _memmove_addr, _memset_addr, _string_at_addr, _cast_addr - -## void *memmove(void *, const void *, size_t); -memmove = CFUNCTYPE(c_void_p, c_void_p, c_void_p, c_size_t)(_memmove_addr) - -## void *memset(void *, int, size_t) -memset = CFUNCTYPE(c_void_p, c_void_p, c_int, c_size_t)(_memset_addr) - -def PYFUNCTYPE(restype, *argtypes): - class CFunctionType(_CFuncPtr): - _argtypes_ = argtypes - _restype_ = restype - _flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI - return CFunctionType - -_cast = PYFUNCTYPE(py_object, c_void_p, py_object, py_object)(_cast_addr) -def cast(obj, typ): - return _cast(obj, obj, typ) - -_string_at = CFUNCTYPE(py_object, c_void_p, c_int)(_string_at_addr) -def string_at(ptr, size=-1): - """string_at(addr[, size]) -> string - - Return the string at addr.""" - return _string_at(ptr, size) - -try: - from _ctypes import _wstring_at_addr -except ImportError: - pass -else: - _wstring_at = CFUNCTYPE(py_object, c_void_p, c_int)(_wstring_at_addr) - def wstring_at(ptr, size=-1): - """wstring_at(addr[, size]) -> string - - Return the string at addr.""" - return _wstring_at(ptr, size) - - -if _os.name in ("nt", "ce"): # COM stuff - def DllGetClassObject(rclsid, riid, ppv): - try: - ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*']) - except ImportError: - return -2147221231 # CLASS_E_CLASSNOTAVAILABLE - else: - return ccom.DllGetClassObject(rclsid, riid, ppv) - - def DllCanUnloadNow(): - try: - ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*']) - except ImportError: - return 0 # S_OK - return ccom.DllCanUnloadNow() - -from ctypes._endian import BigEndianStructure, LittleEndianStructure - -# Fill in specifically-sized types -c_int8 = c_byte -c_uint8 = c_ubyte -for kind in [c_short, c_int, c_long, c_longlong]: - if sizeof(kind) == 2: c_int16 = kind - elif sizeof(kind) == 4: c_int32 = kind - elif sizeof(kind) == 8: c_int64 = kind -for kind in [c_ushort, c_uint, c_ulong, c_ulonglong]: - if sizeof(kind) == 2: c_uint16 = kind - elif sizeof(kind) == 4: c_uint32 = kind - elif sizeof(kind) == 8: c_uint64 = kind -del(kind) diff --git a/sys/lib/python/ctypes/_endian.py b/sys/lib/python/ctypes/_endian.py deleted file mode 100644 index 6de0d47b2..000000000 --- a/sys/lib/python/ctypes/_endian.py +++ /dev/null @@ -1,60 +0,0 @@ -###################################################################### -# This file should be kept compatible with Python 2.3, see PEP 291. # -###################################################################### -import sys -from ctypes import * - -_array_type = type(c_int * 3) - -def _other_endian(typ): - """Return the type with the 'other' byte order. Simple types like - c_int and so on already have __ctype_be__ and __ctype_le__ - attributes which contain the types, for more complicated types - only arrays are supported. - """ - try: - return getattr(typ, _OTHER_ENDIAN) - except AttributeError: - if type(typ) == _array_type: - return _other_endian(typ._type_) * typ._length_ - raise TypeError("This type does not support other endian: %s" % typ) - -class _swapped_meta(type(Structure)): - def __setattr__(self, attrname, value): - if attrname == "_fields_": - fields = [] - for desc in value: - name = desc[0] - typ = desc[1] - rest = desc[2:] - fields.append((name, _other_endian(typ)) + rest) - value = fields - super(_swapped_meta, self).__setattr__(attrname, value) - -################################################################ - -# Note: The Structure metaclass checks for the *presence* (not the -# value!) of a _swapped_bytes_ attribute to determine the bit order in -# structures containing bit fields. - -if sys.byteorder == "little": - _OTHER_ENDIAN = "__ctype_be__" - - LittleEndianStructure = Structure - - class BigEndianStructure(Structure): - """Structure with big endian byte order""" - __metaclass__ = _swapped_meta - _swappedbytes_ = None - -elif sys.byteorder == "big": - _OTHER_ENDIAN = "__ctype_le__" - - BigEndianStructure = Structure - class LittleEndianStructure(Structure): - """Structure with little endian byte order""" - __metaclass__ = _swapped_meta - _swappedbytes_ = None - -else: - raise RuntimeError("Invalid byteorder") diff --git a/sys/lib/python/ctypes/macholib/README.ctypes b/sys/lib/python/ctypes/macholib/README.ctypes deleted file mode 100644 index 4e10cbe41..000000000 --- a/sys/lib/python/ctypes/macholib/README.ctypes +++ /dev/null @@ -1,7 +0,0 @@ -Files in this directory from from Bob Ippolito's py2app. - -License: Any components of the py2app suite may be distributed under -the MIT or PSF open source licenses. - -This is version 1.0, SVN revision 789, from 2006/01/25. -The main repository is http://svn.red-bean.com/bob/macholib/trunk/macholib/
\ No newline at end of file diff --git a/sys/lib/python/ctypes/macholib/__init__.py b/sys/lib/python/ctypes/macholib/__init__.py deleted file mode 100644 index 36149d28a..000000000 --- a/sys/lib/python/ctypes/macholib/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -###################################################################### -# This file should be kept compatible with Python 2.3, see PEP 291. # -###################################################################### -""" -Enough Mach-O to make your head spin. - -See the relevant header files in /usr/include/mach-o - -And also Apple's documentation. -""" - -__version__ = '1.0' diff --git a/sys/lib/python/ctypes/macholib/dyld.py b/sys/lib/python/ctypes/macholib/dyld.py deleted file mode 100644 index 14e21395e..000000000 --- a/sys/lib/python/ctypes/macholib/dyld.py +++ /dev/null @@ -1,169 +0,0 @@ -###################################################################### -# This file should be kept compatible with Python 2.3, see PEP 291. # -###################################################################### -""" -dyld emulation -""" - -import os -from framework import framework_info -from dylib import dylib_info -from itertools import * - -__all__ = [ - 'dyld_find', 'framework_find', - 'framework_info', 'dylib_info', -] - -# These are the defaults as per man dyld(1) -# -DEFAULT_FRAMEWORK_FALLBACK = [ - os.path.expanduser("~/Library/Frameworks"), - "/Library/Frameworks", - "/Network/Library/Frameworks", - "/System/Library/Frameworks", -] - -DEFAULT_LIBRARY_FALLBACK = [ - os.path.expanduser("~/lib"), - "/usr/local/lib", - "/lib", - "/usr/lib", -] - -def ensure_utf8(s): - """Not all of PyObjC and Python understand unicode paths very well yet""" - if isinstance(s, unicode): - return s.encode('utf8') - return s - -def dyld_env(env, var): - if env is None: - env = os.environ - rval = env.get(var) - if rval is None: - return [] - return rval.split(':') - -def dyld_image_suffix(env=None): - if env is None: - env = os.environ - return env.get('DYLD_IMAGE_SUFFIX') - -def dyld_framework_path(env=None): - return dyld_env(env, 'DYLD_FRAMEWORK_PATH') - -def dyld_library_path(env=None): - return dyld_env(env, 'DYLD_LIBRARY_PATH') - -def dyld_fallback_framework_path(env=None): - return dyld_env(env, 'DYLD_FALLBACK_FRAMEWORK_PATH') - -def dyld_fallback_library_path(env=None): - return dyld_env(env, 'DYLD_FALLBACK_LIBRARY_PATH') - -def dyld_image_suffix_search(iterator, env=None): - """For a potential path iterator, add DYLD_IMAGE_SUFFIX semantics""" - suffix = dyld_image_suffix(env) - if suffix is None: - return iterator - def _inject(iterator=iterator, suffix=suffix): - for path in iterator: - if path.endswith('.dylib'): - yield path[:-len('.dylib')] + suffix + '.dylib' - else: - yield path + suffix - yield path - return _inject() - -def dyld_override_search(name, env=None): - # If DYLD_FRAMEWORK_PATH is set and this dylib_name is a - # framework name, use the first file that exists in the framework - # path if any. If there is none go on to search the DYLD_LIBRARY_PATH - # if any. - - framework = framework_info(name) - - if framework is not None: - for path in dyld_framework_path(env): - yield os.path.join(path, framework['name']) - - # If DYLD_LIBRARY_PATH is set then use the first file that exists - # in the path. If none use the original name. - for path in dyld_library_path(env): - yield os.path.join(path, os.path.basename(name)) - -def dyld_executable_path_search(name, executable_path=None): - # If we haven't done any searching and found a library and the - # dylib_name starts with "@executable_path/" then construct the - # library name. - if name.startswith('@executable_path/') and executable_path is not None: - yield os.path.join(executable_path, name[len('@executable_path/'):]) - -def dyld_default_search(name, env=None): - yield name - - framework = framework_info(name) - - if framework is not None: - fallback_framework_path = dyld_fallback_framework_path(env) - for path in fallback_framework_path: - yield os.path.join(path, framework['name']) - - fallback_library_path = dyld_fallback_library_path(env) - for path in fallback_library_path: - yield os.path.join(path, os.path.basename(name)) - - if framework is not None and not fallback_framework_path: - for path in DEFAULT_FRAMEWORK_FALLBACK: - yield os.path.join(path, framework['name']) - - if not fallback_library_path: - for path in DEFAULT_LIBRARY_FALLBACK: - yield os.path.join(path, os.path.basename(name)) - -def dyld_find(name, executable_path=None, env=None): - """ - Find a library or framework using dyld semantics - """ - name = ensure_utf8(name) - executable_path = ensure_utf8(executable_path) - for path in dyld_image_suffix_search(chain( - dyld_override_search(name, env), - dyld_executable_path_search(name, executable_path), - dyld_default_search(name, env), - ), env): - if os.path.isfile(path): - return path - raise ValueError, "dylib %s could not be found" % (name,) - -def framework_find(fn, executable_path=None, env=None): - """ - Find a framework using dyld semantics in a very loose manner. - - Will take input such as: - Python - Python.framework - Python.framework/Versions/Current - """ - try: - return dyld_find(fn, executable_path=executable_path, env=env) - except ValueError, e: - pass - fmwk_index = fn.rfind('.framework') - if fmwk_index == -1: - fmwk_index = len(fn) - fn += '.framework' - fn = os.path.join(fn, os.path.basename(fn[:fmwk_index])) - try: - return dyld_find(fn, executable_path=executable_path, env=env) - except ValueError: - raise e - -def test_dyld_find(): - env = {} - assert dyld_find('libSystem.dylib') == '/usr/lib/libSystem.dylib' - assert dyld_find('System.framework/System') == '/System/Library/Frameworks/System.framework/System' - -if __name__ == '__main__': - test_dyld_find() diff --git a/sys/lib/python/ctypes/macholib/dylib.py b/sys/lib/python/ctypes/macholib/dylib.py deleted file mode 100644 index ea3dd38bd..000000000 --- a/sys/lib/python/ctypes/macholib/dylib.py +++ /dev/null @@ -1,66 +0,0 @@ -###################################################################### -# This file should be kept compatible with Python 2.3, see PEP 291. # -###################################################################### -""" -Generic dylib path manipulation -""" - -import re - -__all__ = ['dylib_info'] - -DYLIB_RE = re.compile(r"""(?x) -(?P<location>^.*)(?:^|/) -(?P<name> - (?P<shortname>\w+?) - (?:\.(?P<version>[^._]+))? - (?:_(?P<suffix>[^._]+))? - \.dylib$ -) -""") - -def dylib_info(filename): - """ - A dylib name can take one of the following four forms: - Location/Name.SomeVersion_Suffix.dylib - Location/Name.SomeVersion.dylib - Location/Name_Suffix.dylib - Location/Name.dylib - - returns None if not found or a mapping equivalent to: - dict( - location='Location', - name='Name.SomeVersion_Suffix.dylib', - shortname='Name', - version='SomeVersion', - suffix='Suffix', - ) - - Note that SomeVersion and Suffix are optional and may be None - if not present. - """ - is_dylib = DYLIB_RE.match(filename) - if not is_dylib: - return None - return is_dylib.groupdict() - - -def test_dylib_info(): - def d(location=None, name=None, shortname=None, version=None, suffix=None): - return dict( - location=location, - name=name, - shortname=shortname, - version=version, - suffix=suffix - ) - assert dylib_info('completely/invalid') is None - assert dylib_info('completely/invalide_debug') is None - assert dylib_info('P/Foo.dylib') == d('P', 'Foo.dylib', 'Foo') - assert dylib_info('P/Foo_debug.dylib') == d('P', 'Foo_debug.dylib', 'Foo', suffix='debug') - assert dylib_info('P/Foo.A.dylib') == d('P', 'Foo.A.dylib', 'Foo', 'A') - assert dylib_info('P/Foo_debug.A.dylib') == d('P', 'Foo_debug.A.dylib', 'Foo_debug', 'A') - assert dylib_info('P/Foo.A_debug.dylib') == d('P', 'Foo.A_debug.dylib', 'Foo', 'A', 'debug') - -if __name__ == '__main__': - test_dylib_info() diff --git a/sys/lib/python/ctypes/macholib/fetch_macholib b/sys/lib/python/ctypes/macholib/fetch_macholib deleted file mode 100755 index e6d6a2265..000000000 --- a/sys/lib/python/ctypes/macholib/fetch_macholib +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -svn export --force http://svn.red-bean.com/bob/macholib/trunk/macholib/ . diff --git a/sys/lib/python/ctypes/macholib/fetch_macholib.bat b/sys/lib/python/ctypes/macholib/fetch_macholib.bat deleted file mode 100644 index f9e1c0dc9..000000000 --- a/sys/lib/python/ctypes/macholib/fetch_macholib.bat +++ /dev/null @@ -1 +0,0 @@ -svn export --force http://svn.red-bean.com/bob/macholib/trunk/macholib/ . diff --git a/sys/lib/python/ctypes/macholib/framework.py b/sys/lib/python/ctypes/macholib/framework.py deleted file mode 100644 index dd7fb2f29..000000000 --- a/sys/lib/python/ctypes/macholib/framework.py +++ /dev/null @@ -1,68 +0,0 @@ -###################################################################### -# This file should be kept compatible with Python 2.3, see PEP 291. # -###################################################################### -""" -Generic framework path manipulation -""" - -import re - -__all__ = ['framework_info'] - -STRICT_FRAMEWORK_RE = re.compile(r"""(?x) -(?P<location>^.*)(?:^|/) -(?P<name> - (?P<shortname>\w+).framework/ - (?:Versions/(?P<version>[^/]+)/)? - (?P=shortname) - (?:_(?P<suffix>[^_]+))? -)$ -""") - -def framework_info(filename): - """ - A framework name can take one of the following four forms: - Location/Name.framework/Versions/SomeVersion/Name_Suffix - Location/Name.framework/Versions/SomeVersion/Name - Location/Name.framework/Name_Suffix - Location/Name.framework/Name - - returns None if not found, or a mapping equivalent to: - dict( - location='Location', - name='Name.framework/Versions/SomeVersion/Name_Suffix', - shortname='Name', - version='SomeVersion', - suffix='Suffix', - ) - - Note that SomeVersion and Suffix are optional and may be None - if not present - """ - is_framework = STRICT_FRAMEWORK_RE.match(filename) - if not is_framework: - return None - return is_framework.groupdict() - -def test_framework_info(): - def d(location=None, name=None, shortname=None, version=None, suffix=None): - return dict( - location=location, - name=name, - shortname=shortname, - version=version, - suffix=suffix - ) - assert framework_info('completely/invalid') is None - assert framework_info('completely/invalid/_debug') is None - assert framework_info('P/F.framework') is None - assert framework_info('P/F.framework/_debug') is None - assert framework_info('P/F.framework/F') == d('P', 'F.framework/F', 'F') - assert framework_info('P/F.framework/F_debug') == d('P', 'F.framework/F_debug', 'F', suffix='debug') - assert framework_info('P/F.framework/Versions') is None - assert framework_info('P/F.framework/Versions/A') is None - assert framework_info('P/F.framework/Versions/A/F') == d('P', 'F.framework/Versions/A/F', 'F', 'A') - assert framework_info('P/F.framework/Versions/A/F_debug') == d('P', 'F.framework/Versions/A/F_debug', 'F', 'A', 'debug') - -if __name__ == '__main__': - test_framework_info() diff --git a/sys/lib/python/ctypes/util.py b/sys/lib/python/ctypes/util.py deleted file mode 100644 index f7133538b..000000000 --- a/sys/lib/python/ctypes/util.py +++ /dev/null @@ -1,154 +0,0 @@ -###################################################################### -# This file should be kept compatible with Python 2.3, see PEP 291. # -###################################################################### -import sys, os - -# find_library(name) returns the pathname of a library, or None. -if os.name == "nt": - def find_library(name): - # See MSDN for the REAL search order. - for directory in os.environ['PATH'].split(os.pathsep): - fname = os.path.join(directory, name) - if os.path.exists(fname): - return fname - if fname.lower().endswith(".dll"): - continue - fname = fname + ".dll" - if os.path.exists(fname): - return fname - return None - -if os.name == "ce": - # search path according to MSDN: - # - absolute path specified by filename - # - The .exe launch directory - # - the Windows directory - # - ROM dll files (where are they?) - # - OEM specified search path: HKLM\Loader\SystemPath - def find_library(name): - return name - -if os.name == "posix" and sys.platform == "darwin": - from ctypes.macholib.dyld import dyld_find as _dyld_find - def find_library(name): - possible = ['lib%s.dylib' % name, - '%s.dylib' % name, - '%s.framework/%s' % (name, name)] - for name in possible: - try: - return _dyld_find(name) - except ValueError: - continue - return None - -elif os.name == "posix": - # Andreas Degert's find functions, using gcc, /sbin/ldconfig, objdump - import re, tempfile, errno - - def _findLib_gcc(name): - expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) - fdout, ccout = tempfile.mkstemp() - os.close(fdout) - cmd = 'if type gcc >/dev/null 2>&1; then CC=gcc; else CC=cc; fi;' \ - '$CC -Wl,-t -o ' + ccout + ' 2>&1 -l' + name - try: - f = os.popen(cmd) - trace = f.read() - f.close() - finally: - try: - os.unlink(ccout) - except OSError, e: - if e.errno != errno.ENOENT: - raise - res = re.search(expr, trace) - if not res: - return None - return res.group(0) - - def _get_soname(f): - # assuming GNU binutils / ELF - if not f: - return None - cmd = "objdump -p -j .dynamic 2>/dev/null " + f - res = re.search(r'\sSONAME\s+([^\s]+)', os.popen(cmd).read()) - if not res: - return None - return res.group(1) - - if (sys.platform.startswith("freebsd") - or sys.platform.startswith("openbsd") - or sys.platform.startswith("dragonfly")): - - def _num_version(libname): - # "libxyz.so.MAJOR.MINOR" => [ MAJOR, MINOR ] - parts = libname.split(".") - nums = [] - try: - while parts: - nums.insert(0, int(parts.pop())) - except ValueError: - pass - return nums or [ sys.maxint ] - - def find_library(name): - ename = re.escape(name) - expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename, ename) - res = re.findall(expr, - os.popen('/sbin/ldconfig -r 2>/dev/null').read()) - if not res: - return _get_soname(_findLib_gcc(name)) - res.sort(cmp= lambda x,y: cmp(_num_version(x), _num_version(y))) - return res[-1] - - else: - - def _findLib_ldconfig(name): - # XXX assuming GLIBC's ldconfig (with option -p) - expr = r'/[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) - res = re.search(expr, - os.popen('/sbin/ldconfig -p 2>/dev/null').read()) - if not res: - # Hm, this works only for libs needed by the python executable. - cmd = 'ldd %s 2>/dev/null' % sys.executable - res = re.search(expr, os.popen(cmd).read()) - if not res: - return None - return res.group(0) - - def find_library(name): - return _get_soname(_findLib_ldconfig(name) or _findLib_gcc(name)) - -################################################################ -# test code - -def test(): - from ctypes import cdll - if os.name == "nt": - print cdll.msvcrt - print cdll.load("msvcrt") - print find_library("msvcrt") - - if os.name == "posix": - # find and load_version - print find_library("m") - print find_library("c") - print find_library("bz2") - - # getattr -## print cdll.m -## print cdll.bz2 - - # load - if sys.platform == "darwin": - print cdll.LoadLibrary("libm.dylib") - print cdll.LoadLibrary("libcrypto.dylib") - print cdll.LoadLibrary("libSystem.dylib") - print cdll.LoadLibrary("System.framework/System") - else: - print cdll.LoadLibrary("libm.so") - print cdll.LoadLibrary("libcrypt.so") - print find_library("crypt") - -if __name__ == "__main__": - test() diff --git a/sys/lib/python/ctypes/wintypes.py b/sys/lib/python/ctypes/wintypes.py deleted file mode 100644 index 97682331f..000000000 --- a/sys/lib/python/ctypes/wintypes.py +++ /dev/null @@ -1,172 +0,0 @@ -###################################################################### -# This file should be kept compatible with Python 2.3, see PEP 291. # -###################################################################### - -# The most useful windows datatypes -from ctypes import * - -BYTE = c_byte -WORD = c_ushort -DWORD = c_ulong - -WCHAR = c_wchar -UINT = c_uint - -DOUBLE = c_double - -BOOLEAN = BYTE -BOOL = c_long - -from ctypes import _SimpleCData -class VARIANT_BOOL(_SimpleCData): - _type_ = "v" - def __repr__(self): - return "%s(%r)" % (self.__class__.__name__, self.value) - -ULONG = c_ulong -LONG = c_long - -# in the windows header files, these are structures. -_LARGE_INTEGER = LARGE_INTEGER = c_longlong -_ULARGE_INTEGER = ULARGE_INTEGER = c_ulonglong - -LPCOLESTR = LPOLESTR = OLESTR = c_wchar_p -LPCWSTR = LPWSTR = c_wchar_p -LPCSTR = LPSTR = c_char_p - -WPARAM = c_uint -LPARAM = c_long - -ATOM = WORD -LANGID = WORD - -COLORREF = DWORD -LGRPID = DWORD -LCTYPE = DWORD - -LCID = DWORD - -################################################################ -# HANDLE types -HANDLE = c_ulong # in the header files: void * - -HACCEL = HANDLE -HBITMAP = HANDLE -HBRUSH = HANDLE -HCOLORSPACE = HANDLE -HDC = HANDLE -HDESK = HANDLE -HDWP = HANDLE -HENHMETAFILE = HANDLE -HFONT = HANDLE -HGDIOBJ = HANDLE -HGLOBAL = HANDLE -HHOOK = HANDLE -HICON = HANDLE -HINSTANCE = HANDLE -HKEY = HANDLE -HKL = HANDLE -HLOCAL = HANDLE -HMENU = HANDLE -HMETAFILE = HANDLE -HMODULE = HANDLE -HMONITOR = HANDLE -HPALETTE = HANDLE -HPEN = HANDLE -HRGN = HANDLE -HRSRC = HANDLE -HSTR = HANDLE -HTASK = HANDLE -HWINSTA = HANDLE -HWND = HANDLE -SC_HANDLE = HANDLE -SERVICE_STATUS_HANDLE = HANDLE - -################################################################ -# Some important structure definitions - -class RECT(Structure): - _fields_ = [("left", c_long), - ("top", c_long), - ("right", c_long), - ("bottom", c_long)] -tagRECT = _RECTL = RECTL = RECT - -class _SMALL_RECT(Structure): - _fields_ = [('Left', c_short), - ('Top', c_short), - ('Right', c_short), - ('Bottom', c_short)] -SMALL_RECT = _SMALL_RECT - -class _COORD(Structure): - _fields_ = [('X', c_short), - ('Y', c_short)] - -class POINT(Structure): - _fields_ = [("x", c_long), - ("y", c_long)] -tagPOINT = _POINTL = POINTL = POINT - -class SIZE(Structure): - _fields_ = [("cx", c_long), - ("cy", c_long)] -tagSIZE = SIZEL = SIZE - -def RGB(red, green, blue): - return red + (green << 8) + (blue << 16) - -class FILETIME(Structure): - _fields_ = [("dwLowDateTime", DWORD), - ("dwHighDateTime", DWORD)] -_FILETIME = FILETIME - -class MSG(Structure): - _fields_ = [("hWnd", HWND), - ("message", c_uint), - ("wParam", WPARAM), - ("lParam", LPARAM), - ("time", DWORD), - ("pt", POINT)] -tagMSG = MSG -MAX_PATH = 260 - -class WIN32_FIND_DATAA(Structure): - _fields_ = [("dwFileAttributes", DWORD), - ("ftCreationTime", FILETIME), - ("ftLastAccessTime", FILETIME), - ("ftLastWriteTime", FILETIME), - ("nFileSizeHigh", DWORD), - ("nFileSizeLow", DWORD), - ("dwReserved0", DWORD), - ("dwReserved1", DWORD), - ("cFileName", c_char * MAX_PATH), - ("cAlternameFileName", c_char * 14)] - -class WIN32_FIND_DATAW(Structure): - _fields_ = [("dwFileAttributes", DWORD), - ("ftCreationTime", FILETIME), - ("ftLastAccessTime", FILETIME), - ("ftLastWriteTime", FILETIME), - ("nFileSizeHigh", DWORD), - ("nFileSizeLow", DWORD), - ("dwReserved0", DWORD), - ("dwReserved1", DWORD), - ("cFileName", c_wchar * MAX_PATH), - ("cAlternameFileName", c_wchar * 14)] - -__all__ = ['ATOM', 'BOOL', 'BOOLEAN', 'BYTE', 'COLORREF', 'DOUBLE', - 'DWORD', 'FILETIME', 'HACCEL', 'HANDLE', 'HBITMAP', 'HBRUSH', - 'HCOLORSPACE', 'HDC', 'HDESK', 'HDWP', 'HENHMETAFILE', 'HFONT', - 'HGDIOBJ', 'HGLOBAL', 'HHOOK', 'HICON', 'HINSTANCE', 'HKEY', - 'HKL', 'HLOCAL', 'HMENU', 'HMETAFILE', 'HMODULE', 'HMONITOR', - 'HPALETTE', 'HPEN', 'HRGN', 'HRSRC', 'HSTR', 'HTASK', 'HWINSTA', - 'HWND', 'LANGID', 'LARGE_INTEGER', 'LCID', 'LCTYPE', 'LGRPID', - 'LONG', 'LPARAM', 'LPCOLESTR', 'LPCSTR', 'LPCWSTR', 'LPOLESTR', - 'LPSTR', 'LPWSTR', 'MAX_PATH', 'MSG', 'OLESTR', 'POINT', - 'POINTL', 'RECT', 'RECTL', 'RGB', 'SC_HANDLE', - 'SERVICE_STATUS_HANDLE', 'SIZE', 'SIZEL', 'SMALL_RECT', 'UINT', - 'ULARGE_INTEGER', 'ULONG', 'VARIANT_BOOL', 'WCHAR', - 'WIN32_FIND_DATAA', 'WIN32_FIND_DATAW', 'WORD', 'WPARAM', '_COORD', - '_FILETIME', '_LARGE_INTEGER', '_POINTL', '_RECTL', '_SMALL_RECT', - '_ULARGE_INTEGER', 'tagMSG', 'tagPOINT', 'tagRECT', 'tagSIZE'] |