message.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. // Author: anuraag@google.com (Anuraag Agrawal)
  31. // Author: tibell@google.com (Johan Tibell)
  32. #ifndef GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_H__
  33. #define GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_H__
  34. #include <Python.h>
  35. #include <memory>
  36. #ifndef _SHARED_PTR_H
  37. #include <google/protobuf/stubs/shared_ptr.h>
  38. #endif
  39. #include <string>
  40. namespace google {
  41. namespace protobuf {
  42. class Message;
  43. class Reflection;
  44. class FieldDescriptor;
  45. class Descriptor;
  46. class DescriptorPool;
  47. class MessageFactory;
  48. #ifdef _SHARED_PTR_H
  49. using std::shared_ptr;
  50. using std::string;
  51. #else
  52. using internal::shared_ptr;
  53. #endif
  54. namespace python {
  55. struct ExtensionDict;
  56. struct PyDescriptorPool;
  57. typedef struct CMessage {
  58. PyObject_HEAD;
  59. // This is the top-level C++ Message object that owns the whole
  60. // proto tree. Every Python CMessage holds a reference to it in
  61. // order to keep it alive as long as there's a Python object that
  62. // references any part of the tree.
  63. shared_ptr<Message> owner;
  64. // Weak reference to a parent CMessage object. This is NULL for any top-level
  65. // message and is set for any child message (i.e. a child submessage or a
  66. // part of a repeated composite field).
  67. //
  68. // Used to make sure all ancestors are also mutable when first modifying
  69. // a child submessage (in other words, turning a default message instance
  70. // into a mutable one).
  71. //
  72. // If a submessage is released (becomes a new top-level message), this field
  73. // MUST be set to NULL. The parent may get deallocated and further attempts
  74. // to use this pointer will result in a crash.
  75. struct CMessage* parent;
  76. // Pointer to the parent's descriptor that describes this submessage.
  77. // Used together with the parent's message when making a default message
  78. // instance mutable.
  79. // The pointer is owned by the global DescriptorPool.
  80. const FieldDescriptor* parent_field_descriptor;
  81. // Pointer to the C++ Message object for this CMessage. The
  82. // CMessage does not own this pointer.
  83. Message* message;
  84. // Indicates this submessage is pointing to a default instance of a message.
  85. // Submessages are always first created as read only messages and are then
  86. // made writable, at which point this field is set to false.
  87. bool read_only;
  88. // A reference to a Python dictionary containing CMessage,
  89. // RepeatedCompositeContainer, and RepeatedScalarContainer
  90. // objects. Used as a cache to make sure we don't have to make a
  91. // Python wrapper for the C++ Message objects on every access, or
  92. // deal with the synchronization nightmare that could create.
  93. PyObject* composite_fields;
  94. // A reference to the dictionary containing the message's extensions.
  95. // Similar to composite_fields, acting as a cache, but also contains the
  96. // required extension dict logic.
  97. ExtensionDict* extensions;
  98. } CMessage;
  99. extern PyTypeObject CMessage_Type;
  100. // The (meta) type of all Messages classes.
  101. // It allows us to cache some C++ pointers in the class object itself, they are
  102. // faster to extract than from the type's dictionary.
  103. struct CMessageClass {
  104. // This is how CPython subclasses C structures: the base structure must be
  105. // the first member of the object.
  106. PyHeapTypeObject super;
  107. // C++ descriptor of this message.
  108. const Descriptor* message_descriptor;
  109. // Owned reference, used to keep the pointer above alive.
  110. PyObject* py_message_descriptor;
  111. // The Python DescriptorPool used to create the class. It is needed to resolve
  112. // fields descriptors, including extensions fields; its C++ MessageFactory is
  113. // used to instantiate submessages.
  114. // This can be different from DESCRIPTOR.file.pool, in the case of a custom
  115. // DescriptorPool which defines new extensions.
  116. // We own the reference, because it's important to keep the descriptors and
  117. // factory alive.
  118. PyDescriptorPool* py_descriptor_pool;
  119. PyObject* AsPyObject() {
  120. return reinterpret_cast<PyObject*>(this);
  121. }
  122. };
  123. namespace cmessage {
  124. // Internal function to create a new empty Message Python object, but with empty
  125. // pointers to the C++ objects.
  126. // The caller must fill self->message, self->owner and eventually self->parent.
  127. CMessage* NewEmptyMessage(CMessageClass* type);
  128. // Release a submessage from its proto tree, making it a new top-level messgae.
  129. // A new message will be created if this is a read-only default instance.
  130. //
  131. // Corresponds to reflection api method ReleaseMessage.
  132. int ReleaseSubMessage(CMessage* self,
  133. const FieldDescriptor* field_descriptor,
  134. CMessage* child_cmessage);
  135. // Retrieves the C++ descriptor of a Python Extension descriptor.
  136. // On error, return NULL with an exception set.
  137. const FieldDescriptor* GetExtensionDescriptor(PyObject* extension);
  138. // Initializes a new CMessage instance for a submessage. Only called once per
  139. // submessage as the result is cached in composite_fields.
  140. //
  141. // Corresponds to reflection api method GetMessage.
  142. PyObject* InternalGetSubMessage(
  143. CMessage* self, const FieldDescriptor* field_descriptor);
  144. // Deletes a range of C++ submessages in a repeated field (following a
  145. // removal in a RepeatedCompositeContainer).
  146. //
  147. // Releases messages to the provided cmessage_list if it is not NULL rather
  148. // than just removing them from the underlying proto. This cmessage_list must
  149. // have a CMessage for each underlying submessage. The CMessages referred to
  150. // by slice will be removed from cmessage_list by this function.
  151. //
  152. // Corresponds to reflection api method RemoveLast.
  153. int InternalDeleteRepeatedField(CMessage* self,
  154. const FieldDescriptor* field_descriptor,
  155. PyObject* slice, PyObject* cmessage_list);
  156. // Sets the specified scalar value to the message.
  157. int InternalSetScalar(CMessage* self,
  158. const FieldDescriptor* field_descriptor,
  159. PyObject* value);
  160. // Sets the specified scalar value to the message. Requires it is not a Oneof.
  161. int InternalSetNonOneofScalar(Message* message,
  162. const FieldDescriptor* field_descriptor,
  163. PyObject* arg);
  164. // Retrieves the specified scalar value from the message.
  165. //
  166. // Returns a new python reference.
  167. PyObject* InternalGetScalar(const Message* message,
  168. const FieldDescriptor* field_descriptor);
  169. // Clears the message, removing all contained data. Extension dictionary and
  170. // submessages are released first if there are remaining external references.
  171. //
  172. // Corresponds to message api method Clear.
  173. PyObject* Clear(CMessage* self);
  174. // Clears the data described by the given descriptor. Used to clear extensions
  175. // (which don't have names). Extension release is handled by ExtensionDict
  176. // class, not this function.
  177. // TODO(anuraag): Try to make this discrepancy in release semantics with
  178. // ClearField less confusing.
  179. //
  180. // Corresponds to reflection api method ClearField.
  181. PyObject* ClearFieldByDescriptor(
  182. CMessage* self, const FieldDescriptor* descriptor);
  183. // Clears the data for the given field name. The message is released if there
  184. // are any external references.
  185. //
  186. // Corresponds to reflection api method ClearField.
  187. PyObject* ClearField(CMessage* self, PyObject* arg);
  188. // Checks if the message has the field described by the descriptor. Used for
  189. // extensions (which have no name).
  190. //
  191. // Corresponds to reflection api method HasField
  192. PyObject* HasFieldByDescriptor(
  193. CMessage* self, const FieldDescriptor* field_descriptor);
  194. // Checks if the message has the named field.
  195. //
  196. // Corresponds to reflection api method HasField.
  197. PyObject* HasField(CMessage* self, PyObject* arg);
  198. // Initializes values of fields on a newly constructed message.
  199. int InitAttributes(CMessage* self, PyObject* kwargs);
  200. PyObject* MergeFrom(CMessage* self, PyObject* arg);
  201. // Retrieves an attribute named 'name' from CMessage 'self'. Returns
  202. // the attribute value on success, or NULL on failure.
  203. //
  204. // Returns a new reference.
  205. PyObject* GetAttr(CMessage* self, PyObject* name);
  206. // Set the value of the attribute named 'name', for CMessage 'self',
  207. // to the value 'value'. Returns -1 on failure.
  208. int SetAttr(CMessage* self, PyObject* name, PyObject* value);
  209. PyObject* FindInitializationErrors(CMessage* self);
  210. // Set the owner field of self and any children of self, recursively.
  211. // Used when self is being released and thus has a new owner (the
  212. // released Message.)
  213. int SetOwner(CMessage* self, const shared_ptr<Message>& new_owner);
  214. int AssureWritable(CMessage* self);
  215. // Returns the "best" DescriptorPool for the given message.
  216. // This is often equivalent to message.DESCRIPTOR.pool, but not always, when
  217. // the message class was created from a MessageFactory using a custom pool which
  218. // uses the generated pool as an underlay.
  219. //
  220. // The returned pool is suitable for finding fields and building submessages,
  221. // even in the case of extensions.
  222. PyDescriptorPool* GetDescriptorPoolForMessage(CMessage* message);
  223. PyObject* SetAllowOversizeProtos(PyObject* m, PyObject* arg);
  224. } // namespace cmessage
  225. /* Is 64bit */
  226. #define IS_64BIT (SIZEOF_LONG == 8)
  227. #define FIELD_IS_REPEATED(field_descriptor) \
  228. ((field_descriptor)->label() == FieldDescriptor::LABEL_REPEATED)
  229. #define GOOGLE_CHECK_GET_INT32(arg, value, err) \
  230. int32 value; \
  231. if (!CheckAndGetInteger(arg, &value, kint32min_py, kint32max_py)) { \
  232. return err; \
  233. }
  234. #define GOOGLE_CHECK_GET_INT64(arg, value, err) \
  235. int64 value; \
  236. if (!CheckAndGetInteger(arg, &value, kint64min_py, kint64max_py)) { \
  237. return err; \
  238. }
  239. #define GOOGLE_CHECK_GET_UINT32(arg, value, err) \
  240. uint32 value; \
  241. if (!CheckAndGetInteger(arg, &value, kPythonZero, kuint32max_py)) { \
  242. return err; \
  243. }
  244. #define GOOGLE_CHECK_GET_UINT64(arg, value, err) \
  245. uint64 value; \
  246. if (!CheckAndGetInteger(arg, &value, kPythonZero, kuint64max_py)) { \
  247. return err; \
  248. }
  249. #define GOOGLE_CHECK_GET_FLOAT(arg, value, err) \
  250. float value; \
  251. if (!CheckAndGetFloat(arg, &value)) { \
  252. return err; \
  253. } \
  254. #define GOOGLE_CHECK_GET_DOUBLE(arg, value, err) \
  255. double value; \
  256. if (!CheckAndGetDouble(arg, &value)) { \
  257. return err; \
  258. }
  259. #define GOOGLE_CHECK_GET_BOOL(arg, value, err) \
  260. bool value; \
  261. if (!CheckAndGetBool(arg, &value)) { \
  262. return err; \
  263. }
  264. extern PyObject* kPythonZero;
  265. extern PyObject* kint32min_py;
  266. extern PyObject* kint32max_py;
  267. extern PyObject* kuint32max_py;
  268. extern PyObject* kint64min_py;
  269. extern PyObject* kint64max_py;
  270. extern PyObject* kuint64max_py;
  271. #define FULL_MODULE_NAME "google.protobuf.pyext._message"
  272. void FormatTypeError(PyObject* arg, char* expected_types);
  273. template<class T>
  274. bool CheckAndGetInteger(
  275. PyObject* arg, T* value, PyObject* min, PyObject* max);
  276. bool CheckAndGetDouble(PyObject* arg, double* value);
  277. bool CheckAndGetFloat(PyObject* arg, float* value);
  278. bool CheckAndGetBool(PyObject* arg, bool* value);
  279. PyObject* CheckString(PyObject* arg, const FieldDescriptor* descriptor);
  280. bool CheckAndSetString(
  281. PyObject* arg, Message* message,
  282. const FieldDescriptor* descriptor,
  283. const Reflection* reflection,
  284. bool append,
  285. int index);
  286. PyObject* ToStringObject(const FieldDescriptor* descriptor, string value);
  287. // Check if the passed field descriptor belongs to the given message.
  288. // If not, return false and set a Python exception (a KeyError)
  289. bool CheckFieldBelongsToMessage(const FieldDescriptor* field_descriptor,
  290. const Message* message);
  291. extern PyObject* PickleError_class;
  292. bool InitProto2MessageModule(PyObject *m);
  293. } // namespace python
  294. } // namespace protobuf
  295. } // namespace google
  296. #endif // GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_H__