Перейти к содержимому

Bus error что значит

  • автор:

Bus error explained

In computing, a bus error is a fault raised by hardware, notifying an operating system (OS) that a process is trying to access memory that the CPU cannot physically address: an invalid address for the address bus, hence the name. In modern use on most architectures these are much rarer than segmentation faults, which occur primarily due to memory access violations: problems in the logical address or permissions.

On POSIX-compliant platforms, bus errors usually result in the SIGBUS signal being sent to the process that caused the error. SIGBUS can also be caused by any general device fault that the computer detects, though a bus error rarely means that the computer hardware is physically broken—it is normally caused by a bug in software. Bus errors may also be raised for certain other paging errors; see below.

Causes

There are at least three main causes of bus errors:

Non-existent address

Software instructs the CPU to read or write a specific physical memory address. Accordingly, the CPU sets this physical address on its address bus and requests all other hardware connected to the CPU to respond with the results, if they answer for this specific address. If no other hardware responds, the CPU raises an exception, stating that the requested physical address is unrecognized by the whole computer system. Note that this only covers physical memory addresses. Trying to access an undefined virtual memory address is generally considered to be a segmentation fault rather than a bus error, though if the MMU is separate, the processor cannot tell the difference.

Unaligned access

Most CPUs are byte-addressable, where each unique memory address refers to an 8-bit byte. Most CPUs can access individual bytes from each memory address, but they generally cannot access larger units (16 bits, 32 bits, 64 bits and so on) without these units being «aligned» to a specific boundary (the x86 platform being a notable exception).

For example, if multi-byte accesses must be 16 bit-aligned, addresses (given in bytes) at 0, 2, 4, 6, and so on would be considered aligned and therefore accessible, while addresses 1, 3, 5, and so on would be considered unaligned. Similarly, if multi-byte accesses must be 32-bit aligned, addresses 0, 4, 8, 12, and so on would be considered aligned and therefore accessible, and all addresses in between would be considered unaligned. Attempting to access a unit larger than a byte at an unaligned address can cause a bus error.

Some systems may have a hybrid of these depending on the architecture being used. For example, for hardware based on the IBM System/360 mainframe, including the IBM System z, Fujitsu B8000, RCA Spectra, and UNIVAC Series 90, instructions must be on a 16-bit boundary, that is, execution addresses must start on an even byte. Attempts to branch to an odd address results in a specification exception. [1] Data, however, may be retrieved from any address in memory, and may be one byte or longer depending on the instruction.

CPUs generally access data at the full width of their data bus at all times. To address bytes, they access memory at the full width of their data bus, then mask and shift to address the individual byte. Systems tolerate this inefficient algorithm, as it is an essential feature for most software, especially string processing. Unlike bytes, larger units can span two aligned addresses and would thus require more than one fetch on the data bus.It is possible for CPUs to support this, but this functionality is rarely required directly at the machine code level, thus CPU designers normally avoid implementing it and instead issue bus errors for unaligned memory access.

Paging errors

FreeBSD, Linux and Solaris can signal a bus error when virtual memory pages cannot be paged in, e.g. because it has disappeared (e.g. accessing a memory-mapped file or executing a binary image which has been truncated while the program was running), [2] or because a just-created memory-mapped file cannot be physically allocated, because the disk is full.

Non-present segment (x86)

On x86 exists an older memory managementmechanism known as segmentation.If the application loads segment register with the selectorof non-present segment (which under POSIX-compliant OSescan only be done with an assembly language), the exceptionis generated. Some OSes used that for swapping, but underLinux this generates SIGBUS.

Example

This is an example of unaligned memory access, written in the C programming language with AT&T assembly syntax.

  1. include

int main(int argc, char **argv)

Compiling and running the example on a POSIX compliant OS on x86 demonstrates the error: $ gcc -ansi sigbus.c -o sigbus$ ./sigbus Bus error$ gdb ./sigbus(gdb) rProgram received signal SIGBUS, Bus error.0x080483ba in main (gdb) x/i $pc0x80483ba : mov DWORD PTR [eax],0x2a(gdb) p/x $eax$1 = 0x804a009(gdb) p/t $eax & (sizeof(int) — 1)$2 = 1 The GDB debugger shows that the immediate value 0x2a is being stored at the location stored in the EAX register, using X86 assembly language. This is an example of register indirect addressing.

Printing the low order bits of the address shows that it is not aligned to a word boundary («dword» using x86 terminology).

Notes and References

    z/Architecture Principles of Operation, SA22-7832-04, Page 6-6, Fifth Edition (September, 2005) IBM Corporation, Poukeepsie, NY, Retrievable from http://publibfp.dhe.ibm.com/epubs/pdf/a2278324.pdf (Retrieved December 31, 2015) Web site: What is SIGBUS — Object specific hardware error?.

