Debian Codegraph @

unit_tests/gtest/src/gtest-port.cc

raw
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: [email protected] (Zhanyong Wan)
31
32 #include "gtest/internal/gtest-port.h"
33
34 #include <limits.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <string.h>
38
39 #if GTEST_OS_WINDOWS_MOBILE
40 # include <windows.h> // For TerminateProcess()
41 #elif GTEST_OS_WINDOWS
42 # include <io.h>
43 # include <sys/stat.h>
44 #else
45 # include <unistd.h>
46 #endif // GTEST_OS_WINDOWS_MOBILE
47
48 #if GTEST_OS_MAC
49 # include <mach/mach_init.h>
50 # include <mach/task.h>
51 # include <mach/vm_map.h>
52 #endif // GTEST_OS_MAC
53
54 #include "gtest/gtest-spi.h"
55 #include "gtest/gtest-message.h"
56 #include "gtest/internal/gtest-internal.h"
57 #include "gtest/internal/gtest-string.h"
58
59 // Indicates that this translation unit is part of Google Test's
60 // implementation. It must come before gtest-internal-inl.h is
61 // included, or there will be a compiler error. This trick is to
62 // prevent a user from accidentally including gtest-internal-inl.h in
63 // his code.
64 #define GTEST_IMPLEMENTATION_ 1
65 #include "src/gtest-internal-inl.h"
66 #undef GTEST_IMPLEMENTATION_
67
68 #ifdef __ICC
69 // Disable explicit warning on Intel compiler
70 #pragma warning disable 2304
71 #endif
72
73
74 namespace testing {
75 namespace internal {
76
77 #if defined(_MSC_VER) || defined(__BORLANDC__)
78 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
79 const int kStdOutFileno = 1;
80 const int kStdErrFileno = 2;
81 #else
82 const int kStdOutFileno = STDOUT_FILENO;
83 const int kStdErrFileno = STDERR_FILENO;
84 #endif // _MSC_VER
85
86 #if GTEST_OS_MAC
87
88 // Returns the number of threads running in the process, or 0 to indicate that
89 // we cannot detect it.
90 size_t GetThreadCount() {
91 const task_t task = mach_task_self();
92 mach_msg_type_number_t thread_count;
93 thread_act_array_t thread_list;
94 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
95 if (status == KERN_SUCCESS) {
96 // task_threads allocates resources in thread_list and we need to free them
97 // to avoid leaks.
98 vm_deallocate(task,
99 reinterpret_cast<vm_address_t>(thread_list),
100 sizeof(thread_t) * thread_count);
101 return static_cast<size_t>(thread_count);
102 } else {
103 return 0;
104 }
105 }
106
107 #else
108
109 size_t GetThreadCount() {
110 // There's no portable way to detect the number of threads, so we just
111 // return 0 to indicate that we cannot detect it.
112 return 0;
113 }
114
115 #endif // GTEST_OS_MAC
116
117 #if GTEST_USES_POSIX_RE
118
119 // Implements RE. Currently only needed for death tests.
120
121 RE::~RE() {
122 if (is_valid_) {
123 // regfree'ing an invalid regex might crash because the content
124 // of the regex is undefined. Since the regex's are essentially
125 // the same, one cannot be valid (or invalid) without the other
126 // being so too.
127 regfree(&partial_regex_);
128 regfree(&full_regex_);
129 }
130 free(const_cast<char*>(pattern_));
131 }
132
133 // Returns true iff regular expression re matches the entire str.
134 bool RE::FullMatch(const char* str, const RE& re) {
135 if (!re.is_valid_) return false;
136
137 regmatch_t match;
138 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
139 }
140
141 // Returns true iff regular expression re matches a substring of str
142 // (including str itself).
143 bool RE::PartialMatch(const char* str, const RE& re) {
144 if (!re.is_valid_) return false;
145
146 regmatch_t match;
147 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
148 }
149
150 // Initializes an RE from its string representation.
151 void RE::Init(const char* regex) {
152 pattern_ = posix::StrDup(regex);
153
154 // Reserves enough bytes to hold the regular expression used for a
155 // full match.
156 const size_t full_regex_len = strlen(regex) + 10;
157 char* const full_pattern = new char[full_regex_len];
158
159 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
160 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
161 // We want to call regcomp(&partial_regex_, ...) even if the
162 // previous expression returns false. Otherwise partial_regex_ may
163 // not be properly initialized can may cause trouble when it's
164 // freed.
165 //
166 // Some implementation of POSIX regex (e.g. on at least some
167 // versions of Cygwin) doesn't accept the empty string as a valid
168 // regex. We change it to an equivalent form "()" to be safe.
169 if (is_valid_) {
170 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
171 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
172 }
173 EXPECT_TRUE(is_valid_)
174 << "Regular expression \"" << regex
175 << "\" is not a valid POSIX Extended regular expression.";
176
177 delete[] full_pattern;
178 }
179
180 #elif GTEST_USES_SIMPLE_RE
181
182 // Returns true iff ch appears anywhere in str (excluding the
183 // terminating '\0' character).
184 bool IsInSet(char ch, const char* str) {
185 return ch != '\0' && strchr(str, ch) != NULL;
186 }
187
188 // Returns true iff ch belongs to the given classification. Unlike
189 // similar functions in <ctype.h>, these aren't affected by the
190 // current locale.
191 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
192 bool IsAsciiPunct(char ch) {
193 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
194 }
195 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
196 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
197 bool IsAsciiWordChar(char ch) {
198 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
199 ('0' <= ch && ch <= '9') || ch == '_';
200 }
201
202 // Returns true iff "\\c" is a supported escape sequence.
203 bool IsValidEscape(char c) {
204 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
205 }
206
207 // Returns true iff the given atom (specified by escaped and pattern)
208 // matches ch. The result is undefined if the atom is invalid.
209 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
210 if (escaped) { // "\\p" where p is pattern_char.
211 switch (pattern_char) {
212 case 'd': return IsAsciiDigit(ch);
213 case 'D': return !IsAsciiDigit(ch);
214 case 'f': return ch == '\f';
215 case 'n': return ch == '\n';
216 case 'r': return ch == '\r';
217 case 's': return IsAsciiWhiteSpace(ch);
218 case 'S': return !IsAsciiWhiteSpace(ch);
219 case 't': return ch == '\t';
220 case 'v': return ch == '\v';
221 case 'w': return IsAsciiWordChar(ch);
222 case 'W': return !IsAsciiWordChar(ch);
223 }
224 return IsAsciiPunct(pattern_char) && pattern_char == ch;
225 }
226
227 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
228 }
229
230 // Helper function used by ValidateRegex() to format error messages.
231 String FormatRegexSyntaxError(const char* regex, int index) {
232 return (Message() << "Syntax error at index " << index
233 << " in simple regular expression \"" << regex << "\": ").GetString();
234 }
235
236 // Generates non-fatal failures and returns false if regex is invalid;
237 // otherwise returns true.
238 bool ValidateRegex(const char* regex) {
239 if (regex == NULL) {
240 // TODO([email protected]): fix the source file location in the
241 // assertion failures to match where the regex is used in user
242 // code.
243 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
244 return false;
245 }
246
247 bool is_valid = true;
248
249 // True iff ?, *, or + can follow the previous atom.
250 bool prev_repeatable = false;
251 for (int i = 0; regex[i]; i++) {
252 if (regex[i] == '\\') { // An escape sequence
253 i++;
254 if (regex[i] == '\0') {
255 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
256 << "'\\' cannot appear at the end.";
257 return false;
258 }
259
260 if (!IsValidEscape(regex[i])) {
261 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
262 << "invalid escape sequence \"\\" << regex[i] << "\".";
263 is_valid = false;
264 }
265 prev_repeatable = true;
266 } else { // Not an escape sequence.
267 const char ch = regex[i];
268
269 if (ch == '^' && i > 0) {
270 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
271 << "'^' can only appear at the beginning.";
272 is_valid = false;
273 } else if (ch == '$' && regex[i + 1] != '\0') {
274 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
275 << "'$' can only appear at the end.";
276 is_valid = false;
277 } else if (IsInSet(ch, "()[]{}|")) {
278 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
279 << "'" << ch << "' is unsupported.";
280 is_valid = false;
281 } else if (IsRepeat(ch) && !prev_repeatable) {
282 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
283 << "'" << ch << "' can only follow a repeatable token.";
284 is_valid = false;
285 }
286
287 prev_repeatable = !IsInSet(ch, "^$?*+");
288 }
289 }
290
291 return is_valid;
292 }
293
294 // Matches a repeated regex atom followed by a valid simple regular
295 // expression. The regex atom is defined as c if escaped is false,
296 // or \c otherwise. repeat is the repetition meta character (?, *,
297 // or +). The behavior is undefined if str contains too many
298 // characters to be indexable by size_t, in which case the test will
299 // probably time out anyway. We are fine with this limitation as
300 // std::string has it too.
301 bool MatchRepetitionAndRegexAtHead(
302 bool escaped, char c, char repeat, const char* regex,
303 const char* str) {
304 const size_t min_count = (repeat == '+') ? 1 : 0;
305 const size_t max_count = (repeat == '?') ? 1 :
306 static_cast<size_t>(-1) - 1;
307 // We cannot call numeric_limits::max() as it conflicts with the
308 // max() macro on Windows.
309
310 for (size_t i = 0; i <= max_count; ++i) {
311 // We know that the atom matches each of the first i characters in str.
312 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
313 // We have enough matches at the head, and the tail matches too.
314 // Since we only care about *whether* the pattern matches str
315 // (as opposed to *how* it matches), there is no need to find a
316 // greedy match.
317 return true;
318 }
319 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
320 return false;
321 }
322 return false;
323 }
324
325 // Returns true iff regex matches a prefix of str. regex must be a
326 // valid simple regular expression and not start with "^", or the
327 // result is undefined.
328 bool MatchRegexAtHead(const char* regex, const char* str) {
329 if (*regex == '\0') // An empty regex matches a prefix of anything.
330 return true;
331
332 // "$" only matches the end of a string. Note that regex being
333 // valid guarantees that there's nothing after "$" in it.
334 if (*regex == '$')
335 return *str == '\0';
336
337 // Is the first thing in regex an escape sequence?
338 const bool escaped = *regex == '\\';
339 if (escaped)
340 ++regex;
341 if (IsRepeat(regex[1])) {
342 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
343 // here's an indirect recursion. It terminates as the regex gets
344 // shorter in each recursion.
345 return MatchRepetitionAndRegexAtHead(
346 escaped, regex[0], regex[1], regex + 2, str);
347 } else {
348 // regex isn't empty, isn't "$", and doesn't start with a
349 // repetition. We match the first atom of regex with the first
350 // character of str and recurse.
351 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
352 MatchRegexAtHead(regex + 1, str + 1);
353 }
354 }
355
356 // Returns true iff regex matches any substring of str. regex must be
357 // a valid simple regular expression, or the result is undefined.
358 //
359 // The algorithm is recursive, but the recursion depth doesn't exceed
360 // the regex length, so we won't need to worry about running out of
361 // stack space normally. In rare cases the time complexity can be
362 // exponential with respect to the regex length + the string length,
363 // but usually it's must faster (often close to linear).
364 bool MatchRegexAnywhere(const char* regex, const char* str) {
365 if (regex == NULL || str == NULL)
366 return false;
367
368 if (*regex == '^')
369 return MatchRegexAtHead(regex + 1, str);
370
371 // A successful match can be anywhere in str.
372 do {
373 if (MatchRegexAtHead(regex, str))
374 return true;
375 } while (*str++ != '\0');
376 return false;
377 }
378
379 // Implements the RE class.
380
381 RE::~RE() {
382 free(const_cast<char*>(pattern_));
383 free(const_cast<char*>(full_pattern_));
384 }
385
386 // Returns true iff regular expression re matches the entire str.
387 bool RE::FullMatch(const char* str, const RE& re) {
388 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
389 }
390
391 // Returns true iff regular expression re matches a substring of str
392 // (including str itself).
393 bool RE::PartialMatch(const char* str, const RE& re) {
394 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
395 }
396
397 // Initializes an RE from its string representation.
398 void RE::Init(const char* regex) {
399 pattern_ = full_pattern_ = NULL;
400 if (regex != NULL) {
401 pattern_ = posix::StrDup(regex);
402 }
403
404 is_valid_ = ValidateRegex(regex);
405 if (!is_valid_) {
406 // No need to calculate the full pattern when the regex is invalid.
407 return;
408 }
409
410 const size_t len = strlen(regex);
411 // Reserves enough bytes to hold the regular expression used for a
412 // full match: we need space to prepend a '^', append a '$', and
413 // terminate the string with '\0'.
414 char* buffer = static_cast<char*>(malloc(len + 3));
415 full_pattern_ = buffer;
416
417 if (*regex != '^')
418 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
419
420 // We don't use snprintf or strncpy, as they trigger a warning when
421 // compiled with VC++ 8.0.
422 memcpy(buffer, regex, len);
423 buffer += len;
424
425 if (len == 0 || regex[len - 1] != '$')
426 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
427
428 *buffer = '\0';
429 }
430
431 #endif // GTEST_USES_POSIX_RE
432
433 const char kUnknownFile[] = "unknown file";
434
435 // Formats a source file path and a line number as they would appear
436 // in an error message from the compiler used to compile this code.
437 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
438 const char* const file_name = file == NULL ? kUnknownFile : file;
439
440 if (line < 0) {
441 return String::Format("%s:", file_name).c_str();
442 }
443 #ifdef _MSC_VER
444 return String::Format("%s(%d):", file_name, line).c_str();
445 #else
446 return String::Format("%s:%d:", file_name, line).c_str();
447 #endif // _MSC_VER
448 }
449
450 // Formats a file location for compiler-independent XML output.
451 // Although this function is not platform dependent, we put it next to
452 // FormatFileLocation in order to contrast the two functions.
453 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
454 // to the file location it produces, unlike FormatFileLocation().
455 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
456 const char* file, int line) {
457 const char* const file_name = file == NULL ? kUnknownFile : file;
458
459 if (line < 0)
460 return file_name;
461 else
462 return String::Format("%s:%d", file_name, line).c_str();
463 }
464
465
466 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
467 : severity_(severity) {
468 const char* const marker =
469 severity == GTEST_INFO ? "[ INFO ]" :
470 severity == GTEST_WARNING ? "[WARNING]" :
471 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
472 GetStream() << ::std::endl << marker << " "
473 << FormatFileLocation(file, line).c_str() << ": ";
474 }
475
476 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
477 GTestLog::~GTestLog() {
478 GetStream() << ::std::endl;
479 if (severity_ == GTEST_FATAL) {
480 fflush(stderr);
481 posix::Abort();
482 }
483 }
484 // Disable Microsoft deprecation warnings for POSIX functions called from
485 // this class (creat, dup, dup2, and close)
486 #ifdef _MSC_VER
487 # pragma warning(push)
488 # pragma warning(disable: 4996)
489 #endif // _MSC_VER
490
491 #if GTEST_HAS_STREAM_REDIRECTION
492
493 // Object that captures an output stream (stdout/stderr).
494 class CapturedStream {
495 public:
496 // The ctor redirects the stream to a temporary file.
497 CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
498
499 # if GTEST_OS_WINDOWS
500 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
501 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
502
503 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
504 const UINT success = ::GetTempFileNameA(temp_dir_path,
505 "gtest_redir",
506 0, // Generate unique file name.
507 temp_file_path);
508 GTEST_CHECK_(success != 0)
509 << "Unable to create a temporary file in " << temp_dir_path;
510 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
511 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
512 << temp_file_path;
513 filename_ = temp_file_path;
514 # else
515 // There's no guarantee that a test has write access to the
516 // current directory, so we create the temporary file in the /tmp
517 // directory instead.
518 char name_template[] = "/tmp/captured_stream.XXXXXX";
519 const int captured_fd = mkstemp(name_template);
520 filename_ = name_template;
521 # endif // GTEST_OS_WINDOWS
522 fflush(NULL);
523 dup2(captured_fd, fd_);
524 close(captured_fd);
525 }
526
527 ~CapturedStream() {
528 remove(filename_.c_str());
529 }
530
531 String GetCapturedString() {
532 if (uncaptured_fd_ != -1) {
533 // Restores the original stream.
534 fflush(NULL);
535 dup2(uncaptured_fd_, fd_);
536 close(uncaptured_fd_);
537 uncaptured_fd_ = -1;
538 }
539
540 FILE* const file = posix::FOpen(filename_.c_str(), "r");
541 const String content = ReadEntireFile(file);
542 posix::FClose(file);
543 return content;
544 }
545
546 private:
547 // Reads the entire content of a file as a String.
548 static String ReadEntireFile(FILE* file);
549
550 // Returns the size (in bytes) of a file.
551 static size_t GetFileSize(FILE* file);
552
553 const int fd_; // A stream to capture.
554 int uncaptured_fd_;
555 // Name of the temporary file holding the stderr output.
556 ::std::string filename_;
557
558 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
559 };
560
561 // Returns the size (in bytes) of a file.
562 size_t CapturedStream::GetFileSize(FILE* file) {
563 fseek(file, 0, SEEK_END);
564 return static_cast<size_t>(ftell(file));
565 }
566
567 // Reads the entire content of a file as a string.
568 String CapturedStream::ReadEntireFile(FILE* file) {
569 const size_t file_size = GetFileSize(file);
570 char* const buffer = new char[file_size];
571
572 size_t bytes_last_read = 0; // # of bytes read in the last fread()
573 size_t bytes_read = 0; // # of bytes read so far
574
575 fseek(file, 0, SEEK_SET);
576
577 // Keeps reading the file until we cannot read further or the
578 // pre-determined file size is reached.
579 do {
580 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
581 bytes_read += bytes_last_read;
582 } while (bytes_last_read > 0 && bytes_read < file_size);
583
584 const String content(buffer, bytes_read);
585 delete[] buffer;
586
587 return content;
588 }
589
590 # ifdef _MSC_VER
591 # pragma warning(pop)
592 # endif // _MSC_VER
593
594 static CapturedStream* g_captured_stderr = NULL;
595 static CapturedStream* g_captured_stdout = NULL;
596
597 // Starts capturing an output stream (stdout/stderr).
598 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
599 if (*stream != NULL) {
600 GTEST_LOG_(FATAL) << "Only one " << stream_name
601 << " capturer can exist at a time.";
602 }
603 *stream = new CapturedStream(fd);
604 }
605
606 // Stops capturing the output stream and returns the captured string.
607 String GetCapturedStream(CapturedStream** captured_stream) {
608 const String content = (*captured_stream)->GetCapturedString();
609
610 delete *captured_stream;
611 *captured_stream = NULL;
612
613 return content;
614 }
615
616 // Starts capturing stdout.
617 void CaptureStdout() {
618 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
619 }
620
621 // Starts capturing stderr.
622 void CaptureStderr() {
623 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
624 }
625
626 // Stops capturing stdout and returns the captured string.
627 String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); }
628
629 // Stops capturing stderr and returns the captured string.
630 String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); }
631
632 #endif // GTEST_HAS_STREAM_REDIRECTION
633
634 #if GTEST_HAS_DEATH_TEST
635
636 // A copy of all command line arguments. Set by InitGoogleTest().
637 ::std::vector<String> g_argvs;
638
639 // Returns the command line as a vector of strings.
640 const ::std::vector<String>& GetArgvs() { return g_argvs; }
641
642 #endif // GTEST_HAS_DEATH_TEST
643
644 #if GTEST_OS_WINDOWS_MOBILE
645 namespace posix {
646 void Abort() {
647 DebugBreak();
648 TerminateProcess(GetCurrentProcess(), 1);
649 }
650 } // namespace posix
651 #endif // GTEST_OS_WINDOWS_MOBILE
652
653 // Returns the name of the environment variable corresponding to the
654 // given flag. For example, FlagToEnvVar("foo") will return
655 // "GTEST_FOO" in the open-source version.
656 static String FlagToEnvVar(const char* flag) {
657 const String full_flag =
658 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
659
660 Message env_var;
661 for (size_t i = 0; i != full_flag.length(); i++) {
662 env_var << ToUpper(full_flag.c_str()[i]);
663 }
664
665 return env_var.GetString();
666 }
667
668 // Parses 'str' for a 32-bit signed integer. If successful, writes
669 // the result to *value and returns true; otherwise leaves *value
670 // unchanged and returns false.
671 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
672 // Parses the environment variable as a decimal integer.
673 char* end = NULL;
674 const long long_value = strtol(str, &end, 10); // NOLINT
675
676 // Has strtol() consumed all characters in the string?
677 if (*end != '\0') {
678 // No - an invalid character was encountered.
679 Message msg;
680 msg << "WARNING: " << src_text
681 << " is expected to be a 32-bit integer, but actually"
682 << " has value \"" << str << "\".\n";
683 printf("%s", msg.GetString().c_str());
684 fflush(stdout);
685 return false;
686 }
687
688 // Is the parsed value in the range of an Int32?
689 const Int32 result = static_cast<Int32>(long_value);
690 if (long_value == LONG_MAX || long_value == LONG_MIN ||
691 // The parsed value overflows as a long. (strtol() returns
692 // LONG_MAX or LONG_MIN when the input overflows.)
693 result != long_value
694 // The parsed value overflows as an Int32.
695 ) {
696 Message msg;
697 msg << "WARNING: " << src_text
698 << " is expected to be a 32-bit integer, but actually"
699 << " has value " << str << ", which overflows.\n";
700 printf("%s", msg.GetString().c_str());
701 fflush(stdout);
702 return false;
703 }
704
705 *value = result;
706 return true;
707 }
708
709 // Reads and returns the Boolean environment variable corresponding to
710 // the given flag; if it's not set, returns default_value.
711 //
712 // The value is considered true iff it's not "0".
713 bool BoolFromGTestEnv(const char* flag, bool default_value) {
714 const String env_var = FlagToEnvVar(flag);
715 const char* const string_value = posix::GetEnv(env_var.c_str());
716 return string_value == NULL ?
717 default_value : strcmp(string_value, "0") != 0;
718 }
719
720 // Reads and returns a 32-bit integer stored in the environment
721 // variable corresponding to the given flag; if it isn't set or
722 // doesn't represent a valid 32-bit integer, returns default_value.
723 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
724 const String env_var = FlagToEnvVar(flag);
725 const char* const string_value = posix::GetEnv(env_var.c_str());
726 if (string_value == NULL) {
727 // The environment variable is not set.
728 return default_value;
729 }
730
731 Int32 result = default_value;
732 if (!ParseInt32(Message() << "Environment variable " << env_var,
733 string_value, &result)) {
734 printf("The default value %s is used.\n",
735 (Message() << default_value).GetString().c_str());
736 fflush(stdout);
737 return default_value;
738 }
739
740 return result;
741 }
742
743 // Reads and returns the string environment variable corresponding to
744 // the given flag; if it's not set, returns default_value.
745 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
746 const String env_var = FlagToEnvVar(flag);
747 const char* const value = posix::GetEnv(env_var.c_str());
748 return value == NULL ? default_value : value;
749 }
750
751 } // namespace internal
752 } // namespace testing