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 #include <google/protobuf/stubs/once.h>
35 #include <google/protobuf/stubs/status.h>
36 #include <google/protobuf/stubs/stringpiece.h>
37 #include <google/protobuf/stubs/strutil.h>
38 #include <google/protobuf/stubs/int128.h>
39 #include <errno.h>
40 #include <sstream>
41 #include <stdio.h>
42 #include <vector>
43 
44 #include "config.h"
45 
46 #ifdef _WIN32
47 #define WIN32_LEAN_AND_MEAN  // We only need minimal includes
48 #include <windows.h>
49 #define snprintf _snprintf    // see comment in strutil.cc
50 #elif defined(HAVE_PTHREAD)
51 #include <pthread.h>
52 #else
53 #error "No suitable threading library available."
54 #endif
55 #if defined(__ANDROID__)
56 #include <android/log.h>
57 #endif
58 
59 namespace google {
60 namespace protobuf {
61 
62 namespace internal {
63 
VerifyVersion(int headerVersion,int minLibraryVersion,const char * filename)64 void VerifyVersion(int headerVersion,
65                    int minLibraryVersion,
66                    const char* filename) {
67   if (GOOGLE_PROTOBUF_VERSION < minLibraryVersion) {
68     // Library is too old for headers.
69     GOOGLE_LOG(FATAL)
70       << "This program requires version " << VersionString(minLibraryVersion)
71       << " of the Protocol Buffer runtime library, but the installed version "
72          "is " << VersionString(GOOGLE_PROTOBUF_VERSION) << ".  Please update "
73          "your library.  If you compiled the program yourself, make sure that "
74          "your headers are from the same version of Protocol Buffers as your "
75          "link-time library.  (Version verification failed in \""
76       << filename << "\".)";
77   }
78   if (headerVersion < kMinHeaderVersionForLibrary) {
79     // Headers are too old for library.
80     GOOGLE_LOG(FATAL)
81       << "This program was compiled against version "
82       << VersionString(headerVersion) << " of the Protocol Buffer runtime "
83          "library, which is not compatible with the installed version ("
84       << VersionString(GOOGLE_PROTOBUF_VERSION) <<  ").  Contact the program "
85          "author for an update.  If you compiled the program yourself, make "
86          "sure that your headers are from the same version of Protocol Buffers "
87          "as your link-time library.  (Version verification failed in \""
88       << filename << "\".)";
89   }
90 }
91 
VersionString(int version)92 string VersionString(int version) {
93   int major = version / 1000000;
94   int minor = (version / 1000) % 1000;
95   int micro = version % 1000;
96 
97   // 128 bytes should always be enough, but we use snprintf() anyway to be
98   // safe.
99   char buffer[128];
100   snprintf(buffer, sizeof(buffer), "%d.%d.%d", major, minor, micro);
101 
102   // Guard against broken MSVC snprintf().
103   buffer[sizeof(buffer)-1] = '\0';
104 
105   return buffer;
106 }
107 
108 }  // namespace internal
109 
110 // ===================================================================
111 // emulates google3/base/logging.cc
112 
113 namespace internal {
114 #if defined(__ANDROID__)
DefaultLogHandler(LogLevel level,const char * filename,int line,const string & message)115 inline void DefaultLogHandler(LogLevel level, const char* filename, int line,
116                               const string& message) {
117 #ifdef GOOGLE_PROTOBUF_MIN_LOG_LEVEL
118   if (level < GOOGLE_PROTOBUF_MIN_LOG_LEVEL) {
119     return;
120   }
121   static const char* level_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
122 
123   static const int android_log_levels[] = {
124       ANDROID_LOG_INFO,   // LOG(INFO),
125       ANDROID_LOG_WARN,   // LOG(WARNING)
126       ANDROID_LOG_ERROR,  // LOG(ERROR)
127       ANDROID_LOG_FATAL,  // LOG(FATAL)
128   };
129 
130   // Bound the logging level.
131   const int android_log_level = android_log_levels[level];
132   ::std::ostringstream ostr;
133   ostr << "[libprotobuf " << level_names[level] << " " << filename << ":"
134        << line << "] " << message.c_str();
135 
136   // Output the log string the Android log at the appropriate level.
137   __android_log_write(android_log_level, "libprotobuf-native",
138                       ostr.str().c_str());
139   // Also output to std::cerr.
140   fprintf(stderr, "%s", ostr.str().c_str());
141   fflush(stderr);
142 
143   // Indicate termination if needed.
144   if (android_log_level == ANDROID_LOG_FATAL) {
145     __android_log_write(ANDROID_LOG_FATAL, "libprotobuf-native",
146                         "terminating.\n");
147   }
148 #endif
149 }
150 #else
151 void DefaultLogHandler(LogLevel level, const char* filename, int line,
152                        const string& message) {
153   static const char* level_names[] = { "INFO", "WARNING", "ERROR", "FATAL" };
154 
155   // We use fprintf() instead of cerr because we want this to work at static
156   // initialization time.
157   fprintf(stderr, "[libprotobuf %s %s:%d] %s\n",
158           level_names[level], filename, line, message.c_str());
159   fflush(stderr);  // Needed on MSVC.
160 }
161 #endif
162 
NullLogHandler(LogLevel,const char *,int,const string &)163 void NullLogHandler(LogLevel /* level */, const char* /* filename */,
164                     int /* line */, const string& /* message */) {
165   // Nothing.
166 }
167 
168 static LogHandler* log_handler_ = &DefaultLogHandler;
169 static int log_silencer_count_ = 0;
170 
171 static Mutex* log_silencer_count_mutex_ = NULL;
172 GOOGLE_PROTOBUF_DECLARE_ONCE(log_silencer_count_init_);
173 
DeleteLogSilencerCount()174 void DeleteLogSilencerCount() {
175   delete log_silencer_count_mutex_;
176   log_silencer_count_mutex_ = NULL;
177 }
InitLogSilencerCount()178 void InitLogSilencerCount() {
179   log_silencer_count_mutex_ = new Mutex;
180   OnShutdown(&DeleteLogSilencerCount);
181 }
InitLogSilencerCountOnce()182 void InitLogSilencerCountOnce() {
183   GoogleOnceInit(&log_silencer_count_init_, &InitLogSilencerCount);
184 }
185 
operator <<(const string & value)186 LogMessage& LogMessage::operator<<(const string& value) {
187   message_ += value;
188   return *this;
189 }
190 
operator <<(const char * value)191 LogMessage& LogMessage::operator<<(const char* value) {
192   message_ += value;
193   return *this;
194 }
195 
operator <<(const StringPiece & value)196 LogMessage& LogMessage::operator<<(const StringPiece& value) {
197   message_ += value.ToString();
198   return *this;
199 }
200 
operator <<(const::google::protobuf::util::Status & status)201 LogMessage& LogMessage::operator<<(
202     const ::google::protobuf::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         , "%" GOOGLE_LL_FORMAT "d")
239 DECLARE_STREAM_OPERATOR(unsigned long long, "%" GOOGLE_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     InitLogSilencerCountOnce();
251     MutexLock lock(log_silencer_count_mutex_);
252     suppress = log_silencer_count_ > 0;
253   }
254 
255   if (!suppress) {
256     log_handler_(level_, filename_, line_, message_);
257   }
258 
259   if (level_ == LOGLEVEL_FATAL) {
260 #if PROTOBUF_USE_EXCEPTIONS
261     throw FatalException(filename_, line_, message_);
262 #else
263     abort();
264 #endif
265   }
266 }
267 
operator =(LogMessage & other)268 void LogFinisher::operator=(LogMessage& other) {
269   other.Finish();
270 }
271 
272 }  // namespace internal
273 
SetLogHandler(LogHandler * new_func)274 LogHandler* SetLogHandler(LogHandler* new_func) {
275   LogHandler* old = internal::log_handler_;
276   if (old == &internal::NullLogHandler) {
277     old = NULL;
278   }
279   if (new_func == NULL) {
280     internal::log_handler_ = &internal::NullLogHandler;
281   } else {
282     internal::log_handler_ = new_func;
283   }
284   return old;
285 }
286 
LogSilencer()287 LogSilencer::LogSilencer() {
288   internal::InitLogSilencerCountOnce();
289   MutexLock lock(internal::log_silencer_count_mutex_);
290   ++internal::log_silencer_count_;
291 };
292 
~LogSilencer()293 LogSilencer::~LogSilencer() {
294   internal::InitLogSilencerCountOnce();
295   MutexLock lock(internal::log_silencer_count_mutex_);
296   --internal::log_silencer_count_;
297 };
298 
299 // ===================================================================
300 // emulates google3/base/callback.cc
301 
~Closure()302 Closure::~Closure() {}
303 
~FunctionClosure0()304 namespace internal { FunctionClosure0::~FunctionClosure0() {} }
305 
DoNothing()306 void DoNothing() {}
307 
308 // ===================================================================
309 // emulates google3/base/mutex.cc
310 
311 #ifdef _WIN32
312 
313 struct Mutex::Internal {
314   CRITICAL_SECTION mutex;
315 #ifndef NDEBUG
316   // Used only to implement AssertHeld().
317   DWORD thread_id;
318 #endif
319 };
320 
Mutex()321 Mutex::Mutex()
322   : mInternal(new Internal) {
323   InitializeCriticalSection(&mInternal->mutex);
324 }
325 
~Mutex()326 Mutex::~Mutex() {
327   DeleteCriticalSection(&mInternal->mutex);
328   delete mInternal;
329 }
330 
Lock()331 void Mutex::Lock() {
332   EnterCriticalSection(&mInternal->mutex);
333 #ifndef NDEBUG
334   mInternal->thread_id = GetCurrentThreadId();
335 #endif
336 }
337 
Unlock()338 void Mutex::Unlock() {
339 #ifndef NDEBUG
340   mInternal->thread_id = 0;
341 #endif
342   LeaveCriticalSection(&mInternal->mutex);
343 }
344 
AssertHeld()345 void Mutex::AssertHeld() {
346 #ifndef NDEBUG
347   GOOGLE_DCHECK_EQ(mInternal->thread_id, GetCurrentThreadId());
348 #endif
349 }
350 
351 #elif defined(HAVE_PTHREAD)
352 
353 struct Mutex::Internal {
354   pthread_mutex_t mutex;
355 };
356 
Mutex()357 Mutex::Mutex()
358   : mInternal(new Internal) {
359   pthread_mutex_init(&mInternal->mutex, NULL);
360 }
361 
~Mutex()362 Mutex::~Mutex() {
363   pthread_mutex_destroy(&mInternal->mutex);
364   delete mInternal;
365 }
366 
Lock()367 void Mutex::Lock() {
368   int result = pthread_mutex_lock(&mInternal->mutex);
369   if (result != 0) {
370     GOOGLE_LOG(FATAL) << "pthread_mutex_lock: " << strerror(result);
371   }
372 }
373 
Unlock()374 void Mutex::Unlock() {
375   int result = pthread_mutex_unlock(&mInternal->mutex);
376   if (result != 0) {
377     GOOGLE_LOG(FATAL) << "pthread_mutex_unlock: " << strerror(result);
378   }
379 }
380 
AssertHeld()381 void Mutex::AssertHeld() {
382   // pthreads dosn't provide a way to check which thread holds the mutex.
383   // TODO(kenton):  Maybe keep track of locking thread ID like with WIN32?
384 }
385 
386 #endif
387 
388 // ===================================================================
389 // emulates google3/util/endian/endian.h
390 //
391 // TODO(xiaofeng): PROTOBUF_LITTLE_ENDIAN is unfortunately defined in
392 // google/protobuf/io/coded_stream.h and therefore can not be used here.
393 // Maybe move that macro definition here in the furture.
ghtonl(uint32 x)394 uint32 ghtonl(uint32 x) {
395   union {
396     uint32 result;
397     uint8 result_array[4];
398   };
399   result_array[0] = static_cast<uint8>(x >> 24);
400   result_array[1] = static_cast<uint8>((x >> 16) & 0xFF);
401   result_array[2] = static_cast<uint8>((x >> 8) & 0xFF);
402   result_array[3] = static_cast<uint8>(x & 0xFF);
403   return result;
404 }
405 
406 // ===================================================================
407 // Shutdown support.
408 
409 namespace internal {
410 
411 typedef void OnShutdownFunc();
412 vector<void (*)()>* shutdown_functions = NULL;
413 Mutex* shutdown_functions_mutex = NULL;
414 GOOGLE_PROTOBUF_DECLARE_ONCE(shutdown_functions_init);
415 
InitShutdownFunctions()416 void InitShutdownFunctions() {
417   shutdown_functions = new vector<void (*)()>;
418   shutdown_functions_mutex = new Mutex;
419 }
420 
InitShutdownFunctionsOnce()421 inline void InitShutdownFunctionsOnce() {
422   GoogleOnceInit(&shutdown_functions_init, &InitShutdownFunctions);
423 }
424 
OnShutdown(void (* func)())425 void OnShutdown(void (*func)()) {
426   InitShutdownFunctionsOnce();
427   MutexLock lock(shutdown_functions_mutex);
428   shutdown_functions->push_back(func);
429 }
430 
431 }  // namespace internal
432 
ShutdownProtobufLibrary()433 void ShutdownProtobufLibrary() {
434   internal::InitShutdownFunctionsOnce();
435 
436   // We don't need to lock shutdown_functions_mutex because it's up to the
437   // caller to make sure that no one is using the library before this is
438   // called.
439 
440   // Make it safe to call this multiple times.
441   if (internal::shutdown_functions == NULL) return;
442 
443   for (int i = 0; i < internal::shutdown_functions->size(); i++) {
444     internal::shutdown_functions->at(i)();
445   }
446   delete internal::shutdown_functions;
447   internal::shutdown_functions = NULL;
448   delete internal::shutdown_functions_mutex;
449   internal::shutdown_functions_mutex = NULL;
450 }
451 
452 #if PROTOBUF_USE_EXCEPTIONS
~FatalException()453 FatalException::~FatalException() throw() {}
454 
what() const455 const char* FatalException::what() const throw() {
456   return message_.c_str();
457 }
458 #endif
459 
460 }  // namespace protobuf
461 }  // namespace google
462