This article is licensed under the GNU Free Documentation License. It uses material from the Wikipedia article "Bus error".

Что такое ошибка шины?

Что означает сообщение об ошибке шины и чем оно отличается от сегфоута?

В настоящее время ошибки шины встречаются редко на x86 и возникают, когда ваш процессор не может даже попытаться получить доступ к памяти, как правило:

  • использование инструкции процессора с адресом, который не удовлетворяет его требованиям выравнивания.

Ошибки сегментации возникают при доступе к памяти, которая не принадлежит вашему процессу, они очень распространены и обычно являются результатом:

  • используя указатель на то, что было освобождено.
  • используя неинициализированный, следовательно, фиктивный указатель.
  • используя нулевой указатель.
  • переполнение буфера.

PS: если быть более точным, это не манипулирование самим указателем, который вызовет проблемы, это доступ к памяти, на которую он указывает (разыменование).

Segfault обращается к памяти, к которой у вас нет доступа. Это только для чтения, у вас нет разрешения и т.д .

Ошибка шины пытается получить доступ к памяти, которая не может быть там. Вы использовали адрес, который не имеет смысла для системы, или неправильный адрес для этой операции.

mmap минимальный пример POSIX 7

«Ошибка шины» возникает, когда ядро ​​отправляет SIGBUS процесс.

Минимальный пример, который производит это, потому что ftruncate был забыт:

Протестировано в Ubuntu 14.04.

POSIX описывает SIGBUS как:

Доступ к неопределенной части объекта памяти.

Спецификация mmap говорит, что:

Ссылки в пределах диапазона адресов, начинающиеся с pa и продолжающиеся для длинных байтов до целых страниц после конца объекта, должны привести к доставке сигнала SIGBUS.

И shm_open говорит, что генерирует объекты размером 0:

Объект общей памяти имеет нулевой размер.

Таким образом, *map = 0 мы касаемся конца выделенного объекта.

Нераспределенный доступ к памяти стека в ARMv8 aarch64

Это было упомянуто в: Что такое ошибка шины? для SPARC, но здесь я приведу более воспроизводимый пример.

Все, что вам нужно, это отдельная программа aarch64:

Затем эта программа вызывает SIGBUS на Ubuntu 18.04 aarch64, ядре Linux 4.15.0 на сервере ThunderX2 .

К сожалению, я не могу воспроизвести его в пользовательском режиме QEMU v4.0.0, я не уверен почему.

Неисправность , как представляется, по желанию и контролируются SCTLR_ELx.SA и SCTLR_EL1.SA0 полями, я обобщил связанные документы немного дальше здесь .

Я полагаю, что ядро ​​вызывает SIGBUS, когда приложение демонстрирует смещение данных на шине данных. Я думаю, что, поскольку большинство [?] Современных компиляторов для большинства процессоров дополняют / выравнивают данные для программистов, проблемы выравнивания в прошлом (по крайней мере) смягчаются, и, следовательно, в наши дни SIGBUS не видят слишком часто (AFAIK).

Вы также можете получить SIGBUS, если по какой-то причине невозможно вставить кодовую страницу.

Один классический случай ошибки шины возникает в некоторых архитектурах, таких как SPARC (по крайней мере, некоторые SPARC, возможно, это было изменено), когда вы делаете неправильный доступ. Например:

Этот фрагмент кода пытается записать 32-разрядное целочисленное значение 0xdeadf00d в адрес, который (скорее всего) не выровнен должным образом, и сгенерирует ошибку шины на архитектурах, которые «разборчивы» в этом отношении. Intel x86, кстати, не такая архитектура, она позволила бы доступ (хотя и выполнял его медленнее).

Конкретный пример ошибки шины, с которой я только что столкнулся при программировании C на OS X:

В случае, если вы не помните, документы strcat добавляют второй аргумент к первому, изменяя первый аргумент (переверните аргументы, и все работает нормально). В Linux это дает ошибку сегментации (как и ожидалось), но в OS X это дает ошибку шины. Зачем? Я действительно не знаю.

Это зависит от вашей ОС, процессора, компилятора и, возможно, других факторов.

В общем, это означает, что шина ЦП не смогла выполнить команду или столкнулась с конфликтом, но это может означать целый ряд вещей, зависящих от среды и выполняемого кода.

Обычно это означает неприсоединенный доступ.

