店播爬取Python脚本

message.cc 107KB

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