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 #define DEBUG false  // STOPSHIP if true
18 #include "config/ConfigKey.h"
19 #include "Log.h"
20 
21 #include "frameworks/base/cmds/statsd/src/statsd_config.pb.h"  // Alert
22 
23 #include <android-base/unique_fd.h>
24 #include <inttypes.h>
25 #include <sys/wait.h>
26 
27 #include <string>
28 
29 namespace {
30 const char kDropboxTag[] = "perfetto";
31 }
32 
33 namespace android {
34 namespace os {
35 namespace statsd {
36 
CollectPerfettoTraceAndUploadToDropbox(const PerfettoDetails & config,int64_t subscription_id,int64_t alert_id,const ConfigKey & configKey)37 bool CollectPerfettoTraceAndUploadToDropbox(const PerfettoDetails& config,
38                                             int64_t subscription_id,
39                                             int64_t alert_id,
40                                             const ConfigKey& configKey) {
41     VLOG("Starting trace collection through perfetto");
42 
43     if (!config.has_trace_config()) {
44         ALOGE("The perfetto trace config is empty, aborting");
45         return false;
46     }
47 
48     char subscriptionId[25];
49     char alertId[25];
50     char configId[25];
51     char configUid[25];
52     snprintf(subscriptionId, sizeof(subscriptionId), "%" PRId64, subscription_id);
53     snprintf(alertId, sizeof(alertId), "%" PRId64, alert_id);
54     snprintf(configId, sizeof(configId), "%" PRId64, configKey.GetId());
55     snprintf(configUid, sizeof(configUid), "%d", configKey.GetUid());
56 
57     android::base::unique_fd readPipe;
58     android::base::unique_fd writePipe;
59     if (!android::base::Pipe(&readPipe, &writePipe)) {
60         ALOGE("pipe() failed while calling the Perfetto client: %s", strerror(errno));
61         return false;
62     }
63 
64     pid_t pid = fork();
65     if (pid < 0) {
66         ALOGE("fork() failed while calling the Perfetto client: %s", strerror(errno));
67         return false;
68     }
69 
70     if (pid == 0) {
71         // Child process.
72 
73         // No malloc calls or library calls after this point. Remember that even
74         // ALOGx (aka android_printLog()) can use dynamic memory for vsprintf().
75 
76         writePipe.reset();  // Close the write end (owned by the main process).
77 
78         // Replace stdin with |readPipe| so the main process can write into it.
79         if (dup2(readPipe.get(), STDIN_FILENO) < 0) _exit(1);
80         readPipe.reset();
81 
82         // Replace stdout/stderr with /dev/null and close any other file
83         // descriptor. This is to avoid SELinux complaining about perfetto
84         // trying to access files accidentally left open by statsd (i.e. files
85         // that have been opened without the O_CLOEXEC flag).
86         int devNullFd = open("/dev/null", O_RDWR | O_CLOEXEC);
87         if (dup2(devNullFd, STDOUT_FILENO) < 0) _exit(2);
88         if (dup2(devNullFd, STDERR_FILENO) < 0) _exit(3);
89         close(devNullFd);
90         for (int i = 0; i < 1024; i++) {
91             if (i != STDIN_FILENO && i != STDOUT_FILENO && i != STDERR_FILENO) close(i);
92         }
93 
94         execl("/system/bin/perfetto", "perfetto", "--background", "--config", "-", "--dropbox",
95               kDropboxTag, "--alert-id", alertId, "--config-id", configId, "--config-uid",
96               configUid, "--subscription-id", subscriptionId, nullptr);
97 
98         // execl() doesn't return in case of success, if we get here something
99         // failed.
100         _exit(4);
101     }
102 
103     // Main process.
104 
105     readPipe.reset();  // Close the read end (owned by the child process).
106 
107     // Using fdopen() because fwrite() has the right logic to chunking write()
108     // over a pipe (see __sfvwrite()).
109     FILE* writePipeStream = android::base::Fdopen(std::move(writePipe), "wb");
110     if (!writePipeStream) {
111         ALOGE("fdopen() failed while calling the Perfetto client: %s", strerror(errno));
112         return false;
113     }
114 
115     const std::string& cfgProto = config.trace_config();
116     size_t bytesWritten = fwrite(cfgProto.data(), 1, cfgProto.size(), writePipeStream);
117     fclose(writePipeStream);
118     if (bytesWritten != cfgProto.size() || cfgProto.size() == 0) {
119         ALOGE("fwrite() failed (ret: %zd) while calling the Perfetto client: %s", bytesWritten,
120               strerror(errno));
121         return false;
122     }
123 
124     // This does NOT wait for the full duration of the trace. It just waits until
125     // the process has read the config from stdin and detached.
126     int childStatus = 0;
127     waitpid(pid, &childStatus, 0);
128     if (!WIFEXITED(childStatus) || WEXITSTATUS(childStatus) != 0) {
129         ALOGE("Child process failed (0x%x) while calling the Perfetto client", childStatus);
130         return false;
131     }
132 
133     VLOG("CollectPerfettoTraceAndUploadToDropbox() succeeded");
134     return true;
135 }
136 
137 }  // namespace statsd
138 }  // namespace os
139 }  // namespace android
140