message_factory.cc 11 KB

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