1package proc
2
3import (
4	"io/ioutil"
5	"path/filepath"
6	"strconv"
7	"strings"
8
9	"android/soong/finder/fs"
10)
11
12// NewProcStatus returns an instance of the ProcStatus that contains memory
13// information of the process. The memory information is extracted from the
14// "/proc/<pid>/status" text file. This is only available for Linux
15// distribution that supports /proc.
16func NewProcStatus(pid int, fileSystem fs.FileSystem) (*ProcStatus, error) {
17	statusFname := filepath.Join("/proc", strconv.Itoa(pid), "status")
18	r, err := fileSystem.Open(statusFname)
19	if err != nil {
20		return &ProcStatus{}, err
21	}
22	defer r.Close()
23
24	data, err := ioutil.ReadAll(r)
25	if err != nil {
26		return &ProcStatus{}, err
27	}
28
29	s := &ProcStatus{
30		pid: pid,
31	}
32
33	for _, l := range strings.Split(string(data), "\n") {
34		// If the status file does not contain "key: values", just skip the line
35		// as the information we are looking for is not needed.
36		if !strings.Contains(l, ":") {
37			continue
38		}
39
40		// At this point, we're only considering entries that has key, single value pairs.
41		kv := strings.SplitN(l, ":", 2)
42		fillProcStatus(s, strings.TrimSpace(kv[0]), strings.TrimSpace(kv[1]))
43	}
44
45	return s, nil
46}
47