message.cc 104 KB

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