message.cc 101 KB

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