1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <stdlib.h>
18 #include <unistd.h>
19 #include <array>
20 #include <memory>
21 #include <vector>
22
23 #include <getopt.h>
24 #include <signal.h>
25
26 #include "perfetto/ext/base/event_fd.h"
27 #include "perfetto/ext/base/scoped_file.h"
28 #include "perfetto/ext/base/unix_socket.h"
29 #include "perfetto/ext/base/watchdog.h"
30 #include "perfetto/ext/tracing/ipc/default_socket.h"
31 #include "src/profiling/memory/heapprofd_producer.h"
32 #include "src/profiling/memory/java_hprof_producer.h"
33 #include "src/profiling/memory/wire_protocol.h"
34
35 #include "perfetto/ext/base/unix_task_runner.h"
36
37 // TODO(rsavitski): the task runner watchdog spawns a thread (normally for
38 // tracking cpu/mem usage) that we don't strictly need.
39
40 namespace perfetto {
41 namespace profiling {
42 namespace {
43
44 int StartChildHeapprofd(pid_t target_pid,
45 std::string target_cmdline,
46 base::ScopedFile inherited_sock_fd);
47 int StartCentralHeapprofd();
48
GetListeningSocket()49 int GetListeningSocket() {
50 const char* sock_fd = getenv(kHeapprofdSocketEnvVar);
51 if (sock_fd == nullptr)
52 PERFETTO_FATAL("Did not inherit socket from init.");
53 char* end;
54 int raw_fd = static_cast<int>(strtol(sock_fd, &end, 10));
55 if (*end != '\0')
56 PERFETTO_FATAL("Invalid %s. Expected decimal integer.",
57 kHeapprofdSocketEnvVar);
58 return raw_fd;
59 }
60
61 base::EventFd* g_dump_evt = nullptr;
62
HeapprofdMain(int argc,char ** argv)63 int HeapprofdMain(int argc, char** argv) {
64 bool cleanup_crash = false;
65 pid_t target_pid = base::kInvalidPid;
66 std::string target_cmdline;
67 base::ScopedFile inherited_sock_fd;
68
69 enum { kCleanupCrash = 256, kTargetPid, kTargetCmd, kInheritFd };
70 static struct option long_options[] = {
71 {"cleanup-after-crash", no_argument, nullptr, kCleanupCrash},
72 {"exclusive-for-pid", required_argument, nullptr, kTargetPid},
73 {"exclusive-for-cmdline", required_argument, nullptr, kTargetCmd},
74 {"inherit-socket-fd", required_argument, nullptr, kInheritFd},
75 {nullptr, 0, nullptr, 0}};
76 int option_index;
77 int c;
78 while ((c = getopt_long(argc, argv, "", long_options, &option_index)) != -1) {
79 switch (c) {
80 case kCleanupCrash:
81 cleanup_crash = true;
82 break;
83 case kTargetPid:
84 if (target_pid != base::kInvalidPid)
85 PERFETTO_FATAL("Duplicate exclusive-for-pid");
86 target_pid = static_cast<pid_t>(atoi(optarg));
87 break;
88 case kTargetCmd: // assumed to be already normalized
89 if (!target_cmdline.empty())
90 PERFETTO_FATAL("Duplicate exclusive-for-cmdline");
91 target_cmdline = std::string(optarg);
92 break;
93 case kInheritFd: // repetition not supported
94 if (inherited_sock_fd)
95 PERFETTO_FATAL("Duplicate inherit-socket-fd");
96 inherited_sock_fd = base::ScopedFile(atoi(optarg));
97 break;
98 default:
99 PERFETTO_ELOG("Usage: %s [--cleanup-after-crash]", argv[0]);
100 return 1;
101 }
102 }
103
104 if (cleanup_crash) {
105 PERFETTO_LOG(
106 "Recovering from crash: unsetting heapprofd system properties. "
107 "Expect SELinux denials for unrelated properties.");
108 SystemProperties::ResetHeapprofdProperties();
109 PERFETTO_LOG(
110 "Finished unsetting heapprofd system properties. "
111 "SELinux denials about properties are unexpected after "
112 "this point.");
113 return 0;
114 }
115
116 // If |target_pid| is given, we're supposed to be operating as a private
117 // heapprofd for that process. Note that we might not be a direct child due to
118 // reparenting.
119 bool tpid_set = target_pid != base::kInvalidPid;
120 bool tcmd_set = !target_cmdline.empty();
121 bool fds_set = !!inherited_sock_fd;
122 if (tpid_set || tcmd_set || fds_set) {
123 if (!tpid_set || !tcmd_set || !fds_set) {
124 PERFETTO_ELOG(
125 "If starting in child mode, requires all of: {--exclusive-for-pid, "
126 "--exclusive-for-cmdline, --inherit_socket_fd}");
127 return 1;
128 }
129
130 return StartChildHeapprofd(target_pid, target_cmdline,
131 std::move(inherited_sock_fd));
132 }
133
134 // Otherwise start as a central daemon.
135 return StartCentralHeapprofd();
136 }
137
StartChildHeapprofd(pid_t target_pid,std::string target_cmdline,base::ScopedFile inherited_sock_fd)138 int StartChildHeapprofd(pid_t target_pid,
139 std::string target_cmdline,
140 base::ScopedFile inherited_sock_fd) {
141 base::UnixTaskRunner task_runner;
142 base::Watchdog::GetInstance()->Start(); // crash on exceedingly long tasks
143 HeapprofdProducer producer(HeapprofdMode::kChild, &task_runner);
144 producer.SetTargetProcess(target_pid, target_cmdline,
145 std::move(inherited_sock_fd));
146 producer.ConnectWithRetries(GetProducerSocket());
147 producer.ScheduleActiveDataSourceWatchdog();
148 task_runner.Run();
149 return 0;
150 }
151
StartCentralHeapprofd()152 int StartCentralHeapprofd() {
153 // We set this up before launching any threads, so we do not have to use a
154 // std::atomic for g_dump_evt.
155 g_dump_evt = new base::EventFd();
156
157 base::UnixTaskRunner task_runner;
158 base::Watchdog::GetInstance()->Start(); // crash on exceedingly long tasks
159 HeapprofdProducer producer(HeapprofdMode::kCentral, &task_runner);
160
161 int listening_raw_socket = GetListeningSocket();
162 auto listening_socket = base::UnixSocket::Listen(
163 base::ScopedFile(listening_raw_socket), &producer.socket_delegate(),
164 &task_runner, base::SockFamily::kUnix, base::SockType::kStream);
165
166 struct sigaction action = {};
167 action.sa_handler = [](int) { g_dump_evt->Notify(); };
168 // Allow to trigger a full dump by sending SIGUSR1 to heapprofd.
169 // This will allow manually deciding when to dump on userdebug.
170 PERFETTO_CHECK(sigaction(SIGUSR1, &action, nullptr) == 0);
171 task_runner.AddFileDescriptorWatch(g_dump_evt->fd(), [&producer] {
172 g_dump_evt->Clear();
173 producer.DumpAll();
174 });
175 producer.ConnectWithRetries(GetProducerSocket());
176 // TODO(fmayer): Create one producer that manages both heapprofd and Java
177 // producers, so we do not have two connections to traced.
178 JavaHprofProducer java_producer(&task_runner);
179 java_producer.ConnectWithRetries(GetProducerSocket());
180 task_runner.Run();
181 return 0;
182 }
183
184 } // namespace
185 } // namespace profiling
186 } // namespace perfetto
187
main(int argc,char ** argv)188 int main(int argc, char** argv) {
189 return perfetto::profiling::HeapprofdMain(argc, argv);
190 }
191