Skip to content

Commit

Permalink
link: sanitizeSymbol: rewrite with no regexp use
Browse files Browse the repository at this point in the history
Instead of using a regular expression in sanitizeSymbol, write a small
for loop to replace any repetitions of unknown characters with a "_".

This removes the last use of regexp from this package.

Signed-off-by: Kir Kolyshkin <kolyshkin@gmail.com>
  • Loading branch information
kolyshkin committed Apr 27, 2022
1 parent 7f2a37f commit c5fea6c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
30 changes: 23 additions & 7 deletions link/uprobe.go
Expand Up @@ -6,7 +6,7 @@ import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"sync"

"github.com/cilium/ebpf"
Expand All @@ -16,10 +16,6 @@ import (
var (
uprobeEventsPath = filepath.Join(tracefsPath, "uprobe_events")

// rgxEventSymbol is used to strip invalid characters from the [k,u]probe symbol
// as they are not allowed to be used as the EVENT token in tracefs.
rgxEventSymbol = regexp.MustCompile("[^a-zA-Z0-9]+")

uprobeRetprobeBit = struct {
once sync.Once
value uint64
Expand Down Expand Up @@ -316,8 +312,28 @@ func tracefsUprobe(args probeArgs) (*perfEvent, error) {
}

// sanitizedSymbol replaces every invalid character for the tracefs api with an underscore.
func sanitizedSymbol(symbol string) string {
return rgxEventSymbol.ReplaceAllString(symbol, "_")
// It is equivalent to calling regexp.MustCompile("[^a-zA-Z0-9]+").ReplaceAllString("_").
func sanitizedSymbol(s string) string {
var b strings.Builder
b.Grow(len(s))
var skip bool
for _, c := range []byte(s) {
switch {
case c >= 'a' && c <= 'z',
c >= 'A' && c <= 'Z',
c >= '0' && c <= '9':
skip = false
b.WriteByte(c)

default:
if !skip {
b.WriteByte('_')
skip = true
}
}
}

return b.String()
}

// uprobeToken creates the PATH:OFFSET(REF_CTR_OFFSET) token for the tracefs api.
Expand Down
4 changes: 3 additions & 1 deletion link/uprobe_test.go
Expand Up @@ -280,9 +280,11 @@ func TestUprobeSanitizedSymbol(t *testing.T) {
expected string
}{
{"readline", "readline"},
{"main.Func", "main_Func"},
{"main.Func123", "main_Func123"},
{"a.....a", "a_a"},
{"./;'{}[]a", "_a"},
{"***xx**xx###", "_xx_xx_"},
{`@P#r$i%v^3*+t)i&k++--`, "_P_r_i_v_3_t_i_k_"},
}

for i, tt := range tests {
Expand Down

0 comments on commit c5fea6c

Please sign in to comment.