/thirdparty/breakpad/third_party/protobuf/protobuf/gtest/src/gtest-port.cc

http://github.com/tomahawk-player/tomahawk · C++ · 711 lines · 435 code · 107 blank · 169 comment · 127 complexity · 3be036a70ece249abef0283b7f32b4e0 MD5 · raw file

  1. // Copyright 2008, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Author: wan@google.com (Zhanyong Wan)
  31. #include <gtest/internal/gtest-port.h>
  32. #include <limits.h>
  33. #include <stdlib.h>
  34. #include <stdio.h>
  35. #if GTEST_OS_WINDOWS_MOBILE
  36. #include <windows.h> // For TerminateProcess()
  37. #elif GTEST_OS_WINDOWS
  38. #include <io.h>
  39. #include <sys/stat.h>
  40. #else
  41. #include <unistd.h>
  42. #endif // GTEST_OS_WINDOWS_MOBILE
  43. #if GTEST_OS_MAC
  44. #include <mach/mach_init.h>
  45. #include <mach/task.h>
  46. #include <mach/vm_map.h>
  47. #endif // GTEST_OS_MAC
  48. #include <gtest/gtest-spi.h>
  49. #include <gtest/gtest-message.h>
  50. #include <gtest/internal/gtest-string.h>
  51. // Indicates that this translation unit is part of Google Test's
  52. // implementation. It must come before gtest-internal-inl.h is
  53. // included, or there will be a compiler error. This trick is to
  54. // prevent a user from accidentally including gtest-internal-inl.h in
  55. // his code.
  56. #define GTEST_IMPLEMENTATION_ 1
  57. #include "src/gtest-internal-inl.h"
  58. #undef GTEST_IMPLEMENTATION_
  59. namespace testing {
  60. namespace internal {
  61. #if defined(_MSC_VER) || defined(__BORLANDC__)
  62. // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
  63. const int kStdOutFileno = 1;
  64. const int kStdErrFileno = 2;
  65. #else
  66. const int kStdOutFileno = STDOUT_FILENO;
  67. const int kStdErrFileno = STDERR_FILENO;
  68. #endif // _MSC_VER
  69. #if GTEST_OS_MAC
  70. // Returns the number of threads running in the process, or 0 to indicate that
  71. // we cannot detect it.
  72. size_t GetThreadCount() {
  73. const task_t task = mach_task_self();
  74. mach_msg_type_number_t thread_count;
  75. thread_act_array_t thread_list;
  76. const kern_return_t status = task_threads(task, &thread_list, &thread_count);
  77. if (status == KERN_SUCCESS) {
  78. // task_threads allocates resources in thread_list and we need to free them
  79. // to avoid leaks.
  80. vm_deallocate(task,
  81. reinterpret_cast<vm_address_t>(thread_list),
  82. sizeof(thread_t) * thread_count);
  83. return static_cast<size_t>(thread_count);
  84. } else {
  85. return 0;
  86. }
  87. }
  88. #else
  89. size_t GetThreadCount() {
  90. // There's no portable way to detect the number of threads, so we just
  91. // return 0 to indicate that we cannot detect it.
  92. return 0;
  93. }
  94. #endif // GTEST_OS_MAC
  95. #if GTEST_USES_POSIX_RE
  96. // Implements RE. Currently only needed for death tests.
  97. RE::~RE() {
  98. if (is_valid_) {
  99. // regfree'ing an invalid regex might crash because the content
  100. // of the regex is undefined. Since the regex's are essentially
  101. // the same, one cannot be valid (or invalid) without the other
  102. // being so too.
  103. regfree(&partial_regex_);
  104. regfree(&full_regex_);
  105. }
  106. free(const_cast<char*>(pattern_));
  107. }
  108. // Returns true iff regular expression re matches the entire str.
  109. bool RE::FullMatch(const char* str, const RE& re) {
  110. if (!re.is_valid_) return false;
  111. regmatch_t match;
  112. return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
  113. }
  114. // Returns true iff regular expression re matches a substring of str
  115. // (including str itself).
  116. bool RE::PartialMatch(const char* str, const RE& re) {
  117. if (!re.is_valid_) return false;
  118. regmatch_t match;
  119. return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
  120. }
  121. // Initializes an RE from its string representation.
  122. void RE::Init(const char* regex) {
  123. pattern_ = posix::StrDup(regex);
  124. // Reserves enough bytes to hold the regular expression used for a
  125. // full match.
  126. const size_t full_regex_len = strlen(regex) + 10;
  127. char* const full_pattern = new char[full_regex_len];
  128. snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
  129. is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
  130. // We want to call regcomp(&partial_regex_, ...) even if the
  131. // previous expression returns false. Otherwise partial_regex_ may
  132. // not be properly initialized can may cause trouble when it's
  133. // freed.
  134. //
  135. // Some implementation of POSIX regex (e.g. on at least some
  136. // versions of Cygwin) doesn't accept the empty string as a valid
  137. // regex. We change it to an equivalent form "()" to be safe.
  138. if (is_valid_) {
  139. const char* const partial_regex = (*regex == '\0') ? "()" : regex;
  140. is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
  141. }
  142. EXPECT_TRUE(is_valid_)
  143. << "Regular expression \"" << regex
  144. << "\" is not a valid POSIX Extended regular expression.";
  145. delete[] full_pattern;
  146. }
  147. #elif GTEST_USES_SIMPLE_RE
  148. // Returns true iff ch appears anywhere in str (excluding the
  149. // terminating '\0' character).
  150. bool IsInSet(char ch, const char* str) {
  151. return ch != '\0' && strchr(str, ch) != NULL;
  152. }
  153. // Returns true iff ch belongs to the given classification. Unlike
  154. // similar functions in <ctype.h>, these aren't affected by the
  155. // current locale.
  156. bool IsDigit(char ch) { return '0' <= ch && ch <= '9'; }
  157. bool IsPunct(char ch) {
  158. return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
  159. }
  160. bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
  161. bool IsWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
  162. bool IsWordChar(char ch) {
  163. return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
  164. ('0' <= ch && ch <= '9') || ch == '_';
  165. }
  166. // Returns true iff "\\c" is a supported escape sequence.
  167. bool IsValidEscape(char c) {
  168. return (IsPunct(c) || IsInSet(c, "dDfnrsStvwW"));
  169. }
  170. // Returns true iff the given atom (specified by escaped and pattern)
  171. // matches ch. The result is undefined if the atom is invalid.
  172. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
  173. if (escaped) { // "\\p" where p is pattern_char.
  174. switch (pattern_char) {
  175. case 'd': return IsDigit(ch);
  176. case 'D': return !IsDigit(ch);
  177. case 'f': return ch == '\f';
  178. case 'n': return ch == '\n';
  179. case 'r': return ch == '\r';
  180. case 's': return IsWhiteSpace(ch);
  181. case 'S': return !IsWhiteSpace(ch);
  182. case 't': return ch == '\t';
  183. case 'v': return ch == '\v';
  184. case 'w': return IsWordChar(ch);
  185. case 'W': return !IsWordChar(ch);
  186. }
  187. return IsPunct(pattern_char) && pattern_char == ch;
  188. }
  189. return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
  190. }
  191. // Helper function used by ValidateRegex() to format error messages.
  192. String FormatRegexSyntaxError(const char* regex, int index) {
  193. return (Message() << "Syntax error at index " << index
  194. << " in simple regular expression \"" << regex << "\": ").GetString();
  195. }
  196. // Generates non-fatal failures and returns false if regex is invalid;
  197. // otherwise returns true.
  198. bool ValidateRegex(const char* regex) {
  199. if (regex == NULL) {
  200. // TODO(wan@google.com): fix the source file location in the
  201. // assertion failures to match where the regex is used in user
  202. // code.
  203. ADD_FAILURE() << "NULL is not a valid simple regular expression.";
  204. return false;
  205. }
  206. bool is_valid = true;
  207. // True iff ?, *, or + can follow the previous atom.
  208. bool prev_repeatable = false;
  209. for (int i = 0; regex[i]; i++) {
  210. if (regex[i] == '\\') { // An escape sequence
  211. i++;
  212. if (regex[i] == '\0') {
  213. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  214. << "'\\' cannot appear at the end.";
  215. return false;
  216. }
  217. if (!IsValidEscape(regex[i])) {
  218. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  219. << "invalid escape sequence \"\\" << regex[i] << "\".";
  220. is_valid = false;
  221. }
  222. prev_repeatable = true;
  223. } else { // Not an escape sequence.
  224. const char ch = regex[i];
  225. if (ch == '^' && i > 0) {
  226. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  227. << "'^' can only appear at the beginning.";
  228. is_valid = false;
  229. } else if (ch == '$' && regex[i + 1] != '\0') {
  230. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  231. << "'$' can only appear at the end.";
  232. is_valid = false;
  233. } else if (IsInSet(ch, "()[]{}|")) {
  234. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  235. << "'" << ch << "' is unsupported.";
  236. is_valid = false;
  237. } else if (IsRepeat(ch) && !prev_repeatable) {
  238. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  239. << "'" << ch << "' can only follow a repeatable token.";
  240. is_valid = false;
  241. }
  242. prev_repeatable = !IsInSet(ch, "^$?*+");
  243. }
  244. }
  245. return is_valid;
  246. }
  247. // Matches a repeated regex atom followed by a valid simple regular
  248. // expression. The regex atom is defined as c if escaped is false,
  249. // or \c otherwise. repeat is the repetition meta character (?, *,
  250. // or +). The behavior is undefined if str contains too many
  251. // characters to be indexable by size_t, in which case the test will
  252. // probably time out anyway. We are fine with this limitation as
  253. // std::string has it too.
  254. bool MatchRepetitionAndRegexAtHead(
  255. bool escaped, char c, char repeat, const char* regex,
  256. const char* str) {
  257. const size_t min_count = (repeat == '+') ? 1 : 0;
  258. const size_t max_count = (repeat == '?') ? 1 :
  259. static_cast<size_t>(-1) - 1;
  260. // We cannot call numeric_limits::max() as it conflicts with the
  261. // max() macro on Windows.
  262. for (size_t i = 0; i <= max_count; ++i) {
  263. // We know that the atom matches each of the first i characters in str.
  264. if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
  265. // We have enough matches at the head, and the tail matches too.
  266. // Since we only care about *whether* the pattern matches str
  267. // (as opposed to *how* it matches), there is no need to find a
  268. // greedy match.
  269. return true;
  270. }
  271. if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
  272. return false;
  273. }
  274. return false;
  275. }
  276. // Returns true iff regex matches a prefix of str. regex must be a
  277. // valid simple regular expression and not start with "^", or the
  278. // result is undefined.
  279. bool MatchRegexAtHead(const char* regex, const char* str) {
  280. if (*regex == '\0') // An empty regex matches a prefix of anything.
  281. return true;
  282. // "$" only matches the end of a string. Note that regex being
  283. // valid guarantees that there's nothing after "$" in it.
  284. if (*regex == '$')
  285. return *str == '\0';
  286. // Is the first thing in regex an escape sequence?
  287. const bool escaped = *regex == '\\';
  288. if (escaped)
  289. ++regex;
  290. if (IsRepeat(regex[1])) {
  291. // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
  292. // here's an indirect recursion. It terminates as the regex gets
  293. // shorter in each recursion.
  294. return MatchRepetitionAndRegexAtHead(
  295. escaped, regex[0], regex[1], regex + 2, str);
  296. } else {
  297. // regex isn't empty, isn't "$", and doesn't start with a
  298. // repetition. We match the first atom of regex with the first
  299. // character of str and recurse.
  300. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
  301. MatchRegexAtHead(regex + 1, str + 1);
  302. }
  303. }
  304. // Returns true iff regex matches any substring of str. regex must be
  305. // a valid simple regular expression, or the result is undefined.
  306. //
  307. // The algorithm is recursive, but the recursion depth doesn't exceed
  308. // the regex length, so we won't need to worry about running out of
  309. // stack space normally. In rare cases the time complexity can be
  310. // exponential with respect to the regex length + the string length,
  311. // but usually it's must faster (often close to linear).
  312. bool MatchRegexAnywhere(const char* regex, const char* str) {
  313. if (regex == NULL || str == NULL)
  314. return false;
  315. if (*regex == '^')
  316. return MatchRegexAtHead(regex + 1, str);
  317. // A successful match can be anywhere in str.
  318. do {
  319. if (MatchRegexAtHead(regex, str))
  320. return true;
  321. } while (*str++ != '\0');
  322. return false;
  323. }
  324. // Implements the RE class.
  325. RE::~RE() {
  326. free(const_cast<char*>(pattern_));
  327. free(const_cast<char*>(full_pattern_));
  328. }
  329. // Returns true iff regular expression re matches the entire str.
  330. bool RE::FullMatch(const char* str, const RE& re) {
  331. return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
  332. }
  333. // Returns true iff regular expression re matches a substring of str
  334. // (including str itself).
  335. bool RE::PartialMatch(const char* str, const RE& re) {
  336. return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
  337. }
  338. // Initializes an RE from its string representation.
  339. void RE::Init(const char* regex) {
  340. pattern_ = full_pattern_ = NULL;
  341. if (regex != NULL) {
  342. pattern_ = posix::StrDup(regex);
  343. }
  344. is_valid_ = ValidateRegex(regex);
  345. if (!is_valid_) {
  346. // No need to calculate the full pattern when the regex is invalid.
  347. return;
  348. }
  349. const size_t len = strlen(regex);
  350. // Reserves enough bytes to hold the regular expression used for a
  351. // full match: we need space to prepend a '^', append a '$', and
  352. // terminate the string with '\0'.
  353. char* buffer = static_cast<char*>(malloc(len + 3));
  354. full_pattern_ = buffer;
  355. if (*regex != '^')
  356. *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
  357. // We don't use snprintf or strncpy, as they trigger a warning when
  358. // compiled with VC++ 8.0.
  359. memcpy(buffer, regex, len);
  360. buffer += len;
  361. if (len == 0 || regex[len - 1] != '$')
  362. *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
  363. *buffer = '\0';
  364. }
  365. #endif // GTEST_USES_POSIX_RE
  366. GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
  367. : severity_(severity) {
  368. const char* const marker =
  369. severity == GTEST_INFO ? "[ INFO ]" :
  370. severity == GTEST_WARNING ? "[WARNING]" :
  371. severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
  372. GetStream() << ::std::endl << marker << " "
  373. << FormatFileLocation(file, line).c_str() << ": ";
  374. }
  375. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  376. GTestLog::~GTestLog() {
  377. GetStream() << ::std::endl;
  378. if (severity_ == GTEST_FATAL) {
  379. fflush(stderr);
  380. posix::Abort();
  381. }
  382. }
  383. // Disable Microsoft deprecation warnings for POSIX functions called from
  384. // this class (creat, dup, dup2, and close)
  385. #ifdef _MSC_VER
  386. #pragma warning(push)
  387. #pragma warning(disable: 4996)
  388. #endif // _MSC_VER
  389. #if GTEST_HAS_STREAM_REDIRECTION_
  390. // Object that captures an output stream (stdout/stderr).
  391. class CapturedStream {
  392. public:
  393. // The ctor redirects the stream to a temporary file.
  394. CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
  395. #if GTEST_OS_WINDOWS
  396. char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  397. char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  398. ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
  399. const UINT success = ::GetTempFileNameA(temp_dir_path,
  400. "gtest_redir",
  401. 0, // Generate unique file name.
  402. temp_file_path);
  403. GTEST_CHECK_(success != 0)
  404. << "Unable to create a temporary file in " << temp_dir_path;
  405. const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
  406. GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
  407. << temp_file_path;
  408. filename_ = temp_file_path;
  409. #else
  410. // There's no guarantee that a test has write access to the
  411. // current directory, so we create the temporary file in the /tmp
  412. // directory instead.
  413. char name_template[] = "/tmp/captured_stream.XXXXXX";
  414. const int captured_fd = mkstemp(name_template);
  415. filename_ = name_template;
  416. #endif // GTEST_OS_WINDOWS
  417. fflush(NULL);
  418. dup2(captured_fd, fd_);
  419. close(captured_fd);
  420. }
  421. ~CapturedStream() {
  422. remove(filename_.c_str());
  423. }
  424. String GetCapturedString() {
  425. if (uncaptured_fd_ != -1) {
  426. // Restores the original stream.
  427. fflush(NULL);
  428. dup2(uncaptured_fd_, fd_);
  429. close(uncaptured_fd_);
  430. uncaptured_fd_ = -1;
  431. }
  432. FILE* const file = posix::FOpen(filename_.c_str(), "r");
  433. const String content = ReadEntireFile(file);
  434. posix::FClose(file);
  435. return content;
  436. }
  437. private:
  438. // Reads the entire content of a file as a String.
  439. static String ReadEntireFile(FILE* file);
  440. // Returns the size (in bytes) of a file.
  441. static size_t GetFileSize(FILE* file);
  442. const int fd_; // A stream to capture.
  443. int uncaptured_fd_;
  444. // Name of the temporary file holding the stderr output.
  445. ::std::string filename_;
  446. GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
  447. };
  448. // Returns the size (in bytes) of a file.
  449. size_t CapturedStream::GetFileSize(FILE* file) {
  450. fseek(file, 0, SEEK_END);
  451. return static_cast<size_t>(ftell(file));
  452. }
  453. // Reads the entire content of a file as a string.
  454. String CapturedStream::ReadEntireFile(FILE* file) {
  455. const size_t file_size = GetFileSize(file);
  456. char* const buffer = new char[file_size];
  457. size_t bytes_last_read = 0; // # of bytes read in the last fread()
  458. size_t bytes_read = 0; // # of bytes read so far
  459. fseek(file, 0, SEEK_SET);
  460. // Keeps reading the file until we cannot read further or the
  461. // pre-determined file size is reached.
  462. do {
  463. bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
  464. bytes_read += bytes_last_read;
  465. } while (bytes_last_read > 0 && bytes_read < file_size);
  466. const String content(buffer, bytes_read);
  467. delete[] buffer;
  468. return content;
  469. }
  470. #ifdef _MSC_VER
  471. #pragma warning(pop)
  472. #endif // _MSC_VER
  473. static CapturedStream* g_captured_stderr = NULL;
  474. static CapturedStream* g_captured_stdout = NULL;
  475. // Starts capturing an output stream (stdout/stderr).
  476. void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
  477. if (*stream != NULL) {
  478. GTEST_LOG_(FATAL) << "Only one " << stream_name
  479. << " capturer can exist at a time.";
  480. }
  481. *stream = new CapturedStream(fd);
  482. }
  483. // Stops capturing the output stream and returns the captured string.
  484. String GetCapturedStream(CapturedStream** captured_stream) {
  485. const String content = (*captured_stream)->GetCapturedString();
  486. delete *captured_stream;
  487. *captured_stream = NULL;
  488. return content;
  489. }
  490. // Starts capturing stdout.
  491. void CaptureStdout() {
  492. CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
  493. }
  494. // Starts capturing stderr.
  495. void CaptureStderr() {
  496. CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
  497. }
  498. // Stops capturing stdout and returns the captured string.
  499. String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); }
  500. // Stops capturing stderr and returns the captured string.
  501. String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); }
  502. #endif // GTEST_HAS_STREAM_REDIRECTION_
  503. #if GTEST_HAS_DEATH_TEST
  504. // A copy of all command line arguments. Set by InitGoogleTest().
  505. ::std::vector<String> g_argvs;
  506. // Returns the command line as a vector of strings.
  507. const ::std::vector<String>& GetArgvs() { return g_argvs; }
  508. #endif // GTEST_HAS_DEATH_TEST
  509. #if GTEST_OS_WINDOWS_MOBILE
  510. namespace posix {
  511. void Abort() {
  512. DebugBreak();
  513. TerminateProcess(GetCurrentProcess(), 1);
  514. }
  515. } // namespace posix
  516. #endif // GTEST_OS_WINDOWS_MOBILE
  517. // Returns the name of the environment variable corresponding to the
  518. // given flag. For example, FlagToEnvVar("foo") will return
  519. // "GTEST_FOO" in the open-source version.
  520. static String FlagToEnvVar(const char* flag) {
  521. const String full_flag =
  522. (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
  523. Message env_var;
  524. for (size_t i = 0; i != full_flag.length(); i++) {
  525. env_var << static_cast<char>(toupper(full_flag.c_str()[i]));
  526. }
  527. return env_var.GetString();
  528. }
  529. // Parses 'str' for a 32-bit signed integer. If successful, writes
  530. // the result to *value and returns true; otherwise leaves *value
  531. // unchanged and returns false.
  532. bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
  533. // Parses the environment variable as a decimal integer.
  534. char* end = NULL;
  535. const long long_value = strtol(str, &end, 10); // NOLINT
  536. // Has strtol() consumed all characters in the string?
  537. if (*end != '\0') {
  538. // No - an invalid character was encountered.
  539. Message msg;
  540. msg << "WARNING: " << src_text
  541. << " is expected to be a 32-bit integer, but actually"
  542. << " has value \"" << str << "\".\n";
  543. printf("%s", msg.GetString().c_str());
  544. fflush(stdout);
  545. return false;
  546. }
  547. // Is the parsed value in the range of an Int32?
  548. const Int32 result = static_cast<Int32>(long_value);
  549. if (long_value == LONG_MAX || long_value == LONG_MIN ||
  550. // The parsed value overflows as a long. (strtol() returns
  551. // LONG_MAX or LONG_MIN when the input overflows.)
  552. result != long_value
  553. // The parsed value overflows as an Int32.
  554. ) {
  555. Message msg;
  556. msg << "WARNING: " << src_text
  557. << " is expected to be a 32-bit integer, but actually"
  558. << " has value " << str << ", which overflows.\n";
  559. printf("%s", msg.GetString().c_str());
  560. fflush(stdout);
  561. return false;
  562. }
  563. *value = result;
  564. return true;
  565. }
  566. // Reads and returns the Boolean environment variable corresponding to
  567. // the given flag; if it's not set, returns default_value.
  568. //
  569. // The value is considered true iff it's not "0".
  570. bool BoolFromGTestEnv(const char* flag, bool default_value) {
  571. const String env_var = FlagToEnvVar(flag);
  572. const char* const string_value = posix::GetEnv(env_var.c_str());
  573. return string_value == NULL ?
  574. default_value : strcmp(string_value, "0") != 0;
  575. }
  576. // Reads and returns a 32-bit integer stored in the environment
  577. // variable corresponding to the given flag; if it isn't set or
  578. // doesn't represent a valid 32-bit integer, returns default_value.
  579. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
  580. const String env_var = FlagToEnvVar(flag);
  581. const char* const string_value = posix::GetEnv(env_var.c_str());
  582. if (string_value == NULL) {
  583. // The environment variable is not set.
  584. return default_value;
  585. }
  586. Int32 result = default_value;
  587. if (!ParseInt32(Message() << "Environment variable " << env_var,
  588. string_value, &result)) {
  589. printf("The default value %s is used.\n",
  590. (Message() << default_value).GetString().c_str());
  591. fflush(stdout);
  592. return default_value;
  593. }
  594. return result;
  595. }
  596. // Reads and returns the string environment variable corresponding to
  597. // the given flag; if it's not set, returns default_value.
  598. const char* StringFromGTestEnv(const char* flag, const char* default_value) {
  599. const String env_var = FlagToEnvVar(flag);
  600. const char* const value = posix::GetEnv(env_var.c_str());
  601. return value == NULL ? default_value : value;
  602. }
  603. } // namespace internal
  604. } // namespace testing