message.cc 104 KB

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