Fabien Sanglard | 5beb078 | 2023-06-14 01:29:23 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2023 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 | #pragma once |
| 18 | |
| 19 | #include <stdint.h> |
| 20 | #include <string> |
| 21 | |
| 22 | #include "utils/LruCache.h" |
| 23 | |
| 24 | // An interface to associate pid to a name. Implemented by looking up /proc/PID. |
| 25 | // To lower syscall impact, results are cached. |
| 26 | class ProcessNames { |
| 27 | public: |
| 28 | ProcessNames() : cache(kMaxCacheEntries) {} |
| 29 | |
| 30 | ~ProcessNames() = default; |
| 31 | |
| 32 | // Returns the executable name or in the case of an app, the package name associated |
| 33 | // with a process pid. |
| 34 | std::string Get(uint64_t pid); |
| 35 | |
| 36 | private: |
| 37 | const std::string ReadCmdline(uint64_t pid); |
| 38 | const std::string ReadComm(uint64_t pid); |
| 39 | const std::string Resolve(uint64_t pid); |
| 40 | |
| 41 | // kMaxCacheEntries should be picked to keep the memory footprint low (1) and yield a |
| 42 | // high cache hit rate (2). |
| 43 | // 1. We cache executable name or package name, which account for roughly 20 characters |
| 44 | // each. Using a 100 figure results in 2 KiB for cache storage. |
| 45 | // 2. Difficult to tune since it depends on how many process are alive and how much they |
| 46 | // generate towards liblob. From manual testing, 100 entries resulted in 99% cache hit |
| 47 | // with AOSP 34, right after boot, and one app active. We could monitor this value by |
| 48 | // augmenting the protobuffer and have a cache hit boolean to generate a cache hit figure |
| 49 | // on the workstation. |
| 50 | static const uint64_t kMaxCacheEntries = 100; |
| 51 | android::LruCache<uint64_t, std::string> cache; |
| 52 | }; |