【发布时间】:2020-07-12 10:29:07
【问题描述】:
我现在正在研究c++异常,遇到了麻烦,程序如下所示
#include<iostream>
#include<unistd.h>
#include<string>
#include<thread>
#include<vector>
#include<exception>
using namespace std;
vector<int> vec(20);
void fn()throw() {
vec.at(10);
}
int main(){
fn();
return 0;
}
我用gdb反汇编fn(),我们可以看到callq 0x4008d0 _Unwind_Resume@plt,是调用stack unwind操作,因为vector::at可能抛出超出范围的异常
Dump of assembler code for function fn():
0x00000000004009e6 <+0>: push %rbp
0x00000000004009e7 <+1>: mov %rsp,%rbp
0x00000000004009ea <+4>: mov $0xa,%esi
0x00000000004009ef <+9>: mov $0x6020a0,%edi
0x00000000004009f4 <+14>: callq 0x400ba6 <std::vector<int, std::allocator<int> >::at(unsigned long)>
0x00000000004009f9 <+19>: jmp 0x400a11 <fn()+43>
0x00000000004009fb <+21>: cmp $0xffffffffffffffff,%rdx
0x00000000004009ff <+25>: je 0x400a09 <fn()+35>
0x0000000000400a01 <+27>: mov %rax,%rdi
0x0000000000400a04 <+30>: callq 0x4008d0 <_Unwind_Resume@plt>
0x0000000000400a09 <+35>: mov %rax,%rdi
0x0000000000400a0c <+38>: callq 0x400880 <__cxa_call_unexpected@plt>
0x0000000000400a11 <+43>: pop %rbp
0x0000000000400a12 <+44>: retq
End of assembler dump.
但是,当我尝试通过调用函数来模仿这个进度时,会抛出异常,汇编代码 call <_unwind_resume> 不存在,为什么?
#include<iostream>
#include<unistd.h>
#include<string>
#include<thread>
#include<vector>
#include<exception>
using namespace std;
class myException:public exception
{
public:
myException(){ }
};
void fn()throw() {
throw myException();
}
void fn2()throw(){
fn();
}
int main(){
fn2();
return 0;
}
函数fn2()的汇编代码,它不包含调用Unwind_Resume@plt,为什么?
(gdb) disassemble fn2
Dump of assembler code for function fn2():
0x0000000000400aec <+0>: push %rbp
0x0000000000400aed <+1>: mov %rsp,%rbp
0x0000000000400af0 <+4>: callq 0x400aa6 <fn()>
0x0000000000400af5 <+9>: nop
0x0000000000400af6 <+10>: pop %rbp
0x0000000000400af7 <+11>: retq
End of assembler dump.
【问题讨论】: