...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/mapreader/reader.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/mapreader

     1  // Copyright 2021 Chaos Mesh Authors.
     2  //
     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 at
     6  //
     7  // http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // 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 and
    13  // limitations under the License.
    14  //
    15  
    16  package mapreader
    17  
    18  import (
    19  	"fmt"
    20  	"os"
    21  	"strconv"
    22  	"strings"
    23  
    24  	"github.com/pkg/errors"
    25  )
    26  
    27  // Entry is one line in /proc/pid/maps
    28  type Entry struct {
    29  	StartAddress uint64
    30  	EndAddress   uint64
    31  	Privilege    string
    32  	PaddingSize  uint64
    33  	Path         string
    34  }
    35  
    36  // Read parse /proc/[pid]/maps and return a list of entry
    37  // The format of /proc/[pid]/maps can be found in `man proc`.
    38  func Read(pid int) ([]Entry, error) {
    39  	data, err := os.ReadFile(fmt.Sprintf("/proc/%d/maps", pid))
    40  	if err != nil {
    41  		return nil, errors.WithStack(err)
    42  	}
    43  
    44  	lines := strings.Split(string(data), "\n")
    45  
    46  	var entries []Entry
    47  	for _, line := range lines {
    48  		sections := strings.Split(line, " ")
    49  		if len(sections) < 3 {
    50  			continue
    51  		}
    52  
    53  		var path string
    54  
    55  		if len(sections) > 5 {
    56  			path = sections[len(sections)-1]
    57  		}
    58  
    59  		addresses := strings.Split(sections[0], "-")
    60  		startAddress, err := strconv.ParseUint(addresses[0], 16, 64)
    61  		if err != nil {
    62  			return nil, errors.WithStack(err)
    63  		}
    64  		endAddresses, err := strconv.ParseUint(addresses[1], 16, 64)
    65  		if err != nil {
    66  			return nil, errors.WithStack(err)
    67  		}
    68  
    69  		privilege := sections[1]
    70  
    71  		paddingSize, err := strconv.ParseUint(sections[2], 16, 64)
    72  		if err != nil {
    73  			return nil, errors.WithStack(err)
    74  		}
    75  
    76  		entries = append(entries, Entry{
    77  			startAddress,
    78  			endAddresses,
    79  			privilege,
    80  			paddingSize,
    81  			path,
    82  		})
    83  	}
    84  
    85  	return entries, nil
    86  }
    87