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 "../gil.h"
16 #endif
17 
18 #include "../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 // Instance map shards are used to reduce mutex contention in free-threaded Python.
153  std::mutex mutex;
155  // alignas(64) would be better, but causes compile errors in macOS before 10.14 (see #5200)
156  char padding[64 - (sizeof(std::mutex) + sizeof(instance_map)) % 64];
157 };
158 
162 struct internals {
163 #ifdef Py_GIL_DISABLED
164  std::mutex mutex;
165 #endif
166  // std::type_index -> pybind11's type information
168  // PyTypeObject* -> base type_info(s)
169  std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py;
170 #ifdef Py_GIL_DISABLED
171  std::unique_ptr<instance_map_shard[]> instance_shards; // void * -> instance*
172  size_t instance_shards_mask;
173 #else
174  instance_map registered_instances; // void * -> instance*
175 #endif
176  std::unordered_set<std::pair<const PyObject *, const char *>, override_hash>
178  type_map<std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
179  std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
180  std::forward_list<ExceptionTranslator> registered_exception_translators;
181  std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across
182  // extensions
183 #if PYBIND11_INTERNALS_VERSION == 4
185 #endif
186  std::forward_list<std::string> static_strings; // Stores the std::strings backing
187  // detail::c_str()
188  PyTypeObject *static_property_type;
189  PyTypeObject *default_metaclass;
190  PyObject *instance_base;
191  // Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
192  PYBIND11_TLS_KEY_INIT(tstate)
193 #if PYBIND11_INTERNALS_VERSION > 4
194  PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
195 #endif // PYBIND11_INTERNALS_VERSION > 4
196  // Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
197  PyInterpreterState *istate = nullptr;
198 
199 #if PYBIND11_INTERNALS_VERSION > 4
200  // Note that we have to use a std::string to allocate memory to ensure a unique address
201  // We want unique addresses since we use pointer equality to compare function records
202  std::string function_record_capsule_name = internals_function_record_capsule_name;
203 #endif
204 
205  internals() = default;
206  internals(const internals &other) = delete;
207  internals &operator=(const internals &other) = delete;
209 #if PYBIND11_INTERNALS_VERSION > 4
210  PYBIND11_TLS_FREE(loader_life_support_tls_key);
211 #endif // PYBIND11_INTERNALS_VERSION > 4
212 
213  // This destructor is called *after* Py_Finalize() in finalize_interpreter().
214  // That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is
215  // called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does
216  // nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
217  // PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX).
218  // Neither of those have anything to do with CPython internals. PyMem_RawFree *requires*
219  // that the `tstate` be allocated with the CPython allocator.
220  PYBIND11_TLS_FREE(tstate);
221  }
222 };
223 
226 struct type_info {
227  PyTypeObject *type;
228  const std::type_info *cpptype;
230  void *(*operator_new)(size_t);
231  void (*init_instance)(instance *, const void *);
232  void (*dealloc)(value_and_holder &v_h);
233  std::vector<PyObject *(*) (PyObject *, PyTypeObject *)> implicit_conversions;
234  std::vector<std::pair<const std::type_info *, void *(*) (void *)>> implicit_casts;
235  std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
236  buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
237  void *get_buffer_data = nullptr;
238  void *(*module_local_load)(PyObject *, const type_info *) = nullptr;
239  /* A simple type never occurs as a (direct or indirect) parent
240  * of a class that makes use of multiple inheritance.
241  * A type can be simple even if it has non-simple ancestors as long as it has no descendants.
242  */
243  bool simple_type : 1;
244  /* True if there is no multiple inheritance in this type's inheritance tree */
246  /* for base vs derived holder_type checks */
247  bool default_holder : 1;
248  /* true if this is a type registered with py::module_local */
249  bool module_local : 1;
250 };
251 
253 #if defined(_MSC_VER) && defined(_DEBUG)
254 # define PYBIND11_BUILD_TYPE "_debug"
255 #else
256 # define PYBIND11_BUILD_TYPE ""
257 #endif
258 
262 #ifndef PYBIND11_COMPILER_TYPE
263 # if defined(_MSC_VER)
264 # define PYBIND11_COMPILER_TYPE "_msvc"
265 # elif defined(__INTEL_COMPILER)
266 # define PYBIND11_COMPILER_TYPE "_icc"
267 # elif defined(__clang__)
268 # define PYBIND11_COMPILER_TYPE "_clang"
269 # elif defined(__PGI)
270 # define PYBIND11_COMPILER_TYPE "_pgi"
271 # elif defined(__MINGW32__)
272 # define PYBIND11_COMPILER_TYPE "_mingw"
273 # elif defined(__CYGWIN__)
274 # define PYBIND11_COMPILER_TYPE "_gcc_cygwin"
275 # elif defined(__GNUC__)
276 # define PYBIND11_COMPILER_TYPE "_gcc"
277 # else
278 # define PYBIND11_COMPILER_TYPE "_unknown"
279 # endif
280 #endif
281 
283 #ifndef PYBIND11_STDLIB
284 # if defined(_LIBCPP_VERSION)
285 # define PYBIND11_STDLIB "_libcpp"
286 # elif defined(__GLIBCXX__) || defined(__GLIBCPP__)
287 # define PYBIND11_STDLIB "_libstdcpp"
288 # else
289 # define PYBIND11_STDLIB ""
290 # endif
291 #endif
292 
295 #ifndef PYBIND11_BUILD_ABI
296 # if defined(__GXX_ABI_VERSION)
297 # define PYBIND11_BUILD_ABI "_cxxabi" PYBIND11_TOSTRING(__GXX_ABI_VERSION)
298 # elif defined(_MSC_VER)
299 # define PYBIND11_BUILD_ABI "_mscver" PYBIND11_TOSTRING(_MSC_VER)
300 # else
301 # define PYBIND11_BUILD_ABI ""
302 # endif
303 #endif
304 
305 #ifndef PYBIND11_INTERNALS_KIND
306 # define PYBIND11_INTERNALS_KIND ""
307 #endif
308 
309 #define PYBIND11_INTERNALS_ID \
310  "__pybind11_internals_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
311  PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB \
312  PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE "__"
313 
314 #define PYBIND11_MODULE_LOCAL_ID \
315  "__pybind11_module_local_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
316  PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB \
317  PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE "__"
318 
322  static internals **internals_pp = nullptr;
323  return internals_pp;
324 }
325 
326 // forward decl
327 inline void translate_exception(std::exception_ptr);
328 
329 template <class T,
331 bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
332  std::exception_ptr nested = exc.nested_ptr();
333  if (nested != nullptr && nested != p) {
334  translate_exception(nested);
335  return true;
336  }
337  return false;
338 }
339 
340 template <class T,
342 bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
343  if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(exc))) {
344  return handle_nested_exception(*nep, p);
345  }
346  return false;
347 }
348 
349 inline bool raise_err(PyObject *exc_type, const char *msg) {
350  if (PyErr_Occurred()) {
351  raise_from(exc_type, msg);
352  return true;
353  }
354  set_error(exc_type, msg);
355  return false;
356 }
357 
358 inline void translate_exception(std::exception_ptr p) {
359  if (!p) {
360  return;
361  }
362  try {
363  std::rethrow_exception(p);
364  } catch (error_already_set &e) {
366  e.restore();
367  return;
368  } catch (const builtin_exception &e) {
369  // Could not use template since it's an abstract class.
370  if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(e))) {
371  handle_nested_exception(*nep, p);
372  }
373  e.set_error();
374  return;
375  } catch (const std::bad_alloc &e) {
377  raise_err(PyExc_MemoryError, e.what());
378  return;
379  } catch (const std::domain_error &e) {
381  raise_err(PyExc_ValueError, e.what());
382  return;
383  } catch (const std::invalid_argument &e) {
385  raise_err(PyExc_ValueError, e.what());
386  return;
387  } catch (const std::length_error &e) {
389  raise_err(PyExc_ValueError, e.what());
390  return;
391  } catch (const std::out_of_range &e) {
393  raise_err(PyExc_IndexError, e.what());
394  return;
395  } catch (const std::range_error &e) {
397  raise_err(PyExc_ValueError, e.what());
398  return;
399  } catch (const std::overflow_error &e) {
401  raise_err(PyExc_OverflowError, e.what());
402  return;
403  } catch (const std::exception &e) {
405  raise_err(PyExc_RuntimeError, e.what());
406  return;
407  } catch (const std::nested_exception &e) {
409  raise_err(PyExc_RuntimeError, "Caught an unknown nested exception!");
410  return;
411  } catch (...) {
412  raise_err(PyExc_RuntimeError, "Caught an unknown exception!");
413  return;
414  }
415 }
416 
417 #if !defined(__GLIBCXX__)
418 inline void translate_local_exception(std::exception_ptr p) {
419  try {
420  if (p) {
421  std::rethrow_exception(p);
422  }
423  } catch (error_already_set &e) {
424  e.restore();
425  return;
426  } catch (const builtin_exception &e) {
427  e.set_error();
428  return;
429  }
430 }
431 #endif
432 
433 inline object get_python_state_dict() {
434  object state_dict;
435 #if PYBIND11_INTERNALS_VERSION <= 4 || PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
436  state_dict = reinterpret_borrow<object>(PyEval_GetBuiltins());
437 #else
438 # if PY_VERSION_HEX < 0x03090000
439  PyInterpreterState *istate = _PyInterpreterState_Get();
440 # else
441  PyInterpreterState *istate = PyInterpreterState_Get();
442 # endif
443  if (istate) {
444  state_dict = reinterpret_borrow<object>(PyInterpreterState_GetDict(istate));
445  }
446 #endif
447  if (!state_dict) {
448  raise_from(PyExc_SystemError, "pybind11::detail::get_python_state_dict() FAILED");
449  throw error_already_set();
450  }
451  return state_dict;
452 }
453 
454 inline object get_internals_obj_from_state_dict(handle state_dict) {
455  return reinterpret_steal<object>(
457 }
458 
460  void *raw_ptr = PyCapsule_GetPointer(obj.ptr(), /*name=*/nullptr);
461  if (raw_ptr == nullptr) {
462  raise_from(PyExc_SystemError, "pybind11::detail::get_internals_pp_from_capsule() FAILED");
463  throw error_already_set();
464  }
465  return static_cast<internals **>(raw_ptr);
466 }
467 
469  // Round-up to the next power of two.
470  // See https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
471  x--;
472  x |= (x >> 1);
473  x |= (x >> 2);
474  x |= (x >> 4);
475  x |= (x >> 8);
476  x |= (x >> 16);
477  x |= (x >> 32);
478  x++;
479  return x;
480 }
481 
484  auto **&internals_pp = get_internals_pp();
485  if (internals_pp && *internals_pp) {
486  return **internals_pp;
487  }
488 
489 #if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
490  gil_scoped_acquire gil;
491 #else
492  // Ensure that the GIL is held since we will need to make Python calls.
493  // Cannot use py::gil_scoped_acquire here since that constructor calls get_internals.
494  struct gil_scoped_acquire_local {
495  gil_scoped_acquire_local() : state(PyGILState_Ensure()) {}
496  gil_scoped_acquire_local(const gil_scoped_acquire_local &) = delete;
497  gil_scoped_acquire_local &operator=(const gil_scoped_acquire_local &) = delete;
498  ~gil_scoped_acquire_local() { PyGILState_Release(state); }
499  const PyGILState_STATE state;
500  } gil;
501 #endif
502  error_scope err_scope;
503 
504  dict state_dict = get_python_state_dict();
505  if (object internals_obj = get_internals_obj_from_state_dict(state_dict)) {
506  internals_pp = get_internals_pp_from_capsule(internals_obj);
507  }
508  if (internals_pp && *internals_pp) {
509  // We loaded the internals through `state_dict`, which means that our `error_already_set`
510  // and `builtin_exception` may be different local classes than the ones set up in the
511  // initial exception translator, below, so add another for our local exception classes.
512  //
513  // libstdc++ doesn't require this (types there are identified only by name)
514  // libc++ with CPython doesn't require this (types are explicitly exported)
515  // libc++ with PyPy still need it, awaiting further investigation
516 #if !defined(__GLIBCXX__)
517  (*internals_pp)->registered_exception_translators.push_front(&translate_local_exception);
518 #endif
519  } else {
520  if (!internals_pp) {
521  internals_pp = new internals *();
522  }
523  auto *&internals_ptr = *internals_pp;
524  internals_ptr = new internals();
525 
526  PyThreadState *tstate = PyThreadState_Get();
527  // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
528  if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->tstate)) {
529  pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
530  }
531  PYBIND11_TLS_REPLACE_VALUE(internals_ptr->tstate, tstate);
532 
533 #if PYBIND11_INTERNALS_VERSION > 4
534  // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
535  if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->loader_life_support_tls_key)) {
536  pybind11_fail("get_internals: could not successfully initialize the "
537  "loader_life_support TSS key!");
538  }
539 #endif
540  internals_ptr->istate = tstate->interp;
541  state_dict[PYBIND11_INTERNALS_ID] = capsule(internals_pp);
542  internals_ptr->registered_exception_translators.push_front(&translate_exception);
543  internals_ptr->static_property_type = make_static_property_type();
544  internals_ptr->default_metaclass = make_default_metaclass();
545  internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
546 #ifdef Py_GIL_DISABLED
547  // Scale proportional to the number of cores. 2x is a heuristic to reduce contention.
548  auto num_shards
549  = static_cast<size_t>(round_up_to_next_pow2(2 * std::thread::hardware_concurrency()));
550  if (num_shards == 0) {
551  num_shards = 1;
552  }
553  internals_ptr->instance_shards.reset(new instance_map_shard[num_shards]);
554  internals_ptr->instance_shards_mask = num_shards - 1;
555 #endif // Py_GIL_DISABLED
556  }
557  return **internals_pp;
558 }
559 
560 // the internals struct (above) is shared between all the modules. local_internals are only
561 // for a single module. Any changes made to internals may require an update to
562 // PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,
563 // restricted to a single module. Whether a module has local internals or not should not
564 // impact any other modules, because the only things accessing the local internals is the
565 // module that contains them.
568  std::forward_list<ExceptionTranslator> registered_exception_translators;
569 #if PYBIND11_INTERNALS_VERSION == 4
570 
571  // For ABI compatibility, we can't store the loader_life_support TLS key in
572  // the `internals` struct directly. Instead, we store it in `shared_data` and
573  // cache a copy in `local_internals`. If we allocated a separate TLS key for
574  // each instance of `local_internals`, we could end up allocating hundreds of
575  // TLS keys if hundreds of different pybind11 modules are loaded (which is a
576  // plausible number).
577  PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
578 
579  // Holds the shared TLS key for the loader_life_support stack.
581  PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
583  // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
584  if (!PYBIND11_TLS_KEY_CREATE(loader_life_support_tls_key)) {
585  pybind11_fail("local_internals: could not successfully initialize the "
586  "loader_life_support TLS key!");
587  }
588  }
589  // We can't help but leak the TLS key, because Python never unloads extension modules.
590  };
591 
593  auto &internals = get_internals();
594  // Get or create the `loader_life_support_stack_key`.
595  auto &ptr = internals.shared_data["_life_support"];
596  if (!ptr) {
598  }
599  loader_life_support_tls_key
600  = static_cast<shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key;
601  }
602 #endif // PYBIND11_INTERNALS_VERSION == 4
603 };
604 
607  // Current static can be created in the interpreter finalization routine. If the later will be
608  // destroyed in another static variable destructor, creation of this static there will cause
609  // static deinitialization fiasco. In order to avoid it we avoid destruction of the
610  // local_internals static. One can read more about the problem and current solution here:
611  // https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables
612  static auto *locals = new local_internals();
613  return *locals;
614 }
615 
616 #ifdef Py_GIL_DISABLED
617 # define PYBIND11_LOCK_INTERNALS(internals) std::unique_lock<std::mutex> lock((internals).mutex)
618 #else
619 # define PYBIND11_LOCK_INTERNALS(internals)
620 #endif
621 
622 template <typename F>
623 inline auto with_internals(const F &cb) -> decltype(cb(get_internals())) {
624  auto &internals = get_internals();
626  return cb(internals);
627 }
628 
630  // David Stafford's variant 13 of the MurmurHash3 finalizer popularized
631  // by the SplitMix PRNG.
632  // https://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
633  z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;
634  z = (z ^ (z >> 27)) * 0x94d049bb133111eb;
635  return z ^ (z >> 31);
636 }
637 
638 template <typename F>
639 inline auto with_instance_map(const void *ptr,
640  const F &cb) -> decltype(cb(std::declval<instance_map &>())) {
641  auto &internals = get_internals();
642 
643 #ifdef Py_GIL_DISABLED
644  // Hash address to compute shard, but ignore low bits. We'd like allocations
645  // from the same thread/core to map to the same shard and allocations from
646  // other threads/cores to map to other shards. Using the high bits is a good
647  // heuristic because memory allocators often have a per-thread
648  // arena/superblock/segment from which smaller allocations are served.
649  auto addr = reinterpret_cast<std::uintptr_t>(ptr);
650  auto hash = mix64(static_cast<std::uint64_t>(addr >> 20));
651  auto idx = static_cast<size_t>(hash & internals.instance_shards_mask);
652 
653  auto &shard = internals.instance_shards[idx];
654  std::unique_lock<std::mutex> lock(shard.mutex);
655  return cb(shard.registered_instances);
656 #else
657  (void) ptr;
658  return cb(internals.registered_instances);
659 #endif
660 }
661 
662 // Returns the number of registered instances for testing purposes. The result may not be
663 // consistent if other threads are registering or unregistering instances concurrently.
664 inline size_t num_registered_instances() {
665  auto &internals = get_internals();
666 #ifdef Py_GIL_DISABLED
667  size_t count = 0;
668  for (size_t i = 0; i <= internals.instance_shards_mask; ++i) {
669  auto &shard = internals.instance_shards[i];
670  std::unique_lock<std::mutex> lock(shard.mutex);
671  count += shard.registered_instances.size();
672  }
673  return count;
674 #else
675  return internals.registered_instances.size();
676 #endif
677 }
678 
683 template <typename... Args>
684 const char *c_str(Args &&...args) {
685  // GCC 4.8 doesn't like parameter unpack within lambda capture, so use
686  // PYBIND11_LOCK_INTERNALS.
687  auto &internals = get_internals();
689  auto &strings = internals.static_strings;
690  strings.emplace_front(std::forward<Args>(args)...);
691  return strings.front().c_str();
692 }
693 
694 inline const char *get_function_record_capsule_name() {
695 #if PYBIND11_INTERNALS_VERSION > 4
696  return get_internals().function_record_capsule_name.c_str();
697 #else
698  return nullptr;
699 #endif
700 }
701 
702 // Determine whether or not the following capsule contains a pybind11 function record.
703 // Note that we use `internals` to make sure that only ABI compatible records are touched.
704 //
705 // This check is currently used in two places:
706 // - An important optimization in functional.h to avoid overhead in C++ -> Python -> C++
707 // - The sibling feature of cpp_function to allow overloads
708 inline bool is_function_record_capsule(const capsule &cap) {
709  // Pointer equality as we rely on internals() to ensure unique pointers
710  return cap.name() == get_function_record_capsule_name();
711 }
712 
714 
715 PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
719  return detail::with_internals([&](detail::internals &internals) {
720  auto it = internals.shared_data.find(name);
721  return it != internals.shared_data.end() ? it->second : nullptr;
722  });
723 }
724 
726 PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
727  return detail::with_internals([&](detail::internals &internals) {
729  return data;
730  });
731 }
732 
736 template <typename T>
737 T &get_or_create_shared_data(const std::string &name) {
738  return *detail::with_internals([&](detail::internals &internals) {
739  auto it = internals.shared_data.find(name);
740  T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr);
741  if (!ptr) {
742  ptr = new T();
743  internals.shared_data[name] = ptr;
744  }
745  return ptr;
746  });
747 }
748 
handle_nested_exception
bool handle_nested_exception(const T &exc, const std::exception_ptr &p)
Definition: internals.h:331
ExceptionTranslator
void(*)(std::exception_ptr) ExceptionTranslator
Definition: internals.h:54
instance_map_shard::padding
char padding[64 -(sizeof(std::mutex)+sizeof(instance_map)) % 64]
Definition: internals.h:156
error_scope
RAII wrapper that temporarily clears any Python error state.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1089
translate_exception
void translate_exception(std::exception_ptr)
Definition: internals.h:358
internals::shared_data
std::unordered_map< std::string, void * > shared_data
Definition: internals.h:181
name
Annotation for function names.
Definition: attr.h:51
internals
Definition: internals.h:162
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:233
with_instance_map
auto with_instance_map(const void *ptr, const F &cb) -> decltype(cb(std::declval< instance_map & >()))
Definition: internals.h:639
error_already_set
Definition: pytypes.h:739
type_info
Definition: internals.h:226
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:468
type_info::simple_type
bool simple_type
Definition: internals.h:243
type_info::type
PyTypeObject * type
Definition: internals.h:227
internals::registered_types_cpp
type_map< type_info * > registered_types_cpp
Definition: internals.h:167
type_info::implicit_casts
std::vector< std::pair< const std::type_info *, void *(*)(void *)> > implicit_casts
Definition: internals.h:234
c
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
PYBIND11_LOCK_INTERNALS
#define PYBIND11_LOCK_INTERNALS(internals)
Definition: internals.h:619
internals::unused_loader_patient_stack_remove_at_v5
std::vector< PyObject * > unused_loader_patient_stack_remove_at_v5
Definition: internals.h:184
make_static_property_type
PyTypeObject * make_static_property_type()
Definition: class.h:64
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:237
type_info::default_holder
bool default_holder
Definition: internals.h:247
local_internals::registered_exception_translators
std::forward_list< ExceptionTranslator > registered_exception_translators
Definition: internals.h:568
type_info::type_size
size_t type_size
Definition: internals.h:229
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:80
capsule
Definition: pytypes.h:1951
PYBIND11_NOINLINE
#define PYBIND11_NOINLINE
Definition: wrap/pybind11/include/pybind11/detail/common.h:194
value_and_holder
Definition: type_caster_base.h:262
T
Eigen::Triplet< double > T
Definition: Tutorial_sparse_example.cpp:6
detail
Definition: testSerializationNonlinear.cpp:70
internals::static_property_type
PyTypeObject * static_property_type
Definition: internals.h:188
make_object_base_type
PyObject * make_object_base_type(PyTypeObject *metaclass)
Definition: class.h:489
get_internals_pp_from_capsule
internals ** get_internals_pp_from_capsule(handle obj)
Definition: internals.h:459
get_internals
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
Definition: internals.h:483
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:232
type_hash
Definition: internals.h:120
internals::registered_exception_translators
std::forward_list< ExceptionTranslator > registered_exception_translators
Definition: internals.h:180
type_info::cpptype
const std::type_info * cpptype
Definition: internals.h:228
type_info::type_align
size_t type_align
Definition: internals.h:229
num_registered_instances
size_t num_registered_instances()
Definition: internals.h:664
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:174
internals::instance_base
PyObject * instance_base
Definition: internals.h:190
get_or_create_shared_data
T & get_or_create_shared_data(const std::string &name)
Definition: internals.h:737
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:583
internals::~internals
~internals()
Definition: internals.h:208
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:2107
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:694
data
int data[]
Definition: Map_placement_new.cpp:1
handle
Definition: pytypes.h:226
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:349
internals::inactive_override_cache
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
Definition: internals.h:177
PYBIND11_INTERNALS_ID
#define PYBIND11_INTERNALS_ID
Definition: internals.h:309
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:726
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:567
local_internals::shared_loader_life_support_data
Definition: internals.h:580
local_internals
Definition: internals.h:566
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:1026
internals::istate
PyInterpreterState * istate
Definition: internals.h:197
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:490
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:418
type_info::direct_conversions
std::vector< bool(*)(PyObject *, void *&)> * direct_conversions
Definition: internals.h:235
instance_map_shard
Definition: internals.h:152
is_function_record_capsule
bool is_function_record_capsule(const capsule &cap)
Definition: internals.h:708
internals::static_strings
std::forward_list< std::string > static_strings
Definition: internals.h:186
type_equal_to
Definition: internals.h:131
get_python_state_dict
object get_python_state_dict()
Definition: internals.h:433
internals::direct_conversions
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
Definition: internals.h:178
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:179
with_internals
auto with_internals(const F &cb) -> decltype(cb(get_internals()))
Definition: internals.h:623
get_internals_obj_from_state_dict
object get_internals_obj_from_state_dict(handle state_dict)
Definition: internals.h:454
std
Definition: BFloat16.h:88
args
Definition: pytypes.h:2210
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:684
get_local_internals
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
Definition: internals.h:606
type_info::module_local
bool module_local
Definition: internals.h:249
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:231
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:629
internals::default_metaclass
PyTypeObject * default_metaclass
Definition: internals.h:189
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:169
uint64_t
unsigned __int64 uint64_t
Definition: ms_stdint.h:95
get_internals_pp
internals **& get_internals_pp()
Definition: internals.h:321
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:718
builtin_exception
C++ bindings of builtin Python exceptions.
Definition: wrap/pybind11/include/pybind11/detail/common.h:998
type_info::simple_ancestors
bool simple_ancestors
Definition: internals.h:245
align_3::t
Point2 t(10, 10)
local_internals::local_internals
local_internals()
Definition: internals.h:592
instance_map_shard::registered_instances
instance_map registered_instances
Definition: internals.h:154
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:654
make_default_metaclass
PyTypeObject * make_default_metaclass()
Definition: class.h:249
test_callbacks.value
value
Definition: test_callbacks.py:160
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
instance_map_shard::mutex
std::mutex mutex
Definition: internals.h:153
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:229


gtsam
Author(s):
autogenerated on Sat Nov 16 2024 04:02:28