blob: 24d01cb2f1d9e18cdc4cbde8104b7429e89612f1 [file] [log] [blame]
Nitin Prasadbeacb282024-12-10 20:20:07 +00001#!/usr/bin/env python3
2
3# Copyright (C) 2024 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Helper utilities for coverage."""
18
19from collections.abc import Sequence
20import dataclasses
21import re
22
23from mobly.controllers import android_device
24
25
26# Sample output:
27# ```
28# USER PID PPID VSZ RSS WCHAN ADDR S NAME
29# root 1 0 10929596 4324 0 0 S init
30# ```
31_PS_PATTERN = re.compile(
32 r"^\s*(\S+)\s+(\d+)\s+(?:\d+)\s+(?:\d+)\s+(?:\d+)\s+(?:\d+)\s+(?:\d+)\s+(?:\S+)\s+(\S+)\s*$"
33)
34_PM_PACKAGE_PREFIX = "package:"
35
36
37@dataclasses.dataclass
38class ProcessInfo:
39 """Information about a running process."""
40
41 user: str
42 name: str
43 pid: int
44
45
46def get_running_processes(
47 device: android_device.AndroidDevice,
48) -> Sequence[ProcessInfo]:
49 """Returns information about all running processes on the device."""
50 processes = []
51 raw_output = device.adb.shell("ps -e")
52 ps_lines = raw_output.decode().split("\n")
53 for line in ps_lines:
54 match = _PS_PATTERN.match(line)
55 if not match:
56 continue
57 processes.append(
58 ProcessInfo(
59 user=match.group(1), pid=int(match.group(2)), name=match.group(3)
60 )
61 )
62 return processes
63
64
65def get_all_packages(device: android_device.AndroidDevice) -> Sequence[str]:
66 """Retrieves the names of all installed packages on the device."""
67 packages = []
68 raw_output = device.adb.shell(["pm", "list", "packages", "-a"])
69 output_lines = raw_output.decode().split("\n")
70 for line in output_lines:
71 line = line.strip()
72 if not line:
73 continue
74 if line.startswith(_PM_PACKAGE_PREFIX):
75 packages.append(line[len(_PM_PACKAGE_PREFIX) :])
76 return packages