Попытка получить доступ к памяти, которая физически отсутствует, также приведет к ошибке шины, но вы не увидите этого, если используете процессор с MMU и операционную систему, которая не глючит, потому что у вас не будет никаких -существующая память сопоставлена ​​с адресным пространством вашего процесса.

Я получал ошибку шины, когда корневой каталог был на 100%.

Причиной ошибки шины в Mac OS X было то, что я попытался выделить около 1 МБ в стеке. Это хорошо работало в одном потоке, но при использовании openMP это приводит к ошибке шины, потому что Mac OS X имеет очень ограниченный размер стека для неосновных потоков .

Я согласен со всеми ответами выше. Вот мои 2 цента относительно ошибки шины:

Ошибка BUS не должна возникать из инструкций в коде программы. Это может произойти, когда вы запускаете двоичный файл и во время выполнения двоичный файл изменяется (перезаписывается сборкой или удаляется и т. Д.).

Проверка, так ли это: Простой способ проверить, является ли это причиной, — запустить запущенные экземпляры одного и того же двоичного файла и запустить сборку. Оба запущенных экземпляра вылетят с SIGBUS ошибкой вскоре после завершения сборки и заменят двоичный файл (тот, который в данный момент запущен обоими экземплярами)

Основная причина: это происходит потому, что ОС меняет страницы памяти, и в некоторых случаях двоичный файл может загружаться не полностью в память, и эти сбои происходят, когда ОС пытается извлечь следующую страницу из того же двоичного файла, но двоичный файл изменился с момента последнего прочитай это.

Чтобы добавить к ответу blxtd выше, также возникают ошибки шины, когда ваш процесс не может попытаться получить доступ к памяти определенной «переменной» .

Заметили « непреднамеренное » использование переменной «i» в первом «цикле for»? Вот что в этом случае вызывает ошибку шины.

Я только что обнаружил, что на процессоре ARMv7 вы можете написать некоторый код, который выдает ошибку сегментации в неоптимизированном состоянии, но при компиляции с -O2 выдает ошибку шины (оптимизируйте больше).

Я использую кросс-компилятор GCC ARM gnueabihf из Ubuntu 64 бит.

Типичное переполнение буфера, которое приводит к ошибке шины,

Здесь, если размер строки в двойных кавычках («») больше размера буфера, это дает ошибку шины.

Bus Error in C++

Learn Algorithms and become a National Programmer

In this article, we will be discussing about "Bus Error In C++" and SIGBUS signal in detail.

Contents:

  • Introduction to Bus Error
  • Main causes of Bus Errors
  • Non-existent address
  • Unaligned access
  • Paging errors
  • Program Code
  • Explanation
  • Quiz

Introduction

When a process attempts to access memory that the CPU cannot physically address, hardware will raise an error to alert the operating system which is known as a bus error.

The bus error also known as SIGBUS is typically signal 10. The acronym SIGBUS stands for "bus error."
In other words, "bus error" means trying to access memory that does not exist.

For Example
if you attempt to access a 12G address but only have 8G of memory.
Or
if you exceed the limit of usable memory.

The following factors affect bus error:
1 . Non-existent address
2 . Unaligned access
3 . Paging errors

1 . Non-existent address

The software gives the CPU instructions to read from or write to a particular physical memory address.
The CPU then assigns this physical address to its address bus and instructs all other hardware to respond in a certain way.
If no response is received from hardware, then the CPU raises an exception that the physical address is unknown or non-existent.

2. Unaligned access

In most CPUs, each memory address corresponds to a single 8-bit byte.
In general, CPUs can access individual bytes from each memory address, but cannot access larger units unless they are "aligned" to a specific boundary.

trying to read a multi-byte value (such as an int, 32-bits) from an odd address generated a bus error.

A 16-bit alignment requirement for multi-byte access would mean that addresses 0, 4, 8, 12, and so on would be aligned and therefore accessible, but all other addresses are unaligned.
A 32-bit alignment requirement for multi-byte access would mean that addresses 0, 4, 8, 12, and so on would be aligned and therefore accessible, but all other addresses are unaligned.

3. Paging errors

When virtual memory pages cannot be paged in or newly created memory is physically allocated because the disc is full, FreeBSD, Linux, and Solaris can raise a bus fault.
Bus error can also result from the operating system’s failure to back a virtual page with virtual memory at least on Linux.

Program Code 1

Output

Explanation:
In this case, it raise a bus error.

Program Code 2

Output

Explanation:
In this case, it raise a bus error.This program is tested on PowerPC Mac .
On modern hardware, it results segmentation fault instead of a bus error.

Program Code 3

Output

Explanation:
In this case,char *str = "Hello Wolrd" is treated as literal. It is the same as const char *str , a constant to string pointer, and attempting to modify a constant string is not enabled.As as a result it raise a bus error.

