message.cc 104 KB

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