Scarab  v2.11.1
Project 8 C++ Utility Library
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 "../pytypes.h"
13 
15 NAMESPACE_BEGIN(detail)
16 // Forward declarations
17 inline PyTypeObject *make_static_property_type();
18 inline PyTypeObject *make_default_metaclass();
19 inline PyObject *make_object_base_type(PyTypeObject *metaclass);
20 
21 // The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
22 // Thread Specific Storage (TSS) API.
23 #if PY_VERSION_HEX >= 0x03070000
24 # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr
25 # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
26 # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (value))
27 # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
28 #else
29  // Usually an int but a long on Cygwin64 with Python 3.x
30 # define PYBIND11_TLS_KEY_INIT(var) decltype(PyThread_create_key()) var = 0
31 # define PYBIND11_TLS_GET_VALUE(key) PyThread_get_key_value((key))
32 # if PY_MAJOR_VERSION < 3
33 # define PYBIND11_TLS_DELETE_VALUE(key) \
34  PyThread_delete_key_value(key)
35 # define PYBIND11_TLS_REPLACE_VALUE(key, value) \
36  do { \
37  PyThread_delete_key_value((key)); \
38  PyThread_set_key_value((key), (value)); \
39  } while (false)
40 # else
41 # define PYBIND11_TLS_DELETE_VALUE(key) \
42  PyThread_set_key_value((key), nullptr)
43 # define PYBIND11_TLS_REPLACE_VALUE(key, value) \
44  PyThread_set_key_value((key), (value))
45 # endif
46 #endif
47 
48 // Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly
49 // other STLs, this means `typeid(A)` from one module won't equal `typeid(A)` from another module
50 // even when `A` is the same, non-hidden-visibility type (e.g. from a common include). Under
51 // libstdc++, this doesn't happen: equality and the type_index hash are based on the type name,
52 // which works. If not under a known-good stl, provide our own name-based hash and equality
53 // functions that use the type name.
54 #if defined(__GLIBCXX__)
55 inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) { return lhs == rhs; }
56 using type_hash = std::hash<std::type_index>;
57 using type_equal_to = std::equal_to<std::type_index>;
58 #else
59 inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) {
60  return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
61 }
62 
63 struct type_hash {
64  size_t operator()(const std::type_index &t) const {
65  size_t hash = 5381;
66  const char *ptr = t.name();
67  while (auto c = static_cast<unsigned char>(*ptr++))
68  hash = (hash * 33) ^ c;
69  return hash;
70  }
71 };
72 
73 struct type_equal_to {
74  bool operator()(const std::type_index &lhs, const std::type_index &rhs) const {
75  return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
76  }
77 };
78 #endif
79 
80 template <typename value_type>
81 using type_map = std::unordered_map<std::type_index, value_type, type_hash, type_equal_to>;
82 
83 struct overload_hash {
84  inline size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
85  size_t value = std::hash<const void *>()(v.first);
86  value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value<<6) + (value>>2);
87  return value;
88  }
89 };
90 
94 struct internals {
95  type_map<type_info *> registered_types_cpp; // std::type_index -> pybind11's type information
96  std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py; // PyTypeObject* -> base type_info(s)
97  std::unordered_multimap<const void *, instance*> registered_instances; // void * -> instance*
98  std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
100  std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
101  std::forward_list<void (*) (std::exception_ptr)> registered_exception_translators;
102  std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions
103  std::vector<PyObject *> loader_patient_stack; // Used by `loader_life_support`
104  std::forward_list<std::string> static_strings; // Stores the std::strings backing detail::c_str()
105  PyTypeObject *static_property_type;
106  PyTypeObject *default_metaclass;
107  PyObject *instance_base;
108 #if defined(WITH_THREAD)
109  PYBIND11_TLS_KEY_INIT(tstate);
110  PyInterpreterState *istate = nullptr;
111 #endif
112 };
113 
116 struct type_info {
117  PyTypeObject *type;
118  const std::type_info *cpptype;
119  size_t type_size, type_align, holder_size_in_ptrs;
120  void *(*operator_new)(size_t);
121  void (*init_instance)(instance *, const void *);
122  void (*dealloc)(value_and_holder &v_h);
123  std::vector<PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions;
124  std::vector<std::pair<const std::type_info *, void *(*)(void *)>> implicit_casts;
125  std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
126  buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
127  void *get_buffer_data = nullptr;
128  void *(*module_local_load)(PyObject *, const type_info *) = nullptr;
129  /* A simple type never occurs as a (direct or indirect) parent
130  * of a class that makes use of multiple inheritance */
131  bool simple_type : 1;
132  /* True if there is no multiple inheritance in this type's inheritance tree */
134  /* for base vs derived holder_type checks */
135  bool default_holder : 1;
136  /* true if this is a type registered with py::module_local */
137  bool module_local : 1;
138 };
139 
141 #define PYBIND11_INTERNALS_VERSION 3
142 
144 #if defined(_MSC_VER) && defined(_DEBUG)
145 # define PYBIND11_BUILD_TYPE "_debug"
146 #else
147 # define PYBIND11_BUILD_TYPE ""
148 #endif
149 
151 #if defined(__GXX_ABI_VERSION)
152 # define PYBIND11_BUILD_ABI "_cxxabi" PYBIND11_TOSTRING(__GXX_ABI_VERSION)
153 #else
154 # define PYBIND11_BUILD_ABI ""
155 #endif
156 
157 #if defined(WITH_THREAD)
158 # define PYBIND11_INTERNALS_KIND ""
159 #else
160 # define PYBIND11_INTERNALS_KIND "_without_thread"
161 #endif
162 
163 #define PYBIND11_INTERNALS_ID "__pybind11_internals_v" \
164  PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) PYBIND11_INTERNALS_KIND PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE "__"
165 
166 #define PYBIND11_MODULE_LOCAL_ID "__pybind11_module_local_v" \
167  PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) PYBIND11_INTERNALS_KIND PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE "__"
168 
172  static internals **internals_pp = nullptr;
173  return internals_pp;
174 }
175 
176 inline void translate_exception(std::exception_ptr p) {
177  try {
178  if (p) std::rethrow_exception(p);
179  } catch (error_already_set &e) { e.restore(); return;
180  } catch (const builtin_exception &e) { e.set_error(); return;
181  } catch (const std::bad_alloc &e) { PyErr_SetString(PyExc_MemoryError, e.what()); return;
182  } catch (const std::domain_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
183  } catch (const std::invalid_argument &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
184  } catch (const std::length_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
185  } catch (const std::out_of_range &e) { PyErr_SetString(PyExc_IndexError, e.what()); return;
186  } catch (const std::range_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
187  } catch (const std::exception &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return;
188  } catch (...) {
189  PyErr_SetString(PyExc_RuntimeError, "Caught an unknown exception!");
190  return;
191  }
192 }
193 
194 #if !defined(__GLIBCXX__)
195 inline void translate_local_exception(std::exception_ptr p) {
196  try {
197  if (p) std::rethrow_exception(p);
198  } catch (error_already_set &e) { e.restore(); return;
199  } catch (const builtin_exception &e) { e.set_error(); return;
200  }
201 }
202 #endif
203 
205 PYBIND11_NOINLINE inline internals &get_internals() {
206  auto **&internals_pp = get_internals_pp();
207  if (internals_pp && *internals_pp)
208  return **internals_pp;
209 
210  // Ensure that the GIL is held since we will need to make Python calls.
211  // Cannot use py::gil_scoped_acquire here since that constructor calls get_internals.
212  struct gil_scoped_acquire_local {
213  gil_scoped_acquire_local() : state (PyGILState_Ensure()) {}
214  ~gil_scoped_acquire_local() { PyGILState_Release(state); }
215  const PyGILState_STATE state;
216  } gil;
217 
218  constexpr auto *id = PYBIND11_INTERNALS_ID;
219  auto builtins = handle(PyEval_GetBuiltins());
220  if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
221  internals_pp = static_cast<internals **>(capsule(builtins[id]));
222 
223  // We loaded builtins through python's builtins, which means that our `error_already_set`
224  // and `builtin_exception` may be different local classes than the ones set up in the
225  // initial exception translator, below, so add another for our local exception classes.
226  //
227  // libstdc++ doesn't require this (types there are identified only by name)
228 #if !defined(__GLIBCXX__)
229  (*internals_pp)->registered_exception_translators.push_front(&translate_local_exception);
230 #endif
231  } else {
232  if (!internals_pp) internals_pp = new internals*();
233  auto *&internals_ptr = *internals_pp;
234  internals_ptr = new internals();
235 #if defined(WITH_THREAD)
236  PyEval_InitThreads();
237  PyThreadState *tstate = PyThreadState_Get();
238  #if PY_VERSION_HEX >= 0x03070000
239  internals_ptr->tstate = PyThread_tss_alloc();
240  if (!internals_ptr->tstate || PyThread_tss_create(internals_ptr->tstate))
241  pybind11_fail("get_internals: could not successfully initialize the TSS key!");
242  PyThread_tss_set(internals_ptr->tstate, tstate);
243  #else
244  internals_ptr->tstate = PyThread_create_key();
245  if (internals_ptr->tstate == -1)
246  pybind11_fail("get_internals: could not successfully initialize the TLS key!");
247  PyThread_set_key_value(internals_ptr->tstate, tstate);
248  #endif
249  internals_ptr->istate = tstate->interp;
250 #endif
251  builtins[id] = capsule(internals_pp);
252  internals_ptr->registered_exception_translators.push_front(&translate_exception);
254  internals_ptr->default_metaclass = make_default_metaclass();
255  internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
256  }
257  return **internals_pp;
258 }
259 
262  static type_map<type_info *> locals{};
263  return locals;
264 }
265 
270 template <typename... Args>
271 const char *c_str(Args &&...args) {
272  auto &strings = get_internals().static_strings;
273  strings.emplace_front(std::forward<Args>(args)...);
274  return strings.front().c_str();
275 }
276 
277 NAMESPACE_END(detail)
278 
279 inline PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
283  auto &internals = detail::get_internals();
284  auto it = internals.shared_data.find(name);
285  return it != internals.shared_data.end() ? it->second : nullptr;
286 }
287 
289 inline PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
290  detail::get_internals().shared_data[name] = data;
291  return data;
292 }
293 
297 template<typename T>
298 T &get_or_create_shared_data(const std::string &name) {
299  auto &internals = detail::get_internals();
300  auto it = internals.shared_data.find(name);
301  T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr);
302  if (!ptr) {
303  ptr = new T();
304  internals.shared_data[name] = ptr;
305  }
306  return *ptr;
307 }
308 
std::unordered_set< std::pair< const PyObject *, const char * >, overload_hash > inactive_overload_cache
Definition: internals.h:98
std::unordered_map< std::type_index, value_type, type_hash, type_equal_to > type_map
Definition: internals.h:81
std::vector< PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions
Definition: internals.h:123
T & get_or_create_shared_data(const std::string &name)
Definition: internals.h:298
PyTypeObject * static_property_type
Definition: internals.h:105
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
Definition: internals.h:96
#define PYBIND11_NAMESPACE
Definition: detail/common.h:26
std::size_t size_t
size_t operator()(const std::type_index &t) const
Definition: internals.h:64
void translate_local_exception(std::exception_ptr p)
Definition: internals.h:195
std::vector< PyObject * > loader_patient_stack
Definition: internals.h:103
internals **& get_internals_pp()
Definition: internals.h:171
virtual void set_error() const =0
Set the error using the Python C API.
type_map< type_info * > & registered_local_types_cpp()
Works like internals.registered_types_cpp, but for module-local registered types: ...
Definition: internals.h:261
C++ bindings of builtin Python exceptions.
arr data(const arr &a, Ix... index)
Information record describing a Python buffer object.
Definition: buffer_info.h:17
bool operator()(const std::type_index &lhs, const std::type_index &rhs) const
Definition: internals.h:74
#define PYBIND11_NOINLINE
Definition: detail/common.h:86
The &#39;instance&#39; type which needs to be standard layout (need to be able to use &#39;offsetof&#39;) ...
bool same_type(const std::type_info &lhs, const std::type_info &rhs)
Definition: internals.h:59
std::unordered_map< std::string, void * > shared_data
Definition: internals.h:102
op_< op_hash, op_u, self_t, undefined_t > hash(const self_t &)
Definition: operators.h:151
std::vector< bool(*)(PyObject *, void *&)> * direct_conversions
Definition: internals.h:125
#define NAMESPACE_END(name)
Definition: detail/common.h:16
PyTypeObject * default_metaclass
Definition: internals.h:106
PyObject * make_object_base_type(PyTypeObject *metaclass)
Definition: class.h:365
const std::type_info * cpptype
Definition: internals.h:118
PyTypeObject * make_default_metaclass()
Definition: class.h:162
void translate_exception(std::exception_ptr p)
Definition: internals.h:176
std::forward_list< void(*)(std::exception_ptr)> registered_exception_translators
Definition: internals.h:101
PyTypeObject * make_static_property_type()
Definition: class.h:48
#define PYBIND11_TLS_KEY_INIT(var)
Definition: internals.h:30
std::unordered_multimap< const void *, instance * > registered_instances
Definition: internals.h:97
#define PYBIND11_INTERNALS_ID
Definition: internals.h:163
Annotation for function names.
Definition: attr.h:33
type_map< type_info * > registered_types_cpp
Definition: internals.h:95
const char * c_str(Args &&...args)
Definition: internals.h:271
std::forward_list< std::string > static_strings
Definition: internals.h:104
#define NAMESPACE_BEGIN(name)
Definition: detail/common.h:13
std::vector< std::pair< const std::type_info *, void *(*)(void *)> > implicit_casts
Definition: internals.h:124
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
Definition: internals.h:99
std::unordered_map< const PyObject *, std::vector< PyObject * > > patients
Definition: internals.h:100
size_t operator()(const std::pair< const PyObject *, const char *> &v) const
Definition: internals.h:84