1 /*
2  * Copyright (C) 2024 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 <filesystem>
18 #include <iostream>
19 #include <string>
20 
21 #include <android-base/file.h>
22 #include <android-base/logging.h>
23 #include <android-base/parseint.h>
24 #include <android-base/properties.h>
25 #include <android-base/strings.h>
26 #include <android_uprobestats_flags.h>
27 #include <config.pb.h>
28 #include <json/json.h>
29 
30 namespace android {
31 namespace uprobestats {
32 namespace process {
33 
getPid(const std::string & processName)34 int getPid(const std::string &processName) {
35   for (const auto &entry : std::filesystem::directory_iterator("/proc")) {
36     std::string cmdline;
37     android::base::ReadFileToString(entry.path() / "cmdline", &cmdline);
38     if (android::base::ReadFileToString(entry.path() / "cmdline", &cmdline) &&
39         (cmdline == processName ||
40          (cmdline.rfind(processName + '\0', 0) == 0))) {
41       std::string pidStr =
42           entry.path().string().substr(entry.path().string().rfind("/") + 1);
43       int pid;
44       if (!android::base::ParseInt(pidStr, &pid)) {
45         return -1;
46       }
47       return pid;
48     }
49   }
50   return -1;
51 }
52 
53 } // namespace process
54 } // namespace uprobestats
55 } // namespace android