Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/workspacekit/pkg/readarg/readarg.go
2500 views
1
//
2
// Copyright 2019 Kinvolk
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
// source: https://github.com/kinvolk/seccompagent/blob/main/pkg/readarg/readarg.go
17
18
package readarg
19
20
import (
21
"bytes"
22
"errors"
23
"fmt"
24
"os"
25
26
"golang.org/x/sys/unix"
27
)
28
29
// OpenMem opens the memory file for the target process. It is done separately,
30
// so that the caller can call libseccomp.NotifIDValid() in between.
31
func OpenMem(pid uint32) (*os.File, error) {
32
if pid == 0 {
33
// This can happen if the seccomp agent is in a pid namespace
34
// where the target pid is not mapped.
35
return nil, errors.New("unknown pid")
36
}
37
return os.OpenFile(fmt.Sprintf("/proc/%d/mem", pid), os.O_RDONLY, 0)
38
}
39
40
func ReadString(memFile *os.File, offset int64) (string, error) {
41
if offset == 0 {
42
return "", nil
43
}
44
var buffer = make([]byte, 4096) // PATH_MAX
45
46
_, err := unix.Pread(int(memFile.Fd()), buffer, offset)
47
if err != nil {
48
return "", err
49
}
50
51
// pread() will always return the size of the buffer, as usually
52
// /proc/pid/mem is bigger than the buffer.
53
// Then, to know when the string we are looking for finishes, we look
54
// for the first \0 (with :bytes.IndexByte(buffer, 0)). As the string
55
// should be nul-terminated, this is a simple way to find it.
56
// Also, as a safety check, we add a ending 0 in the buffer, to avoid
57
// doing buffer[-1] and panic, if the buffer doesn't contain any 0.
58
buffer[len(buffer)-1] = 0
59
s := buffer[:bytes.IndexByte(buffer, 0)]
60
return string(s), nil
61
}
62
63
func ReadBytes(memFile *os.File, offset int64, len int) ([]byte, error) {
64
if offset == 0 && len == 0 {
65
return nil, nil
66
}
67
var buffer = make([]byte, len)
68
69
// pread() will always return the size of the buffer
70
_, err := unix.Pread(int(memFile.Fd()), buffer, offset)
71
if err != nil {
72
return nil, err
73
}
74
75
return buffer, nil
76
}
77
78