在Go语言中,`runtime.deferreturn`函数是否会被调用?

huangapple go评论92阅读模式
英文:

Is the `runtime.deferreturn` ever called in go defer

问题

在一个带有defer的Go函数的底部,汇编代码如下所示:

   0x000000000047e1a0 <+256>:   callq  *%rsi
   0x000000000047e1a2 <+258>:   movb   $0x0,0x7(%rsp)
   0x000000000047e1a7 <+263>:   mov    0x748(%rsp),%rdx
   0x000000000047e1af <+271>:   mov    (%rdx),%rbx
   0x000000000047e1b2 <+274>:   callq  *%rbx
   0x000000000047e1b4 <+276>:   mov    0x750(%rsp),%rbp
   0x000000000047e1bc <+284>:   add    $0x758,%rsp
   0x000000000047e1c3 <+291>:   retq
   0x000000000047e1c4 <+292>:   callq  0x42ea40 <runtime.deferreturn>
   0x000000000047e1c9 <+297>:   mov    0x750(%rsp),%rbp
   0x000000000047e1d1 <+305>:   add    $0x758,%rsp
   0x000000000047e1d8 <+312>:   retq
   0x000000000047e1d9 <+313>:   callq  0x458900 <runtime.morestack>

正如我们所看到的,调用runtime.deferreturn之前有一个retq指令。所以,看起来deferreturn永远不会被调用。我理解得对吗?

英文:

At the bottom of a Go func with defer, the assembly looks like this:

   0x000000000047e1a0 &lt;+256&gt;:   callq  *%rsi
   0x000000000047e1a2 &lt;+258&gt;:   movb   $0x0,0x7(%rsp)
   0x000000000047e1a7 &lt;+263&gt;:   mov    0x748(%rsp),%rdx
   0x000000000047e1af &lt;+271&gt;:   mov    (%rdx),%rbx
   0x000000000047e1b2 &lt;+274&gt;:   callq  *%rbx
   0x000000000047e1b4 &lt;+276&gt;:   mov    0x750(%rsp),%rbp
   0x000000000047e1bc &lt;+284&gt;:   add    $0x758,%rsp
   0x000000000047e1c3 &lt;+291&gt;:   retq
   0x000000000047e1c4 &lt;+292&gt;:   callq  0x42ea40 &lt;runtime.deferreturn&gt;
   0x000000000047e1c9 &lt;+297&gt;:   mov    0x750(%rsp),%rbp
   0x000000000047e1d1 &lt;+305&gt;:   add    $0x758,%rsp
   0x000000000047e1d8 &lt;+312&gt;:   retq
   0x000000000047e1d9 &lt;+313&gt;:   callq  0x458900 &lt;runtime.morestack&gt;

As we can see, there is a retq before call runtime.deferreturn. So, it seems that the deferreturn will never be called. Do I understand this right?

答案1

得分: 0

我们可以看到,在调用runtime.deferreturn之前有一个retq指令。所以,看起来deferreturn永远不会被调用。我理解得对吗?

英文:

> As we can see, there is a retq before call runtime.deferreturn. So, it seems that the deferreturn will never be called. Do I understand this right?

No. The code may be used by the Go runtime, for example, while panicking.

huangapple
  • 本文由 发表于 2022年8月5日 08:40:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/73243522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定