protobuf/python/google/protobuf/pyext/message_factory.cc
Go to the documentation of this file.
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 // * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 // * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 #include <unordered_map>
32 
33 #define PY_SSIZE_T_CLEAN
34 #include <Python.h>
35 
36 #include <google/protobuf/dynamic_message.h>
37 #include <google/protobuf/pyext/descriptor.h>
38 #include <google/protobuf/pyext/message.h>
39 #include <google/protobuf/pyext/message_factory.h>
40 #include <google/protobuf/pyext/scoped_pyobject_ptr.h>
41 
42 #define PyString_AsStringAndSize(ob, charpp, sizep) \
43  (PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
44  PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
45  ? -1 \
46  : 0) \
47  : PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
48 
49 namespace google {
50 namespace protobuf {
51 namespace python {
52 
53 namespace message_factory {
54 
55 PyMessageFactory* NewMessageFactory(PyTypeObject* type, PyDescriptorPool* pool) {
56  PyMessageFactory* factory = reinterpret_cast<PyMessageFactory*>(
57  PyType_GenericAlloc(type, 0));
58  if (factory == NULL) {
59  return NULL;
60  }
61 
62  DynamicMessageFactory* message_factory = new DynamicMessageFactory();
63  // This option might be the default some day.
64  message_factory->SetDelegateToGeneratedFactory(true);
65  factory->message_factory = message_factory;
66 
67  factory->pool = pool;
68  Py_INCREF(pool);
69 
70  factory->classes_by_descriptor = new PyMessageFactory::ClassesByMessageMap();
71 
72  return factory;
73 }
74 
75 PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
76  static const char* kwlist[] = {"pool", 0};
77  PyObject* pool = NULL;
78  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O",
79  const_cast<char**>(kwlist), &pool)) {
80  return NULL;
81  }
82  ScopedPyObjectPtr owned_pool;
83  if (pool == NULL || pool == Py_None) {
84  owned_pool.reset(PyObject_CallFunction(
85  reinterpret_cast<PyObject*>(&PyDescriptorPool_Type), NULL));
86  if (owned_pool == NULL) {
87  return NULL;
88  }
89  pool = owned_pool.get();
90  } else {
91  if (!PyObject_TypeCheck(pool, &PyDescriptorPool_Type)) {
92  PyErr_Format(PyExc_TypeError, "Expected a DescriptorPool, got %s",
93  pool->ob_type->tp_name);
94  return NULL;
95  }
96  }
97 
98  return reinterpret_cast<PyObject*>(
99  NewMessageFactory(type, reinterpret_cast<PyDescriptorPool*>(pool)));
100 }
101 
102 static void Dealloc(PyObject* pself) {
103  PyMessageFactory* self = reinterpret_cast<PyMessageFactory*>(pself);
104 
106  for (iterator it = self->classes_by_descriptor->begin();
107  it != self->classes_by_descriptor->end(); ++it) {
108  Py_CLEAR(it->second);
109  }
110  delete self->classes_by_descriptor;
111  delete self->message_factory;
112  Py_CLEAR(self->pool);
113  Py_TYPE(self)->tp_free(pself);
114 }
115 
116 static int GcTraverse(PyObject* pself, visitproc visit, void* arg) {
117  PyMessageFactory* self = reinterpret_cast<PyMessageFactory*>(pself);
118  Py_VISIT(self->pool);
119  for (const auto& desc_and_class : *self->classes_by_descriptor) {
120  Py_VISIT(desc_and_class.second);
121  }
122  return 0;
123 }
124 
125 static int GcClear(PyObject* pself) {
126  PyMessageFactory* self = reinterpret_cast<PyMessageFactory*>(pself);
127  // Here it's important to not clear self->pool, so that the C++ DescriptorPool
128  // is still alive when self->message_factory is destructed.
129  for (auto& desc_and_class : *self->classes_by_descriptor) {
130  Py_CLEAR(desc_and_class.second);
131  }
132 
133  return 0;
134 }
135 
136 // Add a message class to our database.
138  const Descriptor* message_descriptor,
139  CMessageClass* message_class) {
140  Py_INCREF(message_class);
142  std::pair<iterator, bool> ret = self->classes_by_descriptor->insert(
143  std::make_pair(message_descriptor, message_class));
144  if (!ret.second) {
145  // Update case: DECREF the previous value.
146  Py_DECREF(ret.first->second);
147  ret.first->second = message_class;
148  }
149  return 0;
150 }
151 
152 CMessageClass* GetOrCreateMessageClass(PyMessageFactory* self,
153  const Descriptor* descriptor) {
154  // This is the same implementation as MessageFactory.GetPrototype().
155 
156  // Do not create a MessageClass that already exists.
158  self->classes_by_descriptor->find(descriptor);
159  if (it != self->classes_by_descriptor->end()) {
160  Py_INCREF(it->second);
161  return it->second;
162  }
163  ScopedPyObjectPtr py_descriptor(
165  if (py_descriptor == NULL) {
166  return NULL;
167  }
168  // Create a new message class.
169  ScopedPyObjectPtr args(Py_BuildValue(
170  "s(){sOsOsO}", descriptor->name().c_str(),
171  "DESCRIPTOR", py_descriptor.get(),
172  "__module__", Py_None,
173  "message_factory", self));
174  if (args == NULL) {
175  return NULL;
176  }
177  ScopedPyObjectPtr message_class(PyObject_CallObject(
178  reinterpret_cast<PyObject*>(CMessageClass_Type), args.get()));
179  if (message_class == NULL) {
180  return NULL;
181  }
182  // Create messages class for the messages used by the fields, and registers
183  // all extensions for these messages during the recursion.
184  for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) {
185  const Descriptor* sub_descriptor =
186  descriptor->field(field_idx)->message_type();
187  // It is NULL if the field type is not a message.
188  if (sub_descriptor != NULL) {
189  CMessageClass* result = GetOrCreateMessageClass(self, sub_descriptor);
190  if (result == NULL) {
191  return NULL;
192  }
193  Py_DECREF(result);
194  }
195  }
196 
197  // Register extensions defined in this message.
198  for (int ext_idx = 0 ; ext_idx < descriptor->extension_count() ; ext_idx++) {
199  const FieldDescriptor* extension = descriptor->extension(ext_idx);
200  ScopedPyObjectPtr py_extended_class(
201  GetOrCreateMessageClass(self, extension->containing_type())
202  ->AsPyObject());
203  if (py_extended_class == NULL) {
204  return NULL;
205  }
207  if (py_extension == NULL) {
208  return NULL;
209  }
211  py_extended_class.get(), py_extension.get()));
212  if (result == NULL) {
213  return NULL;
214  }
215  }
216  return reinterpret_cast<CMessageClass*>(message_class.release());
217 }
218 
219 // Retrieve the message class added to our database.
220 CMessageClass* GetMessageClass(PyMessageFactory* self,
221  const Descriptor* message_descriptor) {
223  iterator ret = self->classes_by_descriptor->find(message_descriptor);
224  if (ret == self->classes_by_descriptor->end()) {
225  PyErr_Format(PyExc_TypeError, "No message class registered for '%s'",
226  message_descriptor->full_name().c_str());
227  return NULL;
228  } else {
229  return ret->second;
230  }
231 }
232 
233 static PyMethodDef Methods[] = {
234  {NULL}};
235 
236 static PyObject* GetPool(PyMessageFactory* self, void* closure) {
237  Py_INCREF(self->pool);
238  return reinterpret_cast<PyObject*>(self->pool);
239 }
240 
241 static PyGetSetDef Getters[] = {
242  {"pool", (getter)GetPool, NULL, "DescriptorPool"},
243  {NULL}
244 };
245 
246 } // namespace message_factory
247 
248 PyTypeObject PyMessageFactory_Type = {
249  PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
250  ".MessageFactory", // tp_name
251  sizeof(PyMessageFactory), // tp_basicsize
252  0, // tp_itemsize
253  message_factory::Dealloc, // tp_dealloc
254  0, // tp_print
255  0, // tp_getattr
256  0, // tp_setattr
257  0, // tp_compare
258  0, // tp_repr
259  0, // tp_as_number
260  0, // tp_as_sequence
261  0, // tp_as_mapping
262  0, // tp_hash
263  0, // tp_call
264  0, // tp_str
265  0, // tp_getattro
266  0, // tp_setattro
267  0, // tp_as_buffer
268  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, // tp_flags
269  "A static Message Factory", // tp_doc
270  message_factory::GcTraverse, // tp_traverse
271  message_factory::GcClear, // tp_clear
272  0, // tp_richcompare
273  0, // tp_weaklistoffset
274  0, // tp_iter
275  0, // tp_iternext
276  message_factory::Methods, // tp_methods
277  0, // tp_members
278  message_factory::Getters, // tp_getset
279  0, // tp_base
280  0, // tp_dict
281  0, // tp_descr_get
282  0, // tp_descr_set
283  0, // tp_dictoffset
284  0, // tp_init
285  0, // tp_alloc
286  message_factory::New, // tp_new
287  PyObject_GC_Del, // tp_free
288 };
289 
290 bool InitMessageFactory() {
291  if (PyType_Ready(&PyMessageFactory_Type) < 0) {
292  return false;
293  }
294 
295  return true;
296 }
297 
298 } // namespace python
299 } // namespace protobuf
300 } // namespace google
_gevent_test_main.result
result
Definition: _gevent_test_main.py:96
regen-readme.it
it
Definition: regen-readme.py:15
google::protobuf::python::PyMessageFactory
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.h:49
google::protobuf::extension
const Descriptor::ReservedRange const EnumValueDescriptor const MethodDescriptor extension
Definition: bloaty/third_party/protobuf/src/google/protobuf/descriptor.h:2001
google::protobuf::python::message_factory::GcClear
static int GcClear(PyObject *pself)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:128
google::protobuf::python::ScopedPyObjectPtr
ScopedPythonPtr< PyObject > ScopedPyObjectPtr
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/scoped_pyobject_ptr.h:95
google::protobuf::python::PyMessageFactory::ClassesByMessageMap
std::unordered_map< const Descriptor *, CMessageClass * > ClassesByMessageMap
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.h:69
google::protobuf::python::PyDescriptorPool
struct google::protobuf::python::PyDescriptorPool PyDescriptorPool
google::protobuf::python::message_factory::Methods
static PyMethodDef Methods[]
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:236
New
T * New(Args &&... args)
Definition: third_party/boringssl-with-bazel/src/ssl/internal.h:195
google::protobuf
Definition: bloaty/third_party/protobuf/benchmarks/util/data_proto2_to_proto3_util.h:12
grpc::protobuf::DynamicMessageFactory
GRPC_CUSTOM_DYNAMICMESSAGEFACTORY DynamicMessageFactory
Definition: config_grpc_cli.h:54
FULL_MODULE_NAME
#define FULL_MODULE_NAME
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message.h:331
iterator
const typedef MCPhysReg * iterator
Definition: MCRegisterInfo.h:27
google::protobuf::python::CMessageClass
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message.h:148
google::protobuf::MessageFactory
Definition: bloaty/third_party/protobuf/src/google/protobuf/message.h:1066
Descriptor
Definition: bloaty/third_party/protobuf/ruby/ext/google/protobuf_c/protobuf.h:121
google::protobuf::python::PyFieldDescriptor_FromDescriptor
PyObject * PyFieldDescriptor_FromDescriptor(const FieldDescriptor *field_descriptor)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/descriptor.cc:1037
google::protobuf::python::PyMessageDescriptor_FromDescriptor
PyObject * PyMessageDescriptor_FromDescriptor(const Descriptor *message_descriptor)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/descriptor.cc:722
FieldDescriptor
Definition: bloaty/third_party/protobuf/ruby/ext/google/protobuf_c/protobuf.h:133
google::protobuf::python::InitMessageFactory
bool InitMessageFactory()
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:293
google::protobuf::python::message_factory::Dealloc
static void Dealloc(PyObject *pself)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:105
asyncio_get_stats.args
args
Definition: asyncio_get_stats.py:40
google::protobuf::python::cmessage::RegisterExtension
PyObject * RegisterExtension(PyObject *cls, PyObject *extension_handle)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message.cc:1986
google::protobuf::python::CMessageClass::AsPyObject
PyObject * AsPyObject()
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message.h:166
google::protobuf::python::CMessageClass_Type
PyTypeObject * CMessageClass_Type
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message.cc:514
arg
Definition: cmdline.cc:40
google::protobuf::python::message_factory::GetOrCreateMessageClass
CMessageClass * GetOrCreateMessageClass(PyMessageFactory *self, const Descriptor *descriptor)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:155
google::protobuf::python::message_factory::RegisterMessageClass
int RegisterMessageClass(PyMessageFactory *self, const Descriptor *message_descriptor, CMessageClass *message_class)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:140
google::protobuf::python::PyMessageFactory_Type
PyTypeObject PyMessageFactory_Type
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:251
google::protobuf::python::PyDescriptorPool_Type
PyTypeObject PyDescriptorPool_Type
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/descriptor_pool.cc:677
google::protobuf::Message
Definition: bloaty/third_party/protobuf/src/google/protobuf/message.h:205
google::protobuf::python::message_factory::Getters
static PyGetSetDef Getters[]
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:244
google::protobuf::python::message_factory::New
PyObject * New(PyTypeObject *type, PyObject *args, PyObject *kwargs)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:79
google::protobuf::python::message_factory::NewMessageFactory
PyMessageFactory * NewMessageFactory(PyTypeObject *type, PyDescriptorPool *pool)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:59
ret
UniquePtr< SSL_SESSION > ret
Definition: ssl_x509.cc:1029
A
Definition: miscompile_with_no_unique_address_test.cc:23
google::protobuf::Descriptor
Definition: bloaty/third_party/protobuf/src/google/protobuf/descriptor.h:231
closure
Definition: proxy.cc:59
pool
InternalDescriptorPool * pool
Definition: bloaty/third_party/protobuf/php/ext/google/protobuf/protobuf.h:807
PyVarObject_HEAD_INIT
#define PyVarObject_HEAD_INIT(type, size)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/descriptor.cc:161
Py_TYPE
#define Py_TYPE(ob)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/descriptor.cc:164
asyncio_get_stats.type
type
Definition: asyncio_get_stats.py:37
absl::visit
variant_internal::VisitResult< Visitor, Variants... > visit(Visitor &&vis, Variants &&... vars)
Definition: abseil-cpp/absl/types/variant.h:430
self
PHP_PROTO_OBJECT_FREE_END PHP_PROTO_OBJECT_DTOR_END intern self
Definition: bloaty/third_party/protobuf/php/ext/google/protobuf/map.c:543
descriptor
static const char descriptor[1336]
Definition: certs.upbdefs.c:16
google::protobuf::python::message_factory::GetPool
static PyObject * GetPool(PyMessageFactory *self, void *closure)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:239
google::protobuf::python::message_factory::GetMessageClass
CMessageClass * GetMessageClass(PyMessageFactory *self, const Descriptor *message_descriptor)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:223
google
Definition: bloaty/third_party/protobuf/benchmarks/util/data_proto2_to_proto3_util.h:11
google::protobuf::python::message_factory::GcTraverse
static int GcTraverse(PyObject *pself, visitproc visit, void *arg)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message_factory.cc:119


grpc
Author(s):
autogenerated on Fri May 16 2025 02:59:26