Skip to content

Instantly share code, notes, and snippets.

@CyberLight
Last active July 7, 2023 12:54
Show Gist options
  • Save CyberLight/1da35b4e0093bc12302f to your computer and use it in GitHub Desktop.
Save CyberLight/1da35b4e0093bc12302f to your computer and use it in GitHub Desktop.
GOLANG: Patching private fields with values
package main
import (
redis "gopkg.in/redis.v3"
"reflect"
"unsafe"
"fmt"
)
type A struct {
val string
}
func (a *A) Val() string {
return a.val
}
type B struct {
val []string
}
func (b *B) Val() []string {
return b.val
}
func change_val(f *A, v string) {
pointerVal := reflect.ValueOf(f)
val := reflect.Indirect(pointerVal)
member := val.FieldByName("val")
ptrToY := unsafe.Pointer(member.UnsafeAddr())
realPtrToY := (*string)(ptrToY)
*realPtrToY = v
}
func change_b_val(f *B, v []string) {
pointerVal := reflect.ValueOf(f)
val := reflect.Indirect(pointerVal)
member := val.FieldByName("val")
ptrToY := unsafe.Pointer(member.UnsafeAddr())
realPtrToY := (*[]string)(ptrToY)
*realPtrToY = v
}
func change_redis_val(f *redis.StringCmd, v string) {
pointerVal := reflect.ValueOf(f)
val := reflect.Indirect(pointerVal)
member := val.FieldByName("val")
ptrToY := unsafe.Pointer(member.UnsafeAddr())
realPtrToY := (*[]byte)(ptrToY)
*realPtrToY = []byte(v)
}
func change_redis_slice_val(f *redis.StringSliceCmd, v []string) {
pointerVal := reflect.ValueOf(f)
val := reflect.Indirect(pointerVal)
member := val.FieldByName("val")
ptrToY := unsafe.Pointer(member.UnsafeAddr())
realPtrToY := (*[]string)(ptrToY)
*realPtrToY = v
}
func main(){
m := redis.NewStringCmd("KEYS", "driver*")
change_redis_val(m, "victory")
fmt.Println("Redis value:", m.Val())
m2 := redis.NewStringSliceCmd("HMGET", "option")
change_redis_slice_val(m2, []string{"1", "2", "3"})
fmt.Println("Redis slice value:", m2.Val())
a := new(A)
change_val(a, "lalalal")
fmt.Println(a.Val())
b := new(B)
change_b_val(b, []string{"1", "2", "3"})
fmt.Println(b.Val())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment