如何在Go程序中使用fmt.Println()打印未由该程序分配的内存?

huangapple go评论117阅读模式
英文:

How to fmt.Println() memory not allocated by the go program?

问题

我想打印当前程序从0x100000x50000的虚拟内存内容(在我的系统上包含一个系统调用跳板的区域)。

package main

import (
    "syscall"
    "unsafe"
)

func main() {
    syscall.Syscall(SYS_WRITE, uintptr(1), uintptr(unsafe.Pointer(0x10000)), uintptr(0x40000))
}

然而,当我尝试编译时,我得到了以下错误:

cannot convert 65536 (type int) to type unsafe.Pointer

在我的情况下,cgo 被禁用了(import "C" 在编译时失败)。
另外,syscall.Syscall(SYS_WRITE 是唯一的方法吗?

英文:

I’d like to print the virtual memory content of the current program from 0x10000 to 0x50000 (an area containing a syscall trampoline on my system).

package main

import (
	"syscall"
	"unsafe"
)
func main() {
	syscall.Syscall(SYS_WRITE, uintptr(1), uintptr(unsafe.Pointer(0x10000)), uintptr(0x40000))
}

However when I tried to compile I’m getting that error :

cannot convert 65536 (type int) to type unsafe.Pointer

In my case,cgo is disabled (import "C" fails at compile time).
Also does syscall.Syscall(SYS_WRITE is the only way to do it ?

答案1

得分: 2

你可以将该地址转换为字节切片,然后将其传递给任何Write方法。

要将地址0x10000转换为长度为0x30000的字节切片,你可以使用以下代码:

mem := (*[1 << 30]byte)(unsafe.Pointer(uintptr(0x10000)))[:0x30000:0x30000]

如果大小始终是静态的,你可以直接将数组设置为正确的大小:

mem := (*[0x30000]byte)(unsafe.Pointer(uintptr(0x10000)))[:]

请注意,这是Go语言的代码示例。

英文:

You can convert that address to a slice of bytes, which can then be passed to any Write method.

To convert the address 0x10000 to a slice of bytes with a length of 0x30000, you would use

mem := (*[1 &lt;&lt; 30]byte)(unsafe.Pointer(uintptr(0x10000)))[:0x30000:0x30000]

If the size is always static, you could just set the array to the proper size to start

mem := (*[0x30000]byte)(unsafe.Pointer(uintptr(0x10000)))[:]

答案2

得分: 1

你面临的直接问题是,你应该将0x10000直接转换为uintptr,而不是通过unsafe.Pointer进行转换。我不知道修复这个问题是否会解决你的其他问题。

英文:

The immediate problem you are facing is that you should convert 0x10000 directly to uintptr instead of through unsafe.Pointer. I don't know if fixing that will solve the rest of your problem or not.

huangapple
  • 本文由 发表于 2017年2月14日 01:09:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/42209650.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定