blob: 4fafd6794982519f1505c9a2ca45ebc5e9a217b5 [file] [log] [blame]
Ryan Savitski175c8862020-01-02 19:54:57 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
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 copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#if defined(LIBC_STATIC)
30#error This file should not be compiled for static targets.
31#endif
32
Ryan Savitskie9531632020-01-06 16:51:05 +000033#include <fcntl.h>
Ryan Savitski175c8862020-01-02 19:54:57 +000034#include <signal.h>
Ryan Savitskie9531632020-01-06 16:51:05 +000035#include <string.h>
36#include <sys/socket.h>
37#include <sys/stat.h>
38#include <sys/types.h>
Ryan Savitski1dc41222020-02-17 12:29:46 +000039#include <sys/ucontext.h>
Ryan Savitskie9531632020-01-06 16:51:05 +000040#include <sys/un.h>
Ryan Savitski175c8862020-01-02 19:54:57 +000041
42#include <async_safe/log.h>
43#include <platform/bionic/malloc.h>
44#include <platform/bionic/reserved_signals.h>
Ryan Savitskie9531632020-01-06 16:51:05 +000045#include <private/ErrnoRestorer.h>
46#include <private/ScopedFd.h>
Ryan Savitski175c8862020-01-02 19:54:57 +000047
48#include "malloc_heapprofd.h"
49
50// This file defines the handler for the reserved signal sent by the Android
51// platform's profilers. The accompanying signal value discriminates between
52// specific requestors:
53// 0: heapprofd heap profiler.
Ryan Savitskie9531632020-01-06 16:51:05 +000054// 1: traced_perf perf profiler.
Ryan Savitski175c8862020-01-02 19:54:57 +000055static constexpr int kHeapprofdSignalValue = 0;
Ryan Savitskie9531632020-01-06 16:51:05 +000056static constexpr int kTracedPerfSignalValue = 1;
Ryan Savitski175c8862020-01-02 19:54:57 +000057
58static void HandleProfilingSignal(int, siginfo_t*, void*);
59
60// Called during dynamic libc preinit.
61__LIBC_HIDDEN__ void __libc_init_profiling_handlers() {
62 struct sigaction action = {};
63 action.sa_flags = SA_SIGINFO | SA_RESTART;
64 action.sa_sigaction = HandleProfilingSignal;
65 sigaction(BIONIC_SIGNAL_PROFILER, &action, nullptr);
Florian Mayer96272df2020-03-24 15:59:27 +010066
67 // The perfetto_hprof ART plugin installs a signal handler to handle this signal. That plugin
68 // does not get loaded for a) non-apps, b) non-profilable apps on user. The default signal
69 // disposition is to crash. We do not want the target to crash if we accidentally target a
70 // non-app or non-profilable process.
Florian Mayer96272df2020-03-24 15:59:27 +010071 signal(BIONIC_SIGNAL_ART_PROFILER, SIG_IGN);
Ryan Savitski175c8862020-01-02 19:54:57 +000072}
73
Ryan Savitski1dc41222020-02-17 12:29:46 +000074static void HandleSigsysSeccompOverride(int, siginfo_t*, void*);
Ryan Savitskie9531632020-01-06 16:51:05 +000075static void HandleTracedPerfSignal();
76
Ryan Savitski175c8862020-01-02 19:54:57 +000077static void HandleProfilingSignal(int /*signal_number*/, siginfo_t* info, void* /*ucontext*/) {
Ryan Savitskie9531632020-01-06 16:51:05 +000078 ErrnoRestorer errno_restorer;
79
80 if (info->si_code != SI_QUEUE) {
Ryan Savitski175c8862020-01-02 19:54:57 +000081 return;
Ryan Savitskie9531632020-01-06 16:51:05 +000082 }
Ryan Savitski175c8862020-01-02 19:54:57 +000083
84 int signal_value = info->si_value.sival_int;
Ryan Savitskie9531632020-01-06 16:51:05 +000085 async_safe_format_log(ANDROID_LOG_INFO, "libc", "%s: received profiling signal with si_value: %d",
Ryan Savitski175c8862020-01-02 19:54:57 +000086 getprogname(), signal_value);
87
88 // Proceed only if the process is considered profileable.
89 bool profileable = false;
90 android_mallopt(M_GET_PROCESS_PROFILEABLE, &profileable, sizeof(profileable));
91 if (!profileable) {
92 async_safe_write_log(ANDROID_LOG_ERROR, "libc", "profiling signal rejected (not profileable)");
93 return;
94 }
95
Ryan Savitski1dc41222020-02-17 12:29:46 +000096 // Temporarily override SIGSYS handling, in a best-effort attempt at not
97 // crashing if we happen to be running in a process with a seccomp filter that
98 // disallows some of the syscalls done by this signal handler. This protects
99 // against SECCOMP_RET_TRAP with a crashing SIGSYS handler (typical of android
100 // minijails). Won't help if the filter is using SECCOMP_RET_KILL_*.
101 // Note: the override is process-wide, but short-lived. The syscalls are still
102 // blocked, but the overridden handler recovers from SIGSYS, and fakes the
103 // syscall return value as ENOSYS.
104 struct sigaction sigsys_override = {};
105 sigsys_override.sa_sigaction = &HandleSigsysSeccompOverride;
106 sigsys_override.sa_flags = SA_SIGINFO;
107
108 struct sigaction old_act = {};
109 sigaction(SIGSYS, &sigsys_override, &old_act);
110
Ryan Savitski175c8862020-01-02 19:54:57 +0000111 if (signal_value == kHeapprofdSignalValue) {
112 HandleHeapprofdSignal();
Ryan Savitskie9531632020-01-06 16:51:05 +0000113 } else if (signal_value == kTracedPerfSignalValue) {
114 HandleTracedPerfSignal();
Ryan Savitski175c8862020-01-02 19:54:57 +0000115 } else {
116 async_safe_format_log(ANDROID_LOG_ERROR, "libc", "unrecognized profiling signal si_value: %d",
117 signal_value);
118 }
Ryan Savitski1dc41222020-02-17 12:29:46 +0000119 sigaction(SIGSYS, &old_act, nullptr);
Ryan Savitski175c8862020-01-02 19:54:57 +0000120}
Ryan Savitskie9531632020-01-06 16:51:05 +0000121
122// Open /proc/self/{maps,mem}, connect to traced_perf, send the fds over the
123// socket. Everything happens synchronously within the signal handler. Socket
124// is made non-blocking, and we do not retry.
125static void HandleTracedPerfSignal() {
126 ScopedFd sock_fd{ socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0 /*protocol*/) };
127 if (sock_fd.get() == -1) {
128 async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to create socket: %s", strerror(errno));
129 return;
130 }
131
132 sockaddr_un saddr{ AF_UNIX, "/dev/socket/traced_perf" };
133 size_t addrlen = sizeof(sockaddr_un);
134 if (connect(sock_fd.get(), reinterpret_cast<const struct sockaddr*>(&saddr), addrlen) == -1) {
135 async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to connect to traced_perf socket: %s",
136 strerror(errno));
137 return;
138 }
139
140 ScopedFd maps_fd{ open("/proc/self/maps", O_RDONLY | O_CLOEXEC) };
141 if (maps_fd.get() == -1) {
142 async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to open /proc/self/maps: %s",
143 strerror(errno));
144 return;
145 }
146 ScopedFd mem_fd{ open("/proc/self/mem", O_RDONLY | O_CLOEXEC) };
147 if (mem_fd.get() == -1) {
148 async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to open /proc/self/mem: %s",
149 strerror(errno));
150 return;
151 }
152
153 // Send 1 byte with auxiliary data carrying two fds.
154 int send_fds[2] = { maps_fd.get(), mem_fd.get() };
155 int num_fds = 2;
156 char iobuf[1] = {};
157 msghdr msg_hdr = {};
158 iovec iov = { reinterpret_cast<void*>(iobuf), sizeof(iobuf) };
159 msg_hdr.msg_iov = &iov;
160 msg_hdr.msg_iovlen = 1;
161 alignas(cmsghdr) char control_buf[256] = {};
162 const auto raw_ctl_data_sz = num_fds * sizeof(int);
163 const size_t control_buf_len = static_cast<size_t>(CMSG_SPACE(raw_ctl_data_sz));
164 msg_hdr.msg_control = control_buf;
165 msg_hdr.msg_controllen = control_buf_len; // used by CMSG_FIRSTHDR
166 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg_hdr);
167 cmsg->cmsg_level = SOL_SOCKET;
168 cmsg->cmsg_type = SCM_RIGHTS;
169 cmsg->cmsg_len = static_cast<size_t>(CMSG_LEN(raw_ctl_data_sz));
170 memcpy(CMSG_DATA(cmsg), send_fds, num_fds * sizeof(int));
171
172 if (sendmsg(sock_fd.get(), &msg_hdr, 0) == -1) {
173 async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to sendmsg: %s", strerror(errno));
174 }
175}
Ryan Savitski1dc41222020-02-17 12:29:46 +0000176
177static void HandleSigsysSeccompOverride(int /*signal_number*/, siginfo_t* info,
178 void* void_context) {
179 ErrnoRestorer errno_restorer;
180 if (info->si_code != SYS_SECCOMP) {
181 return;
182 }
183
184 async_safe_format_log(
185 ANDROID_LOG_WARN, "libc",
186 "Profiling setup: trapped seccomp SIGSYS for syscall %d. Returning ENOSYS to caller.",
187 info->si_syscall);
188
189 // The handler is responsible for setting the return value as if the system
190 // call happened (which is arch-specific). Use a plausible unsuccessful value.
191 auto ret = -ENOSYS;
192 ucontext_t* ctx = reinterpret_cast<ucontext_t*>(void_context);
193
194#if defined(__arm__)
195 ctx->uc_mcontext.arm_r0 = ret;
196#elif defined(__aarch64__)
197 ctx->uc_mcontext.regs[0] = ret; // x0
198#elif defined(__i386__)
199 ctx->uc_mcontext.gregs[REG_EAX] = ret;
200#elif defined(__x86_64__)
201 ctx->uc_mcontext.gregs[REG_RAX] = ret;
202#else
203#error "unsupported architecture"
204#endif
205}