1 /*
2  * Copyright (C) 2020 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 <android-base/logging.h>
18 #include <android-base/parseint.h>
19 #include <android-base/strings.h>
20 #include <binder/Binder.h>
21 #include <sys/types.h>
22 #include <fstream>
23 #include <regex>
24 
25 #include <binderdebug/BinderDebug.h>
26 
27 namespace android {
28 
contextToString(BinderDebugContext context)29 static std::string contextToString(BinderDebugContext context) {
30     switch (context) {
31         case BinderDebugContext::BINDER:
32             return "binder";
33         case BinderDebugContext::HWBINDER:
34             return "hwbinder";
35         case BinderDebugContext::VNDBINDER:
36             return "vndbinder";
37         default:
38             return std::string();
39     }
40 }
41 
scanBinderContext(pid_t pid,const std::string & contextName,std::function<void (const std::string &)> eachLine)42 static status_t scanBinderContext(pid_t pid, const std::string& contextName,
43                                   std::function<void(const std::string&)> eachLine) {
44     std::ifstream ifs("/dev/binderfs/binder_logs/proc/" + std::to_string(pid));
45     if (!ifs.is_open()) {
46         ifs.open("/d/binder/proc/" + std::to_string(pid));
47         if (!ifs.is_open()) {
48             return -errno;
49         }
50     }
51 
52     bool isDesiredContext = false;
53     std::string line;
54     while (getline(ifs, line)) {
55         if (base::StartsWith(line, "context")) {
56             isDesiredContext = base::Split(line, " ").back() == contextName;
57             continue;
58         }
59         if (!isDesiredContext) {
60             continue;
61         }
62         eachLine(line);
63     }
64     return OK;
65 }
66 
67 // Examples of what we are looking at:
68 // node 66730: u00007590061890e0 c0000759036130950 pri 0:120 hs 1 hw 1 ls 0 lw 0 is 2 iw 2 tr 1 proc 2300 1790
69 // thread 2999: l 00 need_return 1 tr 0
getBinderPidInfo(BinderDebugContext context,pid_t pid,BinderPidInfo * pidInfo)70 status_t getBinderPidInfo(BinderDebugContext context, pid_t pid, BinderPidInfo* pidInfo) {
71     std::smatch match;
72     static const std::regex kReferencePrefix("^\\s*node \\d+:\\s+u([0-9a-f]+)\\s+c([0-9a-f]+)\\s+");
73     static const std::regex kThreadPrefix("^\\s*thread \\d+:\\s+l\\s+(\\d)(\\d)");
74     std::string contextStr = contextToString(context);
75     status_t ret = scanBinderContext(pid, contextStr, [&](const std::string& line) {
76         if (base::StartsWith(line, "  node")) {
77             std::vector<std::string> splitString = base::Tokenize(line, " ");
78             bool pids = false;
79             uint64_t ptr = 0;
80             for (const auto& token : splitString) {
81                 if (base::StartsWith(token, "u")) {
82                     const std::string ptrString = "0x" + token.substr(1);
83                     if (!::android::base::ParseUint(ptrString.c_str(), &ptr)) {
84                         LOG(ERROR) << "Failed to parse pointer: " << ptrString;
85                         return;
86                     }
87                 } else {
88                     // The last numbers in the line after "proc" are all client PIDs
89                     if (token == "proc") {
90                         pids = true;
91                     } else if (pids) {
92                         int32_t pid;
93                         if (!::android::base::ParseInt(token, &pid)) {
94                             LOG(ERROR) << "Failed to parse pid int: " << token;
95                             return;
96                         }
97                         if (ptr == 0) {
98                             LOG(ERROR) << "We failed to parse the pointer, so we can't add the refPids";
99                             return;
100                         }
101                         pidInfo->refPids[ptr].push_back(pid);
102                     }
103                 }
104             }
105         } else if (base::StartsWith(line, "  thread")) {
106             auto pos = line.find("l ");
107             if (pos != std::string::npos) {
108                 // "1" is waiting in binder driver
109                 // "2" is poll. It's impossible to tell if these are in use.
110                 //     and HIDL default code doesn't use it.
111                 bool isInUse = line.at(pos + 2) != '1';
112                 // "0" is a thread that has called into binder
113                 // "1" is looper thread
114                 // "2" is main looper thread
115                 bool isBinderThread = line.at(pos + 3) != '0';
116                 if (!isBinderThread) {
117                     return;
118                 }
119                 if (isInUse) {
120                     pidInfo->threadUsage++;
121                 }
122 
123                 pidInfo->threadCount++;
124             }
125         }
126     });
127     return ret;
128 }
129 
130 // Examples of what we are looking at:
131 // ref 52493: desc 910 node 52492 s 1 w 1 d 0000000000000000
132 // node 29413: u00007803fc982e80 c000078042c982210 pri 0:139 hs 1 hw 1 ls 0 lw 0 is 2 iw 2 tr 1 proc 488 683
getBinderClientPids(BinderDebugContext context,pid_t pid,pid_t servicePid,int32_t handle,std::vector<pid_t> * pids)133 status_t getBinderClientPids(BinderDebugContext context, pid_t pid, pid_t servicePid,
134                              int32_t handle, std::vector<pid_t>* pids) {
135     std::smatch match;
136     static const std::regex kNodeNumber("^\\s+ref \\d+:\\s+desc\\s+(\\d+)\\s+node\\s+(\\d+).*");
137     std::string contextStr = contextToString(context);
138     int32_t node;
139     status_t ret = scanBinderContext(pid, contextStr, [&](const std::string& line) {
140         if (!base::StartsWith(line, "  ref")) return;
141 
142         std::vector<std::string> splitString = base::Tokenize(line, " ");
143         if (splitString.size() < 12) {
144             LOG(ERROR) << "Failed to parse binder_logs ref entry. Expecting size greater than 11, but got: " << splitString.size();
145             return;
146         }
147         int32_t desc;
148         if (!::android::base::ParseInt(splitString[3].c_str(), &desc)) {
149             LOG(ERROR) << "Failed to parse desc int: " << splitString[3];
150             return;
151         }
152         if (handle != desc) {
153             return;
154         }
155         if (!::android::base::ParseInt(splitString[5].c_str(), &node)) {
156             LOG(ERROR) << "Failed to parse node int: " << splitString[5];
157             return;
158         }
159         LOG(INFO) << "Parsed the node: " << node;
160     });
161     if (ret != OK) {
162         return ret;
163     }
164 
165     ret = scanBinderContext(servicePid, contextStr, [&](const std::string& line) {
166         if (!base::StartsWith(line, "  node")) return;
167 
168         std::vector<std::string> splitString = base::Tokenize(line, " ");
169         if (splitString.size() < 21) {
170             LOG(ERROR) << "Failed to parse binder_logs node entry. Expecting size greater than 20, but got: " << splitString.size();
171             return;
172         }
173 
174         // remove the colon
175         const std::string nodeString = splitString[1].substr(0, splitString[1].size() - 1);
176         int32_t matchedNode;
177         if (!::android::base::ParseInt(nodeString.c_str(), &matchedNode)) {
178             LOG(ERROR) << "Failed to parse node int: " << nodeString;
179             return;
180         }
181 
182         if (node != matchedNode) {
183             return;
184         }
185         bool pidsSection = false;
186         for (const auto& token : splitString) {
187             if (token == "proc") {
188                 pidsSection = true;
189             } else if (pidsSection == true) {
190                 int32_t pid;
191                 if (!::android::base::ParseInt(token.c_str(), &pid)) {
192                     LOG(ERROR) << "Failed to parse PID int: " << token;
193                     return;
194                 }
195                 pids->push_back(pid);
196             }
197         }
198     });
199     return ret;
200 }
201 
getBinderTransactions(pid_t pid,std::string & transactionsOutput)202 status_t getBinderTransactions(pid_t pid, std::string& transactionsOutput) {
203     std::ifstream ifs("/dev/binderfs/binder_logs/transactions");
204     if (!ifs.is_open()) {
205         ifs.open("/d/binder/transactions");
206         if (!ifs.is_open()) {
207             LOG(ERROR) << "Could not open /dev/binderfs/binder_logs/transactions. "
208                        << "Likely a permissions issue. errno: " << errno;
209             return -errno;
210         }
211     }
212 
213     std::string line;
214     while (getline(ifs, line)) {
215         // The section for this pid ends with another "proc <pid>" for another
216         // process. There is only one entry per pid so we can stop looking after
217         // we've grabbed the whole section
218         if (base::StartsWith(line, "proc " + std::to_string(pid))) {
219             do {
220                 transactionsOutput += line + '\n';
221             } while (getline(ifs, line) && !base::StartsWith(line, "proc "));
222             return OK;
223         }
224     }
225 
226     return NAME_NOT_FOUND;
227 }
228 
229 } // namespace  android
230