Path: blob/main/components/workspacekit/pkg/readarg/readarg.go
2500 views
//1// Copyright 2019 Kinvolk2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14//15// source: https://github.com/kinvolk/seccompagent/blob/main/pkg/readarg/readarg.go1617package readarg1819import (20"bytes"21"errors"22"fmt"23"os"2425"golang.org/x/sys/unix"26)2728// OpenMem opens the memory file for the target process. It is done separately,29// so that the caller can call libseccomp.NotifIDValid() in between.30func OpenMem(pid uint32) (*os.File, error) {31if pid == 0 {32// This can happen if the seccomp agent is in a pid namespace33// where the target pid is not mapped.34return nil, errors.New("unknown pid")35}36return os.OpenFile(fmt.Sprintf("/proc/%d/mem", pid), os.O_RDONLY, 0)37}3839func ReadString(memFile *os.File, offset int64) (string, error) {40if offset == 0 {41return "", nil42}43var buffer = make([]byte, 4096) // PATH_MAX4445_, err := unix.Pread(int(memFile.Fd()), buffer, offset)46if err != nil {47return "", err48}4950// pread() will always return the size of the buffer, as usually51// /proc/pid/mem is bigger than the buffer.52// Then, to know when the string we are looking for finishes, we look53// for the first \0 (with :bytes.IndexByte(buffer, 0)). As the string54// should be nul-terminated, this is a simple way to find it.55// Also, as a safety check, we add a ending 0 in the buffer, to avoid56// doing buffer[-1] and panic, if the buffer doesn't contain any 0.57buffer[len(buffer)-1] = 058s := buffer[:bytes.IndexByte(buffer, 0)]59return string(s), nil60}6162func ReadBytes(memFile *os.File, offset int64, len int) ([]byte, error) {63if offset == 0 && len == 0 {64return nil, nil65}66var buffer = make([]byte, len)6768// pread() will always return the size of the buffer69_, err := unix.Pread(int(memFile.Fd()), buffer, offset)70if err != nil {71return nil, err72}7374return buffer, nil75}767778