/Unittests/googletest/src/gtest-port.cc

http://unladen-swallow.googlecode.com/ · C++ · 680 lines · 414 code · 101 blank · 165 comment · 122 complexity · 98b7a5fdcc2356c4ff9ada53b9f0252c 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 kStdErrFileno = 2;
  64. #else
  65. const int kStdErrFileno = STDERR_FILENO;
  66. #endif // _MSC_VER
  67. #if GTEST_OS_MAC
  68. // Returns the number of threads running in the process, or 0 to indicate that
  69. // we cannot detect it.
  70. size_t GetThreadCount() {
  71. const task_t task = mach_task_self();
  72. mach_msg_type_number_t thread_count;
  73. thread_act_array_t thread_list;
  74. const kern_return_t status = task_threads(task, &thread_list, &thread_count);
  75. if (status == KERN_SUCCESS) {
  76. // task_threads allocates resources in thread_list and we need to free them
  77. // to avoid leaks.
  78. vm_deallocate(task,
  79. reinterpret_cast<vm_address_t>(thread_list),
  80. sizeof(thread_t) * thread_count);
  81. return static_cast<size_t>(thread_count);
  82. } else {
  83. return 0;
  84. }
  85. }
  86. #else
  87. size_t GetThreadCount() {
  88. // There's no portable way to detect the number of threads, so we just
  89. // return 0 to indicate that we cannot detect it.
  90. return 0;
  91. }
  92. #endif // GTEST_OS_MAC
  93. #if GTEST_USES_POSIX_RE
  94. // Implements RE. Currently only needed for death tests.
  95. RE::~RE() {
  96. regfree(&partial_regex_);
  97. regfree(&full_regex_);
  98. free(const_cast<char*>(pattern_));
  99. }
  100. // Returns true iff regular expression re matches the entire str.
  101. bool RE::FullMatch(const char* str, const RE& re) {
  102. if (!re.is_valid_) return false;
  103. regmatch_t match;
  104. return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
  105. }
  106. // Returns true iff regular expression re matches a substring of str
  107. // (including str itself).
  108. bool RE::PartialMatch(const char* str, const RE& re) {
  109. if (!re.is_valid_) return false;
  110. regmatch_t match;
  111. return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
  112. }
  113. // Initializes an RE from its string representation.
  114. void RE::Init(const char* regex) {
  115. pattern_ = posix::StrDup(regex);
  116. // Reserves enough bytes to hold the regular expression used for a
  117. // full match.
  118. const size_t full_regex_len = strlen(regex) + 10;
  119. char* const full_pattern = new char[full_regex_len];
  120. snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
  121. is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
  122. // We want to call regcomp(&partial_regex_, ...) even if the
  123. // previous expression returns false. Otherwise partial_regex_ may
  124. // not be properly initialized can may cause trouble when it's
  125. // freed.
  126. //
  127. // Some implementation of POSIX regex (e.g. on at least some
  128. // versions of Cygwin) doesn't accept the empty string as a valid
  129. // regex. We change it to an equivalent form "()" to be safe.
  130. const char* const partial_regex = (*regex == '\0') ? "()" : regex;
  131. is_valid_ = (regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0)
  132. && is_valid_;
  133. EXPECT_TRUE(is_valid_)
  134. << "Regular expression \"" << regex
  135. << "\" is not a valid POSIX Extended regular expression.";
  136. delete[] full_pattern;
  137. }
  138. #elif GTEST_USES_SIMPLE_RE
  139. // Returns true iff ch appears anywhere in str (excluding the
  140. // terminating '\0' character).
  141. bool IsInSet(char ch, const char* str) {
  142. return ch != '\0' && strchr(str, ch) != NULL;
  143. }
  144. // Returns true iff ch belongs to the given classification. Unlike
  145. // similar functions in <ctype.h>, these aren't affected by the
  146. // current locale.
  147. bool IsDigit(char ch) { return '0' <= ch && ch <= '9'; }
  148. bool IsPunct(char ch) {
  149. return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
  150. }
  151. bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
  152. bool IsWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
  153. bool IsWordChar(char ch) {
  154. return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
  155. ('0' <= ch && ch <= '9') || ch == '_';
  156. }
  157. // Returns true iff "\\c" is a supported escape sequence.
  158. bool IsValidEscape(char c) {
  159. return (IsPunct(c) || IsInSet(c, "dDfnrsStvwW"));
  160. }
  161. // Returns true iff the given atom (specified by escaped and pattern)
  162. // matches ch. The result is undefined if the atom is invalid.
  163. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
  164. if (escaped) { // "\\p" where p is pattern_char.
  165. switch (pattern_char) {
  166. case 'd': return IsDigit(ch);
  167. case 'D': return !IsDigit(ch);
  168. case 'f': return ch == '\f';
  169. case 'n': return ch == '\n';
  170. case 'r': return ch == '\r';
  171. case 's': return IsWhiteSpace(ch);
  172. case 'S': return !IsWhiteSpace(ch);
  173. case 't': return ch == '\t';
  174. case 'v': return ch == '\v';
  175. case 'w': return IsWordChar(ch);
  176. case 'W': return !IsWordChar(ch);
  177. }
  178. return IsPunct(pattern_char) && pattern_char == ch;
  179. }
  180. return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
  181. }
  182. // Helper function used by ValidateRegex() to format error messages.
  183. String FormatRegexSyntaxError(const char* regex, int index) {
  184. return (Message() << "Syntax error at index " << index
  185. << " in simple regular expression \"" << regex << "\": ").GetString();
  186. }
  187. // Generates non-fatal failures and returns false if regex is invalid;
  188. // otherwise returns true.
  189. bool ValidateRegex(const char* regex) {
  190. if (regex == NULL) {
  191. // TODO(wan@google.com): fix the source file location in the
  192. // assertion failures to match where the regex is used in user
  193. // code.
  194. ADD_FAILURE() << "NULL is not a valid simple regular expression.";
  195. return false;
  196. }
  197. bool is_valid = true;
  198. // True iff ?, *, or + can follow the previous atom.
  199. bool prev_repeatable = false;
  200. for (int i = 0; regex[i]; i++) {
  201. if (regex[i] == '\\') { // An escape sequence
  202. i++;
  203. if (regex[i] == '\0') {
  204. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  205. << "'\\' cannot appear at the end.";
  206. return false;
  207. }
  208. if (!IsValidEscape(regex[i])) {
  209. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  210. << "invalid escape sequence \"\\" << regex[i] << "\".";
  211. is_valid = false;
  212. }
  213. prev_repeatable = true;
  214. } else { // Not an escape sequence.
  215. const char ch = regex[i];
  216. if (ch == '^' && i > 0) {
  217. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  218. << "'^' can only appear at the beginning.";
  219. is_valid = false;
  220. } else if (ch == '$' && regex[i + 1] != '\0') {
  221. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  222. << "'$' can only appear at the end.";
  223. is_valid = false;
  224. } else if (IsInSet(ch, "()[]{}|")) {
  225. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  226. << "'" << ch << "' is unsupported.";
  227. is_valid = false;
  228. } else if (IsRepeat(ch) && !prev_repeatable) {
  229. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  230. << "'" << ch << "' can only follow a repeatable token.";
  231. is_valid = false;
  232. }
  233. prev_repeatable = !IsInSet(ch, "^$?*+");
  234. }
  235. }
  236. return is_valid;
  237. }
  238. // Matches a repeated regex atom followed by a valid simple regular
  239. // expression. The regex atom is defined as c if escaped is false,
  240. // or \c otherwise. repeat is the repetition meta character (?, *,
  241. // or +). The behavior is undefined if str contains too many
  242. // characters to be indexable by size_t, in which case the test will
  243. // probably time out anyway. We are fine with this limitation as
  244. // std::string has it too.
  245. bool MatchRepetitionAndRegexAtHead(
  246. bool escaped, char c, char repeat, const char* regex,
  247. const char* str) {
  248. const size_t min_count = (repeat == '+') ? 1 : 0;
  249. const size_t max_count = (repeat == '?') ? 1 :
  250. static_cast<size_t>(-1) - 1;
  251. // We cannot call numeric_limits::max() as it conflicts with the
  252. // max() macro on Windows.
  253. for (size_t i = 0; i <= max_count; ++i) {
  254. // We know that the atom matches each of the first i characters in str.
  255. if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
  256. // We have enough matches at the head, and the tail matches too.
  257. // Since we only care about *whether* the pattern matches str
  258. // (as opposed to *how* it matches), there is no need to find a
  259. // greedy match.
  260. return true;
  261. }
  262. if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
  263. return false;
  264. }
  265. return false;
  266. }
  267. // Returns true iff regex matches a prefix of str. regex must be a
  268. // valid simple regular expression and not start with "^", or the
  269. // result is undefined.
  270. bool MatchRegexAtHead(const char* regex, const char* str) {
  271. if (*regex == '\0') // An empty regex matches a prefix of anything.
  272. return true;
  273. // "$" only matches the end of a string. Note that regex being
  274. // valid guarantees that there's nothing after "$" in it.
  275. if (*regex == '$')
  276. return *str == '\0';
  277. // Is the first thing in regex an escape sequence?
  278. const bool escaped = *regex == '\\';
  279. if (escaped)
  280. ++regex;
  281. if (IsRepeat(regex[1])) {
  282. // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
  283. // here's an indirect recursion. It terminates as the regex gets
  284. // shorter in each recursion.
  285. return MatchRepetitionAndRegexAtHead(
  286. escaped, regex[0], regex[1], regex + 2, str);
  287. } else {
  288. // regex isn't empty, isn't "$", and doesn't start with a
  289. // repetition. We match the first atom of regex with the first
  290. // character of str and recurse.
  291. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
  292. MatchRegexAtHead(regex + 1, str + 1);
  293. }
  294. }
  295. // Returns true iff regex matches any substring of str. regex must be
  296. // a valid simple regular expression, or the result is undefined.
  297. //
  298. // The algorithm is recursive, but the recursion depth doesn't exceed
  299. // the regex length, so we won't need to worry about running out of
  300. // stack space normally. In rare cases the time complexity can be
  301. // exponential with respect to the regex length + the string length,
  302. // but usually it's must faster (often close to linear).
  303. bool MatchRegexAnywhere(const char* regex, const char* str) {
  304. if (regex == NULL || str == NULL)
  305. return false;
  306. if (*regex == '^')
  307. return MatchRegexAtHead(regex + 1, str);
  308. // A successful match can be anywhere in str.
  309. do {
  310. if (MatchRegexAtHead(regex, str))
  311. return true;
  312. } while (*str++ != '\0');
  313. return false;
  314. }
  315. // Implements the RE class.
  316. RE::~RE() {
  317. free(const_cast<char*>(pattern_));
  318. free(const_cast<char*>(full_pattern_));
  319. }
  320. // Returns true iff regular expression re matches the entire str.
  321. bool RE::FullMatch(const char* str, const RE& re) {
  322. return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
  323. }
  324. // Returns true iff regular expression re matches a substring of str
  325. // (including str itself).
  326. bool RE::PartialMatch(const char* str, const RE& re) {
  327. return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
  328. }
  329. // Initializes an RE from its string representation.
  330. void RE::Init(const char* regex) {
  331. pattern_ = full_pattern_ = NULL;
  332. if (regex != NULL) {
  333. pattern_ = posix::StrDup(regex);
  334. }
  335. is_valid_ = ValidateRegex(regex);
  336. if (!is_valid_) {
  337. // No need to calculate the full pattern when the regex is invalid.
  338. return;
  339. }
  340. const size_t len = strlen(regex);
  341. // Reserves enough bytes to hold the regular expression used for a
  342. // full match: we need space to prepend a '^', append a '$', and
  343. // terminate the string with '\0'.
  344. char* buffer = static_cast<char*>(malloc(len + 3));
  345. full_pattern_ = buffer;
  346. if (*regex != '^')
  347. *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
  348. // We don't use snprintf or strncpy, as they trigger a warning when
  349. // compiled with VC++ 8.0.
  350. memcpy(buffer, regex, len);
  351. buffer += len;
  352. if (len == 0 || regex[len - 1] != '$')
  353. *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
  354. *buffer = '\0';
  355. }
  356. #endif // GTEST_USES_POSIX_RE
  357. GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
  358. : severity_(severity) {
  359. const char* const marker =
  360. severity == GTEST_INFO ? "[ INFO ]" :
  361. severity == GTEST_WARNING ? "[WARNING]" :
  362. severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
  363. GetStream() << ::std::endl << marker << " "
  364. << FormatFileLocation(file, line).c_str() << ": ";
  365. }
  366. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  367. GTestLog::~GTestLog() {
  368. GetStream() << ::std::endl;
  369. if (severity_ == GTEST_FATAL) {
  370. fflush(stderr);
  371. posix::Abort();
  372. }
  373. }
  374. // Disable Microsoft deprecation warnings for POSIX functions called from
  375. // this class (creat, dup, dup2, and close)
  376. #ifdef _MSC_VER
  377. #pragma warning(push)
  378. #pragma warning(disable: 4996)
  379. #endif // _MSC_VER
  380. // Defines the stderr capturer.
  381. class CapturedStderr {
  382. public:
  383. // The ctor redirects stderr to a temporary file.
  384. CapturedStderr() {
  385. #if GTEST_OS_WINDOWS_MOBILE
  386. // Not supported on Windows CE.
  387. posix::Abort();
  388. #else
  389. uncaptured_fd_ = dup(kStdErrFileno);
  390. #if GTEST_OS_WINDOWS
  391. char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  392. char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  393. ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
  394. ::GetTempFileNameA(temp_dir_path, "gtest_redir", 0, temp_file_path);
  395. const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
  396. filename_ = temp_file_path;
  397. #else
  398. // There's no guarantee that a test has write access to the
  399. // current directory, so we create the temporary file in the /tmp
  400. // directory instead.
  401. char name_template[] = "/tmp/captured_stderr.XXXXXX";
  402. const int captured_fd = mkstemp(name_template);
  403. filename_ = name_template;
  404. #endif // GTEST_OS_WINDOWS
  405. fflush(NULL);
  406. dup2(captured_fd, kStdErrFileno);
  407. close(captured_fd);
  408. #endif // GTEST_OS_WINDOWS_MOBILE
  409. }
  410. ~CapturedStderr() {
  411. #if !GTEST_OS_WINDOWS_MOBILE
  412. remove(filename_.c_str());
  413. #endif // !GTEST_OS_WINDOWS_MOBILE
  414. }
  415. // Stops redirecting stderr.
  416. void StopCapture() {
  417. #if !GTEST_OS_WINDOWS_MOBILE
  418. // Restores the original stream.
  419. fflush(NULL);
  420. dup2(uncaptured_fd_, kStdErrFileno);
  421. close(uncaptured_fd_);
  422. uncaptured_fd_ = -1;
  423. #endif // !GTEST_OS_WINDOWS_MOBILE
  424. }
  425. // Returns the name of the temporary file holding the stderr output.
  426. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
  427. // can use it here.
  428. ::std::string filename() const { return filename_; }
  429. private:
  430. int uncaptured_fd_;
  431. ::std::string filename_;
  432. };
  433. #ifdef _MSC_VER
  434. #pragma warning(pop)
  435. #endif // _MSC_VER
  436. static CapturedStderr* g_captured_stderr = NULL;
  437. // Returns the size (in bytes) of a file.
  438. static size_t GetFileSize(FILE * file) {
  439. fseek(file, 0, SEEK_END);
  440. return static_cast<size_t>(ftell(file));
  441. }
  442. // Reads the entire content of a file as a string.
  443. static String ReadEntireFile(FILE * file) {
  444. const size_t file_size = GetFileSize(file);
  445. char* const buffer = new char[file_size];
  446. size_t bytes_last_read = 0; // # of bytes read in the last fread()
  447. size_t bytes_read = 0; // # of bytes read so far
  448. fseek(file, 0, SEEK_SET);
  449. // Keeps reading the file until we cannot read further or the
  450. // pre-determined file size is reached.
  451. do {
  452. bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
  453. bytes_read += bytes_last_read;
  454. } while (bytes_last_read > 0 && bytes_read < file_size);
  455. const String content(buffer, bytes_read);
  456. delete[] buffer;
  457. return content;
  458. }
  459. // Starts capturing stderr.
  460. void CaptureStderr() {
  461. if (g_captured_stderr != NULL) {
  462. GTEST_LOG_(FATAL) << "Only one stderr capturer can exist at one time.";
  463. }
  464. g_captured_stderr = new CapturedStderr;
  465. }
  466. // Stops capturing stderr and returns the captured string.
  467. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can
  468. // use it here.
  469. String GetCapturedStderr() {
  470. g_captured_stderr->StopCapture();
  471. FILE* const file = posix::FOpen(g_captured_stderr->filename().c_str(), "r");
  472. const String content = ReadEntireFile(file);
  473. posix::FClose(file);
  474. delete g_captured_stderr;
  475. g_captured_stderr = NULL;
  476. return content;
  477. }
  478. #if GTEST_HAS_DEATH_TEST
  479. // A copy of all command line arguments. Set by InitGoogleTest().
  480. ::std::vector<String> g_argvs;
  481. // Returns the command line as a vector of strings.
  482. const ::std::vector<String>& GetArgvs() { return g_argvs; }
  483. #endif // GTEST_HAS_DEATH_TEST
  484. #if GTEST_OS_WINDOWS_MOBILE
  485. namespace posix {
  486. void Abort() {
  487. DebugBreak();
  488. TerminateProcess(GetCurrentProcess(), 1);
  489. }
  490. } // namespace posix
  491. #endif // GTEST_OS_WINDOWS_MOBILE
  492. // Returns the name of the environment variable corresponding to the
  493. // given flag. For example, FlagToEnvVar("foo") will return
  494. // "GTEST_FOO" in the open-source version.
  495. static String FlagToEnvVar(const char* flag) {
  496. const String full_flag =
  497. (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
  498. Message env_var;
  499. for (size_t i = 0; i != full_flag.length(); i++) {
  500. env_var << static_cast<char>(toupper(full_flag.c_str()[i]));
  501. }
  502. return env_var.GetString();
  503. }
  504. // Parses 'str' for a 32-bit signed integer. If successful, writes
  505. // the result to *value and returns true; otherwise leaves *value
  506. // unchanged and returns false.
  507. bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
  508. // Parses the environment variable as a decimal integer.
  509. char* end = NULL;
  510. const long long_value = strtol(str, &end, 10); // NOLINT
  511. // Has strtol() consumed all characters in the string?
  512. if (*end != '\0') {
  513. // No - an invalid character was encountered.
  514. Message msg;
  515. msg << "WARNING: " << src_text
  516. << " is expected to be a 32-bit integer, but actually"
  517. << " has value \"" << str << "\".\n";
  518. printf("%s", msg.GetString().c_str());
  519. fflush(stdout);
  520. return false;
  521. }
  522. // Is the parsed value in the range of an Int32?
  523. const Int32 result = static_cast<Int32>(long_value);
  524. if (long_value == LONG_MAX || long_value == LONG_MIN ||
  525. // The parsed value overflows as a long. (strtol() returns
  526. // LONG_MAX or LONG_MIN when the input overflows.)
  527. result != long_value
  528. // The parsed value overflows as an Int32.
  529. ) {
  530. Message msg;
  531. msg << "WARNING: " << src_text
  532. << " is expected to be a 32-bit integer, but actually"
  533. << " has value " << str << ", which overflows.\n";
  534. printf("%s", msg.GetString().c_str());
  535. fflush(stdout);
  536. return false;
  537. }
  538. *value = result;
  539. return true;
  540. }
  541. // Reads and returns the Boolean environment variable corresponding to
  542. // the given flag; if it's not set, returns default_value.
  543. //
  544. // The value is considered true iff it's not "0".
  545. bool BoolFromGTestEnv(const char* flag, bool default_value) {
  546. const String env_var = FlagToEnvVar(flag);
  547. const char* const string_value = posix::GetEnv(env_var.c_str());
  548. return string_value == NULL ?
  549. default_value : strcmp(string_value, "0") != 0;
  550. }
  551. // Reads and returns a 32-bit integer stored in the environment
  552. // variable corresponding to the given flag; if it isn't set or
  553. // doesn't represent a valid 32-bit integer, returns default_value.
  554. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
  555. const String env_var = FlagToEnvVar(flag);
  556. const char* const string_value = posix::GetEnv(env_var.c_str());
  557. if (string_value == NULL) {
  558. // The environment variable is not set.
  559. return default_value;
  560. }
  561. Int32 result = default_value;
  562. if (!ParseInt32(Message() << "Environment variable " << env_var,
  563. string_value, &result)) {
  564. printf("The default value %s is used.\n",
  565. (Message() << default_value).GetString().c_str());
  566. fflush(stdout);
  567. return default_value;
  568. }
  569. return result;
  570. }
  571. // Reads and returns the string environment variable corresponding to
  572. // the given flag; if it's not set, returns default_value.
  573. const char* StringFromGTestEnv(const char* flag, const char* default_value) {
  574. const String env_var = FlagToEnvVar(flag);
  575. const char* const value = posix::GetEnv(env_var.c_str());
  576. return value == NULL ? default_value : value;
  577. }
  578. } // namespace internal
  579. } // namespace testing