message.cc 101 KB

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