common.cc 12 KB

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