Skip to content

Commit

Permalink
Clean up code
Browse files Browse the repository at this point in the history
Signed-off-by: grantseltzer <grantseltzer@gmail.com>
  • Loading branch information
grantseltzer committed Jun 27, 2022
1 parent e012153 commit c53023e
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions helpers/kernel_symbols.go
Expand Up @@ -2,6 +2,7 @@ package helpers

import (
"bufio"
"errors"
"fmt"
"os"
"strconv"
Expand Down Expand Up @@ -31,15 +32,15 @@ type KernelSymbol struct {
}

/* NewKernelSymbolsMap initiates the kernel symbol map by parsing the /proc/kallsyms file.
* each line continas the symbol's address, segment type, name, module owner (which can be empty in case the symbol is owned by the system)
* each line contains the symbol's address, segment type, name, module owner (which can be empty in case the symbol is owned by the system)
* Note: the key of the map is the symbol owner and the symbol name (with undercase between them)
*/
func NewKernelSymbolsMap() (*KernelSymbolTable, error) {
var KernelSymbols = KernelSymbolTable{}
KernelSymbols.symbolMap = make(map[string]KernelSymbol)
file, err := os.Open("/proc/kallsyms")
if err != nil {
return nil, fmt.Errorf("Could not open /proc/kallsyms")
return nil, fmt.Errorf("could not open /proc/kallsyms: %w", err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
Expand All @@ -54,26 +55,30 @@ func NewKernelSymbolsMap() (*KernelSymbolTable, error) {
if err != nil {
continue
}
symbolName := line[2]
symbolType := line[1]
symbolName := line[2]

symbolOwner := "system"
//if the line is only 3 words then the symbol is owned by the system
if len(line) > 3 {
// When a symbol is contained in a kernel module, it will be specified
// within square brackets, otherwise it's part of the system
symbolOwner = line[3]
symbolOwner = strings.TrimPrefix(line[3], "[")
symbolOwner = strings.TrimPrefix(symbolOwner, "[")
symbolOwner = strings.TrimSuffix(symbolOwner, "]")
}

symbolKey := fmt.Sprintf("%s_%s", symbolOwner, symbolName)
KernelSymbols.symbolMap[symbolKey] = KernelSymbol{symbolName, symbolType, symbolAddr, symbolOwner}
}
KernelSymbols.initialized = true
return &KernelSymbols, nil
}

// TextSegmentContains checks if a given address is in the kernel text segment by compare it to the kernel text segment address boundaries
// TextSegmentContains checks if a given address is in the kernel text segment
// by comparing it to the kernel text segment address boundaries
func (k *KernelSymbolTable) TextSegmentContains(addr uint64) (bool, error) {
if !k.initialized {
return false, fmt.Errorf("KernelSymbolTable symbols map isnt initialized\n")
return false, errors.New("kernel symbols map isnt initialized")
}
stext, err := k.GetSymbolByName("system", "_stext")
if err != nil {
Expand Down

0 comments on commit c53023e

Please sign in to comment.