message.cc 105 KB

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