message.cc 101 KB

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