message_factory.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. #include <unordered_map>
  31. #include <Python.h>
  32. #include <google/protobuf/dynamic_message.h>
  33. #include <google/protobuf/pyext/descriptor.h>
  34. #include <google/protobuf/pyext/message.h>
  35. #include <google/protobuf/pyext/message_factory.h>
  36. #include <google/protobuf/pyext/scoped_pyobject_ptr.h>
  37. #if PY_MAJOR_VERSION >= 3
  38. #if PY_VERSION_HEX < 0x03030000
  39. #error "Python 3.0 - 3.2 are not supported."
  40. #endif
  41. #define PyString_AsStringAndSize(ob, charpp, sizep) \
  42. (PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
  43. PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
  44. ? -1 \
  45. : 0) \
  46. : PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
  47. #endif
  48. namespace google {
  49. namespace protobuf {
  50. namespace python {
  51. namespace message_factory {
  52. PyMessageFactory* NewMessageFactory(PyTypeObject* type, PyDescriptorPool* pool) {
  53. PyMessageFactory* factory = reinterpret_cast<PyMessageFactory*>(
  54. PyType_GenericAlloc(type, 0));
  55. if (factory == NULL) {
  56. return NULL;
  57. }
  58. DynamicMessageFactory* message_factory = new DynamicMessageFactory();
  59. // This option might be the default some day.
  60. message_factory->SetDelegateToGeneratedFactory(true);
  61. factory->message_factory = message_factory;
  62. factory->pool = pool;
  63. Py_INCREF(pool);
  64. factory->classes_by_descriptor = new PyMessageFactory::ClassesByMessageMap();
  65. return factory;
  66. }
  67. PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
  68. static char* kwlist[] = {"pool", 0};
  69. PyObject* pool = NULL;
  70. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &pool)) {
  71. return NULL;
  72. }
  73. ScopedPyObjectPtr owned_pool;
  74. if (pool == NULL || pool == Py_None) {
  75. owned_pool.reset(PyObject_CallFunction(
  76. reinterpret_cast<PyObject*>(&PyDescriptorPool_Type), NULL));
  77. if (owned_pool == NULL) {
  78. return NULL;
  79. }
  80. pool = owned_pool.get();
  81. } else {
  82. if (!PyObject_TypeCheck(pool, &PyDescriptorPool_Type)) {
  83. PyErr_Format(PyExc_TypeError, "Expected a DescriptorPool, got %s",
  84. pool->ob_type->tp_name);
  85. return NULL;
  86. }
  87. }
  88. return reinterpret_cast<PyObject*>(
  89. NewMessageFactory(type, reinterpret_cast<PyDescriptorPool*>(pool)));
  90. }
  91. static void Dealloc(PyObject* pself) {
  92. PyMessageFactory* self = reinterpret_cast<PyMessageFactory*>(pself);
  93. typedef PyMessageFactory::ClassesByMessageMap::iterator iterator;
  94. for (iterator it = self->classes_by_descriptor->begin();
  95. it != self->classes_by_descriptor->end(); ++it) {
  96. Py_CLEAR(it->second);
  97. }
  98. delete self->classes_by_descriptor;
  99. delete self->message_factory;
  100. Py_CLEAR(self->pool);
  101. Py_TYPE(self)->tp_free(pself);
  102. }
  103. static int GcTraverse(PyObject* pself, visitproc visit, void* arg) {
  104. PyMessageFactory* self = reinterpret_cast<PyMessageFactory*>(pself);
  105. Py_VISIT(self->pool);
  106. for (const auto& desc_and_class : *self->classes_by_descriptor) {
  107. Py_VISIT(desc_and_class.second);
  108. }
  109. return 0;
  110. }
  111. static int GcClear(PyObject* pself) {
  112. PyMessageFactory* self = reinterpret_cast<PyMessageFactory*>(pself);
  113. // Here it's important to not clear self->pool, so that the C++ DescriptorPool
  114. // is still alive when self->message_factory is destructed.
  115. for (auto& desc_and_class : *self->classes_by_descriptor) {
  116. Py_CLEAR(desc_and_class.second);
  117. }
  118. return 0;
  119. }
  120. // Add a message class to our database.
  121. int RegisterMessageClass(PyMessageFactory* self,
  122. const Descriptor* message_descriptor,
  123. CMessageClass* message_class) {
  124. Py_INCREF(message_class);
  125. typedef PyMessageFactory::ClassesByMessageMap::iterator iterator;
  126. std::pair<iterator, bool> ret = self->classes_by_descriptor->insert(
  127. std::make_pair(message_descriptor, message_class));
  128. if (!ret.second) {
  129. // Update case: DECREF the previous value.
  130. Py_DECREF(ret.first->second);
  131. ret.first->second = message_class;
  132. }
  133. return 0;
  134. }
  135. CMessageClass* GetOrCreateMessageClass(PyMessageFactory* self,
  136. const Descriptor* descriptor) {
  137. // This is the same implementation as MessageFactory.GetPrototype().
  138. // Do not create a MessageClass that already exists.
  139. std::unordered_map<const Descriptor*, CMessageClass*>::iterator it =
  140. self->classes_by_descriptor->find(descriptor);
  141. if (it != self->classes_by_descriptor->end()) {
  142. Py_INCREF(it->second);
  143. return it->second;
  144. }
  145. ScopedPyObjectPtr py_descriptor(
  146. PyMessageDescriptor_FromDescriptor(descriptor));
  147. if (py_descriptor == NULL) {
  148. return NULL;
  149. }
  150. // Create a new message class.
  151. ScopedPyObjectPtr args(Py_BuildValue(
  152. "s(){sOsOsO}", descriptor->name().c_str(),
  153. "DESCRIPTOR", py_descriptor.get(),
  154. "__module__", Py_None,
  155. "message_factory", self));
  156. if (args == NULL) {
  157. return NULL;
  158. }
  159. ScopedPyObjectPtr message_class(PyObject_CallObject(
  160. reinterpret_cast<PyObject*>(CMessageClass_Type), args.get()));
  161. if (message_class == NULL) {
  162. return NULL;
  163. }
  164. // Create messages class for the messages used by the fields, and registers
  165. // all extensions for these messages during the recursion.
  166. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) {
  167. const Descriptor* sub_descriptor =
  168. descriptor->field(field_idx)->message_type();
  169. // It is NULL if the field type is not a message.
  170. if (sub_descriptor != NULL) {
  171. CMessageClass* result = GetOrCreateMessageClass(self, sub_descriptor);
  172. if (result == NULL) {
  173. return NULL;
  174. }
  175. Py_DECREF(result);
  176. }
  177. }
  178. // Register extensions defined in this message.
  179. for (int ext_idx = 0 ; ext_idx < descriptor->extension_count() ; ext_idx++) {
  180. const FieldDescriptor* extension = descriptor->extension(ext_idx);
  181. ScopedPyObjectPtr py_extended_class(
  182. GetOrCreateMessageClass(self, extension->containing_type())
  183. ->AsPyObject());
  184. if (py_extended_class == NULL) {
  185. return NULL;
  186. }
  187. ScopedPyObjectPtr py_extension(PyFieldDescriptor_FromDescriptor(extension));
  188. if (py_extension == NULL) {
  189. return NULL;
  190. }
  191. ScopedPyObjectPtr result(cmessage::RegisterExtension(
  192. py_extended_class.get(), py_extension.get()));
  193. if (result == NULL) {
  194. return NULL;
  195. }
  196. }
  197. return reinterpret_cast<CMessageClass*>(message_class.release());
  198. }
  199. // Retrieve the message class added to our database.
  200. CMessageClass* GetMessageClass(PyMessageFactory* self,
  201. const Descriptor* message_descriptor) {
  202. typedef PyMessageFactory::ClassesByMessageMap::iterator iterator;
  203. iterator ret = self->classes_by_descriptor->find(message_descriptor);
  204. if (ret == self->classes_by_descriptor->end()) {
  205. PyErr_Format(PyExc_TypeError, "No message class registered for '%s'",
  206. message_descriptor->full_name().c_str());
  207. return NULL;
  208. } else {
  209. return ret->second;
  210. }
  211. }
  212. static PyMethodDef Methods[] = {
  213. {NULL}};
  214. static PyObject* GetPool(PyMessageFactory* self, void* closure) {
  215. Py_INCREF(self->pool);
  216. return reinterpret_cast<PyObject*>(self->pool);
  217. }
  218. static PyGetSetDef Getters[] = {
  219. {"pool", (getter)GetPool, NULL, "DescriptorPool"},
  220. {NULL}
  221. };
  222. } // namespace message_factory
  223. PyTypeObject PyMessageFactory_Type = {
  224. PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
  225. ".MessageFactory", // tp_name
  226. sizeof(PyMessageFactory), // tp_basicsize
  227. 0, // tp_itemsize
  228. message_factory::Dealloc, // tp_dealloc
  229. 0, // tp_print
  230. 0, // tp_getattr
  231. 0, // tp_setattr
  232. 0, // tp_compare
  233. 0, // tp_repr
  234. 0, // tp_as_number
  235. 0, // tp_as_sequence
  236. 0, // tp_as_mapping
  237. 0, // tp_hash
  238. 0, // tp_call
  239. 0, // tp_str
  240. 0, // tp_getattro
  241. 0, // tp_setattro
  242. 0, // tp_as_buffer
  243. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, // tp_flags
  244. "A static Message Factory", // tp_doc
  245. message_factory::GcTraverse, // tp_traverse
  246. message_factory::GcClear, // tp_clear
  247. 0, // tp_richcompare
  248. 0, // tp_weaklistoffset
  249. 0, // tp_iter
  250. 0, // tp_iternext
  251. message_factory::Methods, // tp_methods
  252. 0, // tp_members
  253. message_factory::Getters, // tp_getset
  254. 0, // tp_base
  255. 0, // tp_dict
  256. 0, // tp_descr_get
  257. 0, // tp_descr_set
  258. 0, // tp_dictoffset
  259. 0, // tp_init
  260. 0, // tp_alloc
  261. message_factory::New, // tp_new
  262. PyObject_GC_Del, // tp_free
  263. };
  264. bool InitMessageFactory() {
  265. if (PyType_Ready(&PyMessageFactory_Type) < 0) {
  266. return false;
  267. }
  268. return true;
  269. }
  270. } // namespace python
  271. } // namespace protobuf
  272. } // namespace google