message.h 14 KB

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