Skip to content

Commit 69f11cb

Browse files
zhangbo9674HermitSun
authored andcommitted
[PIR] Add c++ call stack for ir enforce (PaddlePaddle#60170)
* refine * fix
1 parent f3ef109 commit 69f11cb

1 file changed

Lines changed: 45 additions & 1 deletion

File tree

paddle/common/enforce.h

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,9 +172,53 @@ inline bool is_error(const T& stat) {
172172
}
173173

174174
namespace pir {
175+
176+
#ifdef __GNUC__
177+
inline std::string demangle(std::string name) {
178+
int status = -4; // some arbitrary value to eliminate the compiler warning
179+
std::unique_ptr<char, void (*)(void*)> res{
180+
abi::__cxa_demangle(name.c_str(), NULL, NULL, &status), std::free};
181+
return (status == 0) ? res.get() : name;
182+
}
183+
#else
184+
inline std::string demangle(std::string name) { return name; }
185+
#endif
186+
187+
static std::string GetCurrentTraceBackString() {
188+
std::ostringstream sout;
189+
sout << "\n\n--------------------------------------\n";
190+
sout << "C++ Traceback (most recent call last):";
191+
sout << "\n--------------------------------------\n";
192+
#if !defined(_WIN32) && !defined(PADDLE_WITH_MUSL)
193+
static constexpr int TRACE_STACK_LIMIT = 100;
194+
195+
void* call_stack[TRACE_STACK_LIMIT];
196+
auto size = backtrace(call_stack, TRACE_STACK_LIMIT);
197+
auto symbols = backtrace_symbols(call_stack, size);
198+
Dl_info info;
199+
int idx = 0;
200+
int end_idx = 0;
201+
for (int i = size - 1; i >= end_idx; --i) {
202+
if (dladdr(call_stack[i], &info) && info.dli_sname) {
203+
auto demangled = demangle(info.dli_sname);
204+
std::string path(info.dli_fname);
205+
// C++ traceback info are from core.so
206+
if (path.substr(path.length() - 3).compare(".so") == 0) {
207+
sout << idx++ << " " << demangled << "\n";
208+
}
209+
}
210+
}
211+
free(symbols);
212+
#else
213+
sout << "Not support stack backtrace yet.\n";
214+
#endif
215+
return sout.str();
216+
}
217+
175218
class IrNotMetException : public std::exception {
176219
public:
177-
explicit IrNotMetException(const std::string& str) : err_str_(str) {}
220+
explicit IrNotMetException(const std::string& str)
221+
: err_str_(str + GetCurrentTraceBackString()) {}
178222

179223
const char* what() const noexcept override { return err_str_.c_str(); }
180224

0 commit comments

Comments
 (0)