Bug Summary

File:root/firefox-clang/third_party/googletest/googletest/src/gtest-internal-inl.h
Warning:line 141, column 7
Excessive padding in 'class testing::internal::GTestFlagSaver' (32 padding bytes, where 0 is optimal). Optimal fields order: color_, death_test_style_, filter_, internal_run_death_test_, output_, stream_result_to_, random_seed_, repeat_, stack_trace_depth_, also_run_disabled_tests_, break_on_failure_, catch_exceptions_, death_test_use_fork_, fail_fast_, list_tests_, brief_, print_time_, print_utf8_, recreate_environments_when_repeating_, shuffle_, throw_on_failure_, consider reordering the fields or adding explicit padding members

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -O2 -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name gtest-all.cc -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -ffp-contract=off -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/third_party/zucchini/tests/gtest -fcoverage-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/third_party/zucchini/tests/gtest -resource-dir /usr/lib/llvm-23/lib/clang/23 -include /root/firefox-clang/config/gcc_hidden.h -include /root/firefox-clang/obj-x86_64-pc-linux-gnu/mozilla-config.h -D _GLIBCXX_ASSERTIONS=1 -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/system_wrappers -U _FORTIFY_SOURCE -D _FORTIFY_SOURCE=2 -D DEBUG=1 -D UNICODE -D ENABLED_VLOG_LEVEL=1 -I /root/firefox-clang/third_party/zucchini/tests/gtest -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/third_party/zucchini/tests/gtest -I /root/firefox-clang/third_party/abseil-cpp -I /root/firefox-clang/third_party/googletest/googletest -I /root/firefox-clang/third_party/googletest/googletest/include -I /root/firefox-clang/third_party/zucchini/chromium-shim -I /root/firefox-clang/third_party/zucchini/chromium -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nss -D MOZILLA_CLIENT -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/x86_64-linux-gnu/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16/backward -internal-isystem /usr/lib/llvm-23/lib/clang/23/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -Wno-error=pessimizing-move -Wno-error=large-by-value-copy=128 -Wno-error=implicit-int-float-conversion -Wno-error=thread-safety-analysis -Wno-error=tautological-type-limit-compare -Wno-invalid-offsetof -Wno-range-loop-analysis -Wno-deprecated-anon-enum-enum-conversion -Wno-deprecated-enum-enum-conversion -Wno-inline-new-delete -Wno-error=deprecated-declarations -Wno-error=array-bounds -Wno-error=free-nonheap-object -Wno-error=atomic-alignment -Wno-error=deprecated-builtins -Wno-psabi -Wno-error=builtin-macro-redefined -Wno-vla-cxx-extension -Wno-unknown-warning-option -Wno-character-conversion -std=gnu++20 -fdeprecated-macro -ferror-limit 19 -fstrict-flex-arrays=1 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fno-rtti -fgnuc-version=4.2.1 -fno-implicit-modules -fskip-odr-check-in-gmf -fno-sized-deallocation -fno-aligned-allocation -fdiagnostics-absolute-paths -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -mllvm -dwarf-linkage-names=Abstract -faddrsig -fdwarf2-cfi-asm -o /tmp/scan-build-2026-09-01-224014-2642839-1 -x c++ /root/firefox-clang/third_party/googletest/googletest/src/gtest-all.cc
1// Copyright 2005, 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// Utility functions and classes used by the Google C++ testing framework.//
31// This file contains purely Google Test's internal implementation. Please
32// DO NOT #INCLUDE IT IN A USER PROGRAM.
33
34#ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
35#define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
36
37#ifndef _WIN32_WCE
38#include <errno(*__errno_location ()).h>
39#endif // !_WIN32_WCE
40#include <stddef.h>
41#include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
42#include <string.h> // For memmove.
43
44#include <algorithm>
45#include <cstdint>
46#include <memory>
47#include <set>
48#include <string>
49#include <unordered_map>
50#include <vector>
51
52#include "gtest/internal/gtest-port.h"
53
54#if GTEST_CAN_STREAM_RESULTS_1
55#include <arpa/inet.h> // NOLINT
56#include <netdb.h> // NOLINT
57#endif
58
59#ifdef GTEST_OS_WINDOWS
60#include <windows.h> // NOLINT
61#endif // GTEST_OS_WINDOWS
62
63#include "gtest/gtest-spi.h"
64#include "gtest/gtest.h"
65
66GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
67/* class A needs to have dll-interface to be used by clients of class B */)
68
69// Declares the flags.
70//
71// We don't want the users to modify this flag in the code, but want
72// Google Test's own unit tests to be able to access it. Therefore we
73// declare it here as opposed to in gtest.h.
74GTEST_DECLARE_bool_(death_test_use_fork)namespace testing { extern bool FLAGS_gtest_death_test_use_fork
; } static_assert(true, "no-op to require trailing semicolon"
)
;
75
76namespace testing {
77namespace internal {
78
79// The value of GetTestTypeId() as seen from within the Google Test
80// library. This is solely for testing GetTestTypeId().
81GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
82
83// A valid random seed must be in [1, kMaxRandomSeed].
84const int kMaxRandomSeed = 99999;
85
86// g_help_flag is true if and only if the --help flag or an equivalent form
87// is specified on the command line.
88GTEST_API_ extern bool g_help_flag;
89
90// Returns the current time in milliseconds.
91GTEST_API_ TimeInMillis GetTimeInMillis();
92
93// Returns true if and only if Google Test should use colors in the output.
94GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
95
96// Formats the given time in milliseconds as seconds. If the input is an exact N
97// seconds, the output has a trailing decimal point (e.g., "N." instead of "N").
98GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
99
100// Converts the given time in milliseconds to a date string in the ISO 8601
101// format, without the timezone information. N.B.: due to the use the
102// non-reentrant localtime() function, this function is not thread safe. Do
103// not use it in any code that can be called from multiple threads.
104GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
105
106// Parses a string for an Int32 flag, in the form of "--flag=value".
107//
108// On success, stores the value of the flag in *value, and returns
109// true. On failure, returns false without changing *value.
110GTEST_API_ bool ParseFlag(const char* str, const char* flag, int32_t* value);
111
112// Returns a random seed in range [1, kMaxRandomSeed] based on the
113// given --gtest_random_seed flag value.
114inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {
115 const unsigned int raw_seed =
116 (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis())
117 : static_cast<unsigned int>(random_seed_flag);
118
119 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
120 // it's easy to type.
121 const int normalized_seed =
122 static_cast<int>((raw_seed - 1U) %
123 static_cast<unsigned int>(kMaxRandomSeed)) +
124 1;
125 return normalized_seed;
126}
127
128// Returns the first valid random seed after 'seed'. The behavior is
129// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
130// considered to be 1.
131inline int GetNextRandomSeed(int seed) {
132 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)switch (0) case 0: default: if (::testing::internal::IsTrue(1
<= seed && seed <= kMaxRandomSeed)) ; else ::testing
::internal::GTestLog(::testing::internal::GTEST_FATAL, "/root/firefox-clang/third_party/googletest/googletest/src/gtest-internal-inl.h"
, 132) .GetStream() << "Condition " "1 <= seed && seed <= kMaxRandomSeed"
" failed. "
133 << "Invalid random seed " << seed << " - must be in [1, "
134 << kMaxRandomSeed << "].";
135 const int next_seed = seed + 1;
136 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
137}
138
139// This class saves the values of all Google Test flags in its c'tor, and
140// restores them in its d'tor.
141class GTestFlagSaver {
Excessive padding in 'class testing::internal::GTestFlagSaver' (32 padding bytes, where 0 is optimal). Optimal fields order: color_, death_test_style_, filter_, internal_run_death_test_, output_, stream_result_to_, random_seed_, repeat_, stack_trace_depth_, also_run_disabled_tests_, break_on_failure_, catch_exceptions_, death_test_use_fork_, fail_fast_, list_tests_, brief_, print_time_, print_utf8_, recreate_environments_when_repeating_, shuffle_, throw_on_failure_, consider reordering the fields or adding explicit padding members
142 public:
143 // The c'tor.
144 GTestFlagSaver() {
145 also_run_disabled_tests_ = GTEST_FLAG_GET(also_run_disabled_tests)::testing::FLAGS_gtest_also_run_disabled_tests;
146 break_on_failure_ = GTEST_FLAG_GET(break_on_failure)::testing::FLAGS_gtest_break_on_failure;
147 catch_exceptions_ = GTEST_FLAG_GET(catch_exceptions)::testing::FLAGS_gtest_catch_exceptions;
148 color_ = GTEST_FLAG_GET(color)::testing::FLAGS_gtest_color;
149 death_test_style_ = GTEST_FLAG_GET(death_test_style)::testing::FLAGS_gtest_death_test_style;
150 death_test_use_fork_ = GTEST_FLAG_GET(death_test_use_fork)::testing::FLAGS_gtest_death_test_use_fork;
151 fail_fast_ = GTEST_FLAG_GET(fail_fast)::testing::FLAGS_gtest_fail_fast;
152 filter_ = GTEST_FLAG_GET(filter)::testing::FLAGS_gtest_filter;
153 internal_run_death_test_ = GTEST_FLAG_GET(internal_run_death_test)::testing::FLAGS_gtest_internal_run_death_test;
154 list_tests_ = GTEST_FLAG_GET(list_tests)::testing::FLAGS_gtest_list_tests;
155 output_ = GTEST_FLAG_GET(output)::testing::FLAGS_gtest_output;
156 brief_ = GTEST_FLAG_GET(brief)::testing::FLAGS_gtest_brief;
157 print_time_ = GTEST_FLAG_GET(print_time)::testing::FLAGS_gtest_print_time;
158 print_utf8_ = GTEST_FLAG_GET(print_utf8)::testing::FLAGS_gtest_print_utf8;
159 random_seed_ = GTEST_FLAG_GET(random_seed)::testing::FLAGS_gtest_random_seed;
160 repeat_ = GTEST_FLAG_GET(repeat)::testing::FLAGS_gtest_repeat;
161 recreate_environments_when_repeating_ =
162 GTEST_FLAG_GET(recreate_environments_when_repeating)::testing::FLAGS_gtest_recreate_environments_when_repeating;
163 shuffle_ = GTEST_FLAG_GET(shuffle)::testing::FLAGS_gtest_shuffle;
164 stack_trace_depth_ = GTEST_FLAG_GET(stack_trace_depth)::testing::FLAGS_gtest_stack_trace_depth;
165 stream_result_to_ = GTEST_FLAG_GET(stream_result_to)::testing::FLAGS_gtest_stream_result_to;
166 throw_on_failure_ = GTEST_FLAG_GET(throw_on_failure)::testing::FLAGS_gtest_throw_on_failure;
167 }
168
169 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
170 ~GTestFlagSaver() {
171 GTEST_FLAG_SET(also_run_disabled_tests, also_run_disabled_tests_)(void)(::testing::FLAGS_gtest_also_run_disabled_tests = also_run_disabled_tests_
)
;
172 GTEST_FLAG_SET(break_on_failure, break_on_failure_)(void)(::testing::FLAGS_gtest_break_on_failure = break_on_failure_
)
;
173 GTEST_FLAG_SET(catch_exceptions, catch_exceptions_)(void)(::testing::FLAGS_gtest_catch_exceptions = catch_exceptions_
)
;
174 GTEST_FLAG_SET(color, color_)(void)(::testing::FLAGS_gtest_color = color_);
175 GTEST_FLAG_SET(death_test_style, death_test_style_)(void)(::testing::FLAGS_gtest_death_test_style = death_test_style_
)
;
176 GTEST_FLAG_SET(death_test_use_fork, death_test_use_fork_)(void)(::testing::FLAGS_gtest_death_test_use_fork = death_test_use_fork_
)
;
177 GTEST_FLAG_SET(filter, filter_)(void)(::testing::FLAGS_gtest_filter = filter_);
178 GTEST_FLAG_SET(fail_fast, fail_fast_)(void)(::testing::FLAGS_gtest_fail_fast = fail_fast_);
179 GTEST_FLAG_SET(internal_run_death_test, internal_run_death_test_)(void)(::testing::FLAGS_gtest_internal_run_death_test = internal_run_death_test_
)
;
180 GTEST_FLAG_SET(list_tests, list_tests_)(void)(::testing::FLAGS_gtest_list_tests = list_tests_);
181 GTEST_FLAG_SET(output, output_)(void)(::testing::FLAGS_gtest_output = output_);
182 GTEST_FLAG_SET(brief, brief_)(void)(::testing::FLAGS_gtest_brief = brief_);
183 GTEST_FLAG_SET(print_time, print_time_)(void)(::testing::FLAGS_gtest_print_time = print_time_);
184 GTEST_FLAG_SET(print_utf8, print_utf8_)(void)(::testing::FLAGS_gtest_print_utf8 = print_utf8_);
185 GTEST_FLAG_SET(random_seed, random_seed_)(void)(::testing::FLAGS_gtest_random_seed = random_seed_);
186 GTEST_FLAG_SET(repeat, repeat_)(void)(::testing::FLAGS_gtest_repeat = repeat_);
187 GTEST_FLAG_SET(recreate_environments_when_repeating,(void)(::testing::FLAGS_gtest_recreate_environments_when_repeating
= recreate_environments_when_repeating_)
188 recreate_environments_when_repeating_)(void)(::testing::FLAGS_gtest_recreate_environments_when_repeating
= recreate_environments_when_repeating_)
;
189 GTEST_FLAG_SET(shuffle, shuffle_)(void)(::testing::FLAGS_gtest_shuffle = shuffle_);
190 GTEST_FLAG_SET(stack_trace_depth, stack_trace_depth_)(void)(::testing::FLAGS_gtest_stack_trace_depth = stack_trace_depth_
)
;
191 GTEST_FLAG_SET(stream_result_to, stream_result_to_)(void)(::testing::FLAGS_gtest_stream_result_to = stream_result_to_
)
;
192 GTEST_FLAG_SET(throw_on_failure, throw_on_failure_)(void)(::testing::FLAGS_gtest_throw_on_failure = throw_on_failure_
)
;
193 }
194
195 private:
196 // Fields for saving the original values of flags.
197 bool also_run_disabled_tests_;
198 bool break_on_failure_;
199 bool catch_exceptions_;
200 std::string color_;
201 std::string death_test_style_;
202 bool death_test_use_fork_;
203 bool fail_fast_;
204 std::string filter_;
205 std::string internal_run_death_test_;
206 bool list_tests_;
207 std::string output_;
208 bool brief_;
209 bool print_time_;
210 bool print_utf8_;
211 int32_t random_seed_;
212 int32_t repeat_;
213 bool recreate_environments_when_repeating_;
214 bool shuffle_;
215 int32_t stack_trace_depth_;
216 std::string stream_result_to_;
217 bool throw_on_failure_;
218};
219
220// Converts a Unicode code point to a narrow string in UTF-8 encoding.
221// code_point parameter is of type UInt32 because wchar_t may not be
222// wide enough to contain a code point.
223// If the code_point is not a valid Unicode code point
224// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
225// to "(Invalid Unicode 0xXXXXXXXX)".
226GTEST_API_ std::string CodePointToUtf8(uint32_t code_point);
227
228// Converts a wide string to a narrow string in UTF-8 encoding.
229// The wide string is assumed to have the following encoding:
230// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
231// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
232// Parameter str points to a null-terminated wide string.
233// Parameter num_chars may additionally limit the number
234// of wchar_t characters processed. -1 is used when the entire string
235// should be processed.
236// If the string contains code points that are not valid Unicode code points
237// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
238// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
239// and contains invalid UTF-16 surrogate pairs, values in those pairs
240// will be encoded as individual Unicode characters from Basic Normal Plane.
241GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
242
243// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
244// if the variable is present. If a file already exists at this location, this
245// function will write over it. If the variable is present, but the file cannot
246// be created, prints an error and exits.
247void WriteToShardStatusFileIfNeeded();
248
249// Checks whether sharding is enabled by examining the relevant flag values.
250// If the flags are set, but inconsistent (e.g., shard_index >= total_shards),
251// prints an error and exits. If in_subprocess_for_death_test, sharding is
252// disabled because it must only be applied to the original test
253// process. Otherwise, we could filter out death tests we intended to execute.
254GTEST_API_ bool ShouldShard(bool in_subprocess_for_death_test);
255
256// Parses the environment variable var as a 32-bit integer. If it is unset,
257// returns default_val. If it is not a 32-bit integer, prints an error and
258// and aborts.
259GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);
260
261// Given the total number of shards, the shard index, and the test id,
262// returns true if and only if the test should be run on this shard. The test id
263// is some arbitrary but unique non-negative integer assigned to each test
264// method. Assumes that 0 <= shard_index < total_shards.
265GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index,
266 int test_id);
267
268// STL container utilities.
269
270// Returns the number of elements in the given container that satisfy
271// the given predicate.
272template <class Container, typename Predicate>
273inline int CountIf(const Container& c, Predicate predicate) {
274 // Implemented as an explicit loop since std::count_if() in libCstd on
275 // Solaris has a non-standard signature.
276 int count = 0;
277 for (auto it = c.begin(); it != c.end(); ++it) {
278 if (predicate(*it)) ++count;
279 }
280 return count;
281}
282
283// Applies a function/functor to each element in the container.
284template <class Container, typename Functor>
285void ForEach(const Container& c, Functor functor) {
286 std::for_each(c.begin(), c.end(), functor);
287}
288
289// Returns the i-th element of the vector, or default_value if i is not
290// in range [0, v.size()).
291template <typename E>
292inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
293 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value
294 : v[static_cast<size_t>(i)];
295}
296
297// Performs an in-place shuffle of a range of the vector's elements.
298// 'begin' and 'end' are element indices as an STL-style range;
299// i.e. [begin, end) are shuffled, where 'end' == size() means to
300// shuffle to the end of the vector.
301template <typename E>
302void ShuffleRange(internal::Random* random, int begin, int end,
303 std::vector<E>* v) {
304 const int size = static_cast<int>(v->size());
305 GTEST_CHECK_(0 <= begin && begin <= size)switch (0) case 0: default: if (::testing::internal::IsTrue(0
<= begin && begin <= size)) ; else ::testing::
internal::GTestLog(::testing::internal::GTEST_FATAL, "/root/firefox-clang/third_party/googletest/googletest/src/gtest-internal-inl.h"
, 305) .GetStream() << "Condition " "0 <= begin && begin <= size"
" failed. "
306 << "Invalid shuffle range start " << begin << ": must be in range [0, "
307 << size << "].";
308 GTEST_CHECK_(begin <= end && end <= size)switch (0) case 0: default: if (::testing::internal::IsTrue(begin
<= end && end <= size)) ; else ::testing::internal
::GTestLog(::testing::internal::GTEST_FATAL, "/root/firefox-clang/third_party/googletest/googletest/src/gtest-internal-inl.h"
, 308) .GetStream() << "Condition " "begin <= end && end <= size"
" failed. "
309 << "Invalid shuffle range finish " << end << ": must be in range ["
310 << begin << ", " << size << "].";
311
312 // Fisher-Yates shuffle, from
313 // https://en.wikipedia.org/wiki/Fisher-Yates_shuffle
314 for (int range_width = end - begin; range_width >= 2; range_width--) {
315 const int last_in_range = begin + range_width - 1;
316 const int selected =
317 begin +
318 static_cast<int>(random->Generate(static_cast<uint32_t>(range_width)));
319 std::swap((*v)[static_cast<size_t>(selected)],
320 (*v)[static_cast<size_t>(last_in_range)]);
321 }
322}
323
324// Performs an in-place shuffle of the vector's elements.
325template <typename E>
326inline void Shuffle(internal::Random* random, std::vector<E>* v) {
327 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
328}
329
330// A function for deleting an object. Handy for being used as a
331// functor.
332template <typename T>
333static void Delete(T* x) {
334 delete x;
335}
336
337// A predicate that checks the key of a TestProperty against a known key.
338//
339// TestPropertyKeyIs is copyable.
340class TestPropertyKeyIs {
341 public:
342 // Constructor.
343 //
344 // TestPropertyKeyIs has NO default constructor.
345 explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
346
347 // Returns true if and only if the test name of test property matches on key_.
348 bool operator()(const TestProperty& test_property) const {
349 return test_property.key() == key_;
350 }
351
352 private:
353 std::string key_;
354};
355
356// Class UnitTestOptions.
357//
358// This class contains functions for processing options the user
359// specifies when running the tests. It has only static members.
360//
361// In most cases, the user can specify an option using either an
362// environment variable or a command line flag. E.g. you can set the
363// test filter using either GTEST_FILTER or --gtest_filter. If both
364// the variable and the flag are present, the latter overrides the
365// former.
366class GTEST_API_ UnitTestOptions {
367 public:
368 // Functions for processing the gtest_output flag.
369
370 // Returns the output format, or "" for normal printed output.
371 static std::string GetOutputFormat();
372
373 // Returns the absolute path of the requested output file, or the
374 // default (test_detail.xml in the original working directory) if
375 // none was explicitly specified.
376 static std::string GetAbsolutePathToOutputFile();
377
378 // Functions for processing the gtest_filter flag.
379
380 // Returns true if and only if the user-specified filter matches the test
381 // suite name and the test name.
382 static bool FilterMatchesTest(const std::string& test_suite_name,
383 const std::string& test_name);
384
385#ifdef GTEST_OS_WINDOWS
386 // Function for supporting the gtest_catch_exception flag.
387
388 // Returns EXCEPTION_EXECUTE_HANDLER if given SEH exception was handled, or
389 // EXCEPTION_CONTINUE_SEARCH otherwise.
390 // This function is useful as an __except condition.
391 static int GTestProcessSEH(DWORD seh_code, const char* location);
392#endif // GTEST_OS_WINDOWS
393
394 // Returns true if "name" matches the ':' separated list of glob-style
395 // filters in "filter".
396 static bool MatchesFilter(const std::string& name, const char* filter);
397};
398
399#if GTEST_HAS_FILE_SYSTEM1
400// Returns the current application's name, removing directory path if that
401// is present. Used by UnitTestOptions::GetOutputFile.
402GTEST_API_ FilePath GetCurrentExecutableName();
403#endif // GTEST_HAS_FILE_SYSTEM
404
405// The role interface for getting the OS stack trace as a string.
406class OsStackTraceGetterInterface {
407 public:
408 OsStackTraceGetterInterface() = default;
409 virtual ~OsStackTraceGetterInterface() = default;
410
411 // Returns the current OS stack trace as an std::string. Parameters:
412 //
413 // max_depth - the maximum number of stack frames to be included
414 // in the trace.
415 // skip_count - the number of top frames to be skipped; doesn't count
416 // against max_depth.
417 virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
418
419 // UponLeavingGTest() should be called immediately before Google Test calls
420 // user code. It saves some information about the current stack that
421 // CurrentStackTrace() will use to find and hide Google Test stack frames.
422 virtual void UponLeavingGTest() = 0;
423
424 // This string is inserted in place of stack frames that are part of
425 // Google Test's implementation.
426 static const char* const kElidedFramesMarker;
427
428 private:
429 OsStackTraceGetterInterface(const OsStackTraceGetterInterface&) = delete;
430 OsStackTraceGetterInterface& operator=(const OsStackTraceGetterInterface&) =
431 delete;
432};
433
434// A working implementation of the OsStackTraceGetterInterface interface.
435class OsStackTraceGetter : public OsStackTraceGetterInterface {
436 public:
437 OsStackTraceGetter() = default;
438
439 std::string CurrentStackTrace(int max_depth, int skip_count) override;
440 void UponLeavingGTest() override;
441
442 private:
443#ifdef GTEST_HAS_ABSL
444 Mutex mutex_; // Protects all internal state.
445
446 // We save the stack frame below the frame that calls user code.
447 // We do this because the address of the frame immediately below
448 // the user code changes between the call to UponLeavingGTest()
449 // and any calls to the stack trace code from within the user code.
450 void* caller_frame_ = nullptr;
451#endif // GTEST_HAS_ABSL
452
453 OsStackTraceGetter(const OsStackTraceGetter&) = delete;
454 OsStackTraceGetter& operator=(const OsStackTraceGetter&) = delete;
455};
456
457// Information about a Google Test trace point.
458struct TraceInfo {
459 const char* file;
460 int line;
461 std::string message;
462};
463
464// This is the default global test part result reporter used in UnitTestImpl.
465// This class should only be used by UnitTestImpl.
466class DefaultGlobalTestPartResultReporter
467 : public TestPartResultReporterInterface {
468 public:
469 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
470 // Implements the TestPartResultReporterInterface. Reports the test part
471 // result in the current test.
472 void ReportTestPartResult(const TestPartResult& result) override;
473
474 private:
475 UnitTestImpl* const unit_test_;
476
477 DefaultGlobalTestPartResultReporter(
478 const DefaultGlobalTestPartResultReporter&) = delete;
479 DefaultGlobalTestPartResultReporter& operator=(
480 const DefaultGlobalTestPartResultReporter&) = delete;
481};
482
483// This is the default per thread test part result reporter used in
484// UnitTestImpl. This class should only be used by UnitTestImpl.
485class DefaultPerThreadTestPartResultReporter
486 : public TestPartResultReporterInterface {
487 public:
488 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
489 // Implements the TestPartResultReporterInterface. The implementation just
490 // delegates to the current global test part result reporter of *unit_test_.
491 void ReportTestPartResult(const TestPartResult& result) override;
492
493 private:
494 UnitTestImpl* const unit_test_;
495
496 DefaultPerThreadTestPartResultReporter(
497 const DefaultPerThreadTestPartResultReporter&) = delete;
498 DefaultPerThreadTestPartResultReporter& operator=(
499 const DefaultPerThreadTestPartResultReporter&) = delete;
500};
501
502// The private implementation of the UnitTest class. We don't protect
503// the methods under a mutex, as this class is not accessible by a
504// user and the UnitTest class that delegates work to this class does
505// proper locking.
506class GTEST_API_ UnitTestImpl {
507 public:
508 explicit UnitTestImpl(UnitTest* parent);
509 virtual ~UnitTestImpl();
510
511 // There are two different ways to register your own TestPartResultReporter.
512 // You can register your own reporter to listen either only for test results
513 // from the current thread or for results from all threads.
514 // By default, each per-thread test result reporter just passes a new
515 // TestPartResult to the global test result reporter, which registers the
516 // test part result for the currently running test.
517
518 // Returns the global test part result reporter.
519 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
520
521 // Sets the global test part result reporter.
522 void SetGlobalTestPartResultReporter(
523 TestPartResultReporterInterface* reporter);
524
525 // Returns the test part result reporter for the current thread.
526 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
527
528 // Sets the test part result reporter for the current thread.
529 void SetTestPartResultReporterForCurrentThread(
530 TestPartResultReporterInterface* reporter);
531
532 // Gets the number of successful test suites.
533 int successful_test_suite_count() const;
534
535 // Gets the number of failed test suites.
536 int failed_test_suite_count() const;
537
538 // Gets the number of all test suites.
539 int total_test_suite_count() const;
540
541 // Gets the number of all test suites that contain at least one test
542 // that should run.
543 int test_suite_to_run_count() const;
544
545 // Gets the number of successful tests.
546 int successful_test_count() const;
547
548 // Gets the number of skipped tests.
549 int skipped_test_count() const;
550
551 // Gets the number of failed tests.
552 int failed_test_count() const;
553
554 // Gets the number of disabled tests that will be reported in the XML report.
555 int reportable_disabled_test_count() const;
556
557 // Gets the number of disabled tests.
558 int disabled_test_count() const;
559
560 // Gets the number of tests to be printed in the XML report.
561 int reportable_test_count() const;
562
563 // Gets the number of all tests.
564 int total_test_count() const;
565
566 // Gets the number of tests that should run.
567 int test_to_run_count() const;
568
569 // Gets the time of the test program start, in ms from the start of the
570 // UNIX epoch.
571 TimeInMillis start_timestamp() const { return start_timestamp_; }
572
573 // Gets the elapsed time, in milliseconds.
574 TimeInMillis elapsed_time() const { return elapsed_time_; }
575
576 // Returns true if and only if the unit test passed (i.e. all test suites
577 // passed).
578 bool Passed() const { return !Failed(); }
579
580 // Returns true if and only if the unit test failed (i.e. some test suite
581 // failed or something outside of all tests failed).
582 bool Failed() const {
583 return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
584 }
585
586 // Gets the i-th test suite among all the test suites. i can range from 0 to
587 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
588 const TestSuite* GetTestSuite(int i) const {
589 const int index = GetElementOr(test_suite_indices_, i, -1);
590 return index < 0 ? nullptr : test_suites_[static_cast<size_t>(i)];
591 }
592
593 // Legacy API is deprecated but still available
594#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
595 const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }
596#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
597
598 // Gets the i-th test suite among all the test suites. i can range from 0 to
599 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
600 TestSuite* GetMutableSuiteCase(int i) {
601 const int index = GetElementOr(test_suite_indices_, i, -1);
602 return index < 0 ? nullptr : test_suites_[static_cast<size_t>(index)];
603 }
604
605 // Provides access to the event listener list.
606 TestEventListeners* listeners() { return &listeners_; }
607
608 // Returns the TestResult for the test that's currently running, or
609 // the TestResult for the ad hoc test if no test is running.
610 TestResult* current_test_result();
611
612 // Returns the TestResult for the ad hoc test.
613 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
614
615 // Sets the OS stack trace getter.
616 //
617 // Does nothing if the input and the current OS stack trace getter
618 // are the same; otherwise, deletes the old getter and makes the
619 // input the current getter.
620 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
621
622 // Returns the current OS stack trace getter if it is not NULL;
623 // otherwise, creates an OsStackTraceGetter, makes it the current
624 // getter, and returns it.
625 OsStackTraceGetterInterface* os_stack_trace_getter();
626
627 // Returns the current OS stack trace as an std::string.
628 //
629 // The maximum number of stack frames to be included is specified by
630 // the gtest_stack_trace_depth flag. The skip_count parameter
631 // specifies the number of top frames to be skipped, which doesn't
632 // count against the number of frames to be included.
633 //
634 // For example, if Foo() calls Bar(), which in turn calls
635 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
636 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
637 std::string CurrentOsStackTraceExceptTop(int skip_count)
638 GTEST_NO_INLINE___attribute__((noinline)) GTEST_NO_TAIL_CALL___attribute__((disable_tail_calls));
639
640 // Finds and returns a TestSuite with the given name. If one doesn't
641 // exist, creates one and returns it.
642 //
643 // Arguments:
644 //
645 // test_suite_name: name of the test suite
646 // type_param: the name of the test's type parameter, or NULL if
647 // this is not a typed or a type-parameterized test.
648 // set_up_tc: pointer to the function that sets up the test suite
649 // tear_down_tc: pointer to the function that tears down the test suite
650 TestSuite* GetTestSuite(const std::string& test_suite_name,
651 const char* type_param,
652 internal::SetUpTestSuiteFunc set_up_tc,
653 internal::TearDownTestSuiteFunc tear_down_tc);
654
655// Legacy API is deprecated but still available
656#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
657 TestCase* GetTestCase(const std::string& test_case_name,
658 const char* type_param,
659 internal::SetUpTestSuiteFunc set_up_tc,
660 internal::TearDownTestSuiteFunc tear_down_tc) {
661 return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);
662 }
663#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
664
665 // Adds a TestInfo to the unit test.
666 //
667 // Arguments:
668 //
669 // set_up_tc: pointer to the function that sets up the test suite
670 // tear_down_tc: pointer to the function that tears down the test suite
671 // test_info: the TestInfo object
672 void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
673 internal::TearDownTestSuiteFunc tear_down_tc,
674 TestInfo* test_info) {
675#if GTEST_HAS_FILE_SYSTEM1
676 // In order to support thread-safe death tests, we need to
677 // remember the original working directory when the test program
678 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
679 // the user may have changed the current directory before calling
680 // RUN_ALL_TESTS(). Therefore we capture the current directory in
681 // AddTestInfo(), which is called to register a TEST or TEST_F
682 // before main() is reached.
683 if (original_working_dir_.IsEmpty()) {
684 original_working_dir_ = FilePath::GetCurrentDir();
685 GTEST_CHECK_(!original_working_dir_.IsEmpty())switch (0) case 0: default: if (::testing::internal::IsTrue(!
original_working_dir_.IsEmpty())) ; else ::testing::internal::
GTestLog(::testing::internal::GTEST_FATAL, "/root/firefox-clang/third_party/googletest/googletest/src/gtest-internal-inl.h"
, 685) .GetStream() << "Condition " "!original_working_dir_.IsEmpty()"
" failed. "
686 << "Failed to get the current working directory.";
687 }
688#endif // GTEST_HAS_FILE_SYSTEM
689
690 GetTestSuite(test_info->test_suite_name_, test_info->type_param(),
691 set_up_tc, tear_down_tc)
692 ->AddTestInfo(test_info);
693 }
694
695 // Returns ParameterizedTestSuiteRegistry object used to keep track of
696 // value-parameterized tests and instantiate and register them.
697 internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
698 return parameterized_test_registry_;
699 }
700
701 std::set<std::string>* ignored_parameterized_test_suites() {
702 return &ignored_parameterized_test_suites_;
703 }
704
705 // Returns TypeParameterizedTestSuiteRegistry object used to keep track of
706 // type-parameterized tests and instantiations of them.
707 internal::TypeParameterizedTestSuiteRegistry&
708 type_parameterized_test_registry() {
709 return type_parameterized_test_registry_;
710 }
711
712 // Registers all parameterized tests defined using TEST_P and
713 // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter
714 // combination. This method can be called more then once; it has guards
715 // protecting from registering the tests more then once. If
716 // value-parameterized tests are disabled, RegisterParameterizedTests is
717 // present but does nothing.
718 void RegisterParameterizedTests();
719
720 // Runs all tests in this UnitTest object, prints the result, and
721 // returns true if all tests are successful. If any exception is
722 // thrown during a test, this test is considered to be failed, but
723 // the rest of the tests will still be run.
724 bool RunAllTests();
725
726 // Clears the results of all tests, except the ad hoc tests.
727 void ClearNonAdHocTestResult() {
728 ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
729 }
730
731 // Clears the results of ad-hoc test assertions.
732 void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); }
733
734 // Adds a TestProperty to the current TestResult object when invoked in a
735 // context of a test or a test suite, or to the global property set. If the
736 // result already contains a property with the same key, the value will be
737 // updated.
738 void RecordProperty(const TestProperty& test_property);
739
740 enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL };
741
742 // Matches the full name of each test against the user-specified
743 // filter to decide whether the test should run, then records the
744 // result in each TestSuite and TestInfo object.
745 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
746 // based on sharding variables in the environment.
747 // Returns the number of tests that should run.
748 int FilterTests(ReactionToSharding shard_tests);
749
750 // Prints the names of the tests matching the user-specified filter flag.
751 void ListTestsMatchingFilter();
752
753 const TestSuite* current_test_suite() const { return current_test_suite_; }
754 TestInfo* current_test_info() { return current_test_info_; }
755 const TestInfo* current_test_info() const { return current_test_info_; }
756
757 // Returns the vector of environments that need to be set-up/torn-down
758 // before/after the tests are run.
759 std::vector<Environment*>& environments() { return environments_; }
760
761 // Getters for the per-thread Google Test trace stack.
762 std::vector<TraceInfo>& gtest_trace_stack() {
763 return *(gtest_trace_stack_.pointer());
764 }
765 const std::vector<TraceInfo>& gtest_trace_stack() const {
766 return gtest_trace_stack_.get();
767 }
768
769#ifdef GTEST_HAS_DEATH_TEST1
770 void InitDeathTestSubprocessControlInfo() {
771 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
772 }
773 // Returns a pointer to the parsed --gtest_internal_run_death_test
774 // flag, or NULL if that flag was not specified.
775 // This information is useful only in a death test child process.
776 // Must not be called before a call to InitGoogleTest.
777 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
778 return internal_run_death_test_flag_.get();
779 }
780
781 // Returns a pointer to the current death test factory.
782 internal::DeathTestFactory* death_test_factory() {
783 return death_test_factory_.get();
784 }
785
786 void SuppressTestEventsIfInSubprocess();
787
788 friend class ReplaceDeathTestFactory;
789#endif // GTEST_HAS_DEATH_TEST
790
791 // Initializes the event listener performing XML output as specified by
792 // UnitTestOptions. Must not be called before InitGoogleTest.
793 void ConfigureXmlOutput();
794
795#if GTEST_CAN_STREAM_RESULTS_1
796 // Initializes the event listener for streaming test results to a socket.
797 // Must not be called before InitGoogleTest.
798 void ConfigureStreamingOutput();
799#endif
800
801 // Performs initialization dependent upon flag values obtained in
802 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
803 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
804 // this function is also called from RunAllTests. Since this function can be
805 // called more than once, it has to be idempotent.
806 void PostFlagParsingInit();
807
808 // Gets the random seed used at the start of the current test iteration.
809 int random_seed() const { return random_seed_; }
810
811 // Gets the random number generator.
812 internal::Random* random() { return &random_; }
813
814 // Shuffles all test suites, and the tests within each test suite,
815 // making sure that death tests are still run first.
816 void ShuffleTests();
817
818 // Restores the test suites and tests to their order before the first shuffle.
819 void UnshuffleTests();
820
821 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
822 // UnitTest::Run() starts.
823 bool catch_exceptions() const { return catch_exceptions_; }
824
825 private:
826 // Returns true if a warning should be issued if no tests match the test
827 // filter flag.
828 bool ShouldWarnIfNoTestsMatchFilter() const;
829
830 struct CompareTestSuitesByPointer {
831 bool operator()(const TestSuite* lhs, const TestSuite* rhs) const {
832 return lhs->name_ < rhs->name_;
833 }
834 };
835
836 friend class ::testing::UnitTest;
837
838 // Used by UnitTest::Run() to capture the state of
839 // GTEST_FLAG(catch_exceptions) at the moment it starts.
840 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
841
842 // Sets the TestSuite object for the test that's currently running.
843 void set_current_test_suite(TestSuite* a_current_test_suite) {
844 current_test_suite_ = a_current_test_suite;
845 }
846
847 // Sets the TestInfo object for the test that's currently running. If
848 // current_test_info is NULL, the assertion results will be stored in
849 // ad_hoc_test_result_.
850 void set_current_test_info(TestInfo* a_current_test_info) {
851 current_test_info_ = a_current_test_info;
852 }
853
854 // The UnitTest object that owns this implementation object.
855 UnitTest* const parent_;
856
857#if GTEST_HAS_FILE_SYSTEM1
858 // The working directory when the first TEST() or TEST_F() was
859 // executed.
860 internal::FilePath original_working_dir_;
861#endif // GTEST_HAS_FILE_SYSTEM
862
863 // The default test part result reporters.
864 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
865 DefaultPerThreadTestPartResultReporter
866 default_per_thread_test_part_result_reporter_;
867
868 // Points to (but doesn't own) the global test part result reporter.
869 TestPartResultReporterInterface* global_test_part_result_reporter_;
870
871 // Protects read and write access to global_test_part_result_reporter_.
872 internal::Mutex global_test_part_result_reporter_mutex_;
873
874 // Points to (but doesn't own) the per-thread test part result reporter.
875 internal::ThreadLocal<TestPartResultReporterInterface*>
876 per_thread_test_part_result_reporter_;
877
878 // The vector of environments that need to be set-up/torn-down
879 // before/after the tests are run.
880 std::vector<Environment*> environments_;
881
882 // The vector of TestSuites in their original order. It owns the
883 // elements in the vector.
884 std::vector<TestSuite*> test_suites_;
885
886 // The set of TestSuites by name.
887 std::unordered_map<std::string, TestSuite*> test_suites_by_name_;
888
889 // Provides a level of indirection for the test suite list to allow
890 // easy shuffling and restoring the test suite order. The i-th
891 // element of this vector is the index of the i-th test suite in the
892 // shuffled order.
893 std::vector<int> test_suite_indices_;
894
895 // ParameterizedTestRegistry object used to register value-parameterized
896 // tests.
897 internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
898 internal::TypeParameterizedTestSuiteRegistry
899 type_parameterized_test_registry_;
900
901 // The set holding the name of parameterized
902 // test suites that may go uninstantiated.
903 std::set<std::string> ignored_parameterized_test_suites_;
904
905 // Indicates whether RegisterParameterizedTests() has been called already.
906 bool parameterized_tests_registered_;
907
908 // Index of the last death test suite registered. Initially -1.
909 int last_death_test_suite_;
910
911 // This points to the TestSuite for the currently running test. It
912 // changes as Google Test goes through one test suite after another.
913 // When no test is running, this is set to NULL and Google Test
914 // stores assertion results in ad_hoc_test_result_. Initially NULL.
915 TestSuite* current_test_suite_;
916
917 // This points to the TestInfo for the currently running test. It
918 // changes as Google Test goes through one test after another. When
919 // no test is running, this is set to NULL and Google Test stores
920 // assertion results in ad_hoc_test_result_. Initially NULL.
921 TestInfo* current_test_info_;
922
923 // Normally, a user only writes assertions inside a TEST or TEST_F,
924 // or inside a function called by a TEST or TEST_F. Since Google
925 // Test keeps track of which test is current running, it can
926 // associate such an assertion with the test it belongs to.
927 //
928 // If an assertion is encountered when no TEST or TEST_F is running,
929 // Google Test attributes the assertion result to an imaginary "ad hoc"
930 // test, and records the result in ad_hoc_test_result_.
931 TestResult ad_hoc_test_result_;
932
933 // The list of event listeners that can be used to track events inside
934 // Google Test.
935 TestEventListeners listeners_;
936
937 // The OS stack trace getter. Will be deleted when the UnitTest
938 // object is destructed. By default, an OsStackTraceGetter is used,
939 // but the user can set this field to use a custom getter if that is
940 // desired.
941 OsStackTraceGetterInterface* os_stack_trace_getter_;
942
943 // True if and only if PostFlagParsingInit() has been called.
944 bool post_flag_parse_init_performed_;
945
946 // The random number seed used at the beginning of the test run.
947 int random_seed_;
948
949 // Our random number generator.
950 internal::Random random_;
951
952 // The time of the test program start, in ms from the start of the
953 // UNIX epoch.
954 TimeInMillis start_timestamp_;
955
956 // How long the test took to run, in milliseconds.
957 TimeInMillis elapsed_time_;
958
959#ifdef GTEST_HAS_DEATH_TEST1
960 // The decomposed components of the gtest_internal_run_death_test flag,
961 // parsed when RUN_ALL_TESTS is called.
962 std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
963 std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
964#endif // GTEST_HAS_DEATH_TEST
965
966 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
967 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
968
969 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
970 // starts.
971 bool catch_exceptions_;
972
973 UnitTestImpl(const UnitTestImpl&) = delete;
974 UnitTestImpl& operator=(const UnitTestImpl&) = delete;
975}; // class UnitTestImpl
976
977// Convenience function for accessing the global UnitTest
978// implementation object.
979inline UnitTestImpl* GetUnitTestImpl() {
980 return UnitTest::GetInstance()->impl();
981}
982
983#ifdef GTEST_USES_SIMPLE_RE
984
985// Internal helper functions for implementing the simple regular
986// expression matcher.
987GTEST_API_ bool IsInSet(char ch, const char* str);
988GTEST_API_ bool IsAsciiDigit(char ch);
989GTEST_API_ bool IsAsciiPunct(char ch);
990GTEST_API_ bool IsRepeat(char ch);
991GTEST_API_ bool IsAsciiWhiteSpace(char ch);
992GTEST_API_ bool IsAsciiWordChar(char ch);
993GTEST_API_ bool IsValidEscape(char ch);
994GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
995GTEST_API_ bool ValidateRegex(const char* regex);
996GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
997GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch,
998 char repeat, const char* regex,
999 const char* str);
1000GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1001
1002#endif // GTEST_USES_SIMPLE_RE
1003
1004// Parses the command line for Google Test flags, without initializing
1005// other parts of Google Test.
1006GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1007GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1008
1009#ifdef GTEST_HAS_DEATH_TEST1
1010
1011// Returns the message describing the last system error, regardless of the
1012// platform.
1013GTEST_API_ std::string GetLastErrnoDescription();
1014
1015// Attempts to parse a string into a positive integer pointed to by the
1016// number parameter. Returns true if that is possible.
1017// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1018// it here.
1019template <typename Integer>
1020bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1021 // Fail fast if the given string does not begin with a digit;
1022 // this bypasses strtoXXX's "optional leading whitespace and plus
1023 // or minus sign" semantics, which are undesirable here.
1024 if (str.empty() || !IsDigit(str[0])) {
1025 return false;
1026 }
1027 errno(*__errno_location ()) = 0;
1028
1029 char* end;
1030 // BiggestConvertible is the largest integer type that system-provided
1031 // string-to-number conversion routines can return.
1032 using BiggestConvertible = unsigned long long; // NOLINT
1033
1034 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); // NOLINT
1035 const bool parse_success = *end == '\0' && errno(*__errno_location ()) == 0;
1036
1037 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed))switch (0) case 0: default: if (::testing::internal::IsTrue(sizeof
(Integer) <= sizeof(parsed))) ; else ::testing::internal::
GTestLog(::testing::internal::GTEST_FATAL, "/root/firefox-clang/third_party/googletest/googletest/src/gtest-internal-inl.h"
, 1037) .GetStream() << "Condition " "sizeof(Integer) <= sizeof(parsed)"
" failed. "
;
1038
1039 const Integer result = static_cast<Integer>(parsed);
1040 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1041 *number = result;
1042 return true;
1043 }
1044 return false;
1045}
1046#endif // GTEST_HAS_DEATH_TEST
1047
1048// TestResult contains some private methods that should be hidden from
1049// Google Test user but are required for testing. This class allow our tests
1050// to access them.
1051//
1052// This class is supplied only for the purpose of testing Google Test's own
1053// constructs. Do not use it in user tests, either directly or indirectly.
1054class TestResultAccessor {
1055 public:
1056 static void RecordProperty(TestResult* test_result,
1057 const std::string& xml_element,
1058 const TestProperty& property) {
1059 test_result->RecordProperty(xml_element, property);
1060 }
1061
1062 static void ClearTestPartResults(TestResult* test_result) {
1063 test_result->ClearTestPartResults();
1064 }
1065
1066 static const std::vector<testing::TestPartResult>& test_part_results(
1067 const TestResult& test_result) {
1068 return test_result.test_part_results();
1069 }
1070};
1071
1072#if GTEST_CAN_STREAM_RESULTS_1
1073
1074// Streams test results to the given port on the given host machine.
1075class StreamingListener : public EmptyTestEventListener {
1076 public:
1077 // Abstract base class for writing strings to a socket.
1078 class AbstractSocketWriter {
1079 public:
1080 virtual ~AbstractSocketWriter() = default;
1081
1082 // Sends a string to the socket.
1083 virtual void Send(const std::string& message) = 0;
1084
1085 // Closes the socket.
1086 virtual void CloseConnection() {}
1087
1088 // Sends a string and a newline to the socket.
1089 void SendLn(const std::string& message) { Send(message + "\n"); }
1090 };
1091
1092 // Concrete class for actually writing strings to a socket.
1093 class SocketWriter : public AbstractSocketWriter {
1094 public:
1095 SocketWriter(const std::string& host, const std::string& port)
1096 : sockfd_(-1), host_name_(host), port_num_(port) {
1097 MakeConnection();
1098 }
1099
1100 ~SocketWriter() override {
1101 if (sockfd_ != -1) CloseConnection();
1102 }
1103
1104 // Sends a string to the socket.
1105 void Send(const std::string& message) override {
1106 GTEST_CHECK_(sockfd_ != -1)switch (0) case 0: default: if (::testing::internal::IsTrue(sockfd_
!= -1)) ; else ::testing::internal::GTestLog(::testing::internal
::GTEST_FATAL, "/root/firefox-clang/third_party/googletest/googletest/src/gtest-internal-inl.h"
, 1106) .GetStream() << "Condition " "sockfd_ != -1" " failed. "
1107 << "Send() can be called only when there is a connection.";
1108
1109 const auto len = static_cast<size_t>(message.length());
1110 if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {
1111 GTEST_LOG_(WARNING)::testing::internal::GTestLog(::testing::internal::GTEST_WARNING
, "/root/firefox-clang/third_party/googletest/googletest/src/gtest-internal-inl.h"
, 1111) .GetStream()
<< "stream_result_to: failed to stream to "
1112 << host_name_ << ":" << port_num_;
1113 }
1114 }
1115
1116 private:
1117 // Creates a client socket and connects to the server.
1118 void MakeConnection();
1119
1120 // Closes the socket.
1121 void CloseConnection() override {
1122 GTEST_CHECK_(sockfd_ != -1)switch (0) case 0: default: if (::testing::internal::IsTrue(sockfd_
!= -1)) ; else ::testing::internal::GTestLog(::testing::internal
::GTEST_FATAL, "/root/firefox-clang/third_party/googletest/googletest/src/gtest-internal-inl.h"
, 1122) .GetStream() << "Condition " "sockfd_ != -1" " failed. "
1123 << "CloseConnection() can be called only when there is a connection.";
1124
1125 close(sockfd_);
1126 sockfd_ = -1;
1127 }
1128
1129 int sockfd_; // socket file descriptor
1130 const std::string host_name_;
1131 const std::string port_num_;
1132
1133 SocketWriter(const SocketWriter&) = delete;
1134 SocketWriter& operator=(const SocketWriter&) = delete;
1135 }; // class SocketWriter
1136
1137 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1138 static std::string UrlEncode(const char* str);
1139
1140 StreamingListener(const std::string& host, const std::string& port)
1141 : socket_writer_(new SocketWriter(host, port)) {
1142 Start();
1143 }
1144
1145 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1146 : socket_writer_(socket_writer) {
1147 Start();
1148 }
1149
1150 void OnTestProgramStart(const UnitTest& /* unit_test */) override {
1151 SendLn("event=TestProgramStart");
1152 }
1153
1154 void OnTestProgramEnd(const UnitTest& unit_test) override {
1155 // Note that Google Test current only report elapsed time for each
1156 // test iteration, not for the entire test program.
1157 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1158
1159 // Notify the streaming server to stop.
1160 socket_writer_->CloseConnection();
1161 }
1162
1163 void OnTestIterationStart(const UnitTest& /* unit_test */,
1164 int iteration) override {
1165 SendLn("event=TestIterationStart&iteration=" +
1166 StreamableToString(iteration));
1167 }
1168
1169 void OnTestIterationEnd(const UnitTest& unit_test,
1170 int /* iteration */) override {
1171 SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) +
1172 "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) +
1173 "ms");
1174 }
1175
1176 // Note that "event=TestCaseStart" is a wire format and has to remain
1177 // "case" for compatibility
1178 void OnTestSuiteStart(const TestSuite& test_suite) override {
1179 SendLn(std::string("event=TestCaseStart&name=") + test_suite.name());
1180 }
1181
1182 // Note that "event=TestCaseEnd" is a wire format and has to remain
1183 // "case" for compatibility
1184 void OnTestSuiteEnd(const TestSuite& test_suite) override {
1185 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_suite.Passed()) +
1186 "&elapsed_time=" + StreamableToString(test_suite.elapsed_time()) +
1187 "ms");
1188 }
1189
1190 void OnTestStart(const TestInfo& test_info) override {
1191 SendLn(std::string("event=TestStart&name=") + test_info.name());
1192 }
1193
1194 void OnTestEnd(const TestInfo& test_info) override {
1195 SendLn("event=TestEnd&passed=" +
1196 FormatBool((test_info.result())->Passed()) + "&elapsed_time=" +
1197 StreamableToString((test_info.result())->elapsed_time()) + "ms");
1198 }
1199
1200 void OnTestPartResult(const TestPartResult& test_part_result) override {
1201 const char* file_name = test_part_result.file_name();
1202 if (file_name == nullptr) file_name = "";
1203 SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1204 "&line=" + StreamableToString(test_part_result.line_number()) +
1205 "&message=" + UrlEncode(test_part_result.message()));
1206 }
1207
1208 private:
1209 // Sends the given message and a newline to the socket.
1210 void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
1211
1212 // Called at the start of streaming to notify the receiver what
1213 // protocol we are using.
1214 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1215
1216 std::string FormatBool(bool value) { return value ? "1" : "0"; }
1217
1218 const std::unique_ptr<AbstractSocketWriter> socket_writer_;
1219
1220 StreamingListener(const StreamingListener&) = delete;
1221 StreamingListener& operator=(const StreamingListener&) = delete;
1222}; // class StreamingListener
1223
1224#endif // GTEST_CAN_STREAM_RESULTS_
1225
1226} // namespace internal
1227} // namespace testing
1228
1229GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
1230
1231#endif // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_