Skip to content

Commit

Permalink
Adds support for patching value struct (#5)
Browse files Browse the repository at this point in the history
* adds support for patching value struct

* add go versions to the matrix
  • Loading branch information
tonyredondo authored May 10, 2020
1 parent 1a86426 commit 872e88c
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 4 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ jobs:
name: Test
strategy:
matrix:
go_version: [1.12, 1.13]
go_version: [1.11, 1.12, 1.13, 1.14]
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
Expand Down
5 changes: 3 additions & 2 deletions patcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,11 @@ func PatchMethod(target, redirection interface{}) (*Patch, error) {
return patch, nil
}
func PatchInstanceMethodByName(target reflect.Type, methodName string, redirection interface{}) (*Patch, error) {
if target.Kind() == reflect.Struct {
method, ok := target.MethodByName(methodName)
if !ok && target.Kind() == reflect.Struct {
target = reflect.PtrTo(target)
method, ok = target.MethodByName(methodName)
}
method, ok := target.MethodByName(methodName)
if !ok {
return nil, errors.New(fmt.Sprintf("Method '%v' not found", methodName))
}
Expand Down
31 changes: 31 additions & 0 deletions patcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ func (s *myStruct) Method() int {
return 1
}

//go:noinline
func (s myStruct) ValueMethod() int {
return 1
}

func TestPatcher(t *testing.T) {
patch, err := PatchMethod(methodA, methodB)
if err != nil {
Expand Down Expand Up @@ -62,3 +67,29 @@ func TestInstancePatcher(t *testing.T) {
t.Fatal("The unpatch did not work")
}
}

func TestInstanceValuePatcher(t *testing.T) {
mStruct := myStruct{}

var patch *Patch
var err error
patch, err = PatchInstanceMethodByName(reflect.TypeOf(mStruct), "ValueMethod", func(m myStruct) int {
patch.Unpatch()
defer patch.Patch()
return 41 + m.Method()
})
if err != nil {
t.Fatal(err)
}

if mStruct.ValueMethod() != 42 {
t.Fatal("The patch did not work")
}
err = patch.Unpatch()
if err != nil {
t.Fatal(err)
}
if mStruct.ValueMethod() != 1 {
t.Fatal("The unpatch did not work")
}
}
2 changes: 1 addition & 1 deletion patcher_unsupported.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ import (
// Gets the jump function rewrite bytes
func getJumpFuncBytes(to uintptr) ([]byte, error) {
return nil, errors.New(fmt.Sprintf("Unsupported architecture: %s", runtime.GOARCH))
}
}

0 comments on commit 872e88c

Please sign in to comment.