1 // Copyright 2020 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 <string.h>
6 #include <unistd.h>
7
8 #include "base/files/file_path.h"
9 #include "base/files/file_util.h"
10 #include "base/process/set_process_title_linux.h"
11 #include "base/strings/string_util.h"
12 #include "build/build_config.h"
13 #include "testing/gtest/include/gtest/gtest.h"
14
15 #if BUILDFLAG(IS_CHROMEOS)
16 #include "base/profiler/module_cache.h"
17 #endif
18
19 namespace {
20
21 const std::string kNullChr(1, '\0');
22
ReadCmdline()23 std::string ReadCmdline() {
24 std::string cmdline;
25 CHECK(base::ReadFileToString(base::FilePath("/proc/self/cmdline"), &cmdline));
26 // The process title appears in different formats depending on Linux kernel
27 // version:
28 // "title" (on Linux --4.17)
29 // "title\0\0\0...\0" (on Linux 4.18--5.2)
30 // "title\0" (on Linux 5.3--)
31 //
32 // For unit tests, just trim trailing null characters to support all cases.
33 return std::string(base::TrimString(cmdline, kNullChr, base::TRIM_TRAILING));
34 }
35
TEST(SetProcTitleLinuxTest,Simple)36 TEST(SetProcTitleLinuxTest, Simple) {
37 setproctitle("a %s cat", "cute");
38 EXPECT_TRUE(base::EndsWith(ReadCmdline(), " a cute cat",
39 base::CompareCase::SENSITIVE))
40 << ReadCmdline();
41
42 setproctitle("-a %s cat", "cute");
43 EXPECT_EQ(ReadCmdline(), "a cute cat");
44 }
45
TEST(SetProcTitleLinuxTest,Empty)46 TEST(SetProcTitleLinuxTest, Empty) {
47 setproctitle("-");
48 EXPECT_EQ(ReadCmdline(), "");
49 }
50
TEST(SetProcTitleLinuxTest,Long)51 TEST(SetProcTitleLinuxTest, Long) {
52 setproctitle("-long cat is l%0100000dng", 0);
53 EXPECT_TRUE(base::StartsWith(ReadCmdline(), "long cat is l00000000",
54 base::CompareCase::SENSITIVE))
55 << ReadCmdline();
56 }
57
58 #if BUILDFLAG(IS_CHROMEOS)
TEST(SetProcTitleLinuxTest,GetModuleForAddressWorksWithSetProcTitle)59 TEST(SetProcTitleLinuxTest, GetModuleForAddressWorksWithSetProcTitle) {
60 // Ensure that after calling setproctitle(), GetModuleForAddress() returns a
61 // Module with a valid GetDebugBasename(), not something that includes all the
62 // command-line flags. The code we're testing is actually in
63 // base/profiler/module_cache_posix.cc, but we need to test it here for
64 // dependencies.
65 setproctitle("%s", "/opt/google/chrome/chrome --type=renderer --foo=bar");
66
67 base::ModuleCache module_cache;
68 // We're assuming the code in this file is linked into the main unittest
69 // binary not a shared library.
70 const base::ModuleCache::Module* module = module_cache.GetModuleForAddress(
71 reinterpret_cast<uintptr_t>(&ReadCmdline));
72 ASSERT_NE(module, nullptr);
73 EXPECT_EQ(module->GetDebugBasename().value(), "chrome");
74 }
75
76 #endif // BUILDFLAG(IS_CHROMEOS)
77
78 } // namespace
79