1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/profiler/stack_base_address_posix.h"
6
7 #include "base/numerics/clamped_math.h"
8 #include "base/process/process_handle.h"
9 #include "build/build_config.h"
10 #include "build/chromeos_buildflags.h"
11 #include "testing/gmock/include/gmock/gmock.h"
12 #include "testing/gtest/include/gtest/gtest.h"
13
14 namespace base {
15
16 using ::testing::Gt;
17 using ::testing::Le;
18 using ::testing::Optional;
19
20 // ASAN moves local variables outside of the stack extents.
21 #if defined(ADDRESS_SANITIZER)
22 #define MAYBE_CurrentThread DISABLED_CurrentThread
23 #elif BUILDFLAG(IS_LINUX)
24 // We don't support getting the stack base address on Linux.
25 // https://crbug.com/1394278
26 #define MAYBE_CurrentThread DISABLED_CurrentThread
27 #else
28 #define MAYBE_CurrentThread CurrentThread
29 #endif
TEST(GetThreadStackBaseAddressTest,MAYBE_CurrentThread)30 TEST(GetThreadStackBaseAddressTest, MAYBE_CurrentThread) {
31 std::optional<uintptr_t> base =
32 GetThreadStackBaseAddress(PlatformThread::CurrentId(), pthread_self());
33 EXPECT_THAT(base, Optional(Gt(0u)));
34 uintptr_t stack_addr = reinterpret_cast<uintptr_t>(&base);
35 // Check that end of stack is within 4MiB of a current stack address.
36 EXPECT_THAT(base, Optional(Le(ClampAdd(stack_addr, 4 * 1024 * 1024))));
37 }
38
39 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
40
TEST(GetThreadStackBaseAddressTest,MainThread)41 TEST(GetThreadStackBaseAddressTest, MainThread) {
42 // GetThreadStackBaseAddress does not use pthread_id for main thread on these
43 // platforms.
44 std::optional<uintptr_t> base =
45 GetThreadStackBaseAddress(GetCurrentProcId(), pthread_t());
46 EXPECT_THAT(base, Optional(Gt(0u)));
47 }
48
49 #endif // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
50 } // namespace base
51