message.cc 104 KB

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