go:linkname

Go语言中,可以使用//go:linkname,链接出runtime代码中非导出的函数供用户使用,internal包中的方法,也可以如此操作。

//go:linkname localname [importpath.name]

This special directive does not apply to the Go code that follows it. Instead, the //go:linkname directive instructs the compiler to use “importpath.name” as the object file symbol name for the variable or function declared as “localname” in the source code. If the “importpath.name” argument is omitted, the directive uses the symbol’s default object file symbol name and only has the effect of making the symbol accessible to other packages. Because this directive can subvert the type system and package modularity, it is only enabled in files that have imported “unsafe”.

该特殊指令不适用于遵循它的GO代码。相反,//go:linkname 指令指示编译器将“ importpath.name”用作变量或函数的对象文件符号名称,称为源代码中的“ localName”。
如果省略了“ importpath.name”参数,则该指令使用该符号的默认对象文件符号名称,并且只能使其他软件包可以访问该符号。
由于该指令可以颠覆类型系统和软件包模块化,因此仅在导入“不安全”的文件中启用它。

简单测试一下,使用go:linkname 时应注意需导入unsafe包,不用的话可将其用_忽略掉。

package main

import "fmt"
import _ "unsafe"

//go:linkname FastRand runtime.fastrand
func FastRand() uint32

func main() {
	fmt.Println(FastRand())
}

如此一来,我们是不是就可以把分配内存与释放内存的函数链接出来一起玩耍了?是不是就可以手动管理Go内存了?

封幼麟老师测试channel不关闭,且不被使用后是否会被自动GC的demo
答案是会被回收

package main

import (
	"runtime"
	"unsafe"
)

type markBits struct {
	bytep *uint8
	mask  uint8
	index uintptr
}

//go:linkname isMarked runtime.markBits.isMarked
func isMarked(m markBits) bool

//go:linkname spanOf runtime.spanOf
func spanOf(p uintptr) unsafe.Pointer

//go:linkname objIndex runtime.(*mspan).objIndex
func objIndex(s unsafe.Pointer, p uintptr) uintptr

//go:linkname allocBitsForIndex runtime.(*mspan).allocBitsForIndex
func allocBitsForIndex(s unsafe.Pointer, allocBitIndex uintptr) markBits

func allocBitsForAddr(p uintptr) markBits {
	s := spanOf(p)
	objIndex := objIndex(s, p)
	return allocBitsForIndex(s, objIndex)
}

var ca [10]chan int
var pa [10]uintptr

func main() {
	for i := 0; i < len(pa); i++ {
		c := make(chan int, 10)
		p := *(*uintptr)(unsafe.Pointer(&c))
		c <- 1
		c <- 2
		c <- 3
		ca[i] = c
		pa[i] = p
	}

	for i := 0; i < len(pa); i++ {
		if i%2 == 0 {
			continue
		}
		ca[i] = nil
	}

	runtime.GC()

	for i := 0; i < len(pa); i++ {
		println(isMarked(allocBitsForAddr(pa[i])))
	}
}

Reference
https://pkg.go.dev/cmd/compile

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

metabit

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值