go:linkname

简介: go:linkname

初入门径


查看一些官方库的源码时,经常发现找不到其具体的实现,以常用的time.Sleep()为例:

// Sleep至少在持续时间d内暂停当前goroutine,
// 持续时间为负数或零会导致Sleep立即返回
// Sleep pauses the current goroutine for at least the duration d.
// A negative or zero duration causes Sleep to return immediately.
func Sleep(d Duration)

但该方法的实现在哪里? 寻遍time包,也不见Sleep的实现.

其实其实现在 runtime/time.go:

// timeSleep puts the current goroutine to sleep for at least ns nanoseconds.
// timeSleep使当前的goroutine睡眠至少ns纳秒。
//go:linkname timeSleep time.Sleep
func timeSleep(ns int64) {
  if ns <= 0 {
    return
  }
  gp := getg()
  t := gp.timer
  if t == nil {
    t = new(timer)
    gp.timer = t
  }
  t.f = goroutineReady
  t.arg = gp
  t.nextwhen = nanotime() + ns
  gopark(resetForSleep, unsafe.Pointer(t), waitReasonSleep, traceEvGoSleep, 1)
}

go:linkname是源码中最常用的Go指令,其官方定义如下:

//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".

这个指令告诉编译器 为当前源文件中的私有函数或者变量在编译时链接到指定的方法或变量。

因为这个指令破坏了类型系统和包的模块化,因此在使用时必须导入unsafe包.

可以看到runtime/time.go文件是有导入unsafe包的

微信截图_20230627112031.png

对于//go:linkname localname [importpath.name], 这里localname对应timeSleep, importpath.name 对应time.Sleep

但为什么要这么做?

这是因为timeSleep在runtime包里,是不可导出的. 使用go:linkname的目的,就是让time包,可以调用runtime包中原本不可导出的方法




Demo实验


新建demo文件夹,结构如下:

➜  tree
.
├── linkname
│   └── a.go
├── main.go
└── outer
    └── world.go
2 directories, 3 files

a.go:

package linkname
import _ "unsafe"
//go:linkname hello demo/outer.World
func hello() {
  println("hello,world!")
}

world.go:

package outer
import _"demo/linkname"
func World()

main.go:

package main
import "demo/outer"
func main() {
  outer.World()
}

执行 go run main.go,会出现报错:

main.go:3:8: package note/demo/outer is not in GOROOT (/usr/local/opt/go@1.14/libexec/src/note/demo/outer)

参考报错package xxx is not in GOROOT, 将demo文件夹放到GOPATH下:

➜  src echo $GOPATH
/Users/dashen/go
// 将demo文件夹移动到GOPATH下
➜  pwd
/Users/dashen/go/src/demo

执行 go run main.go:

报错如下:

# demo/outer
outer/world.go:5:6: missing function body

这是因为go build默认加会加上-complete参数,这个参数检查到**World()**没有方法,从而抛出如上错误

可以在outer文件夹中增加一个空的.s文件即可绕过这个限制(也可以选择用单独的compile命令进行编译):

➜  demo tree
.
├── linkname
│   └── a.go
├── main.go
└── outer
    ├── i.s
    └── world.go
2 directories, 4 files

执行 go run main.go:

hello,world!




总结&注意事项

微信截图_20230627112417.png

linkname注解非常广泛地应用于Go的源码中, 其指令的格式如下:

//go:linkname hello(具体的实现) demo/outer.World(导出用到哪个地方)

  • //后面不能有空格
  • //go:linkname xxx xxxxx 必须在具体实现的正上方,之间不能有空行

go:linkname引导编译器将当前(私有)方法或者变量在编译时链接到指定的位置的方法或者变量,第一个参数表示当前方法或变量,第二个参数表示目标方法或变量,因为这关指令会破坏系统和包的模块化,因此在使用时必须导入unsafe

该指令不经常用(最好在业务开发中也不要用),但了解这个指令可以帮助理解核心包的很多代码. 在标准库中,为了可以使用另一个包的unexported的方法或者变量,正常情况这些unexported资源是不可包外访问的,但是运行时用这个命令hack一下,就变得可以访问

目录
相关文章
|
存储 Ubuntu 网络协议
轻松搭建Nextcloud私有云盘并实现远程访问【内网穿透】
轻松搭建Nextcloud私有云盘并实现远程访问【内网穿透】
1727 0
|
11月前
|
存储 人工智能 安全
一文详解Kimi的AI Agent如何跑在阿里云上
Kimi携手阿里云,基于ACK与ACS Agent Sandbox构建端到端Agent基础设施:实现秒级沙箱启动、万级并发弹性调度、会话级状态保持及强安全隔离,支撑“深度研究”“OK Computer”等智能体产品稳定高效运行。(239字)
2015 1
一文详解Kimi的AI Agent如何跑在阿里云上
|
人工智能 关系型数据库 MySQL
开源PolarDB-X:单节点误删除binlog恢复
本文由邵亚鹏撰写,分享了在使用开源PolarDB-X过程中,因误删binlog导致数据库服务无法启动的问题及恢复过程。作者结合实践经验,详细介绍了在无备份情况下如何通过单节点恢复机制重启数据库,并提出了避免类似问题的几点建议,包括采用高可用部署、定期备份及升级至最新版本等。
基于android的个人健康管理系统
本系统基于Android Studio与Java开发,采用SpringBoot框架,构建智能化个人健康管理平台。实现健康数据集中管理、实时监测与个性化干预,提升健康管理效率,推动医疗数字化转型。
|
安全 数据安全/隐私保护 Docker
docker私有仓库harbor安装
通过以上步骤,您可以成功在企业内部安装和配置Harbor私有仓库,方便地管理和分发Docker镜像。Harbor不仅提供了基础的镜像管理功能,还增强了安全性、身份管理和审计功能,使其成为企业级容器镜像管理的理想选择。
1087 22
|
JavaScript 前端开发
JS如何配合input框实现模糊搜索
JS如何配合input框实现模糊搜索
729 2
|
消息中间件 Serverless 数据安全/隐私保护
开发者如何使用云消息队列 RabbitMQ 版
【10月更文挑战第13天】开发者如何使用云消息队列 RabbitMQ 版
910 121
|
Python
Matplotlib 安装
Matplotlib 安装
559 3
|
SQL 监控 算法
为Go应用无侵入地添加任意代码
这篇文章旨在提供技术深度和实践指南,帮助开发者理解并应用这项创新技术来提高Golang应用的监控与服务治理能力。在接下来的部分,我们将通过一些实际案例,进一步展示如何在不同场景中应用这项技术,提供更多实践启示。
|
JSON 关系型数据库 API
Python 使用 FastAPI 和 PostgreSQL 构建简单 API
最近一年公司也在卷 LLM 的应用项目,所以我们也从 goper => Pythoner。 这一年使用最多的就是 Python 的 FastAPI 框架。下面一个简易项目让你快速玩转 Python API Web。 API代表应用程序编程接口,是软件开发中最重要的概念之一。它允许程序通过发送和接收数据与其他服务进行交互。API Web 通信最广泛使用的标准之一是 REST,它依赖于JSON 格式或键值对,类似于 Python 的字典。 如果想用 Python 构建一个,那么可以从几个框架中选择。Flask -RESTful、Django Rest Framework 和 FastAPI 是最受