Debugging SIGBUS on x86 Linux

2019-01-18 03:52发布

What can cause SIGBUS (bus error) on a generic x86 userland application in Linux? All of the discussion I've been able to find online is regarding memory alignment errors, which from what I understand doesn't really apply to x86.

(My code is running on a Geode, in case there are any relevant processor-specific quirks there.)

7条回答
爷、活的狠高调
2楼-- · 2019-01-18 04:46

You can get a SIGBUS from an unaligned access if you turn on the unaligned access trap, but normally that's off on an x86. You can also get it from accessing a memory mapped device if there's an error of some kind.

Your best bet is using a debugger to identify the faulting instruction (SIGBUS is synchronous), and trying to see what it was trying to do.

查看更多
甜甜的少女心
3楼-- · 2019-01-18 04:47

Oh yes there's one more weird way to get SIGBUS.

If the kernel fails to page in a code page due to memory pressure (OOM killer must be disabled) or failed IO request, SIGBUS.

查看更多
做自己的国王
4楼-- · 2019-01-18 04:47

This was briefly mentioned above as a "failed IO request", but I'll expand upon it a bit.

A frequent case is when you lazily grow a file using ftruncate, map it into memory, start writing data and then run out of space in your filesystem. Physical space for mapped file is allocated on page faults, if there's none left then process receives a SIGBUS.

If you need your application to correctly recover from this error, it makes sense to explicitly reserve space prior to mmap using fallocate. Handling ENOSPC in errno after fallocate call is much simpler than dealing with signals, especially in a multi-threaded application.

查看更多
欢心
5楼-- · 2019-01-18 04:47

It's a bit off the beaten path, but you can get SIGBUS from an unaligned SSE2 (m128) load.

查看更多
爷的心禁止访问
6楼-- · 2019-01-18 04:48

A common cause of a bus error on x86 Linux is attempting to dereference something that is not really a pointer, or is a wild pointer. For example, failing to initialize a pointer, or assigning an arbitrary integer to a pointer and then attempting to dereference it will normally produce either a segmentation fault or a bus error.

Alignment does apply to x86. Even though memory on an x86 is byte-addressable (so you can have a char pointer to any address), if you have for example an pointer to a 4-byte integer, that pointer must be aligned.

You should run your program in gdb and determine which pointer access is generating the bus error to diagnose the issue.

查看更多
别忘想泡老子
7楼-- · 2019-01-18 04:50

SIGBUS can happen in Linux for quite a few reasons other than memory alignment faults - for example, if you attempt to access an mmap region beyond the end of the mapped file.

Are you using anything like mmap, shared memory regions, or similar?

查看更多
登录 后发表回答