Created
February 5, 2012 20:54
-
-
Save kortschak/1747889 to your computer and use it in GitHub Desktop.
attempt at unsafe manipulation of chan dir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"reflect" | |
"runtime" | |
"unsafe" | |
) | |
type commonType struct { | |
_ uintptr | |
_ uint32 | |
_ uint8 | |
_ uint8 | |
_ uint8 | |
_ uint8 | |
_ *struct{} | |
_ *struct{} | |
_ *struct{} | |
_ *struct{} | |
} | |
func (t *commonType) runtimeType() *runtime.Type { | |
// The runtime.Type always precedes the commonType in memory. | |
// Adjust pointer to find it. | |
var rt struct { | |
i runtime.Type | |
ct commonType | |
} | |
return (*runtime.Type)(unsafe.Pointer(uintptr(unsafe.Pointer(t)) - unsafe.Offsetof(rt.ct))) | |
} | |
func dirPointer(c interface{}) *uintptr { | |
v := reflect.ValueOf(c) | |
t := v.Type() | |
f := (*commonType)(unsafe.Pointer(reflect.ValueOf(t).Pointer())) | |
type chanType struct { | |
_ commonType `reflect:"chan"` | |
elem *runtime.Type | |
dir uintptr | |
} | |
r := (*chanType)(unsafe.Pointer(reflect.ValueOf(*f.runtimeType()).Pointer())) | |
return &r.dir | |
} | |
func main() { | |
var a <-chan int | |
a = make(chan int) | |
d := dirPointer(a) | |
fmt.Printf("chanType.dir: %v\n", reflect.ChanDir(*d)) | |
*d = uintptr(reflect.BothDir) // throws unexpected fault address | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment