Import of Google Test 1.2.1, with the non-essential bits removed.
[oota-llvm.git] / utils / unittest / googletest / src / gtest-port.cc
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
32 #include <gtest/internal/gtest-port.h>
33
34 #include <limits.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37
38 #ifdef GTEST_HAS_DEATH_TEST
39 #include <regex.h>
40 #endif  // GTEST_HAS_DEATH_TEST
41
42 #ifdef _WIN32_WCE
43 #include <windows.h>  // For TerminateProcess()
44 #endif  // _WIN32_WCE
45
46 #include <gtest/gtest-spi.h>
47 #include <gtest/gtest-message.h>
48 #include <gtest/internal/gtest-string.h>
49
50
51 namespace testing {
52 namespace internal {
53
54 #ifdef GTEST_HAS_DEATH_TEST
55
56 // Implements RE.  Currently only needed for death tests.
57
58 RE::~RE() {
59   regfree(&partial_regex_);
60   regfree(&full_regex_);
61   free(const_cast<char*>(pattern_));
62 }
63
64 // Returns true iff regular expression re matches the entire str.
65 bool RE::FullMatch(const char* str, const RE& re) {
66   if (!re.is_valid_) return false;
67
68   regmatch_t match;
69   return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
70 }
71
72 // Returns true iff regular expression re matches a substring of str
73 // (including str itself).
74 bool RE::PartialMatch(const char* str, const RE& re) {
75   if (!re.is_valid_) return false;
76
77   regmatch_t match;
78   return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
79 }
80
81 // Initializes an RE from its string representation.
82 void RE::Init(const char* regex) {
83   pattern_ = strdup(regex);
84
85   // Reserves enough bytes to hold the regular expression used for a
86   // full match.
87   const size_t full_regex_len = strlen(regex) + 10;
88   char* const full_pattern = new char[full_regex_len];
89
90   snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
91   is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
92   // We want to call regcomp(&partial_regex_, ...) even if the
93   // previous expression returns false.  Otherwise partial_regex_ may
94   // not be properly initialized can may cause trouble when it's
95   // freed.
96   is_valid_ = (regcomp(&partial_regex_, regex, REG_EXTENDED) == 0) && is_valid_;
97   EXPECT_TRUE(is_valid_)
98       << "Regular expression \"" << regex
99       << "\" is not a valid POSIX Extended regular expression.";
100
101   delete[] full_pattern;
102 }
103
104 #endif  // GTEST_HAS_DEATH_TEST
105
106 // Logs a message at the given severity level.
107 void GTestLog(GTestLogSeverity severity, const char* file,
108               int line, const char* msg) {
109   const char* const marker =
110       severity == GTEST_INFO ?    "[  INFO ]" :
111       severity == GTEST_WARNING ? "[WARNING]" :
112       severity == GTEST_ERROR ?   "[ ERROR ]" : "[ FATAL ]";
113   fprintf(stderr, "\n%s %s:%d: %s\n", marker, file, line, msg);
114   if (severity == GTEST_FATAL) {
115     abort();
116   }
117 }
118
119 #ifdef GTEST_HAS_DEATH_TEST
120
121 // Defines the stderr capturer.
122
123 class CapturedStderr {
124  public:
125   // The ctor redirects stderr to a temporary file.
126   CapturedStderr() {
127     uncaptured_fd_ = dup(STDERR_FILENO);
128
129     // There's no guarantee that a test has write access to the
130     // current directory, so we create the temporary file in the /tmp
131     // directory instead.
132     char name_template[] = "/tmp/captured_stderr.XXXXXX";
133     const int captured_fd = mkstemp(name_template);
134     filename_ = name_template;
135     fflush(NULL);
136     dup2(captured_fd, STDERR_FILENO);
137     close(captured_fd);
138   }
139
140   ~CapturedStderr() {
141     remove(filename_.c_str());
142   }
143
144   // Stops redirecting stderr.
145   void StopCapture() {
146     // Restores the original stream.
147     fflush(NULL);
148     dup2(uncaptured_fd_, STDERR_FILENO);
149     close(uncaptured_fd_);
150     uncaptured_fd_ = -1;
151   }
152
153   // Returns the name of the temporary file holding the stderr output.
154   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
155   // can use it here.
156   ::std::string filename() const { return filename_; }
157
158  private:
159   int uncaptured_fd_;
160   ::std::string filename_;
161 };
162
163 static CapturedStderr* g_captured_stderr = NULL;
164
165 // Returns the size (in bytes) of a file.
166 static size_t GetFileSize(FILE * file) {
167   fseek(file, 0, SEEK_END);
168   return static_cast<size_t>(ftell(file));
169 }
170
171 // Reads the entire content of a file as a string.
172 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can
173 // use it here.
174 static ::std::string ReadEntireFile(FILE * file) {
175   const size_t file_size = GetFileSize(file);
176   char* const buffer = new char[file_size];
177
178   size_t bytes_last_read = 0;  // # of bytes read in the last fread()
179   size_t bytes_read = 0;       // # of bytes read so far
180
181   fseek(file, 0, SEEK_SET);
182
183   // Keeps reading the file until we cannot read further or the
184   // pre-determined file size is reached.
185   do {
186     bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
187     bytes_read += bytes_last_read;
188   } while (bytes_last_read > 0 && bytes_read < file_size);
189
190   const ::std::string content(buffer, buffer+bytes_read);
191   delete[] buffer;
192
193   return content;
194 }
195
196 // Starts capturing stderr.
197 void CaptureStderr() {
198   if (g_captured_stderr != NULL) {
199     GTEST_LOG_(FATAL, "Only one stderr capturer can exist at one time.");
200   }
201   g_captured_stderr = new CapturedStderr;
202 }
203
204 // Stops capturing stderr and returns the captured string.
205 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can
206 // use it here.
207 ::std::string GetCapturedStderr() {
208   g_captured_stderr->StopCapture();
209   FILE* const file = fopen(g_captured_stderr->filename().c_str(), "r");
210   const ::std::string content = ReadEntireFile(file);
211   fclose(file);
212
213   delete g_captured_stderr;
214   g_captured_stderr = NULL;
215
216   return content;
217 }
218
219 // A copy of all command line arguments.  Set by InitGoogleTest().
220 ::std::vector<String> g_argvs;
221
222 // Returns the command line as a vector of strings.
223 const ::std::vector<String>& GetArgvs() { return g_argvs; }
224
225 #endif  // GTEST_HAS_DEATH_TEST
226
227 #ifdef _WIN32_WCE
228 void abort() {
229   DebugBreak();
230   TerminateProcess(GetCurrentProcess(), 1);
231 }
232 #endif  // _WIN32_WCE
233
234 // Returns the name of the environment variable corresponding to the
235 // given flag.  For example, FlagToEnvVar("foo") will return
236 // "GTEST_FOO" in the open-source version.
237 static String FlagToEnvVar(const char* flag) {
238   const String full_flag = (Message() << GTEST_FLAG_PREFIX << flag).GetString();
239
240   Message env_var;
241   for (int i = 0; i != full_flag.GetLength(); i++) {
242     env_var << static_cast<char>(toupper(full_flag.c_str()[i]));
243   }
244
245   return env_var.GetString();
246 }
247
248 // Reads and returns the Boolean environment variable corresponding to
249 // the given flag; if it's not set, returns default_value.
250 //
251 // The value is considered true iff it's not "0".
252 bool BoolFromGTestEnv(const char* flag, bool default_value) {
253   const String env_var = FlagToEnvVar(flag);
254   const char* const string_value = GetEnv(env_var.c_str());
255   return string_value == NULL ?
256       default_value : strcmp(string_value, "0") != 0;
257 }
258
259 // Parses 'str' for a 32-bit signed integer.  If successful, writes
260 // the result to *value and returns true; otherwise leaves *value
261 // unchanged and returns false.
262 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
263   // Parses the environment variable as a decimal integer.
264   char* end = NULL;
265   const long long_value = strtol(str, &end, 10);  // NOLINT
266
267   // Has strtol() consumed all characters in the string?
268   if (*end != '\0') {
269     // No - an invalid character was encountered.
270     Message msg;
271     msg << "WARNING: " << src_text
272         << " is expected to be a 32-bit integer, but actually"
273         << " has value \"" << str << "\".\n";
274     printf("%s", msg.GetString().c_str());
275     fflush(stdout);
276     return false;
277   }
278
279   // Is the parsed value in the range of an Int32?
280   const Int32 result = static_cast<Int32>(long_value);
281   if (long_value == LONG_MAX || long_value == LONG_MIN ||
282       // The parsed value overflows as a long.  (strtol() returns
283       // LONG_MAX or LONG_MIN when the input overflows.)
284       result != long_value
285       // The parsed value overflows as an Int32.
286       ) {
287     Message msg;
288     msg << "WARNING: " << src_text
289         << " is expected to be a 32-bit integer, but actually"
290         << " has value " << str << ", which overflows.\n";
291     printf("%s", msg.GetString().c_str());
292     fflush(stdout);
293     return false;
294   }
295
296   *value = result;
297   return true;
298 }
299
300 // Reads and returns a 32-bit integer stored in the environment
301 // variable corresponding to the given flag; if it isn't set or
302 // doesn't represent a valid 32-bit integer, returns default_value.
303 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
304   const String env_var = FlagToEnvVar(flag);
305   const char* const string_value = GetEnv(env_var.c_str());
306   if (string_value == NULL) {
307     // The environment variable is not set.
308     return default_value;
309   }
310
311   Int32 result = default_value;
312   if (!ParseInt32(Message() << "Environment variable " << env_var,
313                   string_value, &result)) {
314     printf("The default value %s is used.\n",
315            (Message() << default_value).GetString().c_str());
316     fflush(stdout);
317     return default_value;
318   }
319
320   return result;
321 }
322
323 // Reads and returns the string environment variable corresponding to
324 // the given flag; if it's not set, returns default_value.
325 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
326   const String env_var = FlagToEnvVar(flag);
327   const char* const value = GetEnv(env_var.c_str());
328   return value == NULL ? default_value : value;
329 }
330
331 }  // namespace internal
332 }  // namespace testing