Skip to content

Commit

Permalink
feat(crit): add SearchPattern method on MemoryReader
Browse files Browse the repository at this point in the history
This commit add a new method SearchPattern to MemoryReader to search
for patterns inside the process memory pages. This method accept regular
expressions for flexible pattern matching.

Signed-off-by: Kouame Behouba Manasse <[email protected]>
  • Loading branch information
behouba committed Mar 11, 2024
1 parent d52ba61 commit 49188fc
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions crit/mempages.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"os"
"path/filepath"
"regexp"

"github.com/checkpoint-restore/go-criu/v7/crit/images/mm"
"github.com/checkpoint-restore/go-criu/v7/crit/images/pagemap"
Expand Down Expand Up @@ -193,3 +194,54 @@ func (mr *MemoryReader) GetShmemSize() (int64, error) {

return size, nil
}

// SearchPattern searches for a pattern in the process memory pages.
// If the pattern is found, it returns slices of strings containing the matched patterns
// along with the specified context before and after each match.
func (mr *MemoryReader) SearchPattern(pattern string, context int) ([]string, error) {
if context < 0 {
return nil, errors.New("context size cannot be negative")
}

var results []string
regexPattern, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}

for _, entry := range mr.pagemapEntries {
start := entry.GetVaddr()
end := start + uint64(entry.GetNrPages())*uint64(mr.pageSize)

// Read the entire page content
buffer, err := mr.GetMemPages(start, end)
if err != nil {
return nil, err
}

// Replace null bytes with space
filteredBytes := bytes.ReplaceAll(buffer.Bytes(), []byte{0x0}, []byte{0x20})

// Search for all matching pattern using the regular expression
matches := regexPattern.FindAllIndex(filteredBytes, -1)

for _, match := range matches {
startPattern, endPattern := match[0], match[1]

// Calculate the start and end indices for the context surrounding the match
startContext := startPattern - context
if startContext < 0 {
startContext = startPattern
}

endContext := endPattern + context
if endContext > buffer.Len() {
endContext = endPattern
}

results = append(results, string(filteredBytes[startContext:endContext]))
}
}

return results, nil
}

0 comments on commit 49188fc

Please sign in to comment.