go buildflag之-trimpath

What:

$ go help build
...
    -trimpath
        remove all file system paths from the resulting executable.
        Instead of absolute file system paths, the recorded file names
        will begin either a module path@version (when using modules),
        or a plain import path (when using the standard library, or GOPATH).

也就是说,在编译产物中将不会使用文件的绝对路径,而是使用module、go或者GOPATH。

Why:

添加-trimpath的收益:

  • 减少二进制的size(实测影响微乎其微)
  • 去除编译系统环境信息(目录)的变化对标识符的判断的影响
  • 减少程序日志的size和日志系统的存储占用

影响:

  • 影响debug,展示没有找到方法解决,大家有的话还请不吝赐教!
    $ dlv1.22.1 exec ./testtrimpath
    Type 'help' for list of commands.
    (dlv) b main.main
    Breakpoint 1 set at 0x494e8e for main.main() jidudev.com/tech/infra/log-service/cmd/test.go:8
    (dlv) c
    0x494e8e)
    Warning: debugging optimized function
    

How:

$ go build -trimpath -o xxx .

Validation:

验证方法有很多种,这里选择的是查看二进制的符号所在的文件信息,来判断是否消除了前缀。
其他方法可以尝试:

  • 运行中获取堆栈信息,来check堆栈中代码对应的文件位置
  • 如果有些log库已经实现了打印文件路径,可以直接打印日志查看
  • 制造panic场景,通过堆栈中的文件路径信息进行验证

测试用代码(test.go):

package main

import (
    "math"
    "github.com/google/uuid"
)

func main() {
  println(math.Max(1, 2))
  println(uuid.New().String())
}

直接编译:

为了防止编译器内联影响大家理解,这里统一禁用了内联:

$ go build -gcflags="-l" -o test test.go

$ go tool objdump -s '^math.Max' test | head -2
TEXT math.Max(SB) /root/go/go1.22.1/src/math/dim.go
  dim.go:40     0x46a440        493b6610        CMPQ SP, 0x10(R14)

$ go tool objdump -s '^github.com/google/uuid.New$' test | head -2
TEXT github.com/google/uuid.New(SB) /root/project/go/pkg/mod/github.com/google/uuid@v1.3.1/version4.go
  version4.go:13    0x494a80        493b6610        CMPQ SP, 0x10(R14)

应用-trimpath flag进行编译:

$ go build -gcflags="-l" -trimpath -o testtrimpath test.go 

$ go tool objdump -s '^math.Max' testtrimpath | head -2
TEXT math.Max(SB) math/dim.go
  dim.go:40     0x46a440        493b6610        CMPQ SP, 0x10(R14)

$ go tool objdump -s '^github.com/google/uuid.New$' testtrimpath | head -2
TEXT github.com/google/uuid.New(SB) github.com/google/uuid@v1.3.1/version4.go
  version4.go:13    0x494a80        493b6610        CMPQ SP, 0x10(R14)

相比于直接编译的产物中,标准库的符号,去掉了绝对路径前缀:/root/go/go1.22.1/src/
对于第三发module依赖,其符号删减了module缓存文件路径前缀:/root/project/go/pkg/mod/

编译产物size:

-rwxr-xr-x 1 root root 2191633 Aug  3 10:57 test
-rwxr-xr-x 1 root root 2186769 Aug  3 10:58 testtrimpath

共减少:4864字节(可以忽略不计)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容