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 
31 // This file defines a C++ DescriptorDatabase, which wraps a Python Database
32 // and delegate all its operations to Python methods.
33 
34 #include <google/protobuf/pyext/descriptor_database.h>
35 
36 #include <cstdint>
37 
38 #include <google/protobuf/stubs/logging.h>
39 #include <google/protobuf/stubs/common.h>
40 #include <google/protobuf/descriptor.pb.h>
41 #include <google/protobuf/pyext/message.h>
42 #include <google/protobuf/pyext/scoped_pyobject_ptr.h>
43 
44 namespace google {
45 namespace protobuf {
46 namespace python {
47 
PyDescriptorDatabase(PyObject * py_database)48 PyDescriptorDatabase::PyDescriptorDatabase(PyObject* py_database)
49     : py_database_(py_database) {
50   Py_INCREF(py_database_);
51 }
52 
~PyDescriptorDatabase()53 PyDescriptorDatabase::~PyDescriptorDatabase() { Py_DECREF(py_database_); }
54 
55 // Convert a Python object to a FileDescriptorProto pointer.
56 // Handles all kinds of Python errors, which are simply logged.
GetFileDescriptorProto(PyObject * py_descriptor,FileDescriptorProto * output)57 static bool GetFileDescriptorProto(PyObject* py_descriptor,
58                                    FileDescriptorProto* output) {
59   if (py_descriptor == NULL) {
60     if (PyErr_ExceptionMatches(PyExc_KeyError)) {
61       // Expected error: item was simply not found.
62       PyErr_Clear();
63     } else {
64       GOOGLE_LOG(ERROR) << "DescriptorDatabase method raised an error";
65       PyErr_Print();
66     }
67     return false;
68   }
69   if (py_descriptor == Py_None) {
70     return false;
71   }
72   const Descriptor* filedescriptor_descriptor =
73       FileDescriptorProto::default_instance().GetDescriptor();
74   CMessage* message = reinterpret_cast<CMessage*>(py_descriptor);
75   if (PyObject_TypeCheck(py_descriptor, CMessage_Type) &&
76       message->message->GetDescriptor() == filedescriptor_descriptor) {
77     // Fast path: Just use the pointer.
78     FileDescriptorProto* file_proto =
79         static_cast<FileDescriptorProto*>(message->message);
80     *output = *file_proto;
81     return true;
82   } else {
83     // Slow path: serialize the message. This allows to use databases which
84     // use a different implementation of FileDescriptorProto.
85     ScopedPyObjectPtr serialized_pb(
86         PyObject_CallMethod(py_descriptor, "SerializeToString", NULL));
87     if (serialized_pb == NULL) {
88       GOOGLE_LOG(ERROR)
89           << "DescriptorDatabase method did not return a FileDescriptorProto";
90       PyErr_Print();
91       return false;
92     }
93     char* str;
94     Py_ssize_t len;
95     if (PyBytes_AsStringAndSize(serialized_pb.get(), &str, &len) < 0) {
96       GOOGLE_LOG(ERROR)
97           << "DescriptorDatabase method did not return a FileDescriptorProto";
98       PyErr_Print();
99       return false;
100     }
101     FileDescriptorProto file_proto;
102     if (!file_proto.ParseFromArray(str, len)) {
103       GOOGLE_LOG(ERROR)
104           << "DescriptorDatabase method did not return a FileDescriptorProto";
105       return false;
106     }
107     *output = file_proto;
108     return true;
109   }
110 }
111 
112 // Find a file by file name.
FindFileByName(const std::string & filename,FileDescriptorProto * output)113 bool PyDescriptorDatabase::FindFileByName(const std::string& filename,
114                                           FileDescriptorProto* output) {
115   ScopedPyObjectPtr py_descriptor(PyObject_CallMethod(
116       py_database_, "FindFileByName", "s#", filename.c_str(), filename.size()));
117   return GetFileDescriptorProto(py_descriptor.get(), output);
118 }
119 
120 // Find the file that declares the given fully-qualified symbol name.
FindFileContainingSymbol(const std::string & symbol_name,FileDescriptorProto * output)121 bool PyDescriptorDatabase::FindFileContainingSymbol(
122     const std::string& symbol_name, FileDescriptorProto* output) {
123   ScopedPyObjectPtr py_descriptor(
124       PyObject_CallMethod(py_database_, "FindFileContainingSymbol", "s#",
125                           symbol_name.c_str(), symbol_name.size()));
126   return GetFileDescriptorProto(py_descriptor.get(), output);
127 }
128 
129 // Find the file which defines an extension extending the given message type
130 // with the given field number.
131 // Python DescriptorDatabases are not required to implement this method.
FindFileContainingExtension(const std::string & containing_type,int field_number,FileDescriptorProto * output)132 bool PyDescriptorDatabase::FindFileContainingExtension(
133     const std::string& containing_type, int field_number,
134     FileDescriptorProto* output) {
135   ScopedPyObjectPtr py_method(
136       PyObject_GetAttrString(py_database_, "FindFileContainingExtension"));
137   if (py_method == NULL) {
138     // This method is not implemented, returns without error.
139     PyErr_Clear();
140     return false;
141   }
142   ScopedPyObjectPtr py_descriptor(
143       PyObject_CallFunction(py_method.get(), "s#i", containing_type.c_str(),
144                             containing_type.size(), field_number));
145   return GetFileDescriptorProto(py_descriptor.get(), output);
146 }
147 
148 // Finds the tag numbers used by all known extensions of
149 // containing_type, and appends them to output in an undefined
150 // order.
151 // Python DescriptorDatabases are not required to implement this method.
FindAllExtensionNumbers(const std::string & containing_type,std::vector<int> * output)152 bool PyDescriptorDatabase::FindAllExtensionNumbers(
153     const std::string& containing_type, std::vector<int>* output) {
154   ScopedPyObjectPtr py_method(
155       PyObject_GetAttrString(py_database_, "FindAllExtensionNumbers"));
156   if (py_method == NULL) {
157     // This method is not implemented, returns without error.
158     PyErr_Clear();
159     return false;
160   }
161   ScopedPyObjectPtr py_list(
162       PyObject_CallFunction(py_method.get(), "s#", containing_type.c_str(),
163                             containing_type.size()));
164   if (py_list == NULL) {
165     PyErr_Print();
166     return false;
167   }
168   Py_ssize_t size = PyList_Size(py_list.get());
169   int64_t item_value;
170   for (Py_ssize_t i = 0 ; i < size; ++i) {
171     ScopedPyObjectPtr item(PySequence_GetItem(py_list.get(), i));
172     item_value = PyLong_AsLong(item.get());
173     if (item_value < 0) {
174       GOOGLE_LOG(ERROR)
175           << "FindAllExtensionNumbers method did not return "
176           << "valid extension numbers.";
177       PyErr_Print();
178       return false;
179     }
180     output->push_back(item_value);
181   }
182   return true;
183 }
184 
185 }  // namespace python
186 }  // namespace protobuf
187 }  // namespace google
188