message.cc 105 KB

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