Debian Codegraph @

Lib/ctypes/__init__.py

raw
1 """create and manipulate C data types in Python"""
2
3 import os as _os
4 import sys as _sys
5 import sysconfig as _sysconfig
6 import types as _types
7
8 __version__ = "1.1.0"
9
10 from _ctypes import Union, Structure, Array
11 from _ctypes import _Pointer
12 from _ctypes import CFuncPtr as _CFuncPtr
13 from _ctypes import __version__ as _ctypes_version
14 from _ctypes import RTLD_LOCAL, RTLD_GLOBAL
15 from _ctypes import ArgumentError
16 from _ctypes import SIZEOF_TIME_T
17
18 from struct import calcsize as _calcsize
19
20 if __version__ != _ctypes_version:
21 raise Exception("Version number mismatch", __version__, _ctypes_version)
22
23 if _os.name == "nt":
24 from _ctypes import FormatError
25
26 DEFAULT_MODE = RTLD_LOCAL
27 if _os.name == "posix" and _sys.platform == "darwin":
28 # On OS X 10.3, we use RTLD_GLOBAL as default mode
29 # because RTLD_LOCAL does not work at least on some
30 # libraries. OS X 10.3 is Darwin 7, so we check for
31 # that.
32
33 if int(_os.uname().release.split('.')[0]) < 8:
34 DEFAULT_MODE = RTLD_GLOBAL
35
36 from _ctypes import FUNCFLAG_CDECL as _FUNCFLAG_CDECL, \
37 FUNCFLAG_PYTHONAPI as _FUNCFLAG_PYTHONAPI, \
38 FUNCFLAG_USE_ERRNO as _FUNCFLAG_USE_ERRNO, \
39 FUNCFLAG_USE_LASTERROR as _FUNCFLAG_USE_LASTERROR
40
41 # WINOLEAPI -> HRESULT
42 # WINOLEAPI_(type)
43 #
44 # STDMETHODCALLTYPE
45 #
46 # STDMETHOD(name)
47 # STDMETHOD_(type, name)
48 #
49 # STDAPICALLTYPE
50
51 def create_string_buffer(init, size=None):
52 """create_string_buffer(aBytes) -> character array
53 create_string_buffer(anInteger) -> character array
54 create_string_buffer(aBytes, anInteger) -> character array
55 """
56 if isinstance(init, bytes):
57 if size is None:
58 size = len(init)+1
59 _sys.audit("ctypes.create_string_buffer", init, size)
60 buftype = c_char * size
61 buf = buftype()
62 buf.value = init
63 return buf
64 elif isinstance(init, int):
65 _sys.audit("ctypes.create_string_buffer", None, init)
66 buftype = c_char * init
67 buf = buftype()
68 return buf
69 raise TypeError(init)
70
71 # Alias to create_string_buffer() for backward compatibility
72 c_buffer = create_string_buffer
73
74 _c_functype_cache = {}
75 def CFUNCTYPE(restype, *argtypes, **kw):
76 """CFUNCTYPE(restype, *argtypes,
77 use_errno=False, use_last_error=False) -> function prototype.
78
79 restype: the result type
80 argtypes: a sequence specifying the argument types
81
82 The function prototype can be called in different ways to create a
83 callable object:
84
85 prototype(integer address) -> foreign function
86 prototype(callable) -> create and return a C callable function from callable
87 prototype(integer index, method name[, paramflags]) -> foreign function calling a COM method
88 prototype((ordinal number, dll object)[, paramflags]) -> foreign function exported by ordinal
89 prototype((function name, dll object)[, paramflags]) -> foreign function exported by name
90 """
91 flags = _FUNCFLAG_CDECL
92 if kw.pop("use_errno", False):
93 flags |= _FUNCFLAG_USE_ERRNO
94 if kw.pop("use_last_error", False):
95 flags |= _FUNCFLAG_USE_LASTERROR
96 if kw:
97 raise ValueError("unexpected keyword argument(s) %s" % kw.keys())
98
99 try:
100 return _c_functype_cache[(restype, argtypes, flags)]
101 except KeyError:
102 pass
103
104 class CFunctionType(_CFuncPtr):
105 _argtypes_ = argtypes
106 _restype_ = restype
107 _flags_ = flags
108 _c_functype_cache[(restype, argtypes, flags)] = CFunctionType
109 return CFunctionType
110
111 if _os.name == "nt":
112 from _ctypes import LoadLibrary as _LoadLibrary
113 from _ctypes import FUNCFLAG_STDCALL as _FUNCFLAG_STDCALL
114
115 _win_functype_cache = {}
116 def WINFUNCTYPE(restype, *argtypes, **kw):
117 # docstring set later (very similar to CFUNCTYPE.__doc__)
118 flags = _FUNCFLAG_STDCALL
119 if kw.pop("use_errno", False):
120 flags |= _FUNCFLAG_USE_ERRNO
121 if kw.pop("use_last_error", False):
122 flags |= _FUNCFLAG_USE_LASTERROR
123 if kw:
124 raise ValueError("unexpected keyword argument(s) %s" % kw.keys())
125
126 try:
127 return _win_functype_cache[(restype, argtypes, flags)]
128 except KeyError:
129 pass
130
131 class WinFunctionType(_CFuncPtr):
132 _argtypes_ = argtypes
133 _restype_ = restype
134 _flags_ = flags
135 _win_functype_cache[(restype, argtypes, flags)] = WinFunctionType
136 return WinFunctionType
137 if WINFUNCTYPE.__doc__:
138 WINFUNCTYPE.__doc__ = CFUNCTYPE.__doc__.replace("CFUNCTYPE", "WINFUNCTYPE")
139
140 elif _os.name == "posix":
141 from _ctypes import dlopen as _dlopen
142
143 from _ctypes import sizeof, byref, addressof, alignment, resize
144 from _ctypes import get_errno, set_errno
145 from _ctypes import _SimpleCData
146
147 def _check_size(typ, typecode=None):
148 # Check if sizeof(ctypes_type) against struct.calcsize. This
149 # should protect somewhat against a misconfigured libffi.
150 from struct import calcsize
151 if typecode is None:
152 # Most _type_ codes are the same as used in struct
153 typecode = typ._type_
154 actual, required = sizeof(typ), calcsize(typecode)
155 if actual != required:
156 raise SystemError("sizeof(%s) wrong: %d instead of %d" % \
157 (typ, actual, required))
158
159 class py_object(_SimpleCData):
160 _type_ = "O"
161 def __repr__(self):
162 try:
163 return super().__repr__()
164 except ValueError:
165 return "%s(<NULL>)" % type(self).__name__
166 _check_size(py_object, "P")
167
168 class c_short(_SimpleCData):
169 _type_ = "h"
170 _check_size(c_short)
171
172 class c_ushort(_SimpleCData):
173 _type_ = "H"
174 _check_size(c_ushort)
175
176 class c_long(_SimpleCData):
177 _type_ = "l"
178 _check_size(c_long)
179
180 class c_ulong(_SimpleCData):
181 _type_ = "L"
182 _check_size(c_ulong)
183
184 if _calcsize("i") == _calcsize("l"):
185 # if int and long have the same size, make c_int an alias for c_long
186 c_int = c_long
187 c_uint = c_ulong
188 else:
189 class c_int(_SimpleCData):
190 _type_ = "i"
191 _check_size(c_int)
192
193 class c_uint(_SimpleCData):
194 _type_ = "I"
195 _check_size(c_uint)
196
197 class c_float(_SimpleCData):
198 _type_ = "f"
199 _check_size(c_float)
200
201 class c_double(_SimpleCData):
202 _type_ = "d"
203 _check_size(c_double)
204
205 class c_longdouble(_SimpleCData):
206 _type_ = "g"
207 if sizeof(c_longdouble) == sizeof(c_double):
208 c_longdouble = c_double
209
210 if _calcsize("l") == _calcsize("q"):
211 # if long and long long have the same size, make c_longlong an alias for c_long
212 c_longlong = c_long
213 c_ulonglong = c_ulong
214 else:
215 class c_longlong(_SimpleCData):
216 _type_ = "q"
217 _check_size(c_longlong)
218
219 class c_ulonglong(_SimpleCData):
220 _type_ = "Q"
221 ## def from_param(cls, val):
222 ## return ('d', float(val), val)
223 ## from_param = classmethod(from_param)
224 _check_size(c_ulonglong)
225
226 class c_ubyte(_SimpleCData):
227 _type_ = "B"
228 c_ubyte.__ctype_le__ = c_ubyte.__ctype_be__ = c_ubyte
229 # backward compatibility:
230 ##c_uchar = c_ubyte
231 _check_size(c_ubyte)
232
233 class c_byte(_SimpleCData):
234 _type_ = "b"
235 c_byte.__ctype_le__ = c_byte.__ctype_be__ = c_byte
236 _check_size(c_byte)
237
238 class c_char(_SimpleCData):
239 _type_ = "c"
240 c_char.__ctype_le__ = c_char.__ctype_be__ = c_char
241 _check_size(c_char)
242
243 class c_char_p(_SimpleCData):
244 _type_ = "z"
245 def __repr__(self):
246 return "%s(%s)" % (self.__class__.__name__, c_void_p.from_buffer(self).value)
247 _check_size(c_char_p, "P")
248
249 class c_void_p(_SimpleCData):
250 _type_ = "P"
251 c_voidp = c_void_p # backwards compatibility (to a bug)
252 _check_size(c_void_p)
253
254 class c_bool(_SimpleCData):
255 _type_ = "?"
256
257 from _ctypes import POINTER, pointer, _pointer_type_cache
258
259 class c_wchar_p(_SimpleCData):
260 _type_ = "Z"
261 def __repr__(self):
262 return "%s(%s)" % (self.__class__.__name__, c_void_p.from_buffer(self).value)
263
264 class c_wchar(_SimpleCData):
265 _type_ = "u"
266
267 def _reset_cache():
268 _pointer_type_cache.clear()
269 _c_functype_cache.clear()
270 if _os.name == "nt":
271 _win_functype_cache.clear()
272 # _SimpleCData.c_wchar_p_from_param
273 POINTER(c_wchar).from_param = c_wchar_p.from_param
274 # _SimpleCData.c_char_p_from_param
275 POINTER(c_char).from_param = c_char_p.from_param
276 _pointer_type_cache[None] = c_void_p
277
278 def create_unicode_buffer(init, size=None):
279 """create_unicode_buffer(aString) -> character array
280 create_unicode_buffer(anInteger) -> character array
281 create_unicode_buffer(aString, anInteger) -> character array
282 """
283 if isinstance(init, str):
284 if size is None:
285 if sizeof(c_wchar) == 2:
286 # UTF-16 requires a surrogate pair (2 wchar_t) for non-BMP
287 # characters (outside [U+0000; U+FFFF] range). +1 for trailing
288 # NUL character.
289 size = sum(2 if ord(c) > 0xFFFF else 1 for c in init) + 1
290 else:
291 # 32-bit wchar_t (1 wchar_t per Unicode character). +1 for
292 # trailing NUL character.
293 size = len(init) + 1
294 _sys.audit("ctypes.create_unicode_buffer", init, size)
295 buftype = c_wchar * size
296 buf = buftype()
297 buf.value = init
298 return buf
299 elif isinstance(init, int):
300 _sys.audit("ctypes.create_unicode_buffer", None, init)
301 buftype = c_wchar * init
302 buf = buftype()
303 return buf
304 raise TypeError(init)
305
306
307 def SetPointerType(pointer, cls):
308 import warnings
309 warnings._deprecated("ctypes.SetPointerType", remove=(3, 15))
310 if _pointer_type_cache.get(cls, None) is not None:
311 raise RuntimeError("This type already exists in the cache")
312 if id(pointer) not in _pointer_type_cache:
313 raise RuntimeError("What's this???")
314 pointer.set_type(cls)
315 _pointer_type_cache[cls] = pointer
316 del _pointer_type_cache[id(pointer)]
317
318 def ARRAY(typ, len):
319 return typ * len
320
321 ################################################################
322
323
324 class CDLL(object):
325 """An instance of this class represents a loaded dll/shared
326 library, exporting functions using the standard C calling
327 convention (named 'cdecl' on Windows).
328
329 The exported functions can be accessed as attributes, or by
330 indexing with the function name. Examples:
331
332 <obj>.qsort -> callable object
333 <obj>['qsort'] -> callable object
334
335 Calling the functions releases the Python GIL during the call and
336 reacquires it afterwards.
337 """
338 _func_flags_ = _FUNCFLAG_CDECL
339 _func_restype_ = c_int
340 # default values for repr
341 _name = '<uninitialized>'
342 _handle = 0
343 _FuncPtr = None
344
345 def __init__(self, name, mode=DEFAULT_MODE, handle=None,
346 use_errno=False,
347 use_last_error=False,
348 winmode=None):
349 class _FuncPtr(_CFuncPtr):
350 _flags_ = self._func_flags_
351 _restype_ = self._func_restype_
352 if use_errno:
353 _flags_ |= _FUNCFLAG_USE_ERRNO
354 if use_last_error:
355 _flags_ |= _FUNCFLAG_USE_LASTERROR
356
357 self._FuncPtr = _FuncPtr
358 if name:
359 name = _os.fspath(name)
360
361 self._handle = self._load_library(name, mode, handle, winmode)
362
363 if _os.name == "nt":
364 def _load_library(self, name, mode, handle, winmode):
365 if winmode is None:
366 import nt as _nt
367 winmode = _nt._LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
368 # WINAPI LoadLibrary searches for a DLL if the given name
369 # is not fully qualified with an explicit drive. For POSIX
370 # compatibility, and because the DLL search path no longer
371 # contains the working directory, begin by fully resolving
372 # any name that contains a path separator.
373 if name is not None and ('/' in name or '\\' in name):
374 name = _nt._getfullpathname(name)
375 winmode |= _nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
376 self._name = name
377 if handle is not None:
378 return handle
379 return _LoadLibrary(self._name, winmode)
380
381 else:
382 def _load_library(self, name, mode, handle, winmode):
383 # If the filename that has been provided is an iOS/tvOS/watchOS
384 # .fwork file, dereference the location to the true origin of the
385 # binary.
386 if name and name.endswith(".fwork"):
387 with open(name) as f:
388 name = _os.path.join(
389 _os.path.dirname(_sys.executable),
390 f.read().strip()
391 )
392 if _sys.platform.startswith("aix"):
393 """When the name contains ".a(" and ends with ")",
394 e.g., "libFOO.a(libFOO.so)" - this is taken to be an
395 archive(member) syntax for dlopen(), and the mode is adjusted.
396 Otherwise, name is presented to dlopen() as a file argument.
397 """
398 if name and name.endswith(")") and ".a(" in name:
399 mode |= _os.RTLD_MEMBER | _os.RTLD_NOW
400 self._name = name
401 if handle is not None:
402 return handle
403 return _dlopen(name, mode)
404
405 def __repr__(self):
406 return "<%s '%s', handle %x at %#x>" % \
407 (self.__class__.__name__, self._name,
408 (self._handle & (_sys.maxsize*2 + 1)),
409 id(self) & (_sys.maxsize*2 + 1))
410
411 def __getattr__(self, name):
412 if name.startswith('__') and name.endswith('__'):
413 raise AttributeError(name)
414 func = self.__getitem__(name)
415 setattr(self, name, func)
416 return func
417
418 def __getitem__(self, name_or_ordinal):
419 func = self._FuncPtr((name_or_ordinal, self))
420 if not isinstance(name_or_ordinal, int):
421 func.__name__ = name_or_ordinal
422 return func
423
424 class PyDLL(CDLL):
425 """This class represents the Python library itself. It allows
426 accessing Python API functions. The GIL is not released, and
427 Python exceptions are handled correctly.
428 """
429 _func_flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
430
431 if _os.name == "nt":
432
433 class WinDLL(CDLL):
434 """This class represents a dll exporting functions using the
435 Windows stdcall calling convention.
436 """
437 _func_flags_ = _FUNCFLAG_STDCALL
438
439 # XXX Hm, what about HRESULT as normal parameter?
440 # Mustn't it derive from c_long then?
441 from _ctypes import _check_HRESULT, _SimpleCData
442 class HRESULT(_SimpleCData):
443 _type_ = "l"
444 # _check_retval_ is called with the function's result when it
445 # is used as restype. It checks for the FAILED bit, and
446 # raises an OSError if it is set.
447 #
448 # The _check_retval_ method is implemented in C, so that the
449 # method definition itself is not included in the traceback
450 # when it raises an error - that is what we want (and Python
451 # doesn't have a way to raise an exception in the caller's
452 # frame).
453 _check_retval_ = _check_HRESULT
454
455 class OleDLL(CDLL):
456 """This class represents a dll exporting functions using the
457 Windows stdcall calling convention, and returning HRESULT.
458 HRESULT error values are automatically raised as OSError
459 exceptions.
460 """
461 _func_flags_ = _FUNCFLAG_STDCALL
462 _func_restype_ = HRESULT
463
464 class LibraryLoader(object):
465 def __init__(self, dlltype):
466 self._dlltype = dlltype
467
468 def __getattr__(self, name):
469 if name[0] == '_':
470 raise AttributeError(name)
471 try:
472 dll = self._dlltype(name)
473 except OSError:
474 raise AttributeError(name)
475 setattr(self, name, dll)
476 return dll
477
478 def __getitem__(self, name):
479 return getattr(self, name)
480
481 def LoadLibrary(self, name):
482 return self._dlltype(name)
483
484 __class_getitem__ = classmethod(_types.GenericAlias)
485
486 cdll = LibraryLoader(CDLL)
487 pydll = LibraryLoader(PyDLL)
488
489 if _os.name == "nt":
490 pythonapi = PyDLL("python dll", None, _sys.dllhandle)
491 elif _sys.platform in ["android", "cygwin"]:
492 # These are Unix-like platforms which use a dynamically-linked libpython.
493 pythonapi = PyDLL(_sysconfig.get_config_var("LDLIBRARY"))
494 else:
495 pythonapi = PyDLL(None)
496
497
498 if _os.name == "nt":
499 windll = LibraryLoader(WinDLL)
500 oledll = LibraryLoader(OleDLL)
501
502 GetLastError = windll.kernel32.GetLastError
503 from _ctypes import get_last_error, set_last_error
504
505 def WinError(code=None, descr=None):
506 if code is None:
507 code = GetLastError()
508 if descr is None:
509 descr = FormatError(code).strip()
510 return OSError(None, descr, None, code)
511
512 if sizeof(c_uint) == sizeof(c_void_p):
513 c_size_t = c_uint
514 c_ssize_t = c_int
515 elif sizeof(c_ulong) == sizeof(c_void_p):
516 c_size_t = c_ulong
517 c_ssize_t = c_long
518 elif sizeof(c_ulonglong) == sizeof(c_void_p):
519 c_size_t = c_ulonglong
520 c_ssize_t = c_longlong
521
522 # functions
523
524 from _ctypes import _memmove_addr, _memset_addr, _string_at_addr, _cast_addr
525
526 ## void *memmove(void *, const void *, size_t);
527 memmove = CFUNCTYPE(c_void_p, c_void_p, c_void_p, c_size_t)(_memmove_addr)
528
529 ## void *memset(void *, int, size_t)
530 memset = CFUNCTYPE(c_void_p, c_void_p, c_int, c_size_t)(_memset_addr)
531
532 def PYFUNCTYPE(restype, *argtypes):
533 class CFunctionType(_CFuncPtr):
534 _argtypes_ = argtypes
535 _restype_ = restype
536 _flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
537 return CFunctionType
538
539 _cast = PYFUNCTYPE(py_object, c_void_p, py_object, py_object)(_cast_addr)
540 def cast(obj, typ):
541 return _cast(obj, obj, typ)
542
543 _string_at = PYFUNCTYPE(py_object, c_void_p, c_int)(_string_at_addr)
544 def string_at(ptr, size=-1):
545 """string_at(ptr[, size]) -> string
546
547 Return the byte string at void *ptr."""
548 return _string_at(ptr, size)
549
550 try:
551 from _ctypes import _wstring_at_addr
552 except ImportError:
553 pass
554 else:
555 _wstring_at = PYFUNCTYPE(py_object, c_void_p, c_int)(_wstring_at_addr)
556 def wstring_at(ptr, size=-1):
557 """wstring_at(ptr[, size]) -> string
558
559 Return the wide-character string at void *ptr."""
560 return _wstring_at(ptr, size)
561
562
563 if _os.name == "nt": # COM stuff
564 def DllGetClassObject(rclsid, riid, ppv):
565 try:
566 ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
567 except ImportError:
568 return -2147221231 # CLASS_E_CLASSNOTAVAILABLE
569 else:
570 return ccom.DllGetClassObject(rclsid, riid, ppv)
571
572 def DllCanUnloadNow():
573 try:
574 ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
575 except ImportError:
576 return 0 # S_OK
577 return ccom.DllCanUnloadNow()
578
579 from ctypes._endian import BigEndianStructure, LittleEndianStructure
580 from ctypes._endian import BigEndianUnion, LittleEndianUnion
581
582 # Fill in specifically-sized types
583 c_int8 = c_byte
584 c_uint8 = c_ubyte
585 for kind in [c_short, c_int, c_long, c_longlong]:
586 if sizeof(kind) == 2: c_int16 = kind
587 elif sizeof(kind) == 4: c_int32 = kind
588 elif sizeof(kind) == 8: c_int64 = kind
589 for kind in [c_ushort, c_uint, c_ulong, c_ulonglong]:
590 if sizeof(kind) == 2: c_uint16 = kind
591 elif sizeof(kind) == 4: c_uint32 = kind
592 elif sizeof(kind) == 8: c_uint64 = kind
593 del(kind)
594
595 if SIZEOF_TIME_T == 8:
596 c_time_t = c_int64
597 elif SIZEOF_TIME_T == 4:
598 c_time_t = c_int32
599 else:
600 raise SystemError(f"Unexpected sizeof(time_t): {SIZEOF_TIME_T=}")
601
602 _reset_cache()