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 // Author: kenton@google.com (Kenton Varda)
32
33 #include <google/protobuf/stubs/common.h>
34
35 #include <atomic>
36 #include <errno.h>
37 #include <sstream>
38 #include <stdio.h>
39 #include <vector>
40
41 #ifdef _WIN32
42 #ifndef WIN32_LEAN_AND_MEAN
43 #define WIN32_LEAN_AND_MEAN // We only need minimal includes
44 #endif
45 #include <windows.h>
46 #define snprintf _snprintf // see comment in strutil.cc
47 #elif defined(HAVE_PTHREAD)
48 #include <pthread.h>
49 #else
50 #error "No suitable threading library available."
51 #endif
52 #if defined(__ANDROID__)
53 #include <android/log.h>
54 #endif
55
56 #include <google/protobuf/stubs/callback.h>
57 #include <google/protobuf/stubs/logging.h>
58 #include <google/protobuf/stubs/once.h>
59 #include <google/protobuf/stubs/status.h>
60 #include <google/protobuf/stubs/stringpiece.h>
61 #include <google/protobuf/stubs/strutil.h>
62 #include <google/protobuf/stubs/int128.h>
63
64 #include <google/protobuf/port_def.inc>
65
66 namespace google {
67 namespace protobuf {
68
69 namespace internal {
70
VerifyVersion(int headerVersion,int minLibraryVersion,const char * filename)71 void VerifyVersion(int headerVersion,
72 int minLibraryVersion,
73 const char* filename) {
74 if (GOOGLE_PROTOBUF_VERSION < minLibraryVersion) {
75 // Library is too old for headers.
76 GOOGLE_LOG(FATAL)
77 << "This program requires version " << VersionString(minLibraryVersion)
78 << " of the Protocol Buffer runtime library, but the installed version "
79 "is " << VersionString(GOOGLE_PROTOBUF_VERSION) << ". Please update "
80 "your library. If you compiled the program yourself, make sure that "
81 "your headers are from the same version of Protocol Buffers as your "
82 "link-time library. (Version verification failed in \""
83 << filename << "\".)";
84 }
85 if (headerVersion < kMinHeaderVersionForLibrary) {
86 // Headers are too old for library.
87 GOOGLE_LOG(FATAL)
88 << "This program was compiled against version "
89 << VersionString(headerVersion) << " of the Protocol Buffer runtime "
90 "library, which is not compatible with the installed version ("
91 << VersionString(GOOGLE_PROTOBUF_VERSION) << "). Contact the program "
92 "author for an update. If you compiled the program yourself, make "
93 "sure that your headers are from the same version of Protocol Buffers "
94 "as your link-time library. (Version verification failed in \""
95 << filename << "\".)";
96 }
97 }
98
VersionString(int version)99 string VersionString(int version) {
100 int major = version / 1000000;
101 int minor = (version / 1000) % 1000;
102 int micro = version % 1000;
103
104 // 128 bytes should always be enough, but we use snprintf() anyway to be
105 // safe.
106 char buffer[128];
107 snprintf(buffer, sizeof(buffer), "%d.%d.%d", major, minor, micro);
108
109 // Guard against broken MSVC snprintf().
110 buffer[sizeof(buffer)-1] = '\0';
111
112 return buffer;
113 }
114
115 } // namespace internal
116
117 // ===================================================================
118 // emulates google3/base/logging.cc
119
120 // If the minimum logging level is not set, we default to logging messages for
121 // all levels.
122 #ifndef GOOGLE_PROTOBUF_MIN_LOG_LEVEL
123 #define GOOGLE_PROTOBUF_MIN_LOG_LEVEL LOGLEVEL_INFO
124 #endif
125
126 namespace internal {
127
128 #if defined(__ANDROID__)
DefaultLogHandler(LogLevel level,const char * filename,int line,const string & message)129 inline void DefaultLogHandler(LogLevel level, const char* filename, int line,
130 const string& message) {
131 if (level < GOOGLE_PROTOBUF_MIN_LOG_LEVEL) {
132 return;
133 }
134 static const char* level_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
135
136 static const int android_log_levels[] = {
137 ANDROID_LOG_INFO, // LOG(INFO),
138 ANDROID_LOG_WARN, // LOG(WARNING)
139 ANDROID_LOG_ERROR, // LOG(ERROR)
140 ANDROID_LOG_FATAL, // LOG(FATAL)
141 };
142
143 // Bound the logging level.
144 const int android_log_level = android_log_levels[level];
145 ::std::ostringstream ostr;
146 ostr << "[libprotobuf " << level_names[level] << " " << filename << ":"
147 << line << "] " << message.c_str();
148
149 // Output the log string the Android log at the appropriate level.
150 __android_log_write(android_log_level, "libprotobuf-native",
151 ostr.str().c_str());
152 // Also output to std::cerr.
153 fprintf(stderr, "%s", ostr.str().c_str());
154 fflush(stderr);
155
156 // Indicate termination if needed.
157 if (android_log_level == ANDROID_LOG_FATAL) {
158 __android_log_write(ANDROID_LOG_FATAL, "libprotobuf-native",
159 "terminating.\n");
160 }
161 }
162
163 #else
164 void DefaultLogHandler(LogLevel level, const char* filename, int line,
165 const string& message) {
166 if (level < GOOGLE_PROTOBUF_MIN_LOG_LEVEL) {
167 return;
168 }
169 static const char* level_names[] = { "INFO", "WARNING", "ERROR", "FATAL" };
170
171 // We use fprintf() instead of cerr because we want this to work at static
172 // initialization time.
173 fprintf(stderr, "[libprotobuf %s %s:%d] %s\n",
174 level_names[level], filename, line, message.c_str());
175 fflush(stderr); // Needed on MSVC.
176 }
177 #endif
178
NullLogHandler(LogLevel,const char *,int,const string &)179 void NullLogHandler(LogLevel /* level */, const char* /* filename */,
180 int /* line */, const string& /* message */) {
181 // Nothing.
182 }
183
184 static LogHandler* log_handler_ = &DefaultLogHandler;
185 static std::atomic<int> log_silencer_count_ = ATOMIC_VAR_INIT(0);
186
operator <<(const string & value)187 LogMessage& LogMessage::operator<<(const string& value) {
188 message_ += value;
189 return *this;
190 }
191
operator <<(const char * value)192 LogMessage& LogMessage::operator<<(const char* value) {
193 message_ += value;
194 return *this;
195 }
196
operator <<(const StringPiece & value)197 LogMessage& LogMessage::operator<<(const StringPiece& value) {
198 message_ += value.ToString();
199 return *this;
200 }
201
operator <<(const util::Status & status)202 LogMessage& LogMessage::operator<<(const util::Status& status) {
203 message_ += status.ToString();
204 return *this;
205 }
206
operator <<(const uint128 & value)207 LogMessage& LogMessage::operator<<(const uint128& value) {
208 std::ostringstream str;
209 str << value;
210 message_ += str.str();
211 return *this;
212 }
213
214 // Since this is just for logging, we don't care if the current locale changes
215 // the results -- in fact, we probably prefer that. So we use snprintf()
216 // instead of Simple*toa().
217 #undef DECLARE_STREAM_OPERATOR
218 #define DECLARE_STREAM_OPERATOR(TYPE, FORMAT) \
219 LogMessage& LogMessage::operator<<(TYPE value) { \
220 /* 128 bytes should be big enough for any of the primitive */ \
221 /* values which we print with this, but well use snprintf() */ \
222 /* anyway to be extra safe. */ \
223 char buffer[128]; \
224 snprintf(buffer, sizeof(buffer), FORMAT, value); \
225 /* Guard against broken MSVC snprintf(). */ \
226 buffer[sizeof(buffer)-1] = '\0'; \
227 message_ += buffer; \
228 return *this; \
229 }
230
231 DECLARE_STREAM_OPERATOR(char , "%c" )
232 DECLARE_STREAM_OPERATOR(int , "%d" )
233 DECLARE_STREAM_OPERATOR(unsigned int , "%u" )
234 DECLARE_STREAM_OPERATOR(long , "%ld")
235 DECLARE_STREAM_OPERATOR(unsigned long, "%lu")
236 DECLARE_STREAM_OPERATOR(double , "%g" )
237 DECLARE_STREAM_OPERATOR(void* , "%p" )
238 DECLARE_STREAM_OPERATOR(long long , "%" PROTOBUF_LL_FORMAT "d")
239 DECLARE_STREAM_OPERATOR(unsigned long long, "%" PROTOBUF_LL_FORMAT "u")
240 #undef DECLARE_STREAM_OPERATOR
241
LogMessage(LogLevel level,const char * filename,int line)242 LogMessage::LogMessage(LogLevel level, const char* filename, int line)
243 : level_(level), filename_(filename), line_(line) {}
~LogMessage()244 LogMessage::~LogMessage() {}
245
Finish()246 void LogMessage::Finish() {
247 bool suppress = false;
248
249 if (level_ != LOGLEVEL_FATAL) {
250 suppress = log_silencer_count_ > 0;
251 }
252
253 if (!suppress) {
254 log_handler_(level_, filename_, line_, message_);
255 }
256
257 if (level_ == LOGLEVEL_FATAL) {
258 #if PROTOBUF_USE_EXCEPTIONS
259 throw FatalException(filename_, line_, message_);
260 #else
261 abort();
262 #endif
263 }
264 }
265
operator =(LogMessage & other)266 void LogFinisher::operator=(LogMessage& other) {
267 other.Finish();
268 }
269
270 } // namespace internal
271
SetLogHandler(LogHandler * new_func)272 LogHandler* SetLogHandler(LogHandler* new_func) {
273 LogHandler* old = internal::log_handler_;
274 if (old == &internal::NullLogHandler) {
275 old = nullptr;
276 }
277 if (new_func == nullptr) {
278 internal::log_handler_ = &internal::NullLogHandler;
279 } else {
280 internal::log_handler_ = new_func;
281 }
282 return old;
283 }
284
LogSilencer()285 LogSilencer::LogSilencer() {
286 ++internal::log_silencer_count_;
287 };
288
~LogSilencer()289 LogSilencer::~LogSilencer() {
290 --internal::log_silencer_count_;
291 };
292
293 // ===================================================================
294 // emulates google3/base/callback.cc
295
~Closure()296 Closure::~Closure() {}
297
~FunctionClosure0()298 namespace internal { FunctionClosure0::~FunctionClosure0() {} }
299
DoNothing()300 void DoNothing() {}
301
302 // ===================================================================
303 // emulates google3/util/endian/endian.h
304 //
305 // TODO(xiaofeng): PROTOBUF_LITTLE_ENDIAN is unfortunately defined in
306 // google/protobuf/io/coded_stream.h and therefore can not be used here.
307 // Maybe move that macro definition here in the furture.
ghtonl(uint32 x)308 uint32 ghtonl(uint32 x) {
309 union {
310 uint32 result;
311 uint8 result_array[4];
312 };
313 result_array[0] = static_cast<uint8>(x >> 24);
314 result_array[1] = static_cast<uint8>((x >> 16) & 0xFF);
315 result_array[2] = static_cast<uint8>((x >> 8) & 0xFF);
316 result_array[3] = static_cast<uint8>(x & 0xFF);
317 return result;
318 }
319
320 #if PROTOBUF_USE_EXCEPTIONS
~FatalException()321 FatalException::~FatalException() throw() {}
322
what() const323 const char* FatalException::what() const throw() {
324 return message_.c_str();
325 }
326 #endif
327
328 } // namespace protobuf
329 } // namespace google
330