Program Code 4

Output

Explanation:
In this case ,we used malloc() and created a copy of the original string. here ,ptr is not of the ‘const char *’ type (constant) , so modifiying will not raise any errors. As a result, the reverse string is printed.

What is a bus error? Is it different from a segmentation fault?

What does the "bus error" message mean, and how does it differ from a segmentation fault?

Peter Mortensen's user avatar

17 Answers 17

Bus errors are rare nowadays on x86 and occur when your processor cannot even attempt the memory access requested, typically:

  • using a processor instruction with an address that does not satisfy its alignment requirements.

Segmentation faults occur when accessing memory which does not belong to your process. They are very common and are typically the result of:

  • using a pointer to something that was deallocated.
  • using an uninitialized hence bogus pointer.
  • using a null pointer.
  • overflowing a buffer.

PS: To be more precise, it is not manipulating the pointer itself that will cause issues. It’s accessing the memory it points to (dereferencing).

Peter Mortensen's user avatar

A segfault is accessing memory that you’re not allowed to access. It’s read-only, you don’t have permission, etc.

A bus error is trying to access memory that can’t possibly be there. You’ve used an address that’s meaningless to the system, or the wrong kind of address for that operation.

mmap minimal POSIX 7 example

«Bus error» happens when the kernel sends SIGBUS to a process.

A minimal example that produces it because ftruncate was forgotten:

Tested in Ubuntu 14.04.

POSIX describes SIGBUS as:

Access to an undefined portion of a memory object.

References within the address range starting at pa and continuing for len bytes to whole pages following the end of an object shall result in delivery of a SIGBUS signal.

And shm_open says that it generates objects of size 0:

The shared memory object has a size of zero.

So at *map = 0 we are touching past the end of the allocated object.

Unaligned stack memory accesses in ARMv8 aarch64

This was mentioned at: What is a bus error? for SPARC, but here I will provide a more reproducible example.

All you need is a freestanding aarch64 program:

That program then raises SIGBUS on Ubuntu 18.04 aarch64, Linux kernel 4.15.0 in a ThunderX2 server machine.

Unfortunately, I can’t reproduce it on QEMU v4.0.0 user mode, I’m not sure why.

The fault appears to be optional and controlled by the SCTLR_ELx.SA and SCTLR_EL1.SA0 fields, I have summarized the related docs a bit further here.

Ciro Santilli OurBigBook.com's user avatar

I believe the kernel raises SIGBUS when an application exhibits data misalignment on the data bus. I think that since most[?] modern compilers for most processors pad / align the data for the programmers, the alignment troubles of yore (at least) mitigated, and hence one does not see SIGBUS too often these days (AFAIK).

I agree with all the answers above. Here are my 2 cents regarding the BUS error:

A BUS error need not arise from the instructions within the program’s code. This can happen when you are running a binary and during the execution, the binary is modified (overwritten by a build or deleted, etc.).

Verifying if this is the case

A simple way to check if this is the cause is by launching a couple of instances of the same binary form a build output directory, and running a build after they start. Both the running instances would crash with a SIGBUS error shortly after the build has finished and replaced the binary (the one that both the instances are currently running).

Underlying Reason

This is because OS swaps memory pages and in some cases, the binary might not be entirely loaded in memory. These crashes would occur when the OS tries to fetch the next page from the same binary, but the binary has changed since the last time it was read.

Aditya Vikas Devarapalli's user avatar

On POSIX systems, you can also get the SIGBUS signal when a code page cannot be paged in for some reason.

Peter Mortensen's user avatar

Joshua's user avatar

A specific example of a bus error I just encountered while programming C on OS X:

In case you don’t remember the docs strcat appends the second argument to the first by changing the first argument(flip the arguments and it works fine). On linux this gives a segmentation fault(as expected), but on OS X it gives a bus error. Why? I really don’t know.

One classic instance of a bus error is on certain architectures, such as the SPARC (at least some SPARCs, maybe this has been changed), is when you do a misaligned access. For instance:

This snippet tries to write the 32-bit integer value 0xdeadf00d to an address that is (most likely) not properly aligned, and will generate a bus error on architectures that are "picky" in this regard. The Intel x86 is, by the way, not such an architecture. It would allow the access (albeit execute it more slowly).

Peter Mortensen's user avatar

I was getting a bus error when the root directory was at 100%.

goCards's user avatar

Firstly SIGBUS and SIGSEGV are not a specific type of error but are groups or families of errors. This is why you typically see a signal number(si_no) and a signal code(si_code).

They also depend on the os and architecture as to what can cause them exactly.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *