|
| 1 | +# 引导 |
| 2 | + |
| 3 | +随意编译一个可执行程序。 |
| 4 | + |
| 5 | +```go |
| 6 | +$ gdb test |
| 7 | + |
| 8 | +GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2 |
| 9 | +Copyright (C) 2020 Free Software Foundation, Inc. |
| 10 | + |
| 11 | +Reading symbols from test... |
| 12 | +Loading Go Runtime support. |
| 13 | + |
| 14 | +(gdb) starti |
| 15 | +Starting program: test |
| 16 | + |
| 17 | +Program stopped. |
| 18 | +_rt0_amd64_linux () at /usr/local/go/src/runtime/rt0_linux_amd64.s:8 |
| 19 | +8 JMP _rt0_amd64(SB) |
| 20 | +``` |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | +也可用 `readelf` 获取起始地址。 |
| 25 | + |
| 26 | +```go |
| 27 | +$ readelf -h ./test |
| 28 | + |
| 29 | +ELF Header: |
| 30 | + Entry point address: 0x453860 |
| 31 | + |
| 32 | + |
| 33 | +$ addr2line -e ./test -a 0x453860 |
| 34 | + |
| 35 | +/usr/local/go/src/runtime/rt0_linux_amd64.s:8 |
| 36 | +``` |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | +查看 `go/src/runtime` 目录下以汇编实现的引导过程源码。 |
| 41 | + |
| 42 | +```go |
| 43 | +// rt0_linux_amd64.s |
| 44 | + |
| 45 | +TEXT _rt0_amd64_linux(SB),NOSPLIT,$-8 |
| 46 | + JMP _rt0_amd64(SB) |
| 47 | +``` |
| 48 | + |
| 49 | +```go |
| 50 | +// asm_amd64.s |
| 51 | + |
| 52 | +// _rt0_amd64 is common startup code for most amd64 systems when using |
| 53 | +// internal linking. This is the entry point for the program from the |
| 54 | +// kernel for an ordinary -buildmode=exe program. The stack holds the |
| 55 | +// number of arguments and the C-style argv. |
| 56 | + |
| 57 | +TEXT _rt0_amd64(SB),NOSPLIT,$-8 |
| 58 | + MOVQ 0(SP), DI // argc |
| 59 | + LEAQ 8(SP), SI // argv |
| 60 | + JMP runtime·rt0_go(SB) |
| 61 | +``` |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | +核心流程是创建 `main goroutine(runtime.main)`,并执行 `mstart` 进入调度循环。 |
| 66 | + |
| 67 | +```go |
| 68 | +TEXT runtime·rt0_go(SB),NOSPLIT|TOPFRAME,$0 |
| 69 | + |
| 70 | + CALL runtime·check(SB) |
| 71 | + |
| 72 | + CALL runtime·args(SB) |
| 73 | + CALL runtime·osinit(SB) |
| 74 | + CALL runtime·schedinit(SB) |
| 75 | + |
| 76 | + // create a new goroutine to start program |
| 77 | + MOVQ $runtime·mainPC(SB), AX // entry |
| 78 | + PUSHQ AX |
| 79 | + CALL runtime·newproc(SB) |
| 80 | + POPQ AX |
| 81 | + |
| 82 | + // start this M |
| 83 | + CALL runtime·mstart(SB) |
| 84 | + |
| 85 | + CALL runtime·abort(SB) // mstart should never return |
| 86 | + RET |
| 87 | +``` |
| 88 | + |
| 89 | +```go |
| 90 | +// mainPC is a function value for runtime.main, to be passed to newproc. |
| 91 | + |
| 92 | +DATA runtime·mainPC+0(SB)/8,$runtime·main<ABIInternal>(SB) |
| 93 | +GLOBL runtime·mainPC(SB),RODATA,$8 |
| 94 | +``` |
0 commit comments