internals.h
Go to the documentation of this file.
1 /*
2  pybind11/detail/internals.h: Internal data structure and related functions
3 
4  Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5 
6  All rights reserved. Use of this source code is governed by a
7  BSD-style license that can be found in the LICENSE file.
8 */
9 
10 #pragma once
11 
12 #include "common.h"
13 
14 #if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
15 # include <pybind11/gil.h>
16 #endif
17 
18 #include <pybind11/pytypes.h>
19 
20 #include <exception>
21 #include <mutex>
22 #include <thread>
23 
38 #ifndef PYBIND11_INTERNALS_VERSION
39 # if PY_VERSION_HEX >= 0x030C0000 || defined(_MSC_VER)
40 // Version bump for Python 3.12+, before first 3.12 beta release.
41 // Version bump for MSVC piggy-backed on PR #4779. See comments there.
42 # define PYBIND11_INTERNALS_VERSION 5
43 # else
44 # define PYBIND11_INTERNALS_VERSION 4
45 # endif
46 #endif
47 
48 // This requirement is mainly to reduce the support burden (see PR #4570).
49 static_assert(PY_VERSION_HEX < 0x030C0000 || PYBIND11_INTERNALS_VERSION >= 5,
50  "pybind11 ABI version 5 is the minimum for Python 3.12+");
51 
53 
54 using ExceptionTranslator = void (*)(std::exception_ptr);
55 
57 
58 constexpr const char *internals_function_record_capsule_name = "pybind11_function_record_capsule";
59 
60 // Forward declarations
61 inline PyTypeObject *make_static_property_type();
62 inline PyTypeObject *make_default_metaclass();
63 inline PyObject *make_object_base_type(PyTypeObject *metaclass);
64 
65 // The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
66 // Thread Specific Storage (TSS) API.
67 // Avoid unnecessary allocation of `Py_tss_t`, since we cannot use
68 // `Py_LIMITED_API` anyway.
69 #if PYBIND11_INTERNALS_VERSION > 4
70 # define PYBIND11_TLS_KEY_REF Py_tss_t &
71 # if defined(__clang__)
72 # define PYBIND11_TLS_KEY_INIT(var) \
73  _Pragma("clang diagnostic push") \
74  _Pragma("clang diagnostic ignored \"-Wmissing-field-initializers\"") \
75  Py_tss_t var \
76  = Py_tss_NEEDS_INIT; \
77  _Pragma("clang diagnostic pop")
78 # elif defined(__GNUC__) && !defined(__INTEL_COMPILER)
79 # define PYBIND11_TLS_KEY_INIT(var) \
80  _Pragma("GCC diagnostic push") \
81  _Pragma("GCC diagnostic ignored \"-Wmissing-field-initializers\"") \
82  Py_tss_t var \
83  = Py_tss_NEEDS_INIT; \
84  _Pragma("GCC diagnostic pop")
85 # else
86 # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t var = Py_tss_NEEDS_INIT;
87 # endif
88 # define PYBIND11_TLS_KEY_CREATE(var) (PyThread_tss_create(&(var)) == 0)
89 # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get(&(key))
90 # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set(&(key), (value))
91 # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set(&(key), nullptr)
92 # define PYBIND11_TLS_FREE(key) PyThread_tss_delete(&(key))
93 #else
94 # define PYBIND11_TLS_KEY_REF Py_tss_t *
95 # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr;
96 # define PYBIND11_TLS_KEY_CREATE(var) \
97  (((var) = PyThread_tss_alloc()) != nullptr && (PyThread_tss_create((var)) == 0))
98 # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
99 # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (value))
100 # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
101 # define PYBIND11_TLS_FREE(key) PyThread_tss_free(key)
102 #endif
103 
104 // Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly
105 // other STLs, this means `typeid(A)` from one module won't equal `typeid(A)` from another module
106 // even when `A` is the same, non-hidden-visibility type (e.g. from a common include). Under
107 // libstdc++, this doesn't happen: equality and the type_index hash are based on the type name,
108 // which works. If not under a known-good stl, provide our own name-based hash and equality
109 // functions that use the type name.
110 #if (PYBIND11_INTERNALS_VERSION <= 4 && defined(__GLIBCXX__)) \
111  || (PYBIND11_INTERNALS_VERSION >= 5 && !defined(_LIBCPP_VERSION))
112 inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) { return lhs == rhs; }
113 using type_hash = std::hash<std::type_index>;
114 using type_equal_to = std::equal_to<std::type_index>;
115 #else
116 inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) {
117  return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
118 }
119 
120 struct type_hash {
121  size_t operator()(const std::type_index &t) const {
122  size_t hash = 5381;
123  const char *ptr = t.name();
124  while (auto c = static_cast<unsigned char>(*ptr++)) {
125  hash = (hash * 33) ^ c;
126  }
127  return hash;
128  }
129 };
130 
132  bool operator()(const std::type_index &lhs, const std::type_index &rhs) const {
133  return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
134  }
135 };
136 #endif
137 
138 template <typename value_type>
139 using type_map = std::unordered_map<std::type_index, value_type, type_hash, type_equal_to>;
140 
142  inline size_t operator()(const std::pair<const PyObject *, const char *> &v) const {
143  size_t value = std::hash<const void *>()(v.first);
144  value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value << 6) + (value >> 2);
145  return value;
146  }
147 };
148 
149 using instance_map = std::unordered_multimap<const void *, instance *>;
150 
151 #ifdef Py_GIL_DISABLED
152 // Wrapper around PyMutex to provide BasicLockable semantics
153 class pymutex {
154  PyMutex mutex;
155 
156 public:
157  pymutex() : mutex({}) {}
158  void lock() { PyMutex_Lock(&mutex); }
159  void unlock() { PyMutex_Unlock(&mutex); }
160 };
161 
162 // Instance map shards are used to reduce mutex contention in free-threaded Python.
163 struct instance_map_shard {
164  instance_map registered_instances;
165  pymutex mutex;
166  // alignas(64) would be better, but causes compile errors in macOS before 10.14 (see #5200)
167  char padding[64 - (sizeof(instance_map) + sizeof(pymutex)) % 64];
168 };
169 
170 static_assert(sizeof(instance_map_shard) % 64 == 0,
171  "instance_map_shard size is not a multiple of 64 bytes");
172 #endif
173 
177 struct internals {
178 #ifdef Py_GIL_DISABLED
179  pymutex mutex;
180 #endif
181  // std::type_index -> pybind11's type information
183  // PyTypeObject* -> base type_info(s)
184  std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py;
185 #ifdef Py_GIL_DISABLED
186  std::unique_ptr<instance_map_shard[]> instance_shards; // void * -> instance*
187  size_t instance_shards_mask;
188 #else
189  instance_map registered_instances; // void * -> instance*
190 #endif
191  std::unordered_set<std::pair<const PyObject *, const char *>, override_hash>
193  type_map<std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
194  std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
195  std::forward_list<ExceptionTranslator> registered_exception_translators;
196  std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across
197  // extensions
198 #if PYBIND11_INTERNALS_VERSION == 4
200 #endif
201  std::forward_list<std::string> static_strings; // Stores the std::strings backing
202  // detail::c_str()
203  PyTypeObject *static_property_type;
204  PyTypeObject *default_metaclass;
205  PyObject *instance_base;
206  // Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
207  PYBIND11_TLS_KEY_INIT(tstate)
208 #if PYBIND11_INTERNALS_VERSION > 4
209  PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
210 #endif // PYBIND11_INTERNALS_VERSION > 4
211  // Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
212  PyInterpreterState *istate = nullptr;
213 
214 #if PYBIND11_INTERNALS_VERSION > 4
215  // Note that we have to use a std::string to allocate memory to ensure a unique address
216  // We want unique addresses since we use pointer equality to compare function records
217  std::string function_record_capsule_name = internals_function_record_capsule_name;
218 #endif
219 
220  internals() = default;
221  internals(const internals &other) = delete;
222  internals &operator=(const internals &other) = delete;
224 #if PYBIND11_INTERNALS_VERSION > 4
225  PYBIND11_TLS_FREE(loader_life_support_tls_key);
226 #endif // PYBIND11_INTERNALS_VERSION > 4
227 
228  // This destructor is called *after* Py_Finalize() in finalize_interpreter().
229  // That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is
230  // called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does
231  // nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
232  // PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX).
233  // Neither of those have anything to do with CPython internals. PyMem_RawFree *requires*
234  // that the `tstate` be allocated with the CPython allocator.
235  PYBIND11_TLS_FREE(tstate);
236  }
237 };
238 
241 struct type_info {
242  PyTypeObject *type;
243  const std::type_info *cpptype;
245  void *(*operator_new)(size_t);
246  void (*init_instance)(instance *, const void *);
247  void (*dealloc)(value_and_holder &v_h);
248  std::vector<PyObject *(*) (PyObject *, PyTypeObject *)> implicit_conversions;
249  std::vector<std::pair<const std::type_info *, void *(*) (void *)>> implicit_casts;
250  std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
251  buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
252  void *get_buffer_data = nullptr;
253  void *(*module_local_load)(PyObject *, const type_info *) = nullptr;
254  /* A simple type never occurs as a (direct or indirect) parent
255  * of a class that makes use of multiple inheritance.
256  * A type can be simple even if it has non-simple ancestors as long as it has no descendants.
257  */
258  bool simple_type : 1;
259  /* True if there is no multiple inheritance in this type's inheritance tree */
261  /* for base vs derived holder_type checks */
262  bool default_holder : 1;
263  /* true if this is a type registered with py::module_local */
264  bool module_local : 1;
265 };
266 
268 #if defined(_MSC_VER) && defined(_DEBUG)
269 # define PYBIND11_BUILD_TYPE "_debug"
270 #else
271 # define PYBIND11_BUILD_TYPE ""
272 #endif
273 
277 #ifndef PYBIND11_COMPILER_TYPE
278 # if defined(_MSC_VER)
279 # define PYBIND11_COMPILER_TYPE "_msvc"
280 # elif defined(__INTEL_COMPILER)
281 # define PYBIND11_COMPILER_TYPE "_icc"
282 # elif defined(__clang__)
283 # define PYBIND11_COMPILER_TYPE "_clang"
284 # elif defined(__PGI)
285 # define PYBIND11_COMPILER_TYPE "_pgi"
286 # elif defined(__MINGW32__)
287 # define PYBIND11_COMPILER_TYPE "_mingw"
288 # elif defined(__CYGWIN__)
289 # define PYBIND11_COMPILER_TYPE "_gcc_cygwin"
290 # elif defined(__GNUC__)
291 # define PYBIND11_COMPILER_TYPE "_gcc"
292 # else
293 # define PYBIND11_COMPILER_TYPE "_unknown"
294 # endif
295 #endif
296 
298 #ifndef PYBIND11_STDLIB
299 # if defined(_LIBCPP_VERSION)
300 # define PYBIND11_STDLIB "_libcpp"
301 # elif defined(__GLIBCXX__) || defined(__GLIBCPP__)
302 # define PYBIND11_STDLIB "_libstdcpp"
303 # else
304 # define PYBIND11_STDLIB ""
305 # endif
306 #endif
307 
310 #ifndef PYBIND11_BUILD_ABI
311 # if defined(__GXX_ABI_VERSION)
312 # define PYBIND11_BUILD_ABI "_cxxabi" PYBIND11_TOSTRING(__GXX_ABI_VERSION)
313 # elif defined(_MSC_VER)
314 # define PYBIND11_BUILD_ABI "_mscver" PYBIND11_TOSTRING(_MSC_VER)
315 # else
316 # define PYBIND11_BUILD_ABI ""
317 # endif
318 #endif
319 
320 #ifndef PYBIND11_INTERNALS_KIND
321 # define PYBIND11_INTERNALS_KIND ""
322 #endif
323 
324 #define PYBIND11_PLATFORM_ABI_ID \
325  PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
326  PYBIND11_BUILD_TYPE
327 
328 #define PYBIND11_INTERNALS_ID \
329  "__pybind11_internals_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
330  PYBIND11_PLATFORM_ABI_ID "__"
331 
332 #define PYBIND11_MODULE_LOCAL_ID \
333  "__pybind11_module_local_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
334  PYBIND11_PLATFORM_ABI_ID "__"
335 
339  static internals **internals_pp = nullptr;
340  return internals_pp;
341 }
342 
343 // forward decl
344 inline void translate_exception(std::exception_ptr);
345 
346 template <class T,
348 bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
349  std::exception_ptr nested = exc.nested_ptr();
350  if (nested != nullptr && nested != p) {
351  translate_exception(nested);
352  return true;
353  }
354  return false;
355 }
356 
357 template <class T,
359 bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
360  if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(exc))) {
361  return handle_nested_exception(*nep, p);
362  }
363  return false;
364 }
365 
366 inline bool raise_err(PyObject *exc_type, const char *msg) {
367  if (PyErr_Occurred()) {
368  raise_from(exc_type, msg);
369  return true;
370  }
371  set_error(exc_type, msg);
372  return false;
373 }
374 
375 inline void translate_exception(std::exception_ptr p) {
376  if (!p) {
377  return;
378  }
379  try {
380  std::rethrow_exception(p);
381  } catch (error_already_set &e) {
383  e.restore();
384  return;
385  } catch (const builtin_exception &e) {
386  // Could not use template since it's an abstract class.
387  if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(e))) {
388  handle_nested_exception(*nep, p);
389  }
390  e.set_error();
391  return;
392  } catch (const std::bad_alloc &e) {
394  raise_err(PyExc_MemoryError, e.what());
395  return;
396  } catch (const std::domain_error &e) {
398  raise_err(PyExc_ValueError, e.what());
399  return;
400  } catch (const std::invalid_argument &e) {
402  raise_err(PyExc_ValueError, e.what());
403  return;
404  } catch (const std::length_error &e) {
406  raise_err(PyExc_ValueError, e.what());
407  return;
408  } catch (const std::out_of_range &e) {
410  raise_err(PyExc_IndexError, e.what());
411  return;
412  } catch (const std::range_error &e) {
414  raise_err(PyExc_ValueError, e.what());
415  return;
416  } catch (const std::overflow_error &e) {
418  raise_err(PyExc_OverflowError, e.what());
419  return;
420  } catch (const std::exception &e) {
422  raise_err(PyExc_RuntimeError, e.what());
423  return;
424  } catch (const std::nested_exception &e) {
426  raise_err(PyExc_RuntimeError, "Caught an unknown nested exception!");
427  return;
428  } catch (...) {
429  raise_err(PyExc_RuntimeError, "Caught an unknown exception!");
430  return;
431  }
432 }
433 
434 #if !defined(__GLIBCXX__)
435 inline void translate_local_exception(std::exception_ptr p) {
436  try {
437  if (p) {
438  std::rethrow_exception(p);
439  }
440  } catch (error_already_set &e) {
441  e.restore();
442  return;
443  } catch (const builtin_exception &e) {
444  e.set_error();
445  return;
446  }
447 }
448 #endif
449 
450 inline object get_python_state_dict() {
451  object state_dict;
452 #if PYBIND11_INTERNALS_VERSION <= 4 || PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
453  state_dict = reinterpret_borrow<object>(PyEval_GetBuiltins());
454 #else
455 # if PY_VERSION_HEX < 0x03090000
456  PyInterpreterState *istate = _PyInterpreterState_Get();
457 # else
458  PyInterpreterState *istate = PyInterpreterState_Get();
459 # endif
460  if (istate) {
461  state_dict = reinterpret_borrow<object>(PyInterpreterState_GetDict(istate));
462  }
463 #endif
464  if (!state_dict) {
465  raise_from(PyExc_SystemError, "pybind11::detail::get_python_state_dict() FAILED");
466  throw error_already_set();
467  }
468  return state_dict;
469 }
470 
471 inline object get_internals_obj_from_state_dict(handle state_dict) {
472  return reinterpret_steal<object>(
474 }
475 
477  void *raw_ptr = PyCapsule_GetPointer(obj.ptr(), /*name=*/nullptr);
478  if (raw_ptr == nullptr) {
479  raise_from(PyExc_SystemError, "pybind11::detail::get_internals_pp_from_capsule() FAILED");
480  throw error_already_set();
481  }
482  return static_cast<internals **>(raw_ptr);
483 }
484 
486  // Round-up to the next power of two.
487  // See https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
488  x--;
489  x |= (x >> 1);
490  x |= (x >> 2);
491  x |= (x >> 4);
492  x |= (x >> 8);
493  x |= (x >> 16);
494  x |= (x >> 32);
495  x++;
496  return x;
497 }
498 
501  auto **&internals_pp = get_internals_pp();
502  if (internals_pp && *internals_pp) {
503  return **internals_pp;
504  }
505 
506 #if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
507  gil_scoped_acquire gil;
508 #else
509  // Ensure that the GIL is held since we will need to make Python calls.
510  // Cannot use py::gil_scoped_acquire here since that constructor calls get_internals.
511  struct gil_scoped_acquire_local {
512  gil_scoped_acquire_local() : state(PyGILState_Ensure()) {}
513  gil_scoped_acquire_local(const gil_scoped_acquire_local &) = delete;
514  gil_scoped_acquire_local &operator=(const gil_scoped_acquire_local &) = delete;
515  ~gil_scoped_acquire_local() { PyGILState_Release(state); }
516  const PyGILState_STATE state;
517  } gil;
518 #endif
519  error_scope err_scope;
520 
521  dict state_dict = get_python_state_dict();
522  if (object internals_obj = get_internals_obj_from_state_dict(state_dict)) {
523  internals_pp = get_internals_pp_from_capsule(internals_obj);
524  }
525  if (internals_pp && *internals_pp) {
526  // We loaded the internals through `state_dict`, which means that our `error_already_set`
527  // and `builtin_exception` may be different local classes than the ones set up in the
528  // initial exception translator, below, so add another for our local exception classes.
529  //
530  // libstdc++ doesn't require this (types there are identified only by name)
531  // libc++ with CPython doesn't require this (types are explicitly exported)
532  // libc++ with PyPy still need it, awaiting further investigation
533 #if !defined(__GLIBCXX__)
534  (*internals_pp)->registered_exception_translators.push_front(&translate_local_exception);
535 #endif
536  } else {
537  if (!internals_pp) {
538  internals_pp = new internals *();
539  }
540  auto *&internals_ptr = *internals_pp;
541  internals_ptr = new internals();
542 
543  PyThreadState *tstate = PyThreadState_Get();
544  // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
545  if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->tstate)) {
546  pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
547  }
548  PYBIND11_TLS_REPLACE_VALUE(internals_ptr->tstate, tstate);
549 
550 #if PYBIND11_INTERNALS_VERSION > 4
551  // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
552  if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->loader_life_support_tls_key)) {
553  pybind11_fail("get_internals: could not successfully initialize the "
554  "loader_life_support TSS key!");
555  }
556 #endif
557  internals_ptr->istate = tstate->interp;
558  state_dict[PYBIND11_INTERNALS_ID] = capsule(reinterpret_cast<void *>(internals_pp));
559  internals_ptr->registered_exception_translators.push_front(&translate_exception);
560  internals_ptr->static_property_type = make_static_property_type();
561  internals_ptr->default_metaclass = make_default_metaclass();
562  internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
563 #ifdef Py_GIL_DISABLED
564  // Scale proportional to the number of cores. 2x is a heuristic to reduce contention.
565  auto num_shards
566  = static_cast<size_t>(round_up_to_next_pow2(2 * std::thread::hardware_concurrency()));
567  if (num_shards == 0) {
568  num_shards = 1;
569  }
570  internals_ptr->instance_shards.reset(new instance_map_shard[num_shards]);
571  internals_ptr->instance_shards_mask = num_shards - 1;
572 #endif // Py_GIL_DISABLED
573  }
574  return **internals_pp;
575 }
576 
577 // the internals struct (above) is shared between all the modules. local_internals are only
578 // for a single module. Any changes made to internals may require an update to
579 // PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,
580 // restricted to a single module. Whether a module has local internals or not should not
581 // impact any other modules, because the only things accessing the local internals is the
582 // module that contains them.
585  std::forward_list<ExceptionTranslator> registered_exception_translators;
586 #if PYBIND11_INTERNALS_VERSION == 4
587 
588  // For ABI compatibility, we can't store the loader_life_support TLS key in
589  // the `internals` struct directly. Instead, we store it in `shared_data` and
590  // cache a copy in `local_internals`. If we allocated a separate TLS key for
591  // each instance of `local_internals`, we could end up allocating hundreds of
592  // TLS keys if hundreds of different pybind11 modules are loaded (which is a
593  // plausible number).
594  PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
595 
596  // Holds the shared TLS key for the loader_life_support stack.
598  PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
600  // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
601  if (!PYBIND11_TLS_KEY_CREATE(loader_life_support_tls_key)) {
602  pybind11_fail("local_internals: could not successfully initialize the "
603  "loader_life_support TLS key!");
604  }
605  }
606  // We can't help but leak the TLS key, because Python never unloads extension modules.
607  };
608 
610  auto &internals = get_internals();
611  // Get or create the `loader_life_support_stack_key`.
612  auto &ptr = internals.shared_data["_life_support"];
613  if (!ptr) {
615  }
616  loader_life_support_tls_key
617  = static_cast<shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key;
618  }
619 #endif // PYBIND11_INTERNALS_VERSION == 4
620 };
621 
624  // Current static can be created in the interpreter finalization routine. If the later will be
625  // destroyed in another static variable destructor, creation of this static there will cause
626  // static deinitialization fiasco. In order to avoid it we avoid destruction of the
627  // local_internals static. One can read more about the problem and current solution here:
628  // https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables
629  static auto *locals = new local_internals();
630  return *locals;
631 }
632 
633 #ifdef Py_GIL_DISABLED
634 # define PYBIND11_LOCK_INTERNALS(internals) std::unique_lock<pymutex> lock((internals).mutex)
635 #else
636 # define PYBIND11_LOCK_INTERNALS(internals)
637 #endif
638 
639 template <typename F>
640 inline auto with_internals(const F &cb) -> decltype(cb(get_internals())) {
641  auto &internals = get_internals();
643  return cb(internals);
644 }
645 
647  // David Stafford's variant 13 of the MurmurHash3 finalizer popularized
648  // by the SplitMix PRNG.
649  // https://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
650  z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;
651  z = (z ^ (z >> 27)) * 0x94d049bb133111eb;
652  return z ^ (z >> 31);
653 }
654 
655 template <typename F>
656 inline auto with_instance_map(const void *ptr,
657  const F &cb) -> decltype(cb(std::declval<instance_map &>())) {
658  auto &internals = get_internals();
659 
660 #ifdef Py_GIL_DISABLED
661  // Hash address to compute shard, but ignore low bits. We'd like allocations
662  // from the same thread/core to map to the same shard and allocations from
663  // other threads/cores to map to other shards. Using the high bits is a good
664  // heuristic because memory allocators often have a per-thread
665  // arena/superblock/segment from which smaller allocations are served.
666  auto addr = reinterpret_cast<std::uintptr_t>(ptr);
667  auto hash = mix64(static_cast<std::uint64_t>(addr >> 20));
668  auto idx = static_cast<size_t>(hash & internals.instance_shards_mask);
669 
670  auto &shard = internals.instance_shards[idx];
671  std::unique_lock<pymutex> lock(shard.mutex);
672  return cb(shard.registered_instances);
673 #else
674  (void) ptr;
675  return cb(internals.registered_instances);
676 #endif
677 }
678 
679 // Returns the number of registered instances for testing purposes. The result may not be
680 // consistent if other threads are registering or unregistering instances concurrently.
681 inline size_t num_registered_instances() {
682  auto &internals = get_internals();
683 #ifdef Py_GIL_DISABLED
684  size_t count = 0;
685  for (size_t i = 0; i <= internals.instance_shards_mask; ++i) {
686  auto &shard = internals.instance_shards[i];
687  std::unique_lock<pymutex> lock(shard.mutex);
688  count += shard.registered_instances.size();
689  }
690  return count;
691 #else
692  return internals.registered_instances.size();
693 #endif
694 }
695 
700 template <typename... Args>
701 const char *c_str(Args &&...args) {
702  // GCC 4.8 doesn't like parameter unpack within lambda capture, so use
703  // PYBIND11_LOCK_INTERNALS.
704  auto &internals = get_internals();
706  auto &strings = internals.static_strings;
707  strings.emplace_front(std::forward<Args>(args)...);
708  return strings.front().c_str();
709 }
710 
711 inline const char *get_function_record_capsule_name() {
712 #if PYBIND11_INTERNALS_VERSION > 4
713  return get_internals().function_record_capsule_name.c_str();
714 #else
715  return nullptr;
716 #endif
717 }
718 
719 // Determine whether or not the following capsule contains a pybind11 function record.
720 // Note that we use `internals` to make sure that only ABI compatible records are touched.
721 //
722 // This check is currently used in two places:
723 // - An important optimization in functional.h to avoid overhead in C++ -> Python -> C++
724 // - The sibling feature of cpp_function to allow overloads
725 inline bool is_function_record_capsule(const capsule &cap) {
726  // Pointer equality as we rely on internals() to ensure unique pointers
727  return cap.name() == get_function_record_capsule_name();
728 }
729 
731 
732 PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
736  return detail::with_internals([&](detail::internals &internals) {
737  auto it = internals.shared_data.find(name);
738  return it != internals.shared_data.end() ? it->second : nullptr;
739  });
740 }
741 
743 PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
744  return detail::with_internals([&](detail::internals &internals) {
746  return data;
747  });
748 }
749 
753 template <typename T>
754 T &get_or_create_shared_data(const std::string &name) {
755  return *detail::with_internals([&](detail::internals &internals) {
756  auto it = internals.shared_data.find(name);
757  T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr);
758  if (!ptr) {
759  ptr = new T();
760  internals.shared_data[name] = ptr;
761  }
762  return ptr;
763  });
764 }
765 
handle_nested_exception
bool handle_nested_exception(const T &exc, const std::exception_ptr &p)
Definition: internals.h:348
ExceptionTranslator
void(*)(std::exception_ptr) ExceptionTranslator
Definition: internals.h:54
error_scope
RAII wrapper that temporarily clears any Python error state.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1108
translate_exception
void translate_exception(std::exception_ptr)
Definition: internals.h:375
internals::shared_data
std::unordered_map< std::string, void * > shared_data
Definition: internals.h:196
name
Annotation for function names.
Definition: attr.h:51
internals
Definition: internals.h:177
type_hash::operator()
size_t operator()(const std::type_index &t) const
Definition: internals.h:121
type_info::implicit_conversions
std::vector< PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions
Definition: internals.h:248
with_instance_map
auto with_instance_map(const void *ptr, const F &cb) -> decltype(cb(std::declval< instance_map & >()))
Definition: internals.h:656
error_already_set
Definition: pytypes.h:739
type_info
Definition: internals.h:241
e
Array< double, 1, 3 > e(1./3., 0.5, 2.)
round_up_to_next_pow2
uint64_t round_up_to_next_pow2(uint64_t x)
Definition: internals.h:485
type_info::simple_type
bool simple_type
Definition: internals.h:258
type_info::type
PyTypeObject * type
Definition: internals.h:242
internals::registered_types_cpp
type_map< type_info * > registered_types_cpp
Definition: internals.h:182
type_info::implicit_casts
std::vector< std::pair< const std::type_info *, void *(*)(void *)> > implicit_casts
Definition: internals.h:249
c
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
PYBIND11_LOCK_INTERNALS
#define PYBIND11_LOCK_INTERNALS(internals)
Definition: internals.h:636
internals::unused_loader_patient_stack_remove_at_v5
std::vector< PyObject * > unused_loader_patient_stack_remove_at_v5
Definition: internals.h:199
make_static_property_type
PyTypeObject * make_static_property_type()
Definition: class.h:66
x
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy x
Definition: gnuplot_common_settings.hh:12
type_info::get_buffer_data
void * get_buffer_data
Definition: internals.h:252
type_info::default_holder
bool default_holder
Definition: internals.h:262
local_internals::registered_exception_translators
std::forward_list< ExceptionTranslator > registered_exception_translators
Definition: internals.h:585
type_info::type_size
size_t type_size
Definition: internals.h:244
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:80
capsule
Definition: pytypes.h:1953
PYBIND11_NOINLINE
#define PYBIND11_NOINLINE
Definition: wrap/pybind11/include/pybind11/detail/common.h:194
value_and_holder
Definition: value_and_holder.h:15
T
Eigen::Triplet< double > T
Definition: Tutorial_sparse_example.cpp:6
detail
Definition: testSerializationNonlinear.cpp:69
internals::static_property_type
PyTypeObject * static_property_type
Definition: internals.h:203
make_object_base_type
PyObject * make_object_base_type(PyTypeObject *metaclass)
Definition: class.h:491
get_internals_pp_from_capsule
internals ** get_internals_pp_from_capsule(handle obj)
Definition: internals.h:476
get_internals
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
Definition: internals.h:500
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:76
type_info::dealloc
void(* dealloc)(value_and_holder &v_h)
Definition: internals.h:247
type_hash
Definition: internals.h:120
internals::registered_exception_translators
std::forward_list< ExceptionTranslator > registered_exception_translators
Definition: internals.h:195
type_info::cpptype
const std::type_info * cpptype
Definition: internals.h:243
type_info::type_align
size_t type_align
Definition: internals.h:244
num_registered_instances
size_t num_registered_instances()
Definition: internals.h:681
hash
ssize_t hash(handle obj)
Definition: pytypes.h:934
name
static char name[]
Definition: rgamma.c:72
internals::registered_instances
instance_map registered_instances
Definition: internals.h:189
internals::instance_base
PyObject * instance_base
Definition: internals.h:205
get_or_create_shared_data
T & get_or_create_shared_data(const std::string &name)
Definition: internals.h:754
instance
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
Definition: wrap/pybind11/include/pybind11/detail/common.h:602
internals::~internals
~internals()
Definition: internals.h:223
same_type
bool same_type(const std::type_info &lhs, const std::type_info &rhs)
Definition: internals.h:116
PYBIND11_TLS_REPLACE_VALUE
#define PYBIND11_TLS_REPLACE_VALUE(key, value)
Definition: internals.h:99
dict
Definition: pytypes.h:2109
raise_from
void raise_from(PyObject *type, const char *message)
Definition: pytypes.h:797
get_function_record_capsule_name
const char * get_function_record_capsule_name()
Definition: internals.h:711
data
int data[]
Definition: Map_placement_new.cpp:1
handle
Definition: pytypes.h:226
gil.h
instance_map
std::unordered_multimap< const void *, instance * > instance_map
Definition: internals.h:149
raise_err
bool raise_err(PyObject *exc_type, const char *msg)
Definition: internals.h:366
internals::inactive_override_cache
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
Definition: internals.h:192
PYBIND11_INTERNALS_ID
#define PYBIND11_INTERNALS_ID
Definition: internals.h:328
set_shared_data
PYBIND11_NOINLINE void * set_shared_data(const std::string &name, void *data)
Set the shared data that can be later recovered by get_shared_data().
Definition: internals.h:743
metaclass
Annotation which requests that a special metaclass is created for a type.
Definition: attr.h:85
local_internals::registered_types_cpp
type_map< type_info * > registered_types_cpp
Definition: internals.h:584
local_internals::shared_loader_life_support_data
Definition: internals.h:597
local_internals
Definition: internals.h:583
internals::internals
internals()=default
override_hash
Definition: internals.h:141
internals_function_record_capsule_name
constexpr const char * internals_function_record_capsule_name
Definition: internals.h:58
dict_getitemstringref
PyObject * dict_getitemstringref(PyObject *v, const char *key)
Definition: pytypes.h:983
PYBIND11_TLS_KEY_CREATE
#define PYBIND11_TLS_KEY_CREATE(var)
Definition: internals.h:96
pybind_wrapper_test_script.z
z
Definition: pybind_wrapper_test_script.py:61
PYBIND11_NAMESPACE
Definition: test_custom_type_casters.cpp:24
Eigen::Triplet
A small structure to hold a non zero as a triplet (i,j,value).
Definition: SparseUtil.h:162
common.h
gil_scoped_acquire
Definition: gil.h:53
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1045
internals::istate
PyInterpreterState * istate
Definition: internals.h:212
gtsam::symbol_shorthand::F
Key F(std::uint64_t j)
Definition: inference/Symbol.h:153
size_t
std::size_t size_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:509
set_error
void set_error(const handle &type, const char *message)
Definition: pytypes.h:346
translate_local_exception
void translate_local_exception(std::exception_ptr p)
Definition: internals.h:435
type_info::direct_conversions
std::vector< bool(*)(PyObject *, void *&)> * direct_conversions
Definition: internals.h:250
pytypes.h
is_function_record_capsule
bool is_function_record_capsule(const capsule &cap)
Definition: internals.h:725
internals::static_strings
std::forward_list< std::string > static_strings
Definition: internals.h:201
type_equal_to
Definition: internals.h:131
get_python_state_dict
object get_python_state_dict()
Definition: internals.h:450
internals::direct_conversions
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
Definition: internals.h:193
handle::ptr
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:250
internals::patients
std::unordered_map< const PyObject *, std::vector< PyObject * > > patients
Definition: internals.h:194
with_internals
auto with_internals(const F &cb) -> decltype(cb(get_internals()))
Definition: internals.h:640
get_internals_obj_from_state_dict
object get_internals_obj_from_state_dict(handle state_dict)
Definition: internals.h:471
std
Definition: BFloat16.h:88
args
Definition: pytypes.h:2212
buffer_info
Information record describing a Python buffer object.
Definition: buffer_info.h:46
p
float * p
Definition: Tutorial_Map_using.cpp:9
internals::operator=
internals & operator=(const internals &other)=delete
c_str
const char * c_str(Args &&...args)
Definition: internals.h:701
get_local_internals
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
Definition: internals.h:623
type_info::module_local
bool module_local
Definition: internals.h:264
v
Array< int, Dynamic, 1 > v
Definition: Array_initializer_list_vector_cxx11.cpp:1
type_info::init_instance
void(* init_instance)(instance *, const void *)
Definition: internals.h:246
PYBIND11_TLS_KEY_INIT
#define PYBIND11_TLS_KEY_INIT(var)
Definition: internals.h:95
override_hash::operator()
size_t operator()(const std::pair< const PyObject *, const char * > &v) const
Definition: internals.h:142
mix64
std::uint64_t mix64(std::uint64_t z)
Definition: internals.h:646
internals::default_metaclass
PyTypeObject * default_metaclass
Definition: internals.h:204
type_equal_to::operator()
bool operator()(const std::type_index &lhs, const std::type_index &rhs) const
Definition: internals.h:132
internals::registered_types_py
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
Definition: internals.h:184
uint64_t
unsigned __int64 uint64_t
Definition: ms_stdint.h:95
get_internals_pp
internals **& get_internals_pp()
Definition: internals.h:338
PYBIND11_TLS_FREE
#define PYBIND11_TLS_FREE(key)
Definition: internals.h:101
get_shared_data
PYBIND11_NOINLINE void * get_shared_data(const std::string &name)
Definition: internals.h:735
builtin_exception
C++ bindings of builtin Python exceptions.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1017
type_info::simple_ancestors
bool simple_ancestors
Definition: internals.h:260
align_3::t
Point2 t(10, 10)
local_internals::local_internals
local_internals()
Definition: internals.h:609
enable_if_t
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
Definition: wrap/pybind11/include/pybind11/detail/common.h:673
make_default_metaclass
PyTypeObject * make_default_metaclass()
Definition: class.h:251
test_callbacks.value
value
Definition: test_callbacks.py:162
i
int i
Definition: BiCGSTAB_step_by_step.cpp:9
pybind_wrapper_test_script.other
other
Definition: pybind_wrapper_test_script.py:42
type_map
std::unordered_map< std::type_index, value_type, type_hash, type_equal_to > type_map
Definition: internals.h:139
uintptr_t
_W64 unsigned int uintptr_t
Definition: ms_stdint.h:124
make_changelog.state
state
Definition: make_changelog.py:29
pybind11.msg
msg
Definition: wrap/pybind11/pybind11/__init__.py:6
type_info::holder_size_in_ptrs
size_t holder_size_in_ptrs
Definition: internals.h:244


gtsam
Author(s):
autogenerated on Wed Mar 19 2025 03:01:50