common.cc 12 KB

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