Debian Codegraph @

cmd/runtimetest/mount/mountinfo_linux.go

raw symbols SCIP
1 //go:build linux
2 // +build linux
3
4 package mount
5
6 import (
7 "bufio"
8 "fmt"
9 "io"
10 "os"
11 "strings"
12 )
13
14 const (
15 /* 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
16 (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11)
17
18 (1) mount ID: unique identifier of the mount (may be reused after umount)
19 (2) parent ID: ID of parent (or of self for the top of the mount tree)
20 (3) major:minor: value of st_dev for files on filesystem
21 (4) root: root of the mount within the filesystem
22 (5) mount point: mount point relative to the process's root
23 (6) mount options: per mount options
24 (7) optional fields: zero or more fields of the form "tag[:value]"
25 (8) separator: marks the end of the optional fields
26 (9) filesystem type: name of filesystem of the form "type[.subtype]"
27 (10) mount source: filesystem specific information or "none"
28 (11) super options: per super block options*/
29 mountinfoFormat = "%d %d %d:%d %s %s %s %s"
30 )
31
32 // Parse /proc/self/mountinfo because comparing Dev and ino does not work from
33 // bind mounts
34 func parseMountTable() ([]*Info, error) {
35 f, err := os.Open("/proc/self/mountinfo")
36 if err != nil {
37 return nil, err
38 }
39 defer f.Close()
40
41 return parseInfoFile(f)
42 }
43
44 func parseInfoFile(r io.Reader) ([]*Info, error) {
45 var (
46 s = bufio.NewScanner(r)
47 out = []*Info{}
48 )
49
50 for s.Scan() {
51 if err := s.Err(); err != nil {
52 return nil, err
53 }
54
55 var (
56 p = &Info{}
57 text = s.Text()
58 optionalFields string
59 )
60
61 if _, err := fmt.Sscanf(text, mountinfoFormat,
62 &p.ID, &p.Parent, &p.Major, &p.Minor,
63 &p.Root, &p.Mountpoint, &p.Opts, &optionalFields); err != nil {
64 return nil, fmt.Errorf("Scanning '%s' failed: %s", text, err)
65 }
66 // Safe as mountinfo encodes mountpoints with spaces as \040.
67 index := strings.Index(text, " - ")
68 postSeparatorFields := strings.Split(text[index+3:], " ")
69 if len(postSeparatorFields) < 3 {
70 return nil, fmt.Errorf("Error found less than 3 fields post '-' in %q", text)
71 }
72
73 if optionalFields != "-" {
74 p.Optional = optionalFields
75 }
76
77 p.Fstype = postSeparatorFields[0]
78 p.Source = postSeparatorFields[1]
79 p.VfsOpts = strings.Join(postSeparatorFields[2:], " ")
80 out = append(out, p)
81 }
82 return out, nil
83 }
84
85 // PidMountInfo collects the mounts for a specific process ID. If the process
86 // ID is unknown, it is better to use `GetMounts` which will inspect
87 // "/proc/self/mountinfo" instead.
88 func PidMountInfo(pid int) ([]*Info, error) {
89 f, err := os.Open(fmt.Sprintf("/proc/%d/mountinfo", pid))
90 if err != nil {
91 return nil, err
92 }
93 defer f.Close()
94
95 return parseInfoFile(f)
96 }