Skip to content

Commit 872e88c

Browse files
authored
Adds support for patching value struct (#5)
* adds support for patching value struct * add go versions to the matrix
1 parent 1a86426 commit 872e88c

File tree

4 files changed

+36
-4
lines changed

4 files changed

+36
-4
lines changed

.github/workflows/go.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ jobs:
55
name: Test
66
strategy:
77
matrix:
8-
go_version: [1.12, 1.13]
8+
go_version: [1.11, 1.12, 1.13, 1.14]
99
os: [ubuntu-latest, windows-latest]
1010
runs-on: ${{ matrix.os }}
1111
steps:

patcher.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,11 @@ func PatchMethod(target, redirection interface{}) (*Patch, error) {
4242
return patch, nil
4343
}
4444
func PatchInstanceMethodByName(target reflect.Type, methodName string, redirection interface{}) (*Patch, error) {
45-
if target.Kind() == reflect.Struct {
45+
method, ok := target.MethodByName(methodName)
46+
if !ok && target.Kind() == reflect.Struct {
4647
target = reflect.PtrTo(target)
48+
method, ok = target.MethodByName(methodName)
4749
}
48-
method, ok := target.MethodByName(methodName)
4950
if !ok {
5051
return nil, errors.New(fmt.Sprintf("Method '%v' not found", methodName))
5152
}

patcher_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@ func (s *myStruct) Method() int {
1919
return 1
2020
}
2121

22+
//go:noinline
23+
func (s myStruct) ValueMethod() int {
24+
return 1
25+
}
26+
2227
func TestPatcher(t *testing.T) {
2328
patch, err := PatchMethod(methodA, methodB)
2429
if err != nil {
@@ -62,3 +67,29 @@ func TestInstancePatcher(t *testing.T) {
6267
t.Fatal("The unpatch did not work")
6368
}
6469
}
70+
71+
func TestInstanceValuePatcher(t *testing.T) {
72+
mStruct := myStruct{}
73+
74+
var patch *Patch
75+
var err error
76+
patch, err = PatchInstanceMethodByName(reflect.TypeOf(mStruct), "ValueMethod", func(m myStruct) int {
77+
patch.Unpatch()
78+
defer patch.Patch()
79+
return 41 + m.Method()
80+
})
81+
if err != nil {
82+
t.Fatal(err)
83+
}
84+
85+
if mStruct.ValueMethod() != 42 {
86+
t.Fatal("The patch did not work")
87+
}
88+
err = patch.Unpatch()
89+
if err != nil {
90+
t.Fatal(err)
91+
}
92+
if mStruct.ValueMethod() != 1 {
93+
t.Fatal("The unpatch did not work")
94+
}
95+
}

patcher_unsupported.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@ import (
1212
// Gets the jump function rewrite bytes
1313
func getJumpFuncBytes(to uintptr) ([]byte, error) {
1414
return nil, errors.New(fmt.Sprintf("Unsupported architecture: %s", runtime.GOARCH))
15-
}
15+
}

0 commit comments

Comments
 (0)