2016-05-21 140 views
12

晚上好,隨機讀取內存位置與Golang

我一直在試圖建立其掃描內存值的golang應用程序,但我在努力試圖瞭解如何解決具體的存儲位置。我知道在訪問應用程序中的內存時,您可以使用*variablename來尊重和獲取地址位置,但是如何提供地址位置並將值輸出到屏幕或從RAM中獲取任意大小的下一個分配的對象並將其打印出來值?

預先感謝任何幫助,您可能會願意分享

+0

你想讀*你的進程*內存,我希望,而不是* system *內存,對不對?因爲操作系統通常不允許進程在其內存空間之外進行讀取。 – AkiRoss

+0

此外,答案的質量可能取決於操作系統。您的問題是否與任何操作系統有關,您希望在限制範圍內運行,還是可以考慮依賴於操作系統的解決方案? – AkiRoss

+0

@AkiRoss - 這是一個閱讀另一個進程內存的macintosh應用程序。雖然 – kkirsche

回答

6

我不知道有多少有用的,這將是,但這裏是一個示例代碼。

package main 

import (
    "fmt" 
    "unsafe" 
) 

func main() { 
    var i int = 1 
    fmt.Println("Address : ", &i, " Value : ", i) 

    var address *int 
    address = &i // getting the starting address 

    loc := (uintptr)(unsafe.Pointer(address)) 
    p := unsafe.Pointer(loc) 

    // verification - it should print 1 
    var val int = *((* int)(p)) 
    fmt.Println("Location : ", loc, " Val :",val) // it does print !! 

    // lets print 1000 bytes starting from address of variable i 
    // first memory location contains 1 as expected 
    printValueAtMemoryLocation(loc, 1000) 

    // now lets test for some arbitrary memory location 
    // not so random ! wanted to reduce the diff value also any arbitrary memory location you can't read !! 
    memoryToReach := 842350500000 
    loc = changeToInputLocation(loc, memoryToReach) 
    fmt.Println("Loc is now at : ", loc) 
    // lets print 1000 bytes starting from the memory location "memoryToReach" 
    printValueAtMemoryLocation(loc, 1000) 

} 

func changeToInputLocation(location uintptr, locationToreach int) uintptr { 
    var diff,i int 
    diff = locationToreach - int(location) 

    fmt.Println("We need to travel ", diff, " memory locations !") 

    if diff < 0 { 
     i= diff * -1 
     for i > 0 { 
      location-- 
      i-- 
     } 
    } else { 
     i= diff 
     for i > 0 { 
      location++ 
      i-- 
     } 
    } 
    return location 
} 

func printValueAtMemoryLocation(location uintptr, next int) { 
    var v byte 
    p := unsafe.Pointer(location) 
    fmt.Println("\n") 
    for i:=1; i<next; i++ { 
     p = unsafe.Pointer(location) 
     v = *((*byte)(p)) 
     fmt.Print(v," ") 
     //fmt.Println("Loc : ", loc, " --- Val : ", v) 
     location++ 
    } 
    fmt.Println("\n") 
} 

使用「不安全」軟件包不是一個好主意,也不能讀取任何我相信的任意位置。

對我來說,當我試圖在那裏,最有可能,我沒有讀過訪問其他一些隨機的位置,它把我的錯誤是這樣的:

unexpected fault address 0xc41ff8f780 
fatal error: fault 
[signal SIGBUS: bus error code=0x2 addr=0xc41ff8f780 pc=0x1093ec0] 

但我們希望,也可以是一定的參考價值的您。

+0

很好的答案,如果有幫助!謝謝! – kkirsche

+0

我很高興它幫助:) –