message.cc 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115
  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. #include <google/protobuf/pyext/message.h>
  33. #include <map>
  34. #include <memory>
  35. #ifndef _SHARED_PTR_H
  36. #include <google/protobuf/stubs/shared_ptr.h>
  37. #endif
  38. #include <string>
  39. #include <vector>
  40. #include <structmember.h> // A Python header file.
  41. #ifndef PyVarObject_HEAD_INIT
  42. #define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
  43. #endif
  44. #ifndef Py_TYPE
  45. #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
  46. #endif
  47. #include <google/protobuf/descriptor.pb.h>
  48. #include <google/protobuf/stubs/common.h>
  49. #include <google/protobuf/stubs/logging.h>
  50. #include <google/protobuf/io/coded_stream.h>
  51. #include <google/protobuf/util/message_differencer.h>
  52. #include <google/protobuf/descriptor.h>
  53. #include <google/protobuf/message.h>
  54. #include <google/protobuf/text_format.h>
  55. #include <google/protobuf/unknown_field_set.h>
  56. #include <google/protobuf/pyext/descriptor.h>
  57. #include <google/protobuf/pyext/descriptor_pool.h>
  58. #include <google/protobuf/pyext/extension_dict.h>
  59. #include <google/protobuf/pyext/repeated_composite_container.h>
  60. #include <google/protobuf/pyext/repeated_scalar_container.h>
  61. #include <google/protobuf/pyext/map_container.h>
  62. #include <google/protobuf/pyext/scoped_pyobject_ptr.h>
  63. #include <google/protobuf/stubs/strutil.h>
  64. #if PY_MAJOR_VERSION >= 3
  65. #define PyInt_Check PyLong_Check
  66. #define PyInt_AsLong PyLong_AsLong
  67. #define PyInt_FromLong PyLong_FromLong
  68. #define PyInt_FromSize_t PyLong_FromSize_t
  69. #define PyString_Check PyUnicode_Check
  70. #define PyString_FromString PyUnicode_FromString
  71. #define PyString_FromStringAndSize PyUnicode_FromStringAndSize
  72. #if PY_VERSION_HEX < 0x03030000
  73. #error "Python 3.0 - 3.2 are not supported."
  74. #else
  75. #define PyString_AsString(ob) \
  76. (PyUnicode_Check(ob)? PyUnicode_AsUTF8(ob): PyBytes_AsString(ob))
  77. #define PyString_AsStringAndSize(ob, charpp, sizep) \
  78. (PyUnicode_Check(ob)? \
  79. ((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0): \
  80. PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
  81. #endif
  82. #endif
  83. namespace google {
  84. namespace protobuf {
  85. namespace python {
  86. static PyObject* kDESCRIPTOR;
  87. static PyObject* k_extensions_by_name;
  88. static PyObject* k_extensions_by_number;
  89. PyObject* EnumTypeWrapper_class;
  90. static PyObject* PythonMessage_class;
  91. static PyObject* kEmptyWeakref;
  92. static PyObject* WKT_classes = NULL;
  93. // Defines the Metaclass of all Message classes.
  94. // It allows us to cache some C++ pointers in the class object itself, they are
  95. // faster to extract than from the type's dictionary.
  96. struct PyMessageMeta {
  97. // This is how CPython subclasses C structures: the base structure must be
  98. // the first member of the object.
  99. PyHeapTypeObject super;
  100. // C++ descriptor of this message.
  101. const Descriptor* message_descriptor;
  102. // Owned reference, used to keep the pointer above alive.
  103. PyObject* py_message_descriptor;
  104. // The Python DescriptorPool used to create the class. It is needed to resolve
  105. // fields descriptors, including extensions fields; its C++ MessageFactory is
  106. // used to instantiate submessages.
  107. // This can be different from DESCRIPTOR.file.pool, in the case of a custom
  108. // DescriptorPool which defines new extensions.
  109. // We own the reference, because it's important to keep the descriptors and
  110. // factory alive.
  111. PyDescriptorPool* py_descriptor_pool;
  112. };
  113. namespace message_meta {
  114. static int InsertEmptyWeakref(PyTypeObject* base);
  115. // Add the number of a field descriptor to the containing message class.
  116. // Equivalent to:
  117. // _cls.<field>_FIELD_NUMBER = <number>
  118. static bool AddFieldNumberToClass(
  119. PyObject* cls, const FieldDescriptor* field_descriptor) {
  120. string constant_name = field_descriptor->name() + "_FIELD_NUMBER";
  121. UpperString(&constant_name);
  122. ScopedPyObjectPtr attr_name(PyString_FromStringAndSize(
  123. constant_name.c_str(), constant_name.size()));
  124. if (attr_name == NULL) {
  125. return false;
  126. }
  127. ScopedPyObjectPtr number(PyInt_FromLong(field_descriptor->number()));
  128. if (number == NULL) {
  129. return false;
  130. }
  131. if (PyObject_SetAttr(cls, attr_name.get(), number.get()) == -1) {
  132. return false;
  133. }
  134. return true;
  135. }
  136. // Finalize the creation of the Message class.
  137. static int AddDescriptors(PyObject* cls, const Descriptor* descriptor) {
  138. // If there are extension_ranges, the message is "extendable", and extension
  139. // classes will register themselves in this class.
  140. if (descriptor->extension_range_count() > 0) {
  141. ScopedPyObjectPtr by_name(PyDict_New());
  142. if (PyObject_SetAttr(cls, k_extensions_by_name, by_name.get()) < 0) {
  143. return -1;
  144. }
  145. ScopedPyObjectPtr by_number(PyDict_New());
  146. if (PyObject_SetAttr(cls, k_extensions_by_number, by_number.get()) < 0) {
  147. return -1;
  148. }
  149. }
  150. // For each field set: cls.<field>_FIELD_NUMBER = <number>
  151. for (int i = 0; i < descriptor->field_count(); ++i) {
  152. if (!AddFieldNumberToClass(cls, descriptor->field(i))) {
  153. return -1;
  154. }
  155. }
  156. // For each enum set cls.<enum name> = EnumTypeWrapper(<enum descriptor>).
  157. //
  158. // The enum descriptor we get from
  159. // <messagedescriptor>.enum_types_by_name[name]
  160. // which was built previously.
  161. for (int i = 0; i < descriptor->enum_type_count(); ++i) {
  162. const EnumDescriptor* enum_descriptor = descriptor->enum_type(i);
  163. ScopedPyObjectPtr enum_type(
  164. PyEnumDescriptor_FromDescriptor(enum_descriptor));
  165. if (enum_type == NULL) {
  166. return -1;
  167. }
  168. // Add wrapped enum type to message class.
  169. ScopedPyObjectPtr wrapped(PyObject_CallFunctionObjArgs(
  170. EnumTypeWrapper_class, enum_type.get(), NULL));
  171. if (wrapped == NULL) {
  172. return -1;
  173. }
  174. if (PyObject_SetAttrString(
  175. cls, enum_descriptor->name().c_str(), wrapped.get()) == -1) {
  176. return -1;
  177. }
  178. // For each enum value add cls.<name> = <number>
  179. for (int j = 0; j < enum_descriptor->value_count(); ++j) {
  180. const EnumValueDescriptor* enum_value_descriptor =
  181. enum_descriptor->value(j);
  182. ScopedPyObjectPtr value_number(PyInt_FromLong(
  183. enum_value_descriptor->number()));
  184. if (value_number == NULL) {
  185. return -1;
  186. }
  187. if (PyObject_SetAttrString(cls, enum_value_descriptor->name().c_str(),
  188. value_number.get()) == -1) {
  189. return -1;
  190. }
  191. }
  192. }
  193. // For each extension set cls.<extension name> = <extension descriptor>.
  194. //
  195. // Extension descriptors come from
  196. // <message descriptor>.extensions_by_name[name]
  197. // which was defined previously.
  198. for (int i = 0; i < descriptor->extension_count(); ++i) {
  199. const google::protobuf::FieldDescriptor* field = descriptor->extension(i);
  200. ScopedPyObjectPtr extension_field(PyFieldDescriptor_FromDescriptor(field));
  201. if (extension_field == NULL) {
  202. return -1;
  203. }
  204. // Add the extension field to the message class.
  205. if (PyObject_SetAttrString(
  206. cls, field->name().c_str(), extension_field.get()) == -1) {
  207. return -1;
  208. }
  209. // For each extension set cls.<extension name>_FIELD_NUMBER = <number>.
  210. if (!AddFieldNumberToClass(cls, field)) {
  211. return -1;
  212. }
  213. }
  214. return 0;
  215. }
  216. static PyObject* New(PyTypeObject* type,
  217. PyObject* args, PyObject* kwargs) {
  218. static char *kwlist[] = {"name", "bases", "dict", 0};
  219. PyObject *bases, *dict;
  220. const char* name;
  221. // Check arguments: (name, bases, dict)
  222. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO!O!:type", kwlist,
  223. &name,
  224. &PyTuple_Type, &bases,
  225. &PyDict_Type, &dict)) {
  226. return NULL;
  227. }
  228. // Check bases: only (), or (message.Message,) are allowed
  229. if (!(PyTuple_GET_SIZE(bases) == 0 ||
  230. (PyTuple_GET_SIZE(bases) == 1 &&
  231. PyTuple_GET_ITEM(bases, 0) == PythonMessage_class))) {
  232. PyErr_SetString(PyExc_TypeError,
  233. "A Message class can only inherit from Message");
  234. return NULL;
  235. }
  236. // Check dict['DESCRIPTOR']
  237. PyObject* py_descriptor = PyDict_GetItem(dict, kDESCRIPTOR);
  238. if (py_descriptor == NULL) {
  239. PyErr_SetString(PyExc_TypeError, "Message class has no DESCRIPTOR");
  240. return NULL;
  241. }
  242. if (!PyObject_TypeCheck(py_descriptor, &PyMessageDescriptor_Type)) {
  243. PyErr_Format(PyExc_TypeError, "Expected a message Descriptor, got %s",
  244. py_descriptor->ob_type->tp_name);
  245. return NULL;
  246. }
  247. // Build the arguments to the base metaclass.
  248. // We change the __bases__ classes.
  249. ScopedPyObjectPtr new_args;
  250. const Descriptor* message_descriptor =
  251. PyMessageDescriptor_AsDescriptor(py_descriptor);
  252. if (message_descriptor == NULL) {
  253. return NULL;
  254. }
  255. if (WKT_classes == NULL) {
  256. ScopedPyObjectPtr well_known_types(PyImport_ImportModule(
  257. "google.protobuf.internal.well_known_types"));
  258. GOOGLE_DCHECK(well_known_types != NULL);
  259. WKT_classes = PyObject_GetAttrString(well_known_types.get(), "WKTBASES");
  260. GOOGLE_DCHECK(WKT_classes != NULL);
  261. }
  262. PyObject* well_known_class = PyDict_GetItemString(
  263. WKT_classes, message_descriptor->full_name().c_str());
  264. if (well_known_class == NULL) {
  265. new_args.reset(Py_BuildValue("s(OO)O", name, &CMessage_Type,
  266. PythonMessage_class, dict));
  267. } else {
  268. new_args.reset(Py_BuildValue("s(OOO)O", name, &CMessage_Type,
  269. PythonMessage_class, well_known_class, dict));
  270. }
  271. if (new_args == NULL) {
  272. return NULL;
  273. }
  274. // Call the base metaclass.
  275. ScopedPyObjectPtr result(PyType_Type.tp_new(type, new_args.get(), NULL));
  276. if (result == NULL) {
  277. return NULL;
  278. }
  279. PyMessageMeta* newtype = reinterpret_cast<PyMessageMeta*>(result.get());
  280. // Insert the empty weakref into the base classes.
  281. if (InsertEmptyWeakref(
  282. reinterpret_cast<PyTypeObject*>(PythonMessage_class)) < 0 ||
  283. InsertEmptyWeakref(&CMessage_Type) < 0) {
  284. return NULL;
  285. }
  286. // Cache the descriptor, both as Python object and as C++ pointer.
  287. const Descriptor* descriptor =
  288. PyMessageDescriptor_AsDescriptor(py_descriptor);
  289. if (descriptor == NULL) {
  290. return NULL;
  291. }
  292. Py_INCREF(py_descriptor);
  293. newtype->py_message_descriptor = py_descriptor;
  294. newtype->message_descriptor = descriptor;
  295. // TODO(amauryfa): Don't always use the canonical pool of the descriptor,
  296. // use the MessageFactory optionally passed in the class dict.
  297. newtype->py_descriptor_pool = GetDescriptorPool_FromPool(
  298. descriptor->file()->pool());
  299. if (newtype->py_descriptor_pool == NULL) {
  300. return NULL;
  301. }
  302. Py_INCREF(newtype->py_descriptor_pool);
  303. // Add the message to the DescriptorPool.
  304. if (cdescriptor_pool::RegisterMessageClass(newtype->py_descriptor_pool,
  305. descriptor, result.get()) < 0) {
  306. return NULL;
  307. }
  308. // Continue with type initialization: add other descriptors, enum values...
  309. if (AddDescriptors(result.get(), descriptor) < 0) {
  310. return NULL;
  311. }
  312. return result.release();
  313. }
  314. static void Dealloc(PyMessageMeta *self) {
  315. Py_DECREF(self->py_message_descriptor);
  316. Py_DECREF(self->py_descriptor_pool);
  317. Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
  318. }
  319. // This function inserts and empty weakref at the end of the list of
  320. // subclasses for the main protocol buffer Message class.
  321. //
  322. // This eliminates a O(n^2) behaviour in the internal add_subclass
  323. // routine.
  324. static int InsertEmptyWeakref(PyTypeObject *base_type) {
  325. #if PY_MAJOR_VERSION >= 3
  326. // Python 3.4 has already included the fix for the issue that this
  327. // hack addresses. For further background and the fix please see
  328. // https://bugs.python.org/issue17936.
  329. return 0;
  330. #else
  331. PyObject *subclasses = base_type->tp_subclasses;
  332. if (subclasses && PyList_CheckExact(subclasses)) {
  333. return PyList_Append(subclasses, kEmptyWeakref);
  334. }
  335. return 0;
  336. #endif // PY_MAJOR_VERSION >= 3
  337. }
  338. } // namespace message_meta
  339. PyTypeObject PyMessageMeta_Type = {
  340. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  341. FULL_MODULE_NAME ".MessageMeta", // tp_name
  342. sizeof(PyMessageMeta), // tp_basicsize
  343. 0, // tp_itemsize
  344. (destructor)message_meta::Dealloc, // tp_dealloc
  345. 0, // tp_print
  346. 0, // tp_getattr
  347. 0, // tp_setattr
  348. 0, // tp_compare
  349. 0, // tp_repr
  350. 0, // tp_as_number
  351. 0, // tp_as_sequence
  352. 0, // tp_as_mapping
  353. 0, // tp_hash
  354. 0, // tp_call
  355. 0, // tp_str
  356. 0, // tp_getattro
  357. 0, // tp_setattro
  358. 0, // tp_as_buffer
  359. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
  360. "The metaclass of ProtocolMessages", // tp_doc
  361. 0, // tp_traverse
  362. 0, // tp_clear
  363. 0, // tp_richcompare
  364. 0, // tp_weaklistoffset
  365. 0, // tp_iter
  366. 0, // tp_iternext
  367. 0, // tp_methods
  368. 0, // tp_members
  369. 0, // tp_getset
  370. 0, // tp_base
  371. 0, // tp_dict
  372. 0, // tp_descr_get
  373. 0, // tp_descr_set
  374. 0, // tp_dictoffset
  375. 0, // tp_init
  376. 0, // tp_alloc
  377. message_meta::New, // tp_new
  378. };
  379. static PyMessageMeta* CheckMessageClass(PyTypeObject* cls) {
  380. if (!PyObject_TypeCheck(cls, &PyMessageMeta_Type)) {
  381. PyErr_Format(PyExc_TypeError, "Class %s is not a Message", cls->tp_name);
  382. return NULL;
  383. }
  384. return reinterpret_cast<PyMessageMeta*>(cls);
  385. }
  386. static const Descriptor* GetMessageDescriptor(PyTypeObject* cls) {
  387. PyMessageMeta* type = CheckMessageClass(cls);
  388. if (type == NULL) {
  389. return NULL;
  390. }
  391. return type->message_descriptor;
  392. }
  393. // Forward declarations
  394. namespace cmessage {
  395. int InternalReleaseFieldByDescriptor(
  396. CMessage* self,
  397. const FieldDescriptor* field_descriptor,
  398. PyObject* composite_field);
  399. } // namespace cmessage
  400. // ---------------------------------------------------------------------
  401. // Visiting the composite children of a CMessage
  402. struct ChildVisitor {
  403. // Returns 0 on success, -1 on failure.
  404. int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
  405. return 0;
  406. }
  407. // Returns 0 on success, -1 on failure.
  408. int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
  409. return 0;
  410. }
  411. // Returns 0 on success, -1 on failure.
  412. int VisitCMessage(CMessage* cmessage,
  413. const FieldDescriptor* field_descriptor) {
  414. return 0;
  415. }
  416. };
  417. // Apply a function to a composite field. Does nothing if child is of
  418. // non-composite type.
  419. template<class Visitor>
  420. static int VisitCompositeField(const FieldDescriptor* descriptor,
  421. PyObject* child,
  422. Visitor visitor) {
  423. if (descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
  424. if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  425. if (descriptor->is_map()) {
  426. MapContainer* container = reinterpret_cast<MapContainer*>(child);
  427. if (visitor.VisitMapContainer(container) == -1) {
  428. return -1;
  429. }
  430. } else {
  431. RepeatedCompositeContainer* container =
  432. reinterpret_cast<RepeatedCompositeContainer*>(child);
  433. if (visitor.VisitRepeatedCompositeContainer(container) == -1)
  434. return -1;
  435. }
  436. } else {
  437. RepeatedScalarContainer* container =
  438. reinterpret_cast<RepeatedScalarContainer*>(child);
  439. if (visitor.VisitRepeatedScalarContainer(container) == -1)
  440. return -1;
  441. }
  442. } else if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  443. CMessage* cmsg = reinterpret_cast<CMessage*>(child);
  444. if (visitor.VisitCMessage(cmsg, descriptor) == -1)
  445. return -1;
  446. }
  447. // The ExtensionDict might contain non-composite fields, which we
  448. // skip here.
  449. return 0;
  450. }
  451. // Visit each composite field and extension field of this CMessage.
  452. // Returns -1 on error and 0 on success.
  453. template<class Visitor>
  454. int ForEachCompositeField(CMessage* self, Visitor visitor) {
  455. Py_ssize_t pos = 0;
  456. PyObject* key;
  457. PyObject* field;
  458. // Visit normal fields.
  459. if (self->composite_fields) {
  460. // Never use self->message in this function, it may be already freed.
  461. const Descriptor* message_descriptor =
  462. GetMessageDescriptor(Py_TYPE(self));
  463. while (PyDict_Next(self->composite_fields, &pos, &key, &field)) {
  464. Py_ssize_t key_str_size;
  465. char *key_str_data;
  466. if (PyString_AsStringAndSize(key, &key_str_data, &key_str_size) != 0)
  467. return -1;
  468. const string key_str(key_str_data, key_str_size);
  469. const FieldDescriptor* descriptor =
  470. message_descriptor->FindFieldByName(key_str);
  471. if (descriptor != NULL) {
  472. if (VisitCompositeField(descriptor, field, visitor) == -1)
  473. return -1;
  474. }
  475. }
  476. }
  477. // Visit extension fields.
  478. if (self->extensions != NULL) {
  479. pos = 0;
  480. while (PyDict_Next(self->extensions->values, &pos, &key, &field)) {
  481. const FieldDescriptor* descriptor = cmessage::GetExtensionDescriptor(key);
  482. if (descriptor == NULL)
  483. return -1;
  484. if (VisitCompositeField(descriptor, field, visitor) == -1)
  485. return -1;
  486. }
  487. }
  488. return 0;
  489. }
  490. // ---------------------------------------------------------------------
  491. // Constants used for integer type range checking.
  492. PyObject* kPythonZero;
  493. PyObject* kint32min_py;
  494. PyObject* kint32max_py;
  495. PyObject* kuint32max_py;
  496. PyObject* kint64min_py;
  497. PyObject* kint64max_py;
  498. PyObject* kuint64max_py;
  499. PyObject* EncodeError_class;
  500. PyObject* DecodeError_class;
  501. PyObject* PickleError_class;
  502. // Constant PyString values used for GetAttr/GetItem.
  503. static PyObject* k_cdescriptor;
  504. static PyObject* kfull_name;
  505. /* Is 64bit */
  506. void FormatTypeError(PyObject* arg, char* expected_types) {
  507. PyObject* repr = PyObject_Repr(arg);
  508. if (repr) {
  509. PyErr_Format(PyExc_TypeError,
  510. "%.100s has type %.100s, but expected one of: %s",
  511. PyString_AsString(repr),
  512. Py_TYPE(arg)->tp_name,
  513. expected_types);
  514. Py_DECREF(repr);
  515. }
  516. }
  517. template<class T>
  518. bool CheckAndGetInteger(
  519. PyObject* arg, T* value, PyObject* min, PyObject* max) {
  520. bool is_long = PyLong_Check(arg);
  521. #if PY_MAJOR_VERSION < 3
  522. if (!PyInt_Check(arg) && !is_long) {
  523. FormatTypeError(arg, "int, long");
  524. return false;
  525. }
  526. if (PyObject_Compare(min, arg) > 0 || PyObject_Compare(max, arg) < 0) {
  527. #else
  528. if (!is_long) {
  529. FormatTypeError(arg, "int");
  530. return false;
  531. }
  532. if (PyObject_RichCompareBool(min, arg, Py_LE) != 1 ||
  533. PyObject_RichCompareBool(max, arg, Py_GE) != 1) {
  534. #endif
  535. if (!PyErr_Occurred()) {
  536. PyObject *s = PyObject_Str(arg);
  537. if (s) {
  538. PyErr_Format(PyExc_ValueError,
  539. "Value out of range: %s",
  540. PyString_AsString(s));
  541. Py_DECREF(s);
  542. }
  543. }
  544. return false;
  545. }
  546. #if PY_MAJOR_VERSION < 3
  547. if (!is_long) {
  548. *value = static_cast<T>(PyInt_AsLong(arg));
  549. } else // NOLINT
  550. #endif
  551. {
  552. if (min == kPythonZero) {
  553. *value = static_cast<T>(PyLong_AsUnsignedLongLong(arg));
  554. } else {
  555. *value = static_cast<T>(PyLong_AsLongLong(arg));
  556. }
  557. }
  558. return true;
  559. }
  560. // These are referenced by repeated_scalar_container, and must
  561. // be explicitly instantiated.
  562. template bool CheckAndGetInteger<int32>(
  563. PyObject*, int32*, PyObject*, PyObject*);
  564. template bool CheckAndGetInteger<int64>(
  565. PyObject*, int64*, PyObject*, PyObject*);
  566. template bool CheckAndGetInteger<uint32>(
  567. PyObject*, uint32*, PyObject*, PyObject*);
  568. template bool CheckAndGetInteger<uint64>(
  569. PyObject*, uint64*, PyObject*, PyObject*);
  570. bool CheckAndGetDouble(PyObject* arg, double* value) {
  571. if (!PyInt_Check(arg) && !PyLong_Check(arg) &&
  572. !PyFloat_Check(arg)) {
  573. FormatTypeError(arg, "int, long, float");
  574. return false;
  575. }
  576. *value = PyFloat_AsDouble(arg);
  577. return true;
  578. }
  579. bool CheckAndGetFloat(PyObject* arg, float* value) {
  580. double double_value;
  581. if (!CheckAndGetDouble(arg, &double_value)) {
  582. return false;
  583. }
  584. *value = static_cast<float>(double_value);
  585. return true;
  586. }
  587. bool CheckAndGetBool(PyObject* arg, bool* value) {
  588. if (!PyInt_Check(arg) && !PyBool_Check(arg) && !PyLong_Check(arg)) {
  589. FormatTypeError(arg, "int, long, bool");
  590. return false;
  591. }
  592. *value = static_cast<bool>(PyInt_AsLong(arg));
  593. return true;
  594. }
  595. // Checks whether the given object (which must be "bytes" or "unicode") contains
  596. // valid UTF-8.
  597. bool IsValidUTF8(PyObject* obj) {
  598. if (PyBytes_Check(obj)) {
  599. PyObject* unicode = PyUnicode_FromEncodedObject(obj, "utf-8", NULL);
  600. // Clear the error indicator; we report our own error when desired.
  601. PyErr_Clear();
  602. if (unicode) {
  603. Py_DECREF(unicode);
  604. return true;
  605. } else {
  606. return false;
  607. }
  608. } else {
  609. // Unicode object, known to be valid UTF-8.
  610. return true;
  611. }
  612. }
  613. bool AllowInvalidUTF8(const FieldDescriptor* field) { return false; }
  614. PyObject* CheckString(PyObject* arg, const FieldDescriptor* descriptor) {
  615. GOOGLE_DCHECK(descriptor->type() == FieldDescriptor::TYPE_STRING ||
  616. descriptor->type() == FieldDescriptor::TYPE_BYTES);
  617. if (descriptor->type() == FieldDescriptor::TYPE_STRING) {
  618. if (!PyBytes_Check(arg) && !PyUnicode_Check(arg)) {
  619. FormatTypeError(arg, "bytes, unicode");
  620. return NULL;
  621. }
  622. if (!IsValidUTF8(arg) && !AllowInvalidUTF8(descriptor)) {
  623. PyObject* repr = PyObject_Repr(arg);
  624. PyErr_Format(PyExc_ValueError,
  625. "%s has type str, but isn't valid UTF-8 "
  626. "encoding. Non-UTF-8 strings must be converted to "
  627. "unicode objects before being added.",
  628. PyString_AsString(repr));
  629. Py_DECREF(repr);
  630. return NULL;
  631. }
  632. } else if (!PyBytes_Check(arg)) {
  633. FormatTypeError(arg, "bytes");
  634. return NULL;
  635. }
  636. PyObject* encoded_string = NULL;
  637. if (descriptor->type() == FieldDescriptor::TYPE_STRING) {
  638. if (PyBytes_Check(arg)) {
  639. // The bytes were already validated as correctly encoded UTF-8 above.
  640. encoded_string = arg; // Already encoded.
  641. Py_INCREF(encoded_string);
  642. } else {
  643. encoded_string = PyUnicode_AsEncodedObject(arg, "utf-8", NULL);
  644. }
  645. } else {
  646. // In this case field type is "bytes".
  647. encoded_string = arg;
  648. Py_INCREF(encoded_string);
  649. }
  650. return encoded_string;
  651. }
  652. bool CheckAndSetString(
  653. PyObject* arg, Message* message,
  654. const FieldDescriptor* descriptor,
  655. const Reflection* reflection,
  656. bool append,
  657. int index) {
  658. ScopedPyObjectPtr encoded_string(CheckString(arg, descriptor));
  659. if (encoded_string.get() == NULL) {
  660. return false;
  661. }
  662. char* value;
  663. Py_ssize_t value_len;
  664. if (PyBytes_AsStringAndSize(encoded_string.get(), &value, &value_len) < 0) {
  665. return false;
  666. }
  667. string value_string(value, value_len);
  668. if (append) {
  669. reflection->AddString(message, descriptor, value_string);
  670. } else if (index < 0) {
  671. reflection->SetString(message, descriptor, value_string);
  672. } else {
  673. reflection->SetRepeatedString(message, descriptor, index, value_string);
  674. }
  675. return true;
  676. }
  677. PyObject* ToStringObject(const FieldDescriptor* descriptor, string value) {
  678. if (descriptor->type() != FieldDescriptor::TYPE_STRING) {
  679. return PyBytes_FromStringAndSize(value.c_str(), value.length());
  680. }
  681. PyObject* result = PyUnicode_DecodeUTF8(value.c_str(), value.length(), NULL);
  682. // If the string can't be decoded in UTF-8, just return a string object that
  683. // contains the raw bytes. This can't happen if the value was assigned using
  684. // the members of the Python message object, but can happen if the values were
  685. // parsed from the wire (binary).
  686. if (result == NULL) {
  687. PyErr_Clear();
  688. result = PyBytes_FromStringAndSize(value.c_str(), value.length());
  689. }
  690. return result;
  691. }
  692. bool CheckFieldBelongsToMessage(const FieldDescriptor* field_descriptor,
  693. const Message* message) {
  694. if (message->GetDescriptor() == field_descriptor->containing_type()) {
  695. return true;
  696. }
  697. PyErr_Format(PyExc_KeyError, "Field '%s' does not belong to message '%s'",
  698. field_descriptor->full_name().c_str(),
  699. message->GetDescriptor()->full_name().c_str());
  700. return false;
  701. }
  702. namespace cmessage {
  703. PyDescriptorPool* GetDescriptorPoolForMessage(CMessage* message) {
  704. // No need to check the type: the type of instances of CMessage is always
  705. // an instance of PyMessageMeta. Let's prove it with a debug-only check.
  706. GOOGLE_DCHECK(PyObject_TypeCheck(message, &CMessage_Type));
  707. return reinterpret_cast<PyMessageMeta*>(Py_TYPE(message))->py_descriptor_pool;
  708. }
  709. MessageFactory* GetFactoryForMessage(CMessage* message) {
  710. return GetDescriptorPoolForMessage(message)->message_factory;
  711. }
  712. static int MaybeReleaseOverlappingOneofField(
  713. CMessage* cmessage,
  714. const FieldDescriptor* field) {
  715. #ifdef GOOGLE_PROTOBUF_HAS_ONEOF
  716. Message* message = cmessage->message;
  717. const Reflection* reflection = message->GetReflection();
  718. if (!field->containing_oneof() ||
  719. !reflection->HasOneof(*message, field->containing_oneof()) ||
  720. reflection->HasField(*message, field)) {
  721. // No other field in this oneof, no need to release.
  722. return 0;
  723. }
  724. const OneofDescriptor* oneof = field->containing_oneof();
  725. const FieldDescriptor* existing_field =
  726. reflection->GetOneofFieldDescriptor(*message, oneof);
  727. if (existing_field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
  728. // Non-message fields don't need to be released.
  729. return 0;
  730. }
  731. const char* field_name = existing_field->name().c_str();
  732. PyObject* child_message = cmessage->composite_fields ?
  733. PyDict_GetItemString(cmessage->composite_fields, field_name) : NULL;
  734. if (child_message == NULL) {
  735. // No python reference to this field so no need to release.
  736. return 0;
  737. }
  738. if (InternalReleaseFieldByDescriptor(
  739. cmessage, existing_field, child_message) < 0) {
  740. return -1;
  741. }
  742. return PyDict_DelItemString(cmessage->composite_fields, field_name);
  743. #else
  744. return 0;
  745. #endif
  746. }
  747. // ---------------------------------------------------------------------
  748. // Making a message writable
  749. static Message* GetMutableMessage(
  750. CMessage* parent,
  751. const FieldDescriptor* parent_field) {
  752. Message* parent_message = parent->message;
  753. const Reflection* reflection = parent_message->GetReflection();
  754. if (MaybeReleaseOverlappingOneofField(parent, parent_field) < 0) {
  755. return NULL;
  756. }
  757. return reflection->MutableMessage(
  758. parent_message, parent_field, GetFactoryForMessage(parent));
  759. }
  760. struct FixupMessageReference : public ChildVisitor {
  761. // message must outlive this object.
  762. explicit FixupMessageReference(Message* message) :
  763. message_(message) {}
  764. int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
  765. container->message = message_;
  766. return 0;
  767. }
  768. int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
  769. container->message = message_;
  770. return 0;
  771. }
  772. int VisitMapContainer(MapContainer* container) {
  773. container->message = message_;
  774. return 0;
  775. }
  776. private:
  777. Message* message_;
  778. };
  779. int AssureWritable(CMessage* self) {
  780. if (self == NULL || !self->read_only) {
  781. return 0;
  782. }
  783. if (self->parent == NULL) {
  784. // If parent is NULL but we are trying to modify a read-only message, this
  785. // is a reference to a constant default instance that needs to be replaced
  786. // with a mutable top-level message.
  787. self->message = self->message->New();
  788. self->owner.reset(self->message);
  789. // Cascade the new owner to eventual children: even if this message is
  790. // empty, some submessages or repeated containers might exist already.
  791. SetOwner(self, self->owner);
  792. } else {
  793. // Otherwise, we need a mutable child message.
  794. if (AssureWritable(self->parent) == -1)
  795. return -1;
  796. // Make self->message writable.
  797. Message* mutable_message = GetMutableMessage(
  798. self->parent,
  799. self->parent_field_descriptor);
  800. if (mutable_message == NULL) {
  801. return -1;
  802. }
  803. self->message = mutable_message;
  804. }
  805. self->read_only = false;
  806. // When a CMessage is made writable its Message pointer is updated
  807. // to point to a new mutable Message. When that happens we need to
  808. // update any references to the old, read-only CMessage. There are
  809. // four places such references occur: RepeatedScalarContainer,
  810. // RepeatedCompositeContainer, MapContainer, and ExtensionDict.
  811. if (self->extensions != NULL)
  812. self->extensions->message = self->message;
  813. if (ForEachCompositeField(self, FixupMessageReference(self->message)) == -1)
  814. return -1;
  815. return 0;
  816. }
  817. // --- Globals:
  818. // Retrieve a C++ FieldDescriptor for a message attribute.
  819. // The C++ message must be valid.
  820. // TODO(amauryfa): This function should stay internal, because exception
  821. // handling is not consistent.
  822. static const FieldDescriptor* GetFieldDescriptor(
  823. CMessage* self, PyObject* name) {
  824. const Descriptor *message_descriptor = self->message->GetDescriptor();
  825. char* field_name;
  826. Py_ssize_t size;
  827. if (PyString_AsStringAndSize(name, &field_name, &size) < 0) {
  828. return NULL;
  829. }
  830. const FieldDescriptor *field_descriptor =
  831. message_descriptor->FindFieldByName(string(field_name, size));
  832. if (field_descriptor == NULL) {
  833. // Note: No exception is set!
  834. return NULL;
  835. }
  836. return field_descriptor;
  837. }
  838. // Retrieve a C++ FieldDescriptor for an extension handle.
  839. const FieldDescriptor* GetExtensionDescriptor(PyObject* extension) {
  840. ScopedPyObjectPtr cdescriptor;
  841. if (!PyObject_TypeCheck(extension, &PyFieldDescriptor_Type)) {
  842. // Most callers consider extensions as a plain dictionary. We should
  843. // allow input which is not a field descriptor, and simply pretend it does
  844. // not exist.
  845. PyErr_SetObject(PyExc_KeyError, extension);
  846. return NULL;
  847. }
  848. return PyFieldDescriptor_AsDescriptor(extension);
  849. }
  850. // If value is a string, convert it into an enum value based on the labels in
  851. // descriptor, otherwise simply return value. Always returns a new reference.
  852. static PyObject* GetIntegerEnumValue(const FieldDescriptor& descriptor,
  853. PyObject* value) {
  854. if (PyString_Check(value) || PyUnicode_Check(value)) {
  855. const EnumDescriptor* enum_descriptor = descriptor.enum_type();
  856. if (enum_descriptor == NULL) {
  857. PyErr_SetString(PyExc_TypeError, "not an enum field");
  858. return NULL;
  859. }
  860. char* enum_label;
  861. Py_ssize_t size;
  862. if (PyString_AsStringAndSize(value, &enum_label, &size) < 0) {
  863. return NULL;
  864. }
  865. const EnumValueDescriptor* enum_value_descriptor =
  866. enum_descriptor->FindValueByName(string(enum_label, size));
  867. if (enum_value_descriptor == NULL) {
  868. PyErr_SetString(PyExc_ValueError, "unknown enum label");
  869. return NULL;
  870. }
  871. return PyInt_FromLong(enum_value_descriptor->number());
  872. }
  873. Py_INCREF(value);
  874. return value;
  875. }
  876. // If cmessage_list is not NULL, this function releases values into the
  877. // container CMessages instead of just removing. Repeated composite container
  878. // needs to do this to make sure CMessages stay alive if they're still
  879. // referenced after deletion. Repeated scalar container doesn't need to worry.
  880. int InternalDeleteRepeatedField(
  881. CMessage* self,
  882. const FieldDescriptor* field_descriptor,
  883. PyObject* slice,
  884. PyObject* cmessage_list) {
  885. Message* message = self->message;
  886. Py_ssize_t length, from, to, step, slice_length;
  887. const Reflection* reflection = message->GetReflection();
  888. int min, max;
  889. length = reflection->FieldSize(*message, field_descriptor);
  890. if (PyInt_Check(slice) || PyLong_Check(slice)) {
  891. from = to = PyLong_AsLong(slice);
  892. if (from < 0) {
  893. from = to = length + from;
  894. }
  895. step = 1;
  896. min = max = from;
  897. // Range check.
  898. if (from < 0 || from >= length) {
  899. PyErr_Format(PyExc_IndexError, "list assignment index out of range");
  900. return -1;
  901. }
  902. } else if (PySlice_Check(slice)) {
  903. from = to = step = slice_length = 0;
  904. PySlice_GetIndicesEx(
  905. #if PY_MAJOR_VERSION < 3
  906. reinterpret_cast<PySliceObject*>(slice),
  907. #else
  908. slice,
  909. #endif
  910. length, &from, &to, &step, &slice_length);
  911. if (from < to) {
  912. min = from;
  913. max = to - 1;
  914. } else {
  915. min = to + 1;
  916. max = from;
  917. }
  918. } else {
  919. PyErr_SetString(PyExc_TypeError, "list indices must be integers");
  920. return -1;
  921. }
  922. Py_ssize_t i = from;
  923. std::vector<bool> to_delete(length, false);
  924. while (i >= min && i <= max) {
  925. to_delete[i] = true;
  926. i += step;
  927. }
  928. to = 0;
  929. for (i = 0; i < length; ++i) {
  930. if (!to_delete[i]) {
  931. if (i != to) {
  932. reflection->SwapElements(message, field_descriptor, i, to);
  933. if (cmessage_list != NULL) {
  934. // If a list of cmessages is passed in (i.e. from a repeated
  935. // composite container), swap those as well to correspond to the
  936. // swaps in the underlying message so they're in the right order
  937. // when we start releasing.
  938. PyObject* tmp = PyList_GET_ITEM(cmessage_list, i);
  939. PyList_SET_ITEM(cmessage_list, i,
  940. PyList_GET_ITEM(cmessage_list, to));
  941. PyList_SET_ITEM(cmessage_list, to, tmp);
  942. }
  943. }
  944. ++to;
  945. }
  946. }
  947. while (i > to) {
  948. if (cmessage_list == NULL) {
  949. reflection->RemoveLast(message, field_descriptor);
  950. } else {
  951. CMessage* last_cmessage = reinterpret_cast<CMessage*>(
  952. PyList_GET_ITEM(cmessage_list, PyList_GET_SIZE(cmessage_list) - 1));
  953. repeated_composite_container::ReleaseLastTo(
  954. self, field_descriptor, last_cmessage);
  955. if (PySequence_DelItem(cmessage_list, -1) < 0) {
  956. return -1;
  957. }
  958. }
  959. --i;
  960. }
  961. return 0;
  962. }
  963. // Initializes fields of a message. Used in constructors.
  964. int InitAttributes(CMessage* self, PyObject* kwargs) {
  965. if (kwargs == NULL) {
  966. return 0;
  967. }
  968. Py_ssize_t pos = 0;
  969. PyObject* name;
  970. PyObject* value;
  971. while (PyDict_Next(kwargs, &pos, &name, &value)) {
  972. if (!PyString_Check(name)) {
  973. PyErr_SetString(PyExc_ValueError, "Field name must be a string");
  974. return -1;
  975. }
  976. const FieldDescriptor* descriptor = GetFieldDescriptor(self, name);
  977. if (descriptor == NULL) {
  978. PyErr_Format(PyExc_ValueError, "Protocol message %s has no \"%s\" field.",
  979. self->message->GetDescriptor()->name().c_str(),
  980. PyString_AsString(name));
  981. return -1;
  982. }
  983. if (descriptor->is_map()) {
  984. ScopedPyObjectPtr map(GetAttr(self, name));
  985. const FieldDescriptor* value_descriptor =
  986. descriptor->message_type()->FindFieldByName("value");
  987. if (value_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  988. Py_ssize_t map_pos = 0;
  989. PyObject* map_key;
  990. PyObject* map_value;
  991. while (PyDict_Next(value, &map_pos, &map_key, &map_value)) {
  992. ScopedPyObjectPtr function_return;
  993. function_return.reset(PyObject_GetItem(map.get(), map_key));
  994. if (function_return.get() == NULL) {
  995. return -1;
  996. }
  997. ScopedPyObjectPtr ok(PyObject_CallMethod(
  998. function_return.get(), "MergeFrom", "O", map_value));
  999. if (ok.get() == NULL) {
  1000. return -1;
  1001. }
  1002. }
  1003. } else {
  1004. ScopedPyObjectPtr function_return;
  1005. function_return.reset(
  1006. PyObject_CallMethod(map.get(), "update", "O", value));
  1007. if (function_return.get() == NULL) {
  1008. return -1;
  1009. }
  1010. }
  1011. } else if (descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
  1012. ScopedPyObjectPtr container(GetAttr(self, name));
  1013. if (container == NULL) {
  1014. return -1;
  1015. }
  1016. if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  1017. RepeatedCompositeContainer* rc_container =
  1018. reinterpret_cast<RepeatedCompositeContainer*>(container.get());
  1019. ScopedPyObjectPtr iter(PyObject_GetIter(value));
  1020. if (iter == NULL) {
  1021. PyErr_SetString(PyExc_TypeError, "Value must be iterable");
  1022. return -1;
  1023. }
  1024. ScopedPyObjectPtr next;
  1025. while ((next.reset(PyIter_Next(iter.get()))) != NULL) {
  1026. PyObject* kwargs = (PyDict_Check(next.get()) ? next.get() : NULL);
  1027. ScopedPyObjectPtr new_msg(
  1028. repeated_composite_container::Add(rc_container, NULL, kwargs));
  1029. if (new_msg == NULL) {
  1030. return -1;
  1031. }
  1032. if (kwargs == NULL) {
  1033. // next was not a dict, it's a message we need to merge
  1034. ScopedPyObjectPtr merged(MergeFrom(
  1035. reinterpret_cast<CMessage*>(new_msg.get()), next.get()));
  1036. if (merged.get() == NULL) {
  1037. return -1;
  1038. }
  1039. }
  1040. }
  1041. if (PyErr_Occurred()) {
  1042. // Check to see how PyIter_Next() exited.
  1043. return -1;
  1044. }
  1045. } else if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
  1046. RepeatedScalarContainer* rs_container =
  1047. reinterpret_cast<RepeatedScalarContainer*>(container.get());
  1048. ScopedPyObjectPtr iter(PyObject_GetIter(value));
  1049. if (iter == NULL) {
  1050. PyErr_SetString(PyExc_TypeError, "Value must be iterable");
  1051. return -1;
  1052. }
  1053. ScopedPyObjectPtr next;
  1054. while ((next.reset(PyIter_Next(iter.get()))) != NULL) {
  1055. ScopedPyObjectPtr enum_value(
  1056. GetIntegerEnumValue(*descriptor, next.get()));
  1057. if (enum_value == NULL) {
  1058. return -1;
  1059. }
  1060. ScopedPyObjectPtr new_msg(repeated_scalar_container::Append(
  1061. rs_container, enum_value.get()));
  1062. if (new_msg == NULL) {
  1063. return -1;
  1064. }
  1065. }
  1066. if (PyErr_Occurred()) {
  1067. // Check to see how PyIter_Next() exited.
  1068. return -1;
  1069. }
  1070. } else {
  1071. if (ScopedPyObjectPtr(repeated_scalar_container::Extend(
  1072. reinterpret_cast<RepeatedScalarContainer*>(container.get()),
  1073. value)) ==
  1074. NULL) {
  1075. return -1;
  1076. }
  1077. }
  1078. } else if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  1079. ScopedPyObjectPtr message(GetAttr(self, name));
  1080. if (message == NULL) {
  1081. return -1;
  1082. }
  1083. CMessage* cmessage = reinterpret_cast<CMessage*>(message.get());
  1084. if (PyDict_Check(value)) {
  1085. if (InitAttributes(cmessage, value) < 0) {
  1086. return -1;
  1087. }
  1088. } else {
  1089. ScopedPyObjectPtr merged(MergeFrom(cmessage, value));
  1090. if (merged == NULL) {
  1091. return -1;
  1092. }
  1093. }
  1094. } else {
  1095. ScopedPyObjectPtr new_val;
  1096. if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
  1097. new_val.reset(GetIntegerEnumValue(*descriptor, value));
  1098. if (new_val == NULL) {
  1099. return -1;
  1100. }
  1101. }
  1102. if (SetAttr(self, name, (new_val.get() == NULL) ? value : new_val.get()) <
  1103. 0) {
  1104. return -1;
  1105. }
  1106. }
  1107. }
  1108. return 0;
  1109. }
  1110. // Allocates an incomplete Python Message: the caller must fill self->message,
  1111. // self->owner and eventually self->parent.
  1112. CMessage* NewEmptyMessage(PyObject* type, const Descriptor *descriptor) {
  1113. CMessage* self = reinterpret_cast<CMessage*>(
  1114. PyType_GenericAlloc(reinterpret_cast<PyTypeObject*>(type), 0));
  1115. if (self == NULL) {
  1116. return NULL;
  1117. }
  1118. self->message = NULL;
  1119. self->parent = NULL;
  1120. self->parent_field_descriptor = NULL;
  1121. self->read_only = false;
  1122. self->extensions = NULL;
  1123. self->composite_fields = NULL;
  1124. return self;
  1125. }
  1126. // The __new__ method of Message classes.
  1127. // Creates a new C++ message and takes ownership.
  1128. static PyObject* New(PyTypeObject* cls,
  1129. PyObject* unused_args, PyObject* unused_kwargs) {
  1130. PyMessageMeta* type = CheckMessageClass(cls);
  1131. if (type == NULL) {
  1132. return NULL;
  1133. }
  1134. // Retrieve the message descriptor and the default instance (=prototype).
  1135. const Descriptor* message_descriptor = type->message_descriptor;
  1136. if (message_descriptor == NULL) {
  1137. return NULL;
  1138. }
  1139. const Message* default_message = type->py_descriptor_pool->message_factory
  1140. ->GetPrototype(message_descriptor);
  1141. if (default_message == NULL) {
  1142. PyErr_SetString(PyExc_TypeError, message_descriptor->full_name().c_str());
  1143. return NULL;
  1144. }
  1145. CMessage* self = NewEmptyMessage(reinterpret_cast<PyObject*>(type),
  1146. message_descriptor);
  1147. if (self == NULL) {
  1148. return NULL;
  1149. }
  1150. self->message = default_message->New();
  1151. self->owner.reset(self->message);
  1152. return reinterpret_cast<PyObject*>(self);
  1153. }
  1154. // The __init__ method of Message classes.
  1155. // It initializes fields from keywords passed to the constructor.
  1156. static int Init(CMessage* self, PyObject* args, PyObject* kwargs) {
  1157. if (PyTuple_Size(args) != 0) {
  1158. PyErr_SetString(PyExc_TypeError, "No positional arguments allowed");
  1159. return -1;
  1160. }
  1161. return InitAttributes(self, kwargs);
  1162. }
  1163. // ---------------------------------------------------------------------
  1164. // Deallocating a CMessage
  1165. //
  1166. // Deallocating a CMessage requires that we clear any weak references
  1167. // from children to the message being deallocated.
  1168. // Clear the weak reference from the child to the parent.
  1169. struct ClearWeakReferences : public ChildVisitor {
  1170. int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
  1171. container->parent = NULL;
  1172. // The elements in the container have the same parent as the
  1173. // container itself, so NULL out that pointer as well.
  1174. const Py_ssize_t n = PyList_GET_SIZE(container->child_messages);
  1175. for (Py_ssize_t i = 0; i < n; ++i) {
  1176. CMessage* child_cmessage = reinterpret_cast<CMessage*>(
  1177. PyList_GET_ITEM(container->child_messages, i));
  1178. child_cmessage->parent = NULL;
  1179. }
  1180. return 0;
  1181. }
  1182. int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
  1183. container->parent = NULL;
  1184. return 0;
  1185. }
  1186. int VisitMapContainer(MapContainer* container) {
  1187. container->parent = NULL;
  1188. return 0;
  1189. }
  1190. int VisitCMessage(CMessage* cmessage,
  1191. const FieldDescriptor* field_descriptor) {
  1192. cmessage->parent = NULL;
  1193. return 0;
  1194. }
  1195. };
  1196. static void Dealloc(CMessage* self) {
  1197. // Null out all weak references from children to this message.
  1198. GOOGLE_CHECK_EQ(0, ForEachCompositeField(self, ClearWeakReferences()));
  1199. if (self->extensions) {
  1200. self->extensions->parent = NULL;
  1201. }
  1202. Py_CLEAR(self->extensions);
  1203. Py_CLEAR(self->composite_fields);
  1204. self->owner.reset();
  1205. Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
  1206. }
  1207. // ---------------------------------------------------------------------
  1208. PyObject* IsInitialized(CMessage* self, PyObject* args) {
  1209. PyObject* errors = NULL;
  1210. if (PyArg_ParseTuple(args, "|O", &errors) < 0) {
  1211. return NULL;
  1212. }
  1213. if (self->message->IsInitialized()) {
  1214. Py_RETURN_TRUE;
  1215. }
  1216. if (errors != NULL) {
  1217. ScopedPyObjectPtr initialization_errors(
  1218. FindInitializationErrors(self));
  1219. if (initialization_errors == NULL) {
  1220. return NULL;
  1221. }
  1222. ScopedPyObjectPtr extend_name(PyString_FromString("extend"));
  1223. if (extend_name == NULL) {
  1224. return NULL;
  1225. }
  1226. ScopedPyObjectPtr result(PyObject_CallMethodObjArgs(
  1227. errors,
  1228. extend_name.get(),
  1229. initialization_errors.get(),
  1230. NULL));
  1231. if (result == NULL) {
  1232. return NULL;
  1233. }
  1234. }
  1235. Py_RETURN_FALSE;
  1236. }
  1237. PyObject* HasFieldByDescriptor(
  1238. CMessage* self, const FieldDescriptor* field_descriptor) {
  1239. Message* message = self->message;
  1240. if (!CheckFieldBelongsToMessage(field_descriptor, message)) {
  1241. return NULL;
  1242. }
  1243. if (field_descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
  1244. PyErr_SetString(PyExc_KeyError,
  1245. "Field is repeated. A singular method is required.");
  1246. return NULL;
  1247. }
  1248. bool has_field =
  1249. message->GetReflection()->HasField(*message, field_descriptor);
  1250. return PyBool_FromLong(has_field ? 1 : 0);
  1251. }
  1252. const FieldDescriptor* FindFieldWithOneofs(
  1253. const Message* message, const string& field_name, bool* in_oneof) {
  1254. *in_oneof = false;
  1255. const Descriptor* descriptor = message->GetDescriptor();
  1256. const FieldDescriptor* field_descriptor =
  1257. descriptor->FindFieldByName(field_name);
  1258. if (field_descriptor != NULL) {
  1259. return field_descriptor;
  1260. }
  1261. const OneofDescriptor* oneof_desc =
  1262. descriptor->FindOneofByName(field_name);
  1263. if (oneof_desc != NULL) {
  1264. *in_oneof = true;
  1265. return message->GetReflection()->GetOneofFieldDescriptor(*message,
  1266. oneof_desc);
  1267. }
  1268. return NULL;
  1269. }
  1270. bool CheckHasPresence(const FieldDescriptor* field_descriptor, bool in_oneof) {
  1271. if (field_descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
  1272. PyErr_Format(PyExc_ValueError,
  1273. "Protocol message has no singular \"%s\" field.",
  1274. field_descriptor->name().c_str());
  1275. return false;
  1276. }
  1277. if (field_descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
  1278. // HasField() for a oneof *itself* isn't supported.
  1279. if (in_oneof) {
  1280. PyErr_Format(PyExc_ValueError,
  1281. "Can't test oneof field \"%s\" for presence in proto3, use "
  1282. "WhichOneof instead.",
  1283. field_descriptor->containing_oneof()->name().c_str());
  1284. return false;
  1285. }
  1286. // ...but HasField() for fields *in* a oneof is supported.
  1287. if (field_descriptor->containing_oneof() != NULL) {
  1288. return true;
  1289. }
  1290. if (field_descriptor->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
  1291. PyErr_Format(
  1292. PyExc_ValueError,
  1293. "Can't test non-submessage field \"%s\" for presence in proto3.",
  1294. field_descriptor->name().c_str());
  1295. return false;
  1296. }
  1297. }
  1298. return true;
  1299. }
  1300. PyObject* HasField(CMessage* self, PyObject* arg) {
  1301. char* field_name;
  1302. Py_ssize_t size;
  1303. #if PY_MAJOR_VERSION < 3
  1304. if (PyString_AsStringAndSize(arg, &field_name, &size) < 0) {
  1305. return NULL;
  1306. }
  1307. #else
  1308. field_name = PyUnicode_AsUTF8AndSize(arg, &size);
  1309. if (!field_name) {
  1310. return NULL;
  1311. }
  1312. #endif
  1313. Message* message = self->message;
  1314. bool is_in_oneof;
  1315. const FieldDescriptor* field_descriptor =
  1316. FindFieldWithOneofs(message, string(field_name, size), &is_in_oneof);
  1317. if (field_descriptor == NULL) {
  1318. if (!is_in_oneof) {
  1319. PyErr_Format(PyExc_ValueError, "Unknown field %s.", field_name);
  1320. return NULL;
  1321. } else {
  1322. Py_RETURN_FALSE;
  1323. }
  1324. }
  1325. if (!CheckHasPresence(field_descriptor, is_in_oneof)) {
  1326. return NULL;
  1327. }
  1328. if (message->GetReflection()->HasField(*message, field_descriptor)) {
  1329. Py_RETURN_TRUE;
  1330. }
  1331. if (!message->GetReflection()->SupportsUnknownEnumValues() &&
  1332. field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
  1333. // Special case: Python HasField() differs in semantics from C++
  1334. // slightly: we return HasField('enum_field') == true if there is
  1335. // an unknown enum value present. To implement this we have to
  1336. // look in the UnknownFieldSet.
  1337. const UnknownFieldSet& unknown_field_set =
  1338. message->GetReflection()->GetUnknownFields(*message);
  1339. for (int i = 0; i < unknown_field_set.field_count(); ++i) {
  1340. if (unknown_field_set.field(i).number() == field_descriptor->number()) {
  1341. Py_RETURN_TRUE;
  1342. }
  1343. }
  1344. }
  1345. Py_RETURN_FALSE;
  1346. }
  1347. PyObject* ClearExtension(CMessage* self, PyObject* extension) {
  1348. if (self->extensions != NULL) {
  1349. return extension_dict::ClearExtension(self->extensions, extension);
  1350. } else {
  1351. const FieldDescriptor* descriptor = GetExtensionDescriptor(extension);
  1352. if (descriptor == NULL) {
  1353. return NULL;
  1354. }
  1355. if (ScopedPyObjectPtr(ClearFieldByDescriptor(self, descriptor)) == NULL) {
  1356. return NULL;
  1357. }
  1358. }
  1359. Py_RETURN_NONE;
  1360. }
  1361. PyObject* HasExtension(CMessage* self, PyObject* extension) {
  1362. const FieldDescriptor* descriptor = GetExtensionDescriptor(extension);
  1363. if (descriptor == NULL) {
  1364. return NULL;
  1365. }
  1366. return HasFieldByDescriptor(self, descriptor);
  1367. }
  1368. // ---------------------------------------------------------------------
  1369. // Releasing messages
  1370. //
  1371. // The Python API's ClearField() and Clear() methods behave
  1372. // differently than their C++ counterparts. While the C++ versions
  1373. // clears the children the Python versions detaches the children,
  1374. // without touching their content. This impedance mismatch causes
  1375. // some complexity in the implementation, which is captured in this
  1376. // section.
  1377. //
  1378. // When a CMessage field is cleared we need to:
  1379. //
  1380. // * Release the Message used as the backing store for the CMessage
  1381. // from its parent.
  1382. //
  1383. // * Change the owner field of the released CMessage and all of its
  1384. // children to point to the newly released Message.
  1385. //
  1386. // * Clear the weak references from the released CMessage to the
  1387. // parent.
  1388. //
  1389. // When a RepeatedCompositeContainer field is cleared we need to:
  1390. //
  1391. // * Release all the Message used as the backing store for the
  1392. // CMessages stored in the container.
  1393. //
  1394. // * Change the owner field of all the released CMessage and all of
  1395. // their children to point to the newly released Messages.
  1396. //
  1397. // * Clear the weak references from the released container to the
  1398. // parent.
  1399. struct SetOwnerVisitor : public ChildVisitor {
  1400. // new_owner must outlive this object.
  1401. explicit SetOwnerVisitor(const shared_ptr<Message>& new_owner)
  1402. : new_owner_(new_owner) {}
  1403. int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
  1404. repeated_composite_container::SetOwner(container, new_owner_);
  1405. return 0;
  1406. }
  1407. int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
  1408. repeated_scalar_container::SetOwner(container, new_owner_);
  1409. return 0;
  1410. }
  1411. int VisitMapContainer(MapContainer* container) {
  1412. container->SetOwner(new_owner_);
  1413. return 0;
  1414. }
  1415. int VisitCMessage(CMessage* cmessage,
  1416. const FieldDescriptor* field_descriptor) {
  1417. return SetOwner(cmessage, new_owner_);
  1418. }
  1419. private:
  1420. const shared_ptr<Message>& new_owner_;
  1421. };
  1422. // Change the owner of this CMessage and all its children, recursively.
  1423. int SetOwner(CMessage* self, const shared_ptr<Message>& new_owner) {
  1424. self->owner = new_owner;
  1425. if (ForEachCompositeField(self, SetOwnerVisitor(new_owner)) == -1)
  1426. return -1;
  1427. return 0;
  1428. }
  1429. // Releases the message specified by 'field' and returns the
  1430. // pointer. If the field does not exist a new message is created using
  1431. // 'descriptor'. The caller takes ownership of the returned pointer.
  1432. Message* ReleaseMessage(CMessage* self,
  1433. const Descriptor* descriptor,
  1434. const FieldDescriptor* field_descriptor) {
  1435. MessageFactory* message_factory = GetFactoryForMessage(self);
  1436. Message* released_message = self->message->GetReflection()->ReleaseMessage(
  1437. self->message, field_descriptor, message_factory);
  1438. // ReleaseMessage will return NULL which differs from
  1439. // child_cmessage->message, if the field does not exist. In this case,
  1440. // the latter points to the default instance via a const_cast<>, so we
  1441. // have to reset it to a new mutable object since we are taking ownership.
  1442. if (released_message == NULL) {
  1443. const Message* prototype = message_factory->GetPrototype(descriptor);
  1444. GOOGLE_DCHECK(prototype != NULL);
  1445. released_message = prototype->New();
  1446. }
  1447. return released_message;
  1448. }
  1449. int ReleaseSubMessage(CMessage* self,
  1450. const FieldDescriptor* field_descriptor,
  1451. CMessage* child_cmessage) {
  1452. // Release the Message
  1453. shared_ptr<Message> released_message(ReleaseMessage(
  1454. self, child_cmessage->message->GetDescriptor(), field_descriptor));
  1455. child_cmessage->message = released_message.get();
  1456. child_cmessage->owner.swap(released_message);
  1457. child_cmessage->parent = NULL;
  1458. child_cmessage->parent_field_descriptor = NULL;
  1459. child_cmessage->read_only = false;
  1460. return ForEachCompositeField(child_cmessage,
  1461. SetOwnerVisitor(child_cmessage->owner));
  1462. }
  1463. struct ReleaseChild : public ChildVisitor {
  1464. // message must outlive this object.
  1465. explicit ReleaseChild(CMessage* parent) :
  1466. parent_(parent) {}
  1467. int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
  1468. return repeated_composite_container::Release(
  1469. reinterpret_cast<RepeatedCompositeContainer*>(container));
  1470. }
  1471. int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
  1472. return repeated_scalar_container::Release(
  1473. reinterpret_cast<RepeatedScalarContainer*>(container));
  1474. }
  1475. int VisitMapContainer(MapContainer* container) {
  1476. return reinterpret_cast<MapContainer*>(container)->Release();
  1477. }
  1478. int VisitCMessage(CMessage* cmessage,
  1479. const FieldDescriptor* field_descriptor) {
  1480. return ReleaseSubMessage(parent_, field_descriptor,
  1481. reinterpret_cast<CMessage*>(cmessage));
  1482. }
  1483. CMessage* parent_;
  1484. };
  1485. int InternalReleaseFieldByDescriptor(
  1486. CMessage* self,
  1487. const FieldDescriptor* field_descriptor,
  1488. PyObject* composite_field) {
  1489. return VisitCompositeField(
  1490. field_descriptor,
  1491. composite_field,
  1492. ReleaseChild(self));
  1493. }
  1494. PyObject* ClearFieldByDescriptor(
  1495. CMessage* self,
  1496. const FieldDescriptor* descriptor) {
  1497. if (!CheckFieldBelongsToMessage(descriptor, self->message)) {
  1498. return NULL;
  1499. }
  1500. AssureWritable(self);
  1501. self->message->GetReflection()->ClearField(self->message, descriptor);
  1502. Py_RETURN_NONE;
  1503. }
  1504. PyObject* ClearField(CMessage* self, PyObject* arg) {
  1505. if (!PyString_Check(arg)) {
  1506. PyErr_SetString(PyExc_TypeError, "field name must be a string");
  1507. return NULL;
  1508. }
  1509. #if PY_MAJOR_VERSION < 3
  1510. const char* field_name = PyString_AS_STRING(arg);
  1511. Py_ssize_t size = PyString_GET_SIZE(arg);
  1512. #else
  1513. Py_ssize_t size;
  1514. const char* field_name = PyUnicode_AsUTF8AndSize(arg, &size);
  1515. #endif
  1516. AssureWritable(self);
  1517. Message* message = self->message;
  1518. ScopedPyObjectPtr arg_in_oneof;
  1519. bool is_in_oneof;
  1520. const FieldDescriptor* field_descriptor =
  1521. FindFieldWithOneofs(message, string(field_name, size), &is_in_oneof);
  1522. if (field_descriptor == NULL) {
  1523. if (!is_in_oneof) {
  1524. PyErr_Format(PyExc_ValueError,
  1525. "Protocol message has no \"%s\" field.", field_name);
  1526. return NULL;
  1527. } else {
  1528. Py_RETURN_NONE;
  1529. }
  1530. } else if (is_in_oneof) {
  1531. const string& name = field_descriptor->name();
  1532. arg_in_oneof.reset(PyString_FromStringAndSize(name.c_str(), name.size()));
  1533. arg = arg_in_oneof.get();
  1534. }
  1535. PyObject* composite_field = self->composite_fields ?
  1536. PyDict_GetItem(self->composite_fields, arg) : NULL;
  1537. // Only release the field if there's a possibility that there are
  1538. // references to it.
  1539. if (composite_field != NULL) {
  1540. if (InternalReleaseFieldByDescriptor(self, field_descriptor,
  1541. composite_field) < 0) {
  1542. return NULL;
  1543. }
  1544. PyDict_DelItem(self->composite_fields, arg);
  1545. }
  1546. message->GetReflection()->ClearField(message, field_descriptor);
  1547. if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_ENUM &&
  1548. !message->GetReflection()->SupportsUnknownEnumValues()) {
  1549. UnknownFieldSet* unknown_field_set =
  1550. message->GetReflection()->MutableUnknownFields(message);
  1551. unknown_field_set->DeleteByNumber(field_descriptor->number());
  1552. }
  1553. Py_RETURN_NONE;
  1554. }
  1555. PyObject* Clear(CMessage* self) {
  1556. AssureWritable(self);
  1557. if (ForEachCompositeField(self, ReleaseChild(self)) == -1)
  1558. return NULL;
  1559. Py_CLEAR(self->extensions);
  1560. if (self->composite_fields) {
  1561. PyDict_Clear(self->composite_fields);
  1562. }
  1563. self->message->Clear();
  1564. Py_RETURN_NONE;
  1565. }
  1566. // ---------------------------------------------------------------------
  1567. static string GetMessageName(CMessage* self) {
  1568. if (self->parent_field_descriptor != NULL) {
  1569. return self->parent_field_descriptor->full_name();
  1570. } else {
  1571. return self->message->GetDescriptor()->full_name();
  1572. }
  1573. }
  1574. static PyObject* SerializeToString(CMessage* self, PyObject* args) {
  1575. if (!self->message->IsInitialized()) {
  1576. ScopedPyObjectPtr errors(FindInitializationErrors(self));
  1577. if (errors == NULL) {
  1578. return NULL;
  1579. }
  1580. ScopedPyObjectPtr comma(PyString_FromString(","));
  1581. if (comma == NULL) {
  1582. return NULL;
  1583. }
  1584. ScopedPyObjectPtr joined(
  1585. PyObject_CallMethod(comma.get(), "join", "O", errors.get()));
  1586. if (joined == NULL) {
  1587. return NULL;
  1588. }
  1589. // TODO(haberman): this is a (hopefully temporary) hack. The unit testing
  1590. // infrastructure reloads all pure-Python modules for every test, but not
  1591. // C++ modules (because that's generally impossible:
  1592. // http://bugs.python.org/issue1144263). But if we cache EncodeError, we'll
  1593. // return the EncodeError from a previous load of the module, which won't
  1594. // match a user's attempt to catch EncodeError. So we have to look it up
  1595. // again every time.
  1596. ScopedPyObjectPtr message_module(PyImport_ImportModule(
  1597. "google.protobuf.message"));
  1598. if (message_module.get() == NULL) {
  1599. return NULL;
  1600. }
  1601. ScopedPyObjectPtr encode_error(
  1602. PyObject_GetAttrString(message_module.get(), "EncodeError"));
  1603. if (encode_error.get() == NULL) {
  1604. return NULL;
  1605. }
  1606. PyErr_Format(encode_error.get(),
  1607. "Message %s is missing required fields: %s",
  1608. GetMessageName(self).c_str(), PyString_AsString(joined.get()));
  1609. return NULL;
  1610. }
  1611. int size = self->message->ByteSize();
  1612. if (size <= 0) {
  1613. return PyBytes_FromString("");
  1614. }
  1615. PyObject* result = PyBytes_FromStringAndSize(NULL, size);
  1616. if (result == NULL) {
  1617. return NULL;
  1618. }
  1619. char* buffer = PyBytes_AS_STRING(result);
  1620. self->message->SerializeWithCachedSizesToArray(
  1621. reinterpret_cast<uint8*>(buffer));
  1622. return result;
  1623. }
  1624. static PyObject* SerializePartialToString(CMessage* self) {
  1625. string contents;
  1626. self->message->SerializePartialToString(&contents);
  1627. return PyBytes_FromStringAndSize(contents.c_str(), contents.size());
  1628. }
  1629. // Formats proto fields for ascii dumps using python formatting functions where
  1630. // appropriate.
  1631. class PythonFieldValuePrinter : public TextFormat::FieldValuePrinter {
  1632. public:
  1633. // Python has some differences from C++ when printing floating point numbers.
  1634. //
  1635. // 1) Trailing .0 is always printed.
  1636. // 2) (Python2) Output is rounded to 12 digits.
  1637. // 3) (Python3) The full precision of the double is preserved (and Python uses
  1638. // David M. Gay's dtoa(), when the C++ code uses SimpleDtoa. There are some
  1639. // differences, but they rarely happen)
  1640. //
  1641. // We override floating point printing with the C-API function for printing
  1642. // Python floats to ensure consistency.
  1643. string PrintFloat(float value) const { return PrintDouble(value); }
  1644. string PrintDouble(double value) const {
  1645. // This implementation is not highly optimized (it allocates two temporary
  1646. // Python objects) but it is simple and portable. If this is shown to be a
  1647. // performance bottleneck, we can optimize it, but the results will likely
  1648. // be more complicated to accommodate the differing behavior of double
  1649. // formatting between Python 2 and Python 3.
  1650. //
  1651. // (Though a valid question is: do we really want to make out output
  1652. // dependent on the Python version?)
  1653. ScopedPyObjectPtr py_value(PyFloat_FromDouble(value));
  1654. if (!py_value.get()) {
  1655. return string();
  1656. }
  1657. ScopedPyObjectPtr py_str(PyObject_Str(py_value.get()));
  1658. if (!py_str.get()) {
  1659. return string();
  1660. }
  1661. return string(PyString_AsString(py_str.get()));
  1662. }
  1663. };
  1664. static PyObject* ToStr(CMessage* self) {
  1665. TextFormat::Printer printer;
  1666. // Passes ownership
  1667. printer.SetDefaultFieldValuePrinter(new PythonFieldValuePrinter());
  1668. printer.SetHideUnknownFields(true);
  1669. string output;
  1670. if (!printer.PrintToString(*self->message, &output)) {
  1671. PyErr_SetString(PyExc_ValueError, "Unable to convert message to str");
  1672. return NULL;
  1673. }
  1674. return PyString_FromString(output.c_str());
  1675. }
  1676. PyObject* MergeFrom(CMessage* self, PyObject* arg) {
  1677. CMessage* other_message;
  1678. if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg), &CMessage_Type)) {
  1679. PyErr_SetString(PyExc_TypeError, "Must be a message");
  1680. return NULL;
  1681. }
  1682. other_message = reinterpret_cast<CMessage*>(arg);
  1683. if (other_message->message->GetDescriptor() !=
  1684. self->message->GetDescriptor()) {
  1685. PyErr_Format(PyExc_TypeError,
  1686. "Tried to merge from a message with a different type. "
  1687. "to: %s, from: %s",
  1688. self->message->GetDescriptor()->full_name().c_str(),
  1689. other_message->message->GetDescriptor()->full_name().c_str());
  1690. return NULL;
  1691. }
  1692. AssureWritable(self);
  1693. // TODO(tibell): Message::MergeFrom might turn some child Messages
  1694. // into mutable messages, invalidating the message field in the
  1695. // corresponding CMessages. We should run a FixupMessageReferences
  1696. // pass here.
  1697. self->message->MergeFrom(*other_message->message);
  1698. Py_RETURN_NONE;
  1699. }
  1700. static PyObject* CopyFrom(CMessage* self, PyObject* arg) {
  1701. CMessage* other_message;
  1702. if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg), &CMessage_Type)) {
  1703. PyErr_SetString(PyExc_TypeError, "Must be a message");
  1704. return NULL;
  1705. }
  1706. other_message = reinterpret_cast<CMessage*>(arg);
  1707. if (self == other_message) {
  1708. Py_RETURN_NONE;
  1709. }
  1710. if (other_message->message->GetDescriptor() !=
  1711. self->message->GetDescriptor()) {
  1712. PyErr_Format(PyExc_TypeError,
  1713. "Tried to copy from a message with a different type. "
  1714. "to: %s, from: %s",
  1715. self->message->GetDescriptor()->full_name().c_str(),
  1716. other_message->message->GetDescriptor()->full_name().c_str());
  1717. return NULL;
  1718. }
  1719. AssureWritable(self);
  1720. // CopyFrom on the message will not clean up self->composite_fields,
  1721. // which can leave us in an inconsistent state, so clear it out here.
  1722. (void)ScopedPyObjectPtr(Clear(self));
  1723. self->message->CopyFrom(*other_message->message);
  1724. Py_RETURN_NONE;
  1725. }
  1726. // Protobuf has a 64MB limit built in, this variable will override this. Please
  1727. // do not enable this unless you fully understand the implications: protobufs
  1728. // must all be kept in memory at the same time, so if they grow too big you may
  1729. // get OOM errors. The protobuf APIs do not provide any tools for processing
  1730. // protobufs in chunks. If you have protos this big you should break them up if
  1731. // it is at all convenient to do so.
  1732. static bool allow_oversize_protos = false;
  1733. // Provide a method in the module to set allow_oversize_protos to a boolean
  1734. // value. This method returns the newly value of allow_oversize_protos.
  1735. static PyObject* SetAllowOversizeProtos(PyObject* m, PyObject* arg) {
  1736. if (!arg || !PyBool_Check(arg)) {
  1737. PyErr_SetString(PyExc_TypeError,
  1738. "Argument to SetAllowOversizeProtos must be boolean");
  1739. return NULL;
  1740. }
  1741. allow_oversize_protos = PyObject_IsTrue(arg);
  1742. if (allow_oversize_protos) {
  1743. Py_RETURN_TRUE;
  1744. } else {
  1745. Py_RETURN_FALSE;
  1746. }
  1747. }
  1748. static PyObject* MergeFromString(CMessage* self, PyObject* arg) {
  1749. const void* data;
  1750. Py_ssize_t data_length;
  1751. if (PyObject_AsReadBuffer(arg, &data, &data_length) < 0) {
  1752. return NULL;
  1753. }
  1754. AssureWritable(self);
  1755. io::CodedInputStream input(
  1756. reinterpret_cast<const uint8*>(data), data_length);
  1757. if (allow_oversize_protos) {
  1758. input.SetTotalBytesLimit(INT_MAX, INT_MAX);
  1759. }
  1760. PyDescriptorPool* pool = GetDescriptorPoolForMessage(self);
  1761. input.SetExtensionRegistry(pool->pool, pool->message_factory);
  1762. bool success = self->message->MergePartialFromCodedStream(&input);
  1763. if (success) {
  1764. return PyInt_FromLong(input.CurrentPosition());
  1765. } else {
  1766. PyErr_Format(DecodeError_class, "Error parsing message");
  1767. return NULL;
  1768. }
  1769. }
  1770. static PyObject* ParseFromString(CMessage* self, PyObject* arg) {
  1771. if (ScopedPyObjectPtr(Clear(self)) == NULL) {
  1772. return NULL;
  1773. }
  1774. return MergeFromString(self, arg);
  1775. }
  1776. static PyObject* ByteSize(CMessage* self, PyObject* args) {
  1777. return PyLong_FromLong(self->message->ByteSize());
  1778. }
  1779. static PyObject* RegisterExtension(PyObject* cls,
  1780. PyObject* extension_handle) {
  1781. const FieldDescriptor* descriptor =
  1782. GetExtensionDescriptor(extension_handle);
  1783. if (descriptor == NULL) {
  1784. return NULL;
  1785. }
  1786. ScopedPyObjectPtr extensions_by_name(
  1787. PyObject_GetAttr(cls, k_extensions_by_name));
  1788. if (extensions_by_name == NULL) {
  1789. PyErr_SetString(PyExc_TypeError, "no extensions_by_name on class");
  1790. return NULL;
  1791. }
  1792. ScopedPyObjectPtr full_name(PyObject_GetAttr(extension_handle, kfull_name));
  1793. if (full_name == NULL) {
  1794. return NULL;
  1795. }
  1796. // If the extension was already registered, check that it is the same.
  1797. PyObject* existing_extension =
  1798. PyDict_GetItem(extensions_by_name.get(), full_name.get());
  1799. if (existing_extension != NULL) {
  1800. const FieldDescriptor* existing_extension_descriptor =
  1801. GetExtensionDescriptor(existing_extension);
  1802. if (existing_extension_descriptor != descriptor) {
  1803. PyErr_SetString(PyExc_ValueError, "Double registration of Extensions");
  1804. return NULL;
  1805. }
  1806. // Nothing else to do.
  1807. Py_RETURN_NONE;
  1808. }
  1809. if (PyDict_SetItem(extensions_by_name.get(), full_name.get(),
  1810. extension_handle) < 0) {
  1811. return NULL;
  1812. }
  1813. // Also store a mapping from extension number to implementing class.
  1814. ScopedPyObjectPtr extensions_by_number(
  1815. PyObject_GetAttr(cls, k_extensions_by_number));
  1816. if (extensions_by_number == NULL) {
  1817. PyErr_SetString(PyExc_TypeError, "no extensions_by_number on class");
  1818. return NULL;
  1819. }
  1820. ScopedPyObjectPtr number(PyObject_GetAttrString(extension_handle, "number"));
  1821. if (number == NULL) {
  1822. return NULL;
  1823. }
  1824. if (PyDict_SetItem(extensions_by_number.get(), number.get(),
  1825. extension_handle) < 0) {
  1826. return NULL;
  1827. }
  1828. // Check if it's a message set
  1829. if (descriptor->is_extension() &&
  1830. descriptor->containing_type()->options().message_set_wire_format() &&
  1831. descriptor->type() == FieldDescriptor::TYPE_MESSAGE &&
  1832. descriptor->label() == FieldDescriptor::LABEL_OPTIONAL) {
  1833. ScopedPyObjectPtr message_name(PyString_FromStringAndSize(
  1834. descriptor->message_type()->full_name().c_str(),
  1835. descriptor->message_type()->full_name().size()));
  1836. if (message_name == NULL) {
  1837. return NULL;
  1838. }
  1839. PyDict_SetItem(extensions_by_name.get(), message_name.get(),
  1840. extension_handle);
  1841. }
  1842. Py_RETURN_NONE;
  1843. }
  1844. static PyObject* SetInParent(CMessage* self, PyObject* args) {
  1845. AssureWritable(self);
  1846. Py_RETURN_NONE;
  1847. }
  1848. static PyObject* WhichOneof(CMessage* self, PyObject* arg) {
  1849. Py_ssize_t name_size;
  1850. char *name_data;
  1851. if (PyString_AsStringAndSize(arg, &name_data, &name_size) < 0)
  1852. return NULL;
  1853. string oneof_name = string(name_data, name_size);
  1854. const OneofDescriptor* oneof_desc =
  1855. self->message->GetDescriptor()->FindOneofByName(oneof_name);
  1856. if (oneof_desc == NULL) {
  1857. PyErr_Format(PyExc_ValueError,
  1858. "Protocol message has no oneof \"%s\" field.",
  1859. oneof_name.c_str());
  1860. return NULL;
  1861. }
  1862. const FieldDescriptor* field_in_oneof =
  1863. self->message->GetReflection()->GetOneofFieldDescriptor(
  1864. *self->message, oneof_desc);
  1865. if (field_in_oneof == NULL) {
  1866. Py_RETURN_NONE;
  1867. } else {
  1868. const string& name = field_in_oneof->name();
  1869. return PyString_FromStringAndSize(name.c_str(), name.size());
  1870. }
  1871. }
  1872. static PyObject* GetExtensionDict(CMessage* self, void *closure);
  1873. static PyObject* ListFields(CMessage* self) {
  1874. vector<const FieldDescriptor*> fields;
  1875. self->message->GetReflection()->ListFields(*self->message, &fields);
  1876. // Normally, the list will be exactly the size of the fields.
  1877. ScopedPyObjectPtr all_fields(PyList_New(fields.size()));
  1878. if (all_fields == NULL) {
  1879. return NULL;
  1880. }
  1881. // When there are unknown extensions, the py list will *not* contain
  1882. // the field information. Thus the actual size of the py list will be
  1883. // smaller than the size of fields. Set the actual size at the end.
  1884. Py_ssize_t actual_size = 0;
  1885. for (size_t i = 0; i < fields.size(); ++i) {
  1886. ScopedPyObjectPtr t(PyTuple_New(2));
  1887. if (t == NULL) {
  1888. return NULL;
  1889. }
  1890. if (fields[i]->is_extension()) {
  1891. ScopedPyObjectPtr extension_field(
  1892. PyFieldDescriptor_FromDescriptor(fields[i]));
  1893. if (extension_field == NULL) {
  1894. return NULL;
  1895. }
  1896. // With C++ descriptors, the field can always be retrieved, but for
  1897. // unknown extensions which have not been imported in Python code, there
  1898. // is no message class and we cannot retrieve the value.
  1899. // TODO(amauryfa): consider building the class on the fly!
  1900. if (fields[i]->message_type() != NULL &&
  1901. cdescriptor_pool::GetMessageClass(
  1902. GetDescriptorPoolForMessage(self),
  1903. fields[i]->message_type()) == NULL) {
  1904. PyErr_Clear();
  1905. continue;
  1906. }
  1907. ScopedPyObjectPtr extensions(GetExtensionDict(self, NULL));
  1908. if (extensions == NULL) {
  1909. return NULL;
  1910. }
  1911. // 'extension' reference later stolen by PyTuple_SET_ITEM.
  1912. PyObject* extension = PyObject_GetItem(
  1913. extensions.get(), extension_field.get());
  1914. if (extension == NULL) {
  1915. return NULL;
  1916. }
  1917. PyTuple_SET_ITEM(t.get(), 0, extension_field.release());
  1918. // Steals reference to 'extension'
  1919. PyTuple_SET_ITEM(t.get(), 1, extension);
  1920. } else {
  1921. // Normal field
  1922. const string& field_name = fields[i]->name();
  1923. ScopedPyObjectPtr py_field_name(PyString_FromStringAndSize(
  1924. field_name.c_str(), field_name.length()));
  1925. if (py_field_name == NULL) {
  1926. PyErr_SetString(PyExc_ValueError, "bad string");
  1927. return NULL;
  1928. }
  1929. ScopedPyObjectPtr field_descriptor(
  1930. PyFieldDescriptor_FromDescriptor(fields[i]));
  1931. if (field_descriptor == NULL) {
  1932. return NULL;
  1933. }
  1934. PyObject* field_value = GetAttr(self, py_field_name.get());
  1935. if (field_value == NULL) {
  1936. PyErr_SetObject(PyExc_ValueError, py_field_name.get());
  1937. return NULL;
  1938. }
  1939. PyTuple_SET_ITEM(t.get(), 0, field_descriptor.release());
  1940. PyTuple_SET_ITEM(t.get(), 1, field_value);
  1941. }
  1942. PyList_SET_ITEM(all_fields.get(), actual_size, t.release());
  1943. ++actual_size;
  1944. }
  1945. Py_SIZE(all_fields.get()) = actual_size;
  1946. return all_fields.release();
  1947. }
  1948. PyObject* FindInitializationErrors(CMessage* self) {
  1949. Message* message = self->message;
  1950. vector<string> errors;
  1951. message->FindInitializationErrors(&errors);
  1952. PyObject* error_list = PyList_New(errors.size());
  1953. if (error_list == NULL) {
  1954. return NULL;
  1955. }
  1956. for (size_t i = 0; i < errors.size(); ++i) {
  1957. const string& error = errors[i];
  1958. PyObject* error_string = PyString_FromStringAndSize(
  1959. error.c_str(), error.length());
  1960. if (error_string == NULL) {
  1961. Py_DECREF(error_list);
  1962. return NULL;
  1963. }
  1964. PyList_SET_ITEM(error_list, i, error_string);
  1965. }
  1966. return error_list;
  1967. }
  1968. static PyObject* RichCompare(CMessage* self, PyObject* other, int opid) {
  1969. // Only equality comparisons are implemented.
  1970. if (opid != Py_EQ && opid != Py_NE) {
  1971. Py_INCREF(Py_NotImplemented);
  1972. return Py_NotImplemented;
  1973. }
  1974. bool equals = true;
  1975. // If other is not a message, it cannot be equal.
  1976. if (!PyObject_TypeCheck(other, &CMessage_Type)) {
  1977. equals = false;
  1978. }
  1979. const google::protobuf::Message* other_message =
  1980. reinterpret_cast<CMessage*>(other)->message;
  1981. // If messages don't have the same descriptors, they are not equal.
  1982. if (equals &&
  1983. self->message->GetDescriptor() != other_message->GetDescriptor()) {
  1984. equals = false;
  1985. }
  1986. // Check the message contents.
  1987. if (equals && !google::protobuf::util::MessageDifferencer::Equals(
  1988. *self->message,
  1989. *reinterpret_cast<CMessage*>(other)->message)) {
  1990. equals = false;
  1991. }
  1992. if (equals ^ (opid == Py_EQ)) {
  1993. Py_RETURN_FALSE;
  1994. } else {
  1995. Py_RETURN_TRUE;
  1996. }
  1997. }
  1998. PyObject* InternalGetScalar(const Message* message,
  1999. const FieldDescriptor* field_descriptor) {
  2000. const Reflection* reflection = message->GetReflection();
  2001. if (!CheckFieldBelongsToMessage(field_descriptor, message)) {
  2002. return NULL;
  2003. }
  2004. PyObject* result = NULL;
  2005. switch (field_descriptor->cpp_type()) {
  2006. case FieldDescriptor::CPPTYPE_INT32: {
  2007. int32 value = reflection->GetInt32(*message, field_descriptor);
  2008. result = PyInt_FromLong(value);
  2009. break;
  2010. }
  2011. case FieldDescriptor::CPPTYPE_INT64: {
  2012. int64 value = reflection->GetInt64(*message, field_descriptor);
  2013. result = PyLong_FromLongLong(value);
  2014. break;
  2015. }
  2016. case FieldDescriptor::CPPTYPE_UINT32: {
  2017. uint32 value = reflection->GetUInt32(*message, field_descriptor);
  2018. result = PyInt_FromSize_t(value);
  2019. break;
  2020. }
  2021. case FieldDescriptor::CPPTYPE_UINT64: {
  2022. uint64 value = reflection->GetUInt64(*message, field_descriptor);
  2023. result = PyLong_FromUnsignedLongLong(value);
  2024. break;
  2025. }
  2026. case FieldDescriptor::CPPTYPE_FLOAT: {
  2027. float value = reflection->GetFloat(*message, field_descriptor);
  2028. result = PyFloat_FromDouble(value);
  2029. break;
  2030. }
  2031. case FieldDescriptor::CPPTYPE_DOUBLE: {
  2032. double value = reflection->GetDouble(*message, field_descriptor);
  2033. result = PyFloat_FromDouble(value);
  2034. break;
  2035. }
  2036. case FieldDescriptor::CPPTYPE_BOOL: {
  2037. bool value = reflection->GetBool(*message, field_descriptor);
  2038. result = PyBool_FromLong(value);
  2039. break;
  2040. }
  2041. case FieldDescriptor::CPPTYPE_STRING: {
  2042. string value = reflection->GetString(*message, field_descriptor);
  2043. result = ToStringObject(field_descriptor, value);
  2044. break;
  2045. }
  2046. case FieldDescriptor::CPPTYPE_ENUM: {
  2047. if (!message->GetReflection()->SupportsUnknownEnumValues() &&
  2048. !message->GetReflection()->HasField(*message, field_descriptor)) {
  2049. // Look for the value in the unknown fields.
  2050. const UnknownFieldSet& unknown_field_set =
  2051. message->GetReflection()->GetUnknownFields(*message);
  2052. for (int i = 0; i < unknown_field_set.field_count(); ++i) {
  2053. if (unknown_field_set.field(i).number() ==
  2054. field_descriptor->number() &&
  2055. unknown_field_set.field(i).type() ==
  2056. google::protobuf::UnknownField::TYPE_VARINT) {
  2057. result = PyInt_FromLong(unknown_field_set.field(i).varint());
  2058. break;
  2059. }
  2060. }
  2061. }
  2062. if (result == NULL) {
  2063. const EnumValueDescriptor* enum_value =
  2064. message->GetReflection()->GetEnum(*message, field_descriptor);
  2065. result = PyInt_FromLong(enum_value->number());
  2066. }
  2067. break;
  2068. }
  2069. default:
  2070. PyErr_Format(
  2071. PyExc_SystemError, "Getting a value from a field of unknown type %d",
  2072. field_descriptor->cpp_type());
  2073. }
  2074. return result;
  2075. }
  2076. PyObject* InternalGetSubMessage(
  2077. CMessage* self, const FieldDescriptor* field_descriptor) {
  2078. const Reflection* reflection = self->message->GetReflection();
  2079. PyDescriptorPool* pool = GetDescriptorPoolForMessage(self);
  2080. const Message& sub_message = reflection->GetMessage(
  2081. *self->message, field_descriptor, pool->message_factory);
  2082. PyObject *message_class = cdescriptor_pool::GetMessageClass(
  2083. pool, field_descriptor->message_type());
  2084. if (message_class == NULL) {
  2085. return NULL;
  2086. }
  2087. CMessage* cmsg = cmessage::NewEmptyMessage(message_class,
  2088. sub_message.GetDescriptor());
  2089. if (cmsg == NULL) {
  2090. return NULL;
  2091. }
  2092. cmsg->owner = self->owner;
  2093. cmsg->parent = self;
  2094. cmsg->parent_field_descriptor = field_descriptor;
  2095. cmsg->read_only = !reflection->HasField(*self->message, field_descriptor);
  2096. cmsg->message = const_cast<Message*>(&sub_message);
  2097. return reinterpret_cast<PyObject*>(cmsg);
  2098. }
  2099. int InternalSetNonOneofScalar(
  2100. Message* message,
  2101. const FieldDescriptor* field_descriptor,
  2102. PyObject* arg) {
  2103. const Reflection* reflection = message->GetReflection();
  2104. if (!CheckFieldBelongsToMessage(field_descriptor, message)) {
  2105. return -1;
  2106. }
  2107. switch (field_descriptor->cpp_type()) {
  2108. case FieldDescriptor::CPPTYPE_INT32: {
  2109. GOOGLE_CHECK_GET_INT32(arg, value, -1);
  2110. reflection->SetInt32(message, field_descriptor, value);
  2111. break;
  2112. }
  2113. case FieldDescriptor::CPPTYPE_INT64: {
  2114. GOOGLE_CHECK_GET_INT64(arg, value, -1);
  2115. reflection->SetInt64(message, field_descriptor, value);
  2116. break;
  2117. }
  2118. case FieldDescriptor::CPPTYPE_UINT32: {
  2119. GOOGLE_CHECK_GET_UINT32(arg, value, -1);
  2120. reflection->SetUInt32(message, field_descriptor, value);
  2121. break;
  2122. }
  2123. case FieldDescriptor::CPPTYPE_UINT64: {
  2124. GOOGLE_CHECK_GET_UINT64(arg, value, -1);
  2125. reflection->SetUInt64(message, field_descriptor, value);
  2126. break;
  2127. }
  2128. case FieldDescriptor::CPPTYPE_FLOAT: {
  2129. GOOGLE_CHECK_GET_FLOAT(arg, value, -1);
  2130. reflection->SetFloat(message, field_descriptor, value);
  2131. break;
  2132. }
  2133. case FieldDescriptor::CPPTYPE_DOUBLE: {
  2134. GOOGLE_CHECK_GET_DOUBLE(arg, value, -1);
  2135. reflection->SetDouble(message, field_descriptor, value);
  2136. break;
  2137. }
  2138. case FieldDescriptor::CPPTYPE_BOOL: {
  2139. GOOGLE_CHECK_GET_BOOL(arg, value, -1);
  2140. reflection->SetBool(message, field_descriptor, value);
  2141. break;
  2142. }
  2143. case FieldDescriptor::CPPTYPE_STRING: {
  2144. if (!CheckAndSetString(
  2145. arg, message, field_descriptor, reflection, false, -1)) {
  2146. return -1;
  2147. }
  2148. break;
  2149. }
  2150. case FieldDescriptor::CPPTYPE_ENUM: {
  2151. GOOGLE_CHECK_GET_INT32(arg, value, -1);
  2152. if (reflection->SupportsUnknownEnumValues()) {
  2153. reflection->SetEnumValue(message, field_descriptor, value);
  2154. } else {
  2155. const EnumDescriptor* enum_descriptor = field_descriptor->enum_type();
  2156. const EnumValueDescriptor* enum_value =
  2157. enum_descriptor->FindValueByNumber(value);
  2158. if (enum_value != NULL) {
  2159. reflection->SetEnum(message, field_descriptor, enum_value);
  2160. } else {
  2161. PyErr_Format(PyExc_ValueError, "Unknown enum value: %d", value);
  2162. return -1;
  2163. }
  2164. }
  2165. break;
  2166. }
  2167. default:
  2168. PyErr_Format(
  2169. PyExc_SystemError, "Setting value to a field of unknown type %d",
  2170. field_descriptor->cpp_type());
  2171. return -1;
  2172. }
  2173. return 0;
  2174. }
  2175. int InternalSetScalar(
  2176. CMessage* self,
  2177. const FieldDescriptor* field_descriptor,
  2178. PyObject* arg) {
  2179. if (!CheckFieldBelongsToMessage(field_descriptor, self->message)) {
  2180. return -1;
  2181. }
  2182. if (MaybeReleaseOverlappingOneofField(self, field_descriptor) < 0) {
  2183. return -1;
  2184. }
  2185. return InternalSetNonOneofScalar(self->message, field_descriptor, arg);
  2186. }
  2187. PyObject* FromString(PyTypeObject* cls, PyObject* serialized) {
  2188. PyObject* py_cmsg = PyObject_CallObject(
  2189. reinterpret_cast<PyObject*>(cls), NULL);
  2190. if (py_cmsg == NULL) {
  2191. return NULL;
  2192. }
  2193. CMessage* cmsg = reinterpret_cast<CMessage*>(py_cmsg);
  2194. ScopedPyObjectPtr py_length(MergeFromString(cmsg, serialized));
  2195. if (py_length == NULL) {
  2196. Py_DECREF(py_cmsg);
  2197. return NULL;
  2198. }
  2199. return py_cmsg;
  2200. }
  2201. PyObject* DeepCopy(CMessage* self, PyObject* arg) {
  2202. PyObject* clone = PyObject_CallObject(
  2203. reinterpret_cast<PyObject*>(Py_TYPE(self)), NULL);
  2204. if (clone == NULL) {
  2205. return NULL;
  2206. }
  2207. if (!PyObject_TypeCheck(clone, &CMessage_Type)) {
  2208. Py_DECREF(clone);
  2209. return NULL;
  2210. }
  2211. if (ScopedPyObjectPtr(MergeFrom(
  2212. reinterpret_cast<CMessage*>(clone),
  2213. reinterpret_cast<PyObject*>(self))) == NULL) {
  2214. Py_DECREF(clone);
  2215. return NULL;
  2216. }
  2217. return clone;
  2218. }
  2219. PyObject* ToUnicode(CMessage* self) {
  2220. // Lazy import to prevent circular dependencies
  2221. ScopedPyObjectPtr text_format(
  2222. PyImport_ImportModule("google.protobuf.text_format"));
  2223. if (text_format == NULL) {
  2224. return NULL;
  2225. }
  2226. ScopedPyObjectPtr method_name(PyString_FromString("MessageToString"));
  2227. if (method_name == NULL) {
  2228. return NULL;
  2229. }
  2230. Py_INCREF(Py_True);
  2231. ScopedPyObjectPtr encoded(PyObject_CallMethodObjArgs(
  2232. text_format.get(), method_name.get(), self, Py_True, NULL));
  2233. Py_DECREF(Py_True);
  2234. if (encoded == NULL) {
  2235. return NULL;
  2236. }
  2237. #if PY_MAJOR_VERSION < 3
  2238. PyObject* decoded = PyString_AsDecodedObject(encoded.get(), "utf-8", NULL);
  2239. #else
  2240. PyObject* decoded = PyUnicode_FromEncodedObject(encoded.get(), "utf-8", NULL);
  2241. #endif
  2242. if (decoded == NULL) {
  2243. return NULL;
  2244. }
  2245. return decoded;
  2246. }
  2247. PyObject* Reduce(CMessage* self) {
  2248. ScopedPyObjectPtr constructor(reinterpret_cast<PyObject*>(Py_TYPE(self)));
  2249. constructor.inc();
  2250. ScopedPyObjectPtr args(PyTuple_New(0));
  2251. if (args == NULL) {
  2252. return NULL;
  2253. }
  2254. ScopedPyObjectPtr state(PyDict_New());
  2255. if (state == NULL) {
  2256. return NULL;
  2257. }
  2258. ScopedPyObjectPtr serialized(SerializePartialToString(self));
  2259. if (serialized == NULL) {
  2260. return NULL;
  2261. }
  2262. if (PyDict_SetItemString(state.get(), "serialized", serialized.get()) < 0) {
  2263. return NULL;
  2264. }
  2265. return Py_BuildValue("OOO", constructor.get(), args.get(), state.get());
  2266. }
  2267. PyObject* SetState(CMessage* self, PyObject* state) {
  2268. if (!PyDict_Check(state)) {
  2269. PyErr_SetString(PyExc_TypeError, "state not a dict");
  2270. return NULL;
  2271. }
  2272. PyObject* serialized = PyDict_GetItemString(state, "serialized");
  2273. if (serialized == NULL) {
  2274. return NULL;
  2275. }
  2276. if (ScopedPyObjectPtr(ParseFromString(self, serialized)) == NULL) {
  2277. return NULL;
  2278. }
  2279. Py_RETURN_NONE;
  2280. }
  2281. // CMessage static methods:
  2282. PyObject* _CheckCalledFromGeneratedFile(PyObject* unused,
  2283. PyObject* unused_arg) {
  2284. if (!_CalledFromGeneratedFile(1)) {
  2285. PyErr_SetString(PyExc_TypeError,
  2286. "Descriptors should not be created directly, "
  2287. "but only retrieved from their parent.");
  2288. return NULL;
  2289. }
  2290. Py_RETURN_NONE;
  2291. }
  2292. static PyObject* GetExtensionDict(CMessage* self, void *closure) {
  2293. if (self->extensions) {
  2294. Py_INCREF(self->extensions);
  2295. return reinterpret_cast<PyObject*>(self->extensions);
  2296. }
  2297. // If there are extension_ranges, the message is "extendable". Allocate a
  2298. // dictionary to store the extension fields.
  2299. const Descriptor* descriptor = GetMessageDescriptor(Py_TYPE(self));
  2300. if (descriptor->extension_range_count() > 0) {
  2301. ExtensionDict* extension_dict = extension_dict::NewExtensionDict(self);
  2302. if (extension_dict == NULL) {
  2303. return NULL;
  2304. }
  2305. self->extensions = extension_dict;
  2306. Py_INCREF(self->extensions);
  2307. return reinterpret_cast<PyObject*>(self->extensions);
  2308. }
  2309. PyErr_SetNone(PyExc_AttributeError);
  2310. return NULL;
  2311. }
  2312. static PyGetSetDef Getters[] = {
  2313. {"Extensions", (getter)GetExtensionDict, NULL, "Extension dict"},
  2314. {NULL}
  2315. };
  2316. static PyMethodDef Methods[] = {
  2317. { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
  2318. "Makes a deep copy of the class." },
  2319. { "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
  2320. "Outputs picklable representation of the message." },
  2321. { "__setstate__", (PyCFunction)SetState, METH_O,
  2322. "Inputs picklable representation of the message." },
  2323. { "__unicode__", (PyCFunction)ToUnicode, METH_NOARGS,
  2324. "Outputs a unicode representation of the message." },
  2325. { "ByteSize", (PyCFunction)ByteSize, METH_NOARGS,
  2326. "Returns the size of the message in bytes." },
  2327. { "Clear", (PyCFunction)Clear, METH_NOARGS,
  2328. "Clears the message." },
  2329. { "ClearExtension", (PyCFunction)ClearExtension, METH_O,
  2330. "Clears a message field." },
  2331. { "ClearField", (PyCFunction)ClearField, METH_O,
  2332. "Clears a message field." },
  2333. { "CopyFrom", (PyCFunction)CopyFrom, METH_O,
  2334. "Copies a protocol message into the current message." },
  2335. { "FindInitializationErrors", (PyCFunction)FindInitializationErrors,
  2336. METH_NOARGS,
  2337. "Finds unset required fields." },
  2338. { "FromString", (PyCFunction)FromString, METH_O | METH_CLASS,
  2339. "Creates new method instance from given serialized data." },
  2340. { "HasExtension", (PyCFunction)HasExtension, METH_O,
  2341. "Checks if a message field is set." },
  2342. { "HasField", (PyCFunction)HasField, METH_O,
  2343. "Checks if a message field is set." },
  2344. { "IsInitialized", (PyCFunction)IsInitialized, METH_VARARGS,
  2345. "Checks if all required fields of a protocol message are set." },
  2346. { "ListFields", (PyCFunction)ListFields, METH_NOARGS,
  2347. "Lists all set fields of a message." },
  2348. { "MergeFrom", (PyCFunction)MergeFrom, METH_O,
  2349. "Merges a protocol message into the current message." },
  2350. { "MergeFromString", (PyCFunction)MergeFromString, METH_O,
  2351. "Merges a serialized message into the current message." },
  2352. { "ParseFromString", (PyCFunction)ParseFromString, METH_O,
  2353. "Parses a serialized message into the current message." },
  2354. { "RegisterExtension", (PyCFunction)RegisterExtension, METH_O | METH_CLASS,
  2355. "Registers an extension with the current message." },
  2356. { "SerializePartialToString", (PyCFunction)SerializePartialToString,
  2357. METH_NOARGS,
  2358. "Serializes the message to a string, even if it isn't initialized." },
  2359. { "SerializeToString", (PyCFunction)SerializeToString, METH_NOARGS,
  2360. "Serializes the message to a string, only for initialized messages." },
  2361. { "SetInParent", (PyCFunction)SetInParent, METH_NOARGS,
  2362. "Sets the has bit of the given field in its parent message." },
  2363. { "WhichOneof", (PyCFunction)WhichOneof, METH_O,
  2364. "Returns the name of the field set inside a oneof, "
  2365. "or None if no field is set." },
  2366. // Static Methods.
  2367. { "_CheckCalledFromGeneratedFile", (PyCFunction)_CheckCalledFromGeneratedFile,
  2368. METH_NOARGS | METH_STATIC,
  2369. "Raises TypeError if the caller is not in a _pb2.py file."},
  2370. { NULL, NULL}
  2371. };
  2372. static bool SetCompositeField(
  2373. CMessage* self, PyObject* name, PyObject* value) {
  2374. if (self->composite_fields == NULL) {
  2375. self->composite_fields = PyDict_New();
  2376. if (self->composite_fields == NULL) {
  2377. return false;
  2378. }
  2379. }
  2380. return PyDict_SetItem(self->composite_fields, name, value) == 0;
  2381. }
  2382. PyObject* GetAttr(CMessage* self, PyObject* name) {
  2383. PyObject* value = self->composite_fields ?
  2384. PyDict_GetItem(self->composite_fields, name) : NULL;
  2385. if (value != NULL) {
  2386. Py_INCREF(value);
  2387. return value;
  2388. }
  2389. const FieldDescriptor* field_descriptor = GetFieldDescriptor(self, name);
  2390. if (field_descriptor == NULL) {
  2391. return CMessage_Type.tp_base->tp_getattro(
  2392. reinterpret_cast<PyObject*>(self), name);
  2393. }
  2394. if (field_descriptor->is_map()) {
  2395. PyObject* py_container = NULL;
  2396. const Descriptor* entry_type = field_descriptor->message_type();
  2397. const FieldDescriptor* value_type = entry_type->FindFieldByName("value");
  2398. if (value_type->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  2399. PyObject* value_class = cdescriptor_pool::GetMessageClass(
  2400. GetDescriptorPoolForMessage(self), value_type->message_type());
  2401. if (value_class == NULL) {
  2402. return NULL;
  2403. }
  2404. py_container =
  2405. NewMessageMapContainer(self, field_descriptor, value_class);
  2406. } else {
  2407. py_container = NewScalarMapContainer(self, field_descriptor);
  2408. }
  2409. if (py_container == NULL) {
  2410. return NULL;
  2411. }
  2412. if (!SetCompositeField(self, name, py_container)) {
  2413. Py_DECREF(py_container);
  2414. return NULL;
  2415. }
  2416. return py_container;
  2417. }
  2418. if (field_descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
  2419. PyObject* py_container = NULL;
  2420. if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  2421. PyObject *message_class = cdescriptor_pool::GetMessageClass(
  2422. GetDescriptorPoolForMessage(self), field_descriptor->message_type());
  2423. if (message_class == NULL) {
  2424. return NULL;
  2425. }
  2426. py_container = repeated_composite_container::NewContainer(
  2427. self, field_descriptor, message_class);
  2428. } else {
  2429. py_container = repeated_scalar_container::NewContainer(
  2430. self, field_descriptor);
  2431. }
  2432. if (py_container == NULL) {
  2433. return NULL;
  2434. }
  2435. if (!SetCompositeField(self, name, py_container)) {
  2436. Py_DECREF(py_container);
  2437. return NULL;
  2438. }
  2439. return py_container;
  2440. }
  2441. if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  2442. PyObject* sub_message = InternalGetSubMessage(self, field_descriptor);
  2443. if (sub_message == NULL) {
  2444. return NULL;
  2445. }
  2446. if (!SetCompositeField(self, name, sub_message)) {
  2447. Py_DECREF(sub_message);
  2448. return NULL;
  2449. }
  2450. return sub_message;
  2451. }
  2452. return InternalGetScalar(self->message, field_descriptor);
  2453. }
  2454. int SetAttr(CMessage* self, PyObject* name, PyObject* value) {
  2455. if (self->composite_fields && PyDict_Contains(self->composite_fields, name)) {
  2456. PyErr_SetString(PyExc_TypeError, "Can't set composite field");
  2457. return -1;
  2458. }
  2459. const FieldDescriptor* field_descriptor = GetFieldDescriptor(self, name);
  2460. if (field_descriptor != NULL) {
  2461. AssureWritable(self);
  2462. if (field_descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
  2463. PyErr_Format(PyExc_AttributeError, "Assignment not allowed to repeated "
  2464. "field \"%s\" in protocol message object.",
  2465. field_descriptor->name().c_str());
  2466. return -1;
  2467. } else {
  2468. if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  2469. PyErr_Format(PyExc_AttributeError, "Assignment not allowed to "
  2470. "field \"%s\" in protocol message object.",
  2471. field_descriptor->name().c_str());
  2472. return -1;
  2473. } else {
  2474. return InternalSetScalar(self, field_descriptor, value);
  2475. }
  2476. }
  2477. }
  2478. PyErr_Format(PyExc_AttributeError,
  2479. "Assignment not allowed "
  2480. "(no field \"%s\"in protocol message object).",
  2481. PyString_AsString(name));
  2482. return -1;
  2483. }
  2484. } // namespace cmessage
  2485. PyTypeObject CMessage_Type = {
  2486. PyVarObject_HEAD_INIT(&PyMessageMeta_Type, 0)
  2487. FULL_MODULE_NAME ".CMessage", // tp_name
  2488. sizeof(CMessage), // tp_basicsize
  2489. 0, // tp_itemsize
  2490. (destructor)cmessage::Dealloc, // tp_dealloc
  2491. 0, // tp_print
  2492. 0, // tp_getattr
  2493. 0, // tp_setattr
  2494. 0, // tp_compare
  2495. 0, // tp_repr
  2496. 0, // tp_as_number
  2497. 0, // tp_as_sequence
  2498. 0, // tp_as_mapping
  2499. PyObject_HashNotImplemented, // tp_hash
  2500. 0, // tp_call
  2501. (reprfunc)cmessage::ToStr, // tp_str
  2502. (getattrofunc)cmessage::GetAttr, // tp_getattro
  2503. (setattrofunc)cmessage::SetAttr, // tp_setattro
  2504. 0, // tp_as_buffer
  2505. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
  2506. "A ProtocolMessage", // tp_doc
  2507. 0, // tp_traverse
  2508. 0, // tp_clear
  2509. (richcmpfunc)cmessage::RichCompare, // tp_richcompare
  2510. 0, // tp_weaklistoffset
  2511. 0, // tp_iter
  2512. 0, // tp_iternext
  2513. cmessage::Methods, // tp_methods
  2514. 0, // tp_members
  2515. cmessage::Getters, // tp_getset
  2516. 0, // tp_base
  2517. 0, // tp_dict
  2518. 0, // tp_descr_get
  2519. 0, // tp_descr_set
  2520. 0, // tp_dictoffset
  2521. (initproc)cmessage::Init, // tp_init
  2522. 0, // tp_alloc
  2523. cmessage::New, // tp_new
  2524. };
  2525. // --- Exposing the C proto living inside Python proto to C code:
  2526. const Message* (*GetCProtoInsidePyProtoPtr)(PyObject* msg);
  2527. Message* (*MutableCProtoInsidePyProtoPtr)(PyObject* msg);
  2528. static const Message* GetCProtoInsidePyProtoImpl(PyObject* msg) {
  2529. if (!PyObject_TypeCheck(msg, &CMessage_Type)) {
  2530. return NULL;
  2531. }
  2532. CMessage* cmsg = reinterpret_cast<CMessage*>(msg);
  2533. return cmsg->message;
  2534. }
  2535. static Message* MutableCProtoInsidePyProtoImpl(PyObject* msg) {
  2536. if (!PyObject_TypeCheck(msg, &CMessage_Type)) {
  2537. return NULL;
  2538. }
  2539. CMessage* cmsg = reinterpret_cast<CMessage*>(msg);
  2540. if ((cmsg->composite_fields && PyDict_Size(cmsg->composite_fields) != 0) ||
  2541. (cmsg->extensions != NULL &&
  2542. PyDict_Size(cmsg->extensions->values) != 0)) {
  2543. // There is currently no way of accurately syncing arbitrary changes to
  2544. // the underlying C++ message back to the CMessage (e.g. removed repeated
  2545. // composite containers). We only allow direct mutation of the underlying
  2546. // C++ message if there is no child data in the CMessage.
  2547. return NULL;
  2548. }
  2549. cmessage::AssureWritable(cmsg);
  2550. return cmsg->message;
  2551. }
  2552. static const char module_docstring[] =
  2553. "python-proto2 is a module that can be used to enhance proto2 Python API\n"
  2554. "performance.\n"
  2555. "\n"
  2556. "It provides access to the protocol buffers C++ reflection API that\n"
  2557. "implements the basic protocol buffer functions.";
  2558. void InitGlobals() {
  2559. // TODO(gps): Check all return values in this function for NULL and propagate
  2560. // the error (MemoryError) on up to result in an import failure. These should
  2561. // also be freed and reset to NULL during finalization.
  2562. kPythonZero = PyInt_FromLong(0);
  2563. kint32min_py = PyInt_FromLong(kint32min);
  2564. kint32max_py = PyInt_FromLong(kint32max);
  2565. kuint32max_py = PyLong_FromLongLong(kuint32max);
  2566. kint64min_py = PyLong_FromLongLong(kint64min);
  2567. kint64max_py = PyLong_FromLongLong(kint64max);
  2568. kuint64max_py = PyLong_FromUnsignedLongLong(kuint64max);
  2569. kDESCRIPTOR = PyString_FromString("DESCRIPTOR");
  2570. k_cdescriptor = PyString_FromString("_cdescriptor");
  2571. kfull_name = PyString_FromString("full_name");
  2572. k_extensions_by_name = PyString_FromString("_extensions_by_name");
  2573. k_extensions_by_number = PyString_FromString("_extensions_by_number");
  2574. PyObject *dummy_obj = PySet_New(NULL);
  2575. kEmptyWeakref = PyWeakref_NewRef(dummy_obj, NULL);
  2576. Py_DECREF(dummy_obj);
  2577. }
  2578. bool InitProto2MessageModule(PyObject *m) {
  2579. // Initialize types and globals in descriptor.cc
  2580. if (!InitDescriptor()) {
  2581. return false;
  2582. }
  2583. // Initialize types and globals in descriptor_pool.cc
  2584. if (!InitDescriptorPool()) {
  2585. return false;
  2586. }
  2587. // Initialize constants defined in this file.
  2588. InitGlobals();
  2589. PyMessageMeta_Type.tp_base = &PyType_Type;
  2590. if (PyType_Ready(&PyMessageMeta_Type) < 0) {
  2591. return false;
  2592. }
  2593. PyModule_AddObject(m, "MessageMeta",
  2594. reinterpret_cast<PyObject*>(&PyMessageMeta_Type));
  2595. if (PyType_Ready(&CMessage_Type) < 0) {
  2596. return false;
  2597. }
  2598. // DESCRIPTOR is set on each protocol buffer message class elsewhere, but set
  2599. // it here as well to document that subclasses need to set it.
  2600. PyDict_SetItem(CMessage_Type.tp_dict, kDESCRIPTOR, Py_None);
  2601. // Subclasses with message extensions will override _extensions_by_name and
  2602. // _extensions_by_number with fresh mutable dictionaries in AddDescriptors.
  2603. // All other classes can share this same immutable mapping.
  2604. ScopedPyObjectPtr empty_dict(PyDict_New());
  2605. if (empty_dict == NULL) {
  2606. return false;
  2607. }
  2608. ScopedPyObjectPtr immutable_dict(PyDictProxy_New(empty_dict.get()));
  2609. if (immutable_dict == NULL) {
  2610. return false;
  2611. }
  2612. if (PyDict_SetItem(CMessage_Type.tp_dict,
  2613. k_extensions_by_name, immutable_dict.get()) < 0) {
  2614. return false;
  2615. }
  2616. if (PyDict_SetItem(CMessage_Type.tp_dict,
  2617. k_extensions_by_number, immutable_dict.get()) < 0) {
  2618. return false;
  2619. }
  2620. PyModule_AddObject(m, "Message", reinterpret_cast<PyObject*>(&CMessage_Type));
  2621. // Initialize Repeated container types.
  2622. {
  2623. if (PyType_Ready(&RepeatedScalarContainer_Type) < 0) {
  2624. return false;
  2625. }
  2626. PyModule_AddObject(m, "RepeatedScalarContainer",
  2627. reinterpret_cast<PyObject*>(
  2628. &RepeatedScalarContainer_Type));
  2629. if (PyType_Ready(&RepeatedCompositeContainer_Type) < 0) {
  2630. return false;
  2631. }
  2632. PyModule_AddObject(
  2633. m, "RepeatedCompositeContainer",
  2634. reinterpret_cast<PyObject*>(
  2635. &RepeatedCompositeContainer_Type));
  2636. // Register them as collections.Sequence
  2637. ScopedPyObjectPtr collections(PyImport_ImportModule("collections"));
  2638. if (collections == NULL) {
  2639. return false;
  2640. }
  2641. ScopedPyObjectPtr mutable_sequence(
  2642. PyObject_GetAttrString(collections.get(), "MutableSequence"));
  2643. if (mutable_sequence == NULL) {
  2644. return false;
  2645. }
  2646. if (ScopedPyObjectPtr(
  2647. PyObject_CallMethod(mutable_sequence.get(), "register", "O",
  2648. &RepeatedScalarContainer_Type)) == NULL) {
  2649. return false;
  2650. }
  2651. if (ScopedPyObjectPtr(
  2652. PyObject_CallMethod(mutable_sequence.get(), "register", "O",
  2653. &RepeatedCompositeContainer_Type)) == NULL) {
  2654. return false;
  2655. }
  2656. }
  2657. // Initialize Map container types.
  2658. {
  2659. // ScalarMapContainer_Type derives from our MutableMapping type.
  2660. ScopedPyObjectPtr containers(PyImport_ImportModule(
  2661. "google.protobuf.internal.containers"));
  2662. if (containers == NULL) {
  2663. return false;
  2664. }
  2665. ScopedPyObjectPtr mutable_mapping(
  2666. PyObject_GetAttrString(containers.get(), "MutableMapping"));
  2667. if (mutable_mapping == NULL) {
  2668. return false;
  2669. }
  2670. if (!PyObject_TypeCheck(mutable_mapping.get(), &PyType_Type)) {
  2671. return false;
  2672. }
  2673. Py_INCREF(mutable_mapping.get());
  2674. #if PY_MAJOR_VERSION >= 3
  2675. PyObject* bases = PyTuple_New(1);
  2676. PyTuple_SET_ITEM(bases, 0, mutable_mapping.get());
  2677. ScalarMapContainer_Type =
  2678. PyType_FromSpecWithBases(&ScalarMapContainer_Type_spec, bases);
  2679. PyModule_AddObject(m, "ScalarMapContainer", ScalarMapContainer_Type);
  2680. #else
  2681. ScalarMapContainer_Type.tp_base =
  2682. reinterpret_cast<PyTypeObject*>(mutable_mapping.get());
  2683. if (PyType_Ready(&ScalarMapContainer_Type) < 0) {
  2684. return false;
  2685. }
  2686. PyModule_AddObject(m, "ScalarMapContainer",
  2687. reinterpret_cast<PyObject*>(&ScalarMapContainer_Type));
  2688. #endif
  2689. if (PyType_Ready(&MapIterator_Type) < 0) {
  2690. return false;
  2691. }
  2692. PyModule_AddObject(m, "MapIterator",
  2693. reinterpret_cast<PyObject*>(&MapIterator_Type));
  2694. #if PY_MAJOR_VERSION >= 3
  2695. MessageMapContainer_Type =
  2696. PyType_FromSpecWithBases(&MessageMapContainer_Type_spec, bases);
  2697. PyModule_AddObject(m, "MessageMapContainer", MessageMapContainer_Type);
  2698. #else
  2699. Py_INCREF(mutable_mapping.get());
  2700. MessageMapContainer_Type.tp_base =
  2701. reinterpret_cast<PyTypeObject*>(mutable_mapping.get());
  2702. if (PyType_Ready(&MessageMapContainer_Type) < 0) {
  2703. return false;
  2704. }
  2705. PyModule_AddObject(m, "MessageMapContainer",
  2706. reinterpret_cast<PyObject*>(&MessageMapContainer_Type));
  2707. #endif
  2708. }
  2709. if (PyType_Ready(&ExtensionDict_Type) < 0) {
  2710. return false;
  2711. }
  2712. PyModule_AddObject(
  2713. m, "ExtensionDict",
  2714. reinterpret_cast<PyObject*>(&ExtensionDict_Type));
  2715. // Expose the DescriptorPool used to hold all descriptors added from generated
  2716. // pb2.py files.
  2717. // PyModule_AddObject steals a reference.
  2718. Py_INCREF(GetDefaultDescriptorPool());
  2719. PyModule_AddObject(m, "default_pool",
  2720. reinterpret_cast<PyObject*>(GetDefaultDescriptorPool()));
  2721. PyModule_AddObject(m, "DescriptorPool", reinterpret_cast<PyObject*>(
  2722. &PyDescriptorPool_Type));
  2723. // This implementation provides full Descriptor types, we advertise it so that
  2724. // descriptor.py can use them in replacement of the Python classes.
  2725. PyModule_AddIntConstant(m, "_USE_C_DESCRIPTORS", 1);
  2726. PyModule_AddObject(m, "Descriptor", reinterpret_cast<PyObject*>(
  2727. &PyMessageDescriptor_Type));
  2728. PyModule_AddObject(m, "FieldDescriptor", reinterpret_cast<PyObject*>(
  2729. &PyFieldDescriptor_Type));
  2730. PyModule_AddObject(m, "EnumDescriptor", reinterpret_cast<PyObject*>(
  2731. &PyEnumDescriptor_Type));
  2732. PyModule_AddObject(m, "EnumValueDescriptor", reinterpret_cast<PyObject*>(
  2733. &PyEnumValueDescriptor_Type));
  2734. PyModule_AddObject(m, "FileDescriptor", reinterpret_cast<PyObject*>(
  2735. &PyFileDescriptor_Type));
  2736. PyModule_AddObject(m, "OneofDescriptor", reinterpret_cast<PyObject*>(
  2737. &PyOneofDescriptor_Type));
  2738. PyObject* enum_type_wrapper = PyImport_ImportModule(
  2739. "google.protobuf.internal.enum_type_wrapper");
  2740. if (enum_type_wrapper == NULL) {
  2741. return false;
  2742. }
  2743. EnumTypeWrapper_class =
  2744. PyObject_GetAttrString(enum_type_wrapper, "EnumTypeWrapper");
  2745. Py_DECREF(enum_type_wrapper);
  2746. PyObject* message_module = PyImport_ImportModule(
  2747. "google.protobuf.message");
  2748. if (message_module == NULL) {
  2749. return false;
  2750. }
  2751. EncodeError_class = PyObject_GetAttrString(message_module, "EncodeError");
  2752. DecodeError_class = PyObject_GetAttrString(message_module, "DecodeError");
  2753. PythonMessage_class = PyObject_GetAttrString(message_module, "Message");
  2754. Py_DECREF(message_module);
  2755. PyObject* pickle_module = PyImport_ImportModule("pickle");
  2756. if (pickle_module == NULL) {
  2757. return false;
  2758. }
  2759. PickleError_class = PyObject_GetAttrString(pickle_module, "PickleError");
  2760. Py_DECREF(pickle_module);
  2761. // Override {Get,Mutable}CProtoInsidePyProto.
  2762. GetCProtoInsidePyProtoPtr = GetCProtoInsidePyProtoImpl;
  2763. MutableCProtoInsidePyProtoPtr = MutableCProtoInsidePyProtoImpl;
  2764. return true;
  2765. }
  2766. } // namespace python
  2767. } // namespace protobuf
  2768. static PyMethodDef ModuleMethods[] = {
  2769. {"SetAllowOversizeProtos",
  2770. (PyCFunction)google::protobuf::python::cmessage::SetAllowOversizeProtos,
  2771. METH_O, "Enable/disable oversize proto parsing."},
  2772. };
  2773. #if PY_MAJOR_VERSION >= 3
  2774. static struct PyModuleDef _module = {
  2775. PyModuleDef_HEAD_INIT,
  2776. "_message",
  2777. google::protobuf::python::module_docstring,
  2778. -1,
  2779. ModuleMethods, /* m_methods */
  2780. NULL,
  2781. NULL,
  2782. NULL,
  2783. NULL
  2784. };
  2785. #define INITFUNC PyInit__message
  2786. #define INITFUNC_ERRORVAL NULL
  2787. #else // Python 2
  2788. #define INITFUNC init_message
  2789. #define INITFUNC_ERRORVAL
  2790. #endif
  2791. extern "C" {
  2792. PyMODINIT_FUNC INITFUNC(void) {
  2793. PyObject* m;
  2794. #if PY_MAJOR_VERSION >= 3
  2795. m = PyModule_Create(&_module);
  2796. #else
  2797. m = Py_InitModule3("_message", ModuleMethods,
  2798. google::protobuf::python::module_docstring);
  2799. #endif
  2800. if (m == NULL) {
  2801. return INITFUNC_ERRORVAL;
  2802. }
  2803. if (!google::protobuf::python::InitProto2MessageModule(m)) {
  2804. Py_DECREF(m);
  2805. return INITFUNC_ERRORVAL;
  2806. }
  2807. #if PY_MAJOR_VERSION >= 3
  2808. return m;
  2809. #endif
  2810. }
  2811. }
  2812. } // namespace google