一段简单的程序
package main
func main() {
f1()
}
func f1() (result int) {
defer func() {
result = result + 1
}()
return 12
}
// Output:
// 13
来看看汇编
(gdb) disas
Dump of assembler code for function main.f1:
0x000000000044ebe0 <+0>: mov rcx,QWORD PTR fs:0xfffffffffffffff8
0x000000000044ebe9 <+9>: cmp rsp,QWORD PTR [rcx+0x10]
0x000000000044ebed <+13>: jbe 0x44ec55 <main.f1+117>
0x000000000044ebef <+15>: sub rsp,0x20
0x000000000044ebf3 <+19>: mov QWORD PTR [rsp+0x18],rbp
0x000000000044ebf8 <+24>: lea rbp,[rsp+0x18]
0x000000000044ebfd <+29>: mov QWORD PTR [rsp+0x28],0x0
0x000000000044ec06 <+38>: lea rax,[rsp+0x28]
0x000000000044ec0b <+43>: mov QWORD PTR [rsp+0x10],rax
0x000000000044ec10 <+48>: mov DWORD PTR [rsp],0x8
0x000000000044ec17 <+55>: lea rax,[rip+0x21d92] # 0x4709b0
0x000000000044ec1e <+62>: mov QWORD PTR [rsp+0x8],rax
0x000000000044ec23 <+67>: call 0x420f70 <runtime.deferproc>
0x000000000044ec28 <+72>: test eax,eax
0x000000000044ec2a <+74>: jne 0x44ec45 <main.f1+101>
=> 0x000000000044ec2c <+76>: mov QWORD PTR [rsp+0x28],0xc
0x000000000044ec35 <+85>: nop
0x000000000044ec36 <+86>: call 0x4217f0 <runtime.deferreturn>
0x000000000044ec3b <+91>: mov rbp,QWORD PTR [rsp+0x18]
0x000000000044ec40 <+96>: add rsp,0x20
0x000000000044ec44 <+100>: ret
0x000000000044ec45 <+101>: nop
0x000000000044ec46 <+102>: call 0x4217f0 <runtime.deferreturn>
0x000000000044ec4b <+107>: mov rbp,QWORD PTR [rsp+0x18]
0x000000000044ec50 <+112>: add rsp,0x20
0x000000000044ec54 <+116>: ret
0x000000000044ec55 <+117>: call 0x446f20 <runtime.morestack_noctxt>
0x000000000044ec5a <+122>: jmp 0x44ebe0 <main.f1>
可以看出,系统先执行了deferproc然后给result赋值12再去执行了deferreturn。
如果说defer内的闭包是在deferproc内执行的话,这里的赋值操作会将result直接赋值,
不管闭包内对其做的任何操作,输出的结果应该为12。
来看看deferproc都做了什么
func deferproc(siz int32, fn *funcval) { // arguments of fn follow fn
if getg().m.curg != getg() {
// go code on the system stack can't defer
throw("defer on system stack")
}
// the arguments of fn are in a perilous state. The stack map
// for deferproc does not describe them. So we can't let garbage
// collection or stack copying trigger until we've copied them out
// to somewhere safe. The memmove below does that.
// Until the copy completes, we can only call nosplit routines.
sp := getcallersp()
argp := uintptr(unsafe.Pointer(&fn)) + unsafe.Sizeof(fn)
callerpc := getcallerpc()
d := newdefer(siz)
if d._panic != nil {
throw("deferproc: d.panic != nil after newdefer")
}
d.fn = fn
d.pc = callerpc
d.sp = sp
switch siz {
case 0:
// Do nothing.
case sys.PtrSize:
*(*uintptr)(deferArgs(d)) = *(*uintptr)(unsafe.Pointer(argp))
default:
memmove(deferArgs(d), unsafe.Pointer(argp), uintptr(siz))
}
// deferproc returns 0 normally.
// a deferred func that stops a panic
// makes the deferproc return 1.
// the code the compiler generates always
// checks the return value and jumps to the
// end of the function if deferproc returns != 0.
return0()
// No code can go here - the C return register has
// been set and must not be clobbered.
}
在这里并没有做闭包的调用
再看看deferreturn
func deferreturn(arg0 uintptr) {
gp := getg()
d := gp._defer
if d == nil {
return
}
sp := getcallersp()
if d.sp != sp {
return
}
// Moving arguments around.
//
// Everything called after this point must be recursively
// nosplit because the garbage collector won't know the form
// of the arguments until the jmpdefer can flip the PC over to
// fn.
switch d.siz {
case 0:
// Do nothing.
case sys.PtrSize:
*(*uintptr)(unsafe.Pointer(&arg0)) = *(*uintptr)(deferArgs(d))
default:
memmove(unsafe.Pointer(&arg0), deferArgs(d), uintptr(d.siz))
}
fn := d.fn
d.fn = nil
gp._defer = d.link
freedefer(d)
jmpdefer(fn, uintptr(unsafe.Pointer(&arg0)))
}
// asm_amd64.s
// void jmpdefer(fn, sp);
// called from deferreturn.
// 1. pop the caller
// 2. sub 5 bytes from the callers return
// 3. jmp to the argument
TEXT runtime·jmpdefer(SB), NOSPLIT, $0-16
MOVQ fv+0(FP), DX // fn
MOVQ argp+8(FP), BX // caller sp
LEAQ -8(BX), SP // caller sp after CALL
MOVQ -8(SP), BP // restore BP as if deferreturn returned (harmless if framepointers not in use)
SUBQ $5, (SP) // return to CALL again
MOVQ 0(DX), BX
JMP BX // but first run the deferred function
在这里才是闭包的真正调用
总结
之前一直信奉别人所说的defer执行是在作用域返回前,以为一定会在return之前执行,
经过自己的深入才发现执行的真正顺序。执行的顺序一定要去分析才能了解,
下次再去分析一下panic和defer的调用顺序。
有什么不对的地方欢迎指出