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 #ifndef SRC_PROFILING_COMMON_PROC_UTILS_H_
18 #define SRC_PROFILING_COMMON_PROC_UTILS_H_
19
20 #include <sys/types.h>
21 #include <set>
22 #include <vector>
23
24 #include "perfetto/ext/base/optional.h"
25 #include "perfetto/ext/base/scoped_file.h"
26
27 namespace perfetto {
28 namespace profiling {
29
30 template <typename Fn>
ForEachPid(Fn callback)31 void ForEachPid(Fn callback) {
32 base::ScopedDir proc_dir(opendir("/proc"));
33 if (!proc_dir) {
34 PERFETTO_DFATAL_OR_ELOG("Failed to open /proc");
35 return;
36 }
37 struct dirent* entry;
38 while ((entry = readdir(*proc_dir))) {
39 char* end;
40 long int pid = strtol(entry->d_name, &end, 10);
41 if (*end != '\0')
42 continue;
43 callback(static_cast<pid_t>(pid));
44 }
45 }
46
47 base::Optional<std::vector<std::string>> NormalizeCmdlines(
48 const std::vector<std::string>& cmdlines);
49
50 void FindAllProfilablePids(std::set<pid_t>* pids);
51 void FindPidsForCmdlines(const std::vector<std::string>& cmdlines,
52 std::set<pid_t>* pids);
53 bool GetCmdlineForPID(pid_t pid, std::string* name);
54
55 base::Optional<std::string> ReadStatus(pid_t pid);
56 base::Optional<uint32_t> GetRssAnonAndSwap(const std::string&);
57 // Filters the list of pids (in-place), keeping only the
58 // entries satisfying the minimum size criteria for anonymous memory.
59 void RemoveUnderAnonThreshold(uint32_t min_size_kb, std::set<pid_t>* pids);
60
61 } // namespace profiling
62 } // namespace perfetto
63
64 #endif // SRC_PROFILING_COMMON_PROC_UTILS_H_
65