Golang源码分析 | 程序引导过程

环境说明

CentOS Linux release 7.2 (Final)
go version go1.16.3 linux/amd64
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-80.el7

使用gdb查看程序入口

编写一个简单的go程序

// main.go
package mainfunc main() {print("Hello world")
}
编译go build -gcflags "-N -l" -o simple main.go
使用gdb查看entry
gdb simple
(gdb) info files
Symbols from "/data/project/windeal/golang/simple/simple".
Local exec file:`/data/project/windeal/golang/simple/simple', file type elf64-x86-64.Entry point: 0x45cd800x0000000000401000 - 0x000000000045ecb6 is .text0x000000000045f000 - 0x000000000048bdb5 is .rodata0x000000000048bf40 - 0x000000000048c3e0 is .typelink0x000000000048c3e0 - 0x000000000048c3e8 is .itablink0x000000000048c3e8 - 0x000000000048c3e8 is .gosymtab0x000000000048c400 - 0x00000000004c7b68 is .gopclntab0x00000000004c8000 - 0x00000000004c8020 is .go.buildinfo0x00000000004c8020 - 0x00000000004c9240 is .noptrdata0x00000000004c9240 - 0x00000000004cb3f0 is .data0x00000000004cb400 - 0x00000000004f86b0 is .bss0x00000000004f86c0 - 0x00000000004fd990 is .noptrbss0x0000000000400f9c - 0x0000000000401000 is .note.go.buildid
(gdb) 

可以看到程序的Entry point为 0x45cd80, 对应分段的地址范围,可以算出来程序0x45cd80在.text段。
添加断点,可以看到 Entry point: 0x45cd80 对应的内容

(gdb) b *0x45cd80
Breakpoint 1 at 0x45cd80: file /data/opt/go/src/runtime/rt0_linux_amd64.s, line 8.
(gdb) 

可以得出这个go程序的入口在 file /data/opt/go/src/runtime/rt0_linux_amd64.s, line 8.

在gdb中通过

  • b-设置断点,
  • run-启动程序,
  • n-逐步执行

可以看到程序的引导过程

rt0_linux_amd64.s 
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.#include "textflag.h"TEXT _rt0_amd64_linux(SB),NOSPLIT,$-8JMP	_rt0_amd64(SB)TEXT _rt0_amd64_linux_lib(SB),NOSPLIT,$0JMP	_rt0_amd64_lib(SB)

可以看到这部分没有太多内容,程序直接跳转执行到全局符号 _rt0_amd64(SB)

_rt0_amd64:_rt0_amd64

// _rt0_amd64 is common startup code for most amd64 systems when using
// internal linking. This is the entry point for the program from the
// kernel for an ordinary -buildmode=exe program. The stack holds the
// number of arguments and the C-style argv.
TEXT _rt0_amd64(SB),NOSPLIT,$-8MOVQ	0(SP), DI	// argcLEAQ	8(SP), SI	// argvJMP	runtime·rt0_go(SB)

这段代码把参数个数argc复制到DI寄存器。把参数值地址argv拷贝到SI寄存器。
关联知识:
我们分析的是amd64的源码,汇编指令按64bit寻址,每次操作8个字节的数据。 这里使用的汇编指令都带一个Q表示操作的是8个字节,如果是32bit则指定为MOVL、LEAL等,表示操作4个字节)
这里有个问题,就是为什么起始时0(SP)和8(SP)是argc和argv。 这里看了一些文章结合自己的理解,应该是操作系统的约定(需要进一步确认,留个坑后续补充)

_rt0_amd64:rt0_go

rt0_go 内容比较多,比较复杂, 逐段分析。

命令行参数拷贝

// asm_amd64.s// Defined as ABIInternal since it does not use the stack-based Go ABI (and
// in addition there are no calls to this entry point from Go code).
TEXT runtime·rt0_go<ABIInternal>(SB),NOSPLIT,$0// copy arguments forward on an even stackMOVQ	DI, AX		// argc,MOVQ	SI, BX		// argvSUBQ	$(4*8+7), SP		// 2args 2autoANDQ	$~15, SP	// 最后16位清0,实现16字节对齐MOVQ	AX, 16(SP)MOVQ	BX, 24(SP)// ......  

这一段代码是做命令行参数的拷贝和栈顶指针SP偏移的。

前面两行是把argc、argv拷贝到寄存器AX、BX。
然后SP指针向下移动4*8+7个字节,预留空间用来存放命令行参数

栈空间的寻址是自高地址向低地址

我们看下这个4*8+7的值是怎么来的。实际上是2*8+2*8+7
引导程序先把argc和argv下移,即第一个2*8。即最终的SP+16和SP+4,
第二个2*8字节,在这里并未填充值,它是用来后面给G0传递参数的,让G0启动向一个普通的调用一样。
SP+0和SP+8 可以在rt0_go的后面部分看到赋值

TEXT runtime·rt0_go<ABIInternal>(SB),NOSPLIT,$0......
ok:......MOVL	16(SP), AX		// copy argcMOVL	AX, 0(SP)MOVQ	24(SP), AX		// copy argvMOVQ	AX, 8(SP)......

多偏移的7字节是哪里来的,还没有搞懂。看到很多材料写的是为了后面的16字节对齐,但是如果仅仅只是为了16字节对齐,后面的ANDQ $~15, SP看起来就已经足够了。 先留个坑,后面搞懂了回来补充。

关于16字节对齐
关联知识:CPU有一组SSE指令,这些指令中出现的内存地址必须是16的倍数。
在 SUBQ $(4*8+7), SP之前,因为64bit机器的寻址是8字节为单元, SP对应的内存地址有2中可能:

  • 0x*****0: 最后一位是0,本身是16字节对齐
  • 0x*****8: 最后一位是8,不是16字节对齐。

如果是0x*****0这种情况,那么4*8本身就是16字节对齐的,不需要额外操作。单是如果是0x*****8这种情况的话,就需要做16字节对齐。

G0执行栈初步初始化

继续往下分析

TEXT runtime·rt0_go<ABIInternal>(SB),NOSPLIT,$0......// create istack out of the given (operating system) stack.// _cgo_init may update stackguard.MOVQ	$runtime·g0(SB), DI			// DI = g0LEAQ	(-64*1024+104)(SP), BX	   MOVQ	BX, g_stackguard0(DI)		// g0.stackguard0 = SP + (-64*1024+104)MOVQ	BX, g_stackguard1(DI)		// g0.stackguard1 = SP + (-64*1024+104)MOVQ	BX, (g_stack+stack_lo)(DI) // g0.stack.stack_lo = SP + (-64*1024+104)MOVQ	SP, (g_stack+stack_hi)(DI) // g0.stack.stack_hi = SP + (-64*1024+104)// find out information about the processor we're on,确定CPU处理器信息MOVL	$0, AXCPUIDMOVL	AX, SICMPL	AX, $0JE	nocpuinfo

这一部分是初始化g0的执行栈。
参考结构体g的定义:https://github.com/golang/go/blob/9baddd3f21230c55f0ad2a10f5f20579dcf0a0bb/src/runtime/runtime2.go#L404

TLS 线程本地存储

代码链接

	LEAQ	runtime·m0+m_tls(SB), DI	// DI = m0.tls, CALL	runtime·settls(SB)				 // 设置TLS, 还没完全看懂,待进一步分析// store through it, to make sure it worksget_tls(BX)MOVQ	$0x123, g(BX)MOVQ	runtime·m0+m_tls(SB), AXCMPQ	AX, $0x123				// 判断 TLS 是否设置成功JEQ 2(PC)							// 如果相等则向后跳转两条指令CALL	runtime·abort(SB)	  // 使用 INT 指令执行中断
ok:

关联g0和m0

代码链接

	// set the per-goroutine and per-mach "registers"// g0和m0是全局变量,先获取他们的地址分别存在寄存器CX和AXget_tls(BX)LEAQ	runtime·g0(SB), CXMOVQ	CX, g(BX)LEAQ	runtime·m0(SB), AX// 关联g0和m0	// save m->g0 = g0MOVQ	CX, m_g0(AX)// save m0 to g0->mMOVQ	AX, g_m(CX)

运行时检查

	CLD				// convention is D is always left clearedCALL	runtime·check(SB)

runtime·check(SB)的代码链接, check会进行各种检查,如果检查未通过,直接抛出异常,一般是编译过程发生了错误。
系统级的初始化
代码链接

	MOVL	16(SP), AX		// copy argcMOVL	AX, 0(SP)MOVQ	24(SP), AX		// copy argvMOVQ	AX, 8(SP)CALL	runtime·args(SB)	// 参数的初始化CALL	runtime·osinit(SB)	// CALL	runtime·schedinit(SB)

前面四行是做argc和argv的再一次拷贝。(这里没搞懂为什么需要做多次的参数拷贝,看到一些解释是为了让g0模拟普通goroutine调用)

后面三行是3个函数调用

runtime.args

func args() 代码链接

func args(c int32, v **byte) {argc = cargv = vsysargs(c, v)	
}

把参数存放在全局变量argc和argv中,供其他初始化函数使用。
func sysargs()的代码链接
sysargs()用于将一些内核级别的信息存放到执行栈中(是放在主调的栈中)
对这方面感兴趣的可以搜索golang linux 函数调用栈相关的内容

runtime·osinit

代码链接 osinit()

func osinit() {ncpu = getproccount()								// 获取CPU核心数physHugePageSize = getHugePageSize()	  // 获取内存物理页代销......osArchInit()	//  目前看是个空函数
}

运行时组件初始化

runtime·schedinit(SB) 开始是golang 运行时组件相关的初始化
代码链接

	CALL	runtime·schedinit(SB)

schedinit的代码链接

// The new G calls runtime·main.
func schedinit() {// 各种加锁......// raceinit must be the first call to race detector.// In particular, it must be done before mallocinit below calls racemapshadow._g_ := getg()if raceenabled {_g_.racectx, raceprocctx0 = raceinit()}sched.maxmcount = 10000// The world starts stopped.worldStopped()// 栈、内存分配器、调度器相关初始化moduledataverify()stackinit()			// 初始化执行栈mallocinit()		// 初始化内存分配器mallocfastrandinit() // must run before mcommoninitmcommoninit(_g_.m, -1)   // 初始化当前系统线程,只完成部分通用的初始化	cpuinit()       // must run before alginitalginit()       // maps must not be used before this callmodulesinit()   // provides activeModulestypelinksinit() // uses maps, activeModulesitabsinit()     // uses activeModulessigsave(&_g_.m.sigmask)initSigmask = _g_.m.sigmaskgoargs()goenvs()parsedebugvars()gcinit()// 创建 P, 通过 CPU 核心数和 GOMAXPROCS 环境变量确定 P 的数量lock(&sched.lock)sched.lastpoll = uint64(nanotime())procs := ncpuif n, ok := atoi32(gogetenv("GOMAXPROCS")); ok && n > 0 {procs = n}if procresize(procs) != nil {throw("unknown runnable goroutine during bootstrap")}unlock(&sched.lock)// World is effectively started now, as P's can run.worldStarted()// For cgocheck > 1, we turn on the write barrier at all times// and check all pointer writes. We can't do this until after// procresize because the write barrier needs a P.if debug.cgocheck > 1 {writeBarrier.cgo = truewriteBarrier.enabled = truefor _, p := range allp {p.wbBuf.reset()}}if buildVersion == "" {// Condition should never trigger. This code just serves// to ensure runtime·buildVersion is kept in the resulting binary.buildVersion = "unknown"}if len(modinfo) == 1 {// Condition should never trigger. This code just serves// to ensure runtime·modinfo is kept in the resulting binary.modinfo = ""}
}

主goroutine启动

代码链接

	// create a new goroutine to start programMOVQ	$runtime·mainPC(SB), AX		// entry, 主 goroutine 入口地址runtime.mainPUSHQ	AXPUSHQ	$0			// arg sizeCALL	runtime·newproc(SB)		// 创建执行单元,创建gPOPQ	AXPOPQ	AX// start this MCALL	runtime·mstart(SB)			// 开始启动调度器的调度循环CALL	runtime·abort(SB)	// mstart should never returnRET// Prevent dead-code elimination of debugCallV1, which is// intended to be called by debuggers.MOVQ	$runtime·debugCallV1<ABIInternal>(SB), AX
RET

newproc(SB)的代码链接, newproc 会创建一个g

func newproc(siz int32, fn *funcval) {argp := add(unsafe.Pointer(&fn), sys.PtrSize)gp := getg()pc := getcallerpc()systemstack(func() {newg := newproc1(fn, argp, siz, gp, pc)_p_ := getg().m.p.ptr()runqput(_p_, newg, true)if mainStarted {wakep()}})
}

mstart()

runtime·mstart 相对比较复杂,后面新开一篇文章介绍。
主要调用链路是

mstart()==>mstart1()==>schedule()

主要功能是启动调度器,在shedule()中进行循环调度

我的公众号

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/170687.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

STM32——STM32F4系统架构

文章目录 前言STM32F4XX系统架构 前言 本篇文章为STM32F4系列的系统架构&#xff0c;因为最近在学习F4的板子&#xff0c;暂时先更F4的&#xff0c;有需要F1的后续再更新。 主系统由 32 位多层 AHB 总线矩阵构成&#xff0c;可实现以下部分的互连&#xff1a; STM32F4XX系统架…

docker通过nginx代理tomcat-域名重定向

通过昨天的调试&#xff0c;今天做这个域名就简单了&#xff0c; 正常我们访问网站一般都是通过域名比如&#xff0c;www.baidu.com对吧&#xff0c;有人也通过ip&#xff0c;那么这个怎么做呢&#xff1f;物理机windows可以通过域名访问虚拟机linux的nginx代理转向tomcat服务…

web基础和http协议(粗糙版)

服务部署&#xff0c;集训&#xff0c;分布式&#xff0c;数据库&#xff0c;日志系统&#xff0c;等二阶段 web基础和http协议&#xff1a; web的相关基础知识&#xff0c;包括域名 dns解析 网页的概念以及http协议 1.网络当中通信&#xff1a;端口 ip 协议 tcp/ip 传输过程…

postswigger 靶场(CSRF)攻略-- 1.没有防御措施的 CSRF 漏洞

靶场地址&#xff1a; What is CSRF (Cross-site request forgery)? Tutorial & Examples | Web Security Academy (portswigger.net)https://portswigger.net/web-security/csrf 没有防御措施的 CSRF 漏洞 题目中已告知易受攻击的是电子邮件的更改功能&#xff0c;而目…

MySQL中的索引

目录 一、概念 二、作用和特点 作用 特点 三、使用场景 四、使用 1、查看索引 2、创建索引 3、删除索引 五、索引底层数据结构的实现 B树&#xff08;B-树&#xff09; B树 特点 重复出现的好处 一、概念 索引 翻译成英文&#xff1a;index&#xff08;下标&#xf…

ChatGPT+Roblox,元宇宙的AI叙事逻辑#Leveling Up

MixCopilot 嗨&#xff0c;亲爱的听众朋友们&#xff01;欢迎收听我们的播客节目&#xff01;我是你们的主播&#xff1a;MixCopilot 混合副驾。今天我们要为大家带来的是我们的AI革命系列节目之一。这个系列节目聚焦于AI领域的一些最有影响力的建设者&#xff0c;他们将会讨论…

解决Chrome无法自动同步书签

前提&#xff1a;&#xff08;要求能正常访问google&#xff09; 准备一个谷歌账号 安装Chrome浏览器 开启集装箱插件&#xff08;或者其他能访问谷歌的工具&#xff09; 步骤&#xff1a;&#xff08;使用集装箱插件/能正常访问谷歌的其他工具&#xff09; 下载安装使用“集…

5个高质量的实用办公软件,每一款都是良心推荐

在现代办公环境中&#xff0c;高效的办公软件可以极大地提升工作效率&#xff0c;简化工作流程&#xff0c;帮助我们更好地完成工作。今天就给大家分享5个高质量的实用办公软件&#xff0c;每一款都是良心推荐。 01、FastStone Capture&#xff08;截图工具&#xff09; FastSt…

Python实现WOA智能鲸鱼优化算法优化BP神经网络回归模型(BP神经网络回归算法)项目实战

说明&#xff1a;这是一个机器学习实战项目&#xff08;附带数据代码文档视频讲解&#xff09;&#xff0c;如需数据代码文档视频讲解可以直接到文章最后获取。 1.项目背景 鲸鱼优化算法 (whale optimization algorithm,WOA)是 2016 年由澳大利亚格里菲斯大学的Mirjalili 等提…

【Python大数据笔记_day04_Hadoop】

分布式和集群 分布式:多台服务器协同配合完成同一个大任务(每个服务器都只完成大任务拆分出来的单独1个子任务) 集群:多台服务器联合起来独立做相同的任务(多个服务器分担客户发来的请求) 注意:集群如果客户端请求量(任务量)多,多个服务器同时处理不同请求(不同任务),如果请求量…

【TiDB】TiDB CLuster部署

目录 0 大纲 一 集群部署工具TiUP简介 1 TiUP 简介 2 TiUP使用 3 TiUP使用举例 二 TiDB Cluster安装配置需求 1 生产环境硬件需求 2 操作系统需求 三 TIDB部署 1 软硬件需求以及前置检查​编辑 2 安装TiUP 组件 ​3 集群拓扑文件 4 执行部署命令 &#xff08;1&…

基于开源项目OCR做一个探究(chineseocr_lite)

背景&#xff1a;基于图片识别的技术有很多&#xff0c;应用与各行各业&#xff0c;我们公司围绕电子身份证识别自动录入需求开展&#xff0c;以下是我的研究心得 技术栈&#xff1a;python3.6&#xff0c;chineseocr_lite的onnx推理 环境部署&#xff1a;直接上截图&#xff…