猿问

使用 Golang 读取随机内存位置

晚上好,

我一直在尝试构建一个 golang 应用程序来扫描内存中的值,但我正在努力理解如何解决特定的内存位置。我知道在访问应用程序中的内存时,您可以使用*variablename来尊重并获取地址位置,但是我将如何提供地址位置并将值打印到屏幕或从 RAM 中获取下一个分配的任意大小的对象并打印它的值?

提前感谢您可能愿意分享的任何帮助


至尊宝的传说
浏览 176回答 1
1回答

翻过高山走不出你

我不知道这会有多大用处,但这里有一个示例代码。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "unsafe")func main() {&nbsp; &nbsp; var i int = 1&nbsp; &nbsp; fmt.Println("Address : ", &i, " Value : ", i)&nbsp; &nbsp; var address *int&nbsp; &nbsp; address = &i // getting the starting address&nbsp; &nbsp; loc := (uintptr)(unsafe.Pointer(address))&nbsp; &nbsp; p := unsafe.Pointer(loc)&nbsp; &nbsp; // verification - it should print 1&nbsp; &nbsp; var val int = *((* int)(p))&nbsp; &nbsp; fmt.Println("Location : ", loc, " Val :",val) // it does print !!&nbsp; &nbsp; // lets print 1000 bytes starting from address of variable i&nbsp; &nbsp; // first memory location contains 1 as expected&nbsp; &nbsp; printValueAtMemoryLocation(loc, 1000)&nbsp; &nbsp; // now lets test for some arbitrary memory location&nbsp; &nbsp; // not so random ! wanted to reduce the diff value also any arbitrary memory location you can't read !!&nbsp; &nbsp; memoryToReach := 842350500000&nbsp; &nbsp; loc = changeToInputLocation(loc, memoryToReach)&nbsp; &nbsp; fmt.Println("Loc is now at : ", loc)&nbsp; &nbsp; // lets print 1000 bytes starting from the memory location "memoryToReach"&nbsp; &nbsp; printValueAtMemoryLocation(loc, 1000)}func changeToInputLocation(location uintptr, locationToreach int) uintptr {&nbsp; &nbsp; var diff,i int&nbsp; &nbsp; diff = locationToreach - int(location)&nbsp; &nbsp; fmt.Println("We need to travel ", diff, " memory locations !")&nbsp; &nbsp; if diff < 0 {&nbsp; &nbsp; &nbsp; &nbsp; i= diff * -1&nbsp; &nbsp; &nbsp; &nbsp; for i > 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; location--&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i--&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; i= diff&nbsp; &nbsp; &nbsp; &nbsp; for i > 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; location++&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i--&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return location}func printValueAtMemoryLocation(location uintptr, next int) {&nbsp; &nbsp; var v byte&nbsp; &nbsp; p := unsafe.Pointer(location)&nbsp; &nbsp; fmt.Println("\n")&nbsp; &nbsp; for i:=1; i<next; i++ {&nbsp; &nbsp; &nbsp; &nbsp; p = unsafe.Pointer(location)&nbsp; &nbsp; &nbsp; &nbsp; v = *((*byte)(p))&nbsp; &nbsp; &nbsp; &nbsp; fmt.Print(v," ")&nbsp; &nbsp; &nbsp; &nbsp; //fmt.Println("Loc : ", loc, " --- Val : ", v)&nbsp; &nbsp; &nbsp; &nbsp; location++&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("\n")}使用“不安全”包不是一个好主意,我相信你也不能阅读任何任意位置。对我来说,当我尝试其他一些随机位置时,很可能我没有读取权限,它给我带来了如下错误:unexpected fault address 0xc41ff8f780fatal error: fault[signal SIGBUS: bus error code=0x2 addr=0xc41ff8f780 pc=0x1093ec0]但希望它对你有一些价值。
随时随地看视频慕课网APP

相关分类

Go
我要回答