golang源码调试

使用bitnami/golang搭建go环境

从源码安装go

我们要对源码重新编译后调试,使用go编译器二进制文件,我们调试的go版本是1.24。根据官方文档所述

Go 1.N 版本将需要一个 Go 1.M 编译器, 其中 M 为 N-2,向下舍入为偶数。示例:Go 1.24 和 1.25 需要 Go 1.22。

我们的编译器的版本只要大于等于最低版本要求就可以进行编译,我下载的bootstrap工具链的版本为 go1.23.0.linux-amd64.tar.gz

bitnami/golang 的源码文件在 /opt/bitnami/go 文件夹中,我们要对其进行多次的调试和修改,我们将目录挂载到本地,如果挂载后没有显示对应的文件, 需要取消挂载,将文件夹内容复制出来后重新进行挂载

yaml 复制代码
services:
  golang:
    image: bitnami/golang:1.24
    container_name: golang
    hostname: golang
    tty: true
    command: ["sleep", "infinity"]
    environment:
      GOROOT_BOOTSTRAP: /root/go    # 设置二进制包环境变量信息 
    volumes:
      - "../cmd:/go/src/cmd"        # 后续调试时使用的文件目录挂载 
      - "./data/go:/opt/bitnami/go" # 容器自己go源码位置
      - "./data/bootstrap:/root/go" # 下载后的1.23版本的工具链

修改源码后进行编译

我们对fmt.Println进行修改, 文件位置位于 src/fmt/print.go, 修改如下:

go 复制代码
// Println formats using the default formats for its operands and writes to standard output.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func Println(a ...any) (n int, err error) {
    println("添加调试输出debug")

    return Fprintln(os.Stdout, a...)
}

修改后,我们重新编译源码后运行查看一下结果

shell 复制代码
$ cd /opt/bitnami/go/src

$ ./make.bash
Building Go cmd/dist using /root/go. (go1.23.0 linux/amd64)
Building Go toolchain1 using /root/go.
Building Go bootstrap cmd/go (go_bootstrap) using Go toolchain1.
Building Go toolchain2 using go_bootstrap and Go toolchain1.
Building Go toolchain3 using go_bootstrap and Go toolchain2.
Building packages and commands for linux/amd64.
---
Installed Go for linux/amd64 in /opt/bitnami/go
Installed commands in /opt/bitnami/go/bin

$ cat /go/src/cmd/array/array.go
package main

import "fmt"

func main() {
        fmt.Println("hello world")
}

# 运行查看输出信息
$ go run /go/src/cmd/array/array.go
添加调试输出debug
hello world

将go语言的源代码编译成汇编语言,通过汇编语言分析程序具体执行过程。

shell 复制代码
$ cd /go/src/cmd/array

$ go build -gcflags -S array.go

# 获取汇编指令的优化过程及 Go 语言更详细的编译过程
$ GOSSAFUNC=main go build array.go
# runtime
dumped SSA for main,1 to /go/src/cmd/array/ssa.html
# command-line-arguments
dumped SSA for main,1 to ./ssa.html

在当前文件夹下点击ssa.html后可以查看汇编代码优化的每一个步骤,可以在页面上进行交互查看每个步骤,方便分析编译优化的过程。

参考文档:draven.co/golang/docs...

相关推荐
影灵衣丶18 小时前
Go 1.25 实战解读:绿茶 GC 与容器核心数感知(工程影响与落地)
后端·go
一直_在路上18 小时前
突发高流量应对之道:Go语言限流、熔断、降级三板斧
面试·go
程序员爱钓鱼19 小时前
Go语言100个实战案例-项目实战篇:股票行情数据爬虫
后端·go·trae
程序员爱钓鱼2 天前
Go语言实战案例 — 项目实战篇:简易博客系统(支持评论)
前端·后端·go
郭京京3 天前
go框架gin(中)
后端·go
郭京京3 天前
go框架gin(下)
后端·go
一直_在路上3 天前
Go 语言微服务演进路径:从小型项目到企业级架构
架构·go
程序员爱钓鱼3 天前
Go语言实战案例 — 项目实战篇:任务待办清单 Web 应用
后端·google·go
lypzcgf4 天前
Coze源码分析-资源库-创建知识库-后端源码-应用/领域/数据访问
后端·go·coze·coze源码分析·智能体平台·ai应用平台·agent平台
lypzcgf4 天前
Coze源码分析-资源库-创建知识库-基础设施/存储/安全
安全·go·coze·coze源码分析·智能体平台·ai应用平台·agent开发平台