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