• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "src/profiling/memory/client.h"
18 
19 #include <signal.h>
20 #include <sys/prctl.h>
21 #include <sys/syscall.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 
25 #include <algorithm>
26 #include <atomic>
27 #include <cinttypes>
28 #include <new>
29 
30 #include <unwindstack/Regs.h>
31 #include <unwindstack/RegsGetLocal.h>
32 
33 #include "perfetto/base/compiler.h"
34 #include "perfetto/base/logging.h"
35 #include "perfetto/base/thread_utils.h"
36 #include "perfetto/base/time.h"
37 #include "perfetto/ext/base/file_utils.h"
38 #include "perfetto/ext/base/scoped_file.h"
39 #include "perfetto/ext/base/string_utils.h"
40 #include "perfetto/ext/base/unix_socket.h"
41 #include "perfetto/ext/base/utils.h"
42 #include "src/profiling/memory/sampler.h"
43 #include "src/profiling/memory/scoped_spinlock.h"
44 #include "src/profiling/memory/shared_ring_buffer.h"
45 #include "src/profiling/memory/wire_protocol.h"
46 
47 namespace perfetto {
48 namespace profiling {
49 namespace {
50 
51 const char kSingleByte[1] = {'x'};
52 constexpr auto kResendBackoffUs = 100;
53 
IsMainThread()54 inline bool IsMainThread() {
55   return getpid() == base::GetThreadId();
56 }
57 
UnsetDumpable(int)58 int UnsetDumpable(int) {
59   prctl(PR_SET_DUMPABLE, 0);
60   return 0;
61 }
62 
Contained(const StackRange & base,const char * ptr)63 bool Contained(const StackRange& base, const char* ptr) {
64   return (ptr >= base.begin && ptr < base.end);
65 }
66 
67 }  // namespace
68 
GetMaxTries(const ClientConfiguration & client_config)69 uint64_t GetMaxTries(const ClientConfiguration& client_config) {
70   if (!client_config.block_client)
71     return 1u;
72   if (client_config.block_client_timeout_us == 0)
73     return kInfiniteTries;
74   return std::max<uint64_t>(
75       1ul, client_config.block_client_timeout_us / kResendBackoffUs);
76 }
77 
GetThreadStackRange()78 StackRange GetThreadStackRange() {
79   // In glibc pthread_getattr_np can call realloc, even for a non-main-thread.
80   // This is fine, because the heapprofd wrapper for glibc prevents re-entering
81   // malloc.
82   pthread_attr_t attr;
83   if (pthread_getattr_np(pthread_self(), &attr) != 0)
84     return {nullptr, nullptr};
85   base::ScopedResource<pthread_attr_t*, pthread_attr_destroy, nullptr> cleanup(
86       &attr);
87 
88   char* stackaddr;
89   size_t stacksize;
90   if (pthread_attr_getstack(&attr, reinterpret_cast<void**>(&stackaddr),
91                             &stacksize) != 0)
92     return {nullptr, nullptr};
93   return {stackaddr, stackaddr + stacksize};
94 }
95 
GetSigAltStackRange()96 StackRange GetSigAltStackRange() {
97   stack_t altstack;
98 
99   if (sigaltstack(nullptr, &altstack) == -1) {
100     PERFETTO_PLOG("sigaltstack");
101     return {nullptr, nullptr};
102   }
103 
104   if ((altstack.ss_flags & SS_ONSTACK) == 0) {
105     return {nullptr, nullptr};
106   }
107 
108   return {static_cast<char*>(altstack.ss_sp),
109           static_cast<char*>(altstack.ss_sp) + altstack.ss_size};
110 }
111 
112 // The implementation of pthread_getattr_np for the main thread on bionic uses
113 // malloc, so we cannot use it in GetStackEnd, which we use inside of
114 // RecordMalloc (which is called from malloc). We would re-enter malloc if we
115 // used it.
116 //
117 // This is why we find the stack base for the main-thread when constructing
118 // the client and remember it.
GetMainThreadStackRange()119 StackRange GetMainThreadStackRange() {
120   base::ScopedFstream maps(fopen("/proc/self/maps", "re"));
121   if (!maps) {
122     return {nullptr, nullptr};
123   }
124   while (!feof(*maps)) {
125     char line[1024];
126     char* data = fgets(line, sizeof(line), *maps);
127     if (data != nullptr && strstr(data, "[stack]")) {
128       char* sep = strstr(data, "-");
129       if (sep == nullptr)
130         continue;
131 
132       char* min = reinterpret_cast<char*>(strtoll(data, nullptr, 16));
133       char* max = reinterpret_cast<char*>(strtoll(sep + 1, nullptr, 16));
134       return {min, max};
135     }
136   }
137   return {nullptr, nullptr};
138 }
139 
140 // static
ConnectToHeapprofd(const std::string & sock_name)141 std::optional<base::UnixSocketRaw> Client::ConnectToHeapprofd(
142     const std::string& sock_name) {
143   auto sock = base::UnixSocketRaw::CreateMayFail(base::SockFamily::kUnix,
144                                                  base::SockType::kStream);
145   if (!sock || !sock.Connect(sock_name)) {
146     PERFETTO_PLOG("Failed to connect to %s", sock_name.c_str());
147     return std::nullopt;
148   }
149   if (!sock.SetTxTimeout(kClientSockTimeoutMs)) {
150     PERFETTO_PLOG("Failed to set send timeout for %s", sock_name.c_str());
151     return std::nullopt;
152   }
153   if (!sock.SetRxTimeout(kClientSockTimeoutMs)) {
154     PERFETTO_PLOG("Failed to set receive timeout for %s", sock_name.c_str());
155     return std::nullopt;
156   }
157   return std::move(sock);
158 }
159 
160 // static
CreateAndHandshake(base::UnixSocketRaw sock,UnhookedAllocator<Client> unhooked_allocator)161 std::shared_ptr<Client> Client::CreateAndHandshake(
162     base::UnixSocketRaw sock,
163     UnhookedAllocator<Client> unhooked_allocator) {
164   if (!sock) {
165     PERFETTO_DFATAL_OR_ELOG("Socket not connected.");
166     return nullptr;
167   }
168 
169   sock.DcheckIsBlocking(true);
170 
171   // We might be running in a process that is not dumpable (such as app
172   // processes on user builds), in which case the /proc/self/mem will be chown'd
173   // to root:root, and will not be accessible even to the process itself (see
174   // man 5 proc). In such situations, temporarily mark the process dumpable to
175   // be able to open the files, unsetting dumpability immediately afterwards.
176   int orig_dumpable = prctl(PR_GET_DUMPABLE);
177 
178   enum { kNop, kDoUnset };
179   base::ScopedResource<int, UnsetDumpable, kNop, false> unset_dumpable(kNop);
180   if (orig_dumpable == 0) {
181     unset_dumpable.reset(kDoUnset);
182     prctl(PR_SET_DUMPABLE, 1);
183   }
184 
185   base::ScopedFile maps(base::OpenFile("/proc/self/maps", O_RDONLY));
186   if (!maps) {
187     PERFETTO_DFATAL_OR_ELOG("Failed to open /proc/self/maps");
188     return nullptr;
189   }
190   base::ScopedFile mem(base::OpenFile("/proc/self/mem", O_RDONLY));
191   if (!mem) {
192     PERFETTO_DFATAL_OR_ELOG("Failed to open /proc/self/mem");
193     return nullptr;
194   }
195 
196   // Restore original dumpability value if we overrode it.
197   unset_dumpable.reset();
198 
199   int fds[kHandshakeSize];
200   fds[kHandshakeMaps] = *maps;
201   fds[kHandshakeMem] = *mem;
202 
203   // Send an empty record to transfer fds for /proc/self/maps and
204   // /proc/self/mem.
205   if (sock.Send(kSingleByte, sizeof(kSingleByte), fds, kHandshakeSize) !=
206       sizeof(kSingleByte)) {
207     PERFETTO_DFATAL_OR_ELOG("Failed to send file descriptors.");
208     return nullptr;
209   }
210 
211   ClientConfiguration client_config;
212   base::ScopedFile shmem_fd;
213   size_t recv = 0;
214   while (recv < sizeof(client_config)) {
215     size_t num_fds = 0;
216     base::ScopedFile* fd = nullptr;
217     if (!shmem_fd) {
218       num_fds = 1;
219       fd = &shmem_fd;
220     }
221     ssize_t rd = sock.Receive(reinterpret_cast<char*>(&client_config) + recv,
222                               sizeof(client_config) - recv, fd, num_fds);
223     if (rd == -1) {
224       PERFETTO_PLOG("Failed to receive ClientConfiguration.");
225       return nullptr;
226     }
227     if (rd == 0) {
228       PERFETTO_LOG("Server disconnected while sending ClientConfiguration.");
229       return nullptr;
230     }
231     recv += static_cast<size_t>(rd);
232   }
233 
234   if (!shmem_fd) {
235     PERFETTO_DFATAL_OR_ELOG("Did not receive shmem fd.");
236     return nullptr;
237   }
238 
239   auto shmem = SharedRingBuffer::Attach(std::move(shmem_fd));
240   if (!shmem || !shmem->is_valid()) {
241     PERFETTO_DFATAL_OR_ELOG("Failed to attach to shmem.");
242     return nullptr;
243   }
244 
245   sock.SetBlocking(false);
246   // note: the shared_ptr will retain a copy of the unhooked_allocator
247   return std::allocate_shared<Client>(unhooked_allocator, std::move(sock),
248                                       client_config, std::move(shmem.value()),
249                                       getpid(), GetMainThreadStackRange());
250 }
251 
Client(base::UnixSocketRaw sock,ClientConfiguration client_config,SharedRingBuffer shmem,pid_t pid_at_creation,StackRange main_thread_stack_range)252 Client::Client(base::UnixSocketRaw sock,
253                ClientConfiguration client_config,
254                SharedRingBuffer shmem,
255                pid_t pid_at_creation,
256                StackRange main_thread_stack_range)
257     : client_config_(client_config),
258       max_shmem_tries_(GetMaxTries(client_config_)),
259       sock_(std::move(sock)),
260       main_thread_stack_range_(main_thread_stack_range),
261       shmem_(std::move(shmem)),
262       pid_at_creation_(pid_at_creation) {}
263 
~Client()264 Client::~Client() {
265   // This is work-around for code like the following:
266   // https://android.googlesource.com/platform/libcore/+/4ecb71f94378716f88703b9f7548b5d24839262f/ojluni/src/main/native/UNIXProcess_md.c#427
267   // They fork, close all fds by iterating over /proc/self/fd using opendir.
268   // Unfortunately closedir calls free, which detects the fork, and then tries
269   // to destruct this Client.
270   //
271   // ScopedResource crashes on failure to close, so we explicitly ignore
272   // failures here.
273   int fd = sock_.ReleaseFd().release();
274   if (fd != -1)
275     close(fd);
276 }
277 
GetStackEnd(const char * stackptr)278 const char* Client::GetStackEnd(const char* stackptr) {
279   StackRange thread_stack_range;
280   bool is_main_thread = IsMainThread();
281   if (is_main_thread) {
282     thread_stack_range = main_thread_stack_range_;
283   } else {
284     thread_stack_range = GetThreadStackRange();
285   }
286   if (Contained(thread_stack_range, stackptr)) {
287     return thread_stack_range.end;
288   }
289   StackRange sigalt_stack_range = GetSigAltStackRange();
290   if (Contained(sigalt_stack_range, stackptr)) {
291     return sigalt_stack_range.end;
292   }
293   // The main thread might have expanded since we read its bounds. We now know
294   // it is not the sigaltstack, so it has to be the main stack.
295   // TODO(fmayer): We should reparse maps here, because now we will keep
296   //               hitting the slow-path that calls the sigaltstack syscall.
297   if (is_main_thread && stackptr < thread_stack_range.end) {
298     return thread_stack_range.end;
299   }
300   return nullptr;
301 }
302 
303 // Best-effort detection of whether we're continuing work in a forked child of
304 // the profiled process, in which case we want to stop. Note that due to
305 // malloc_hooks.cc's atfork handler, the proper fork calls should leak the child
306 // before reaching this point. Therefore this logic exists primarily to handle
307 // clone and vfork.
308 // TODO(rsavitski): rename/delete |disable_fork_teardown| config option if this
309 // logic sticks, as the option becomes more clone-specific, and quite narrow.
IsPostFork()310 bool Client::IsPostFork() {
311   if (PERFETTO_UNLIKELY(getpid() != pid_at_creation_)) {
312     // Only print the message once, even if we do not shut down the client.
313     if (!detected_fork_) {
314       detected_fork_ = true;
315       const char* vfork_detected = "";
316 
317       // We use the fact that vfork does not update Bionic's TID cache, so
318       // we will have a mismatch between the actual TID (from the syscall)
319       // and the cached one.
320       //
321       // What we really want to check is if we are sharing virtual memory space
322       // with the original process. This would be
323       // syscall(__NR_kcmp, syscall(__NR_getpid), pid_at_creation_,
324       //         KCMP_VM, 0, 0),
325       //  but that is not compiled into our kernels and disallowed by seccomp.
326       if (!client_config_.disable_vfork_detection &&
327           syscall(__NR_gettid) != base::GetThreadId()) {
328         postfork_return_value_ = true;
329         vfork_detected = " (vfork detected)";
330       } else {
331         postfork_return_value_ = client_config_.disable_fork_teardown;
332       }
333       const char* action =
334           postfork_return_value_ ? "Not shutting down" : "Shutting down";
335       const char* force =
336           postfork_return_value_ ? " (fork teardown disabled)" : "";
337       PERFETTO_LOG(
338           "Detected post-fork child situation. Not profiling the child. "
339           "%s client%s%s",
340           action, force, vfork_detected);
341     }
342     return true;
343   }
344   return false;
345 }
346 
347 // The stack grows towards numerically smaller addresses, so the stack layout
348 // of main calling malloc is as follows.
349 //
350 //               +------------+
351 //               |SendWireMsg |
352 // stackptr +--> +------------+ 0x1000
353 //               |RecordMalloc|    +
354 //               +------------+    |
355 //               | malloc     |    |
356 //               +------------+    |
357 //               |  main      |    v
358 // stackend  +-> +------------+ 0xffff
RecordMalloc(uint32_t heap_id,uint64_t sample_size,uint64_t alloc_size,uint64_t alloc_address)359 bool Client::RecordMalloc(uint32_t heap_id,
360                           uint64_t sample_size,
361                           uint64_t alloc_size,
362                           uint64_t alloc_address) {
363   if (PERFETTO_UNLIKELY(IsPostFork())) {
364     return postfork_return_value_;
365   }
366 
367   AllocMetadata metadata;
368   const char* stackptr = reinterpret_cast<char*>(__builtin_frame_address(0));
369   unwindstack::AsmGetRegs(metadata.register_data);
370   const char* stackend = GetStackEnd(stackptr);
371   if (!stackend) {
372     PERFETTO_ELOG("Failed to find stackend.");
373     shmem_.SetErrorState(SharedRingBuffer::kInvalidStackBounds);
374     return false;
375   }
376   uint64_t stack_size = static_cast<uint64_t>(stackend - stackptr);
377   metadata.sample_size = sample_size;
378   metadata.alloc_size = alloc_size;
379   metadata.alloc_address = alloc_address;
380   metadata.stack_pointer = reinterpret_cast<uint64_t>(stackptr);
381   metadata.arch = unwindstack::Regs::CurrentArch();
382   metadata.sequence_number =
383       1 + sequence_number_[heap_id].fetch_add(1, std::memory_order_acq_rel);
384   metadata.heap_id = heap_id;
385 
386   struct timespec ts;
387   if (clock_gettime(CLOCK_MONOTONIC_COARSE, &ts) == 0) {
388     metadata.clock_monotonic_coarse_timestamp =
389         static_cast<uint64_t>(base::FromPosixTimespec(ts).count());
390   } else {
391     metadata.clock_monotonic_coarse_timestamp = 0;
392   }
393 
394   WireMessage msg{};
395   msg.record_type = RecordType::Malloc;
396   msg.alloc_header = &metadata;
397   msg.payload = const_cast<char*>(stackptr);
398   msg.payload_size = static_cast<size_t>(stack_size);
399 
400   if (SendWireMessageWithRetriesIfBlocking(msg) == -1)
401     return false;
402 
403   if (!shmem_.GetAndResetReaderPaused())
404     return true;
405   return SendControlSocketByte();
406 }
407 
SendWireMessageWithRetriesIfBlocking(const WireMessage & msg)408 int64_t Client::SendWireMessageWithRetriesIfBlocking(const WireMessage& msg) {
409   for (uint64_t i = 0;
410        max_shmem_tries_ == kInfiniteTries || i < max_shmem_tries_; ++i) {
411     if (shmem_.shutting_down())
412       return -1;
413     int64_t res = SendWireMessage(&shmem_, msg);
414     if (PERFETTO_LIKELY(res >= 0))
415       return res;
416     // retry if in blocking mode and still connected
417     if (client_config_.block_client && base::IsAgain(errno) && IsConnected()) {
418       usleep(kResendBackoffUs);
419     } else {
420       break;
421     }
422   }
423   if (IsConnected())
424     shmem_.SetErrorState(SharedRingBuffer::kHitTimeout);
425   PERFETTO_PLOG("Failed to write to shared ring buffer. Disconnecting.");
426   return -1;
427 }
428 
RecordFree(uint32_t heap_id,const uint64_t alloc_address)429 bool Client::RecordFree(uint32_t heap_id, const uint64_t alloc_address) {
430   if (PERFETTO_UNLIKELY(IsPostFork())) {
431     return postfork_return_value_;
432   }
433 
434   FreeEntry current_entry;
435   current_entry.sequence_number =
436       1 + sequence_number_[heap_id].fetch_add(1, std::memory_order_acq_rel);
437   current_entry.addr = alloc_address;
438   current_entry.heap_id = heap_id;
439   WireMessage msg = {};
440   msg.record_type = RecordType::Free;
441   msg.free_header = &current_entry;
442   // Do not send control socket byte, as frees are very cheap to handle, so we
443   // just delay to the next alloc. Sending the control socket byte is ~10x the
444   // rest of the client overhead.
445   int64_t bytes_free = SendWireMessageWithRetriesIfBlocking(msg);
446   if (bytes_free == -1)
447     return false;
448   // Seems like we are filling up the shmem with frees. Flush.
449   if (static_cast<uint64_t>(bytes_free) < shmem_.size() / 2 &&
450       shmem_.GetAndResetReaderPaused()) {
451     return SendControlSocketByte();
452   }
453   return true;
454 }
455 
RecordHeapInfo(uint32_t heap_id,const char * heap_name,uint64_t interval)456 bool Client::RecordHeapInfo(uint32_t heap_id,
457                             const char* heap_name,
458                             uint64_t interval) {
459   if (PERFETTO_UNLIKELY(IsPostFork())) {
460     return postfork_return_value_;
461   }
462 
463   HeapName hnr;
464   hnr.heap_id = heap_id;
465   base::StringCopy(&hnr.heap_name[0], heap_name, sizeof(hnr.heap_name));
466   hnr.sample_interval = interval;
467 
468   WireMessage msg = {};
469   msg.record_type = RecordType::HeapName;
470   msg.heap_name_header = &hnr;
471   return SendWireMessageWithRetriesIfBlocking(msg);
472 }
473 
IsConnected()474 bool Client::IsConnected() {
475   sock_.DcheckIsBlocking(false);
476   char buf[1];
477   ssize_t recv_bytes = sock_.Receive(buf, sizeof(buf), nullptr, 0);
478   if (recv_bytes == 0)
479     return false;
480   // This is not supposed to happen because currently heapprofd does not send
481   // data to the client. Here for generality's sake.
482   if (recv_bytes > 0)
483     return true;
484   return base::IsAgain(errno);
485 }
486 
SendControlSocketByte()487 bool Client::SendControlSocketByte() {
488   // If base::IsAgain(errno), the socket buffer is full, so the service will
489   // pick up the notification even without adding another byte.
490   // In other error cases (usually EPIPE) we want to disconnect, because that
491   // is how the service signals the tracing session was torn down.
492   if (sock_.Send(kSingleByte, sizeof(kSingleByte)) == -1 &&
493       !base::IsAgain(errno)) {
494     if (shmem_.shutting_down()) {
495       PERFETTO_LOG("Profiling session ended.");
496     } else {
497       PERFETTO_PLOG("Failed to send control socket byte.");
498     }
499     return false;
500   }
501   return true;
502 }
503 
504 }  // namespace profiling
505 }  // namespace perfetto
506