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 <sys/types.h> 20 #include <unistd.h> 21 22 #include <string> 23 #include <unordered_map> 24 #include <vector> 25 26 #include "common/libs/utils/result.h" 27 28 /** 29 * @file Utility functions to retrieve information from proc filesystem 30 * 31 * As of now, the major consumer is cvd. 32 */ 33 namespace cuttlefish { 34 35 static constexpr char kProcDir[] = "/proc"; 36 37 struct ProcInfo { 38 pid_t pid_; 39 uid_t real_owner_; 40 uid_t effective_owner_; 41 std::string actual_exec_path_; 42 std::unordered_map<std::string, std::string> envs_; 43 std::vector<std::string> args_; 44 }; 45 Result<ProcInfo> ExtractProcInfo(const pid_t pid); 46 47 // collects all pids whose owner is uid 48 Result<std::vector<pid_t>> CollectPids(const uid_t uid = getuid()); 49 50 /* collects all pids that meet the following: 51 * 52 * 1. Belongs to the uid 53 * 2. cpp_basename(readlink(/proc/<pid>/exe)) == exec_name 54 * 55 */ 56 Result<std::vector<pid_t>> CollectPidsByExecName(const std::string& exec_name, 57 const uid_t uid = getuid()); 58 59 /* collects all pids that meet the following: 60 * 61 * 1. Belongs to the uid 62 * 2. readlink(/proc/<pid>/exe) == exec_name 63 * 64 */ 65 Result<std::vector<pid_t>> CollectPidsByExecPath(const std::string& exec_path, 66 const uid_t uid = getuid()); 67 68 /** 69 * When argv[0] != exec_path, collects PIDs based on argv[0] 70 * 71 */ 72 Result<std::vector<pid_t>> CollectPidsByArgv0(const std::string& expected_argv0, 73 const uid_t uid = getuid()); 74 75 Result<uid_t> OwnerUid(const pid_t pid); 76 77 // retrieves command line args for the pid 78 Result<std::vector<std::string>> GetCmdArgs(const pid_t pid); 79 80 // retrieves the path to the executable file used for the pid 81 // this does not work for the defunct processes 82 Result<std::string> GetExecutablePath(const pid_t pid); 83 84 // retrieves the environment variables of the process, pid 85 Result<std::unordered_map<std::string, std::string>> GetEnvs(const pid_t pid); 86 87 Result<pid_t> Ppid(const pid_t pid); 88 89 } // namespace cuttlefish 90