Linux ошибка сегментирования как исправить

Не всегда программы в Linux запускаются как положено. Иногда, в силу разных причин программа вместо нормальной работы выдает ошибку. Но нам не нужна ошибка, нам нужна программа, вернее, та функция, которую она должна выполнять. Сегодня мы поговорим об одной из самых серьезных и непонятных ошибок. Это ошибка сегментации Ubuntu. Если такая ошибка происходит только один раз, то на нее можно не обращать внимания, но если это регулярное явление нужно что-то делать.

Конечно, случается эта проблема не только в Ubuntu, а во всех Linux дистрибутивах, поэтому наша инструкция будет актуальна для них тоже. Но сосредоточимся мы в основном на Ubuntu. Рассмотрим что такое ошибка сегментирования linux, почему она возникает, а также как с этим бороться и что делать.

Что такое ошибка сегментации?

Ошибка сегментации, Segmentation fault, или Segfault, или SIGSEGV в Ubuntu и других Unix подобных дистрибутивах, означает ошибку работы с памятью. Когда вы получаете эту ошибку, это значит, что срабатывает системный механизм защиты памяти, потому что программа попыталась получить доступ или записать данные в ту часть памяти, к которой у нее нет прав обращаться.

Чтобы понять почему так происходит, давайте рассмотрим как устроена работа с памятью в Linux, я попытаюсь все упростить, но приблизительно так оно и работает.

Допустим, в вашей системе есть 6 Гигабайт оперативной памяти, каждой программе нужно выделить определенную область, куда будет записана она сама, ее данные и новые данные, которые она будет создавать. Чтобы дать возможность каждой из запущенных программ использовать все шесть гигабайт памяти был придуман механизм виртуального адресного пространства. Создается виртуальное пространство очень большого размера, а из него уже выделяется по 6 Гб для каждой программы. Если интересно, это адресное пространство можно найти в файле /proc/kcore, только не вздумайте никуда его копировать.

Выделенное адресное пространство для программы называется сегментом. Как только программа попытается записать или прочитать данные не из своего сегмента, ядро отправит ей сигнал SIGSEGV и программа завершится с нашей ошибкой. Более того, каждый сегмент поделен на секции, в некоторые из них запись невозможна, другие нельзя выполнять, если программа и тут попытается сделать что-то запрещенное, мы опять получим ошибку сегментации Ubuntu.

Почему возникает ошибка сегментации?

И зачем бы это порядочной программе лезть, куда ей не положено? Да в принципе, незачем. Это происходит из-за ошибки при написании программ или несовместимых версиях библиотек и ПО. Часто эта ошибка встречается в программах на Си или C++. В этом языке программисты могут вручную работать с памятью, а язык со своей стороны не контролирует, чтобы они это делали правильно, поэтому одно неверное обращение к памяти может обрушить программу.

Почему может возникать эта ошибка при несовместимости библиотек? По той же причине — неверному обращению к памяти. Представим, что у нас есть библиотека linux (набор функций), в которой есть функция, которая выполняет определенную задачу. Для работы нашей функции нужны данные, поэтому при вызове ей нужно передать строку. Наша старая версия библиотеки ожидает, что длина строки будет до 256 символов. Но программа была обновлена формат записи поменялся, и теперь она передает библиотеке строку размером 512 символов. Если обновить программу, но оставить старую версию библиотеки, то при передаче такой строки 256 символов запишутся нормально в подготовленное место, а вот вторые 256 перезапишут данные программы, и возможно, попытаются выйти за пределы сегмента, тогда и будет ошибка сегментирования linux.

Что делать если возникла ошибка сегментирования?

Если вы думаете, что это ошибка в программе, то вам остается только отправить отчет об ошибке разработчикам. Но вы все-таки еще можете попытаться что-то сделать.

Например, если падает с ошибкой сегментации неизвестная программа, то мы можем решить что это вина разработчиков, но если с такой ошибкой падает chrome или firefox при запуске возникает вопрос, может мы делаем что-то не так? Ведь это уже хорошо протестированные программы.

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

sudo apt update
sudo apt full-upgrade

Если это не помогло, нужно обнулить настройки программы до значений по умолчанию, возможно, удалить кэш. Настройки программ в Linux обычно содержатся в домашней папке, скрытых подкаталогах с именем программы. Также, настройки и кэш могут содержаться в каталогах ~/.config и ~/.cache. Просто удалите папки программы и попробуйте снова ее запустить. Если и это не помогло, вы можете попробовать полностью удалить программу, а потом снова ее установить, возможно, какие-нибудь зависимости были повреждены:

sudo apt remove пакет_программы
sudo apt autoremove
sudo apt install пакет_программы

Если есть возможность, попробуйте установить программу из другого источника, например, не из PPA, а более старую версию, из официальных репозиториев.

Когда вы все это выполнили, скорее всего, проблема не в вашем дистрибутиве, а в самой программе. Нужно отправлять отчет разработчикам. В Ubuntu это можно сделать с помощью программы apport-bug. Обычно Ubuntu предлагает это сделать сразу, после того как программа завершилась с ошибкой сегментирования. Если же ошибка сегментирования Ubuntu встречается не в системной программе, то вам придется самим искать разработчиков и вручную описывать что произошло.

Чтобы помочь разработчикам решить проблему, недостаточно отправить им только сообщение что вы поймали Segmentation Fault, нужно подробно описать проблему, действия, которые вы выполняли перед этим, так чтобы разработчик мог их воспроизвести. Также, желательно прикрепить к отчету последние функции, которые вызывала программа (стек вызовов функций), это может очень сильно помочь разработчикам.

Рассмотрим, как его получить. Это не так уж сложно. Сначала запустите вашу программу, затем узнайте ее PID с помощью команды:

pgrep программа

Дальше запускаем отладчик gdb:

sudo gdb -q

Подключаемся к программе:

(gdb) attach ваш_pid

После подключения программа станет на паузу, продолжаем ее выполнение командой:

(gdb) continue

segfault

Затем вам осталось только вызвать ошибку:

segfault1

И набрать команду, которая выведет стек последних вызовов:

(gdb) backtrace

Вывод этой команды и нужно отправлять разработчикам. Чтобы отключиться от программы и выйти наберите:

(gdb) detach
(gdb) quit

Дальше остается отправить отчет и ждать исправления ошибки. Если вы не уверены, что ошибка в программе, можете поспрашивать на форумах. Когда у вас есть стек вызовов, уже можно попытаться, если не понять в чем проблема, то попытаться узнать, не сталкивался ли с подобной проблемой еще кто-то.

Выводы

Теперь у вас есть приблизительный план действий, что нужно делать, когда появляется ошибка сегментирования сделан дамп памяти ubuntu. Если вы знаете другие способы решить эту проблему, напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

What does it mean?

See AU: What is a segmentation fault? post and also this post which have some examples how reproduce it, SO: What is segmentation fault?.

The simplest description I can come with (may be not the perfect):

The program tried to access a memory area out side its own section. Operating system blocks it.

Some cases: Reading value with uninitialized pointer, Going out of range in an array, Function call (when backward compatibility not maintained), …

However, it is not always easy find the cause with large programs or those which relay on other project lib’s. And most of the cases end up with a bug report, either for target program or one of its dependencies (either upstream project or downstream distribution package).

How can I resolve this issue?

  • Fire a bug report

    If you didn’t make any custom configuration/setup and you all updates installed. fire a bug report, see How do I report a bug?

    If open source supported by Ubuntu use ubuntu-bug (apport-bug). For 3rd party closed source, check their help pages how to report bugs and collect related data.

  • Take initiative to debug

    If you you have even a little programming background, it is recommended that you try your best to resolve it yourself. There many bug reports out there inactive for years. At least, you may be able to collect enough debug data that help resolve the issue when reporting it.

    That’s means that you are breaking the user abstraction level and opening the black box! (FLOSS actually has transparent box).

Some Useful Tools for Debugging

Some … I mean there are many other useful tools out there that you gonna find when you dig in more.

  1. apport-bug logs / core dump / backtrace

    If you don’t have an error message before segmentation fault. Run it with --save option and look for back-trace log:

    apport-bug program-cmd --save bug-report_output.txt
    
  2. gdb backtrace / debuging source code

    If it didn’t work, use gdb:

    $ gdb program-cmd
    (gdb) run
    (gdb) backtrace
    

    If you get any error message, check the web, launchpad and in upstream project bug tracker if there any similar cases.

    For some advanced users or who are following a c/c++ learning path, they could download the corresponding -dbg symbols packages. Then you can use gdb to trace program flow through the source and get the exact function/instruction that raise the runtime error.

    For Ubuntu(Debian) based distributions, source code of a package can be downloaded using:

    apt-get source <package-name>
    
  3. strace system call tracing

    Another tool that may help is strace, I like it. It’s really a powerful tool.

    It presents itself:

    In the simplest case strace runs the specified command until it exits. It intercepts and records the system calls which are called by a
    process and the signals which are received by a process. The name of each system call, its arguments and its return value are printed on
    standard error or to the file specified with the -o option.

    strace is a useful diagnostic, instructional, and debugging tool. System administrators, diagnosticians and trouble-shooters will find it
    invaluable for solving problems with programs for which the source is not readily available since they do not need to be recompiled in
    order to trace them. Students, hackers and the overly-curious will find that a great deal can be learned about a system and its system
    calls by tracing even ordinary programs. And programmers will find that since system calls and signals are events that happen at the
    user/kernel interface, a close examination of this boundary is very useful for bug isolation, sanity checking and attempting to capture
    race conditions.

    Source: man strace

  4. ltrace dynamic library call tracing

    ltrace is a program that simply runs the specified command until
    it
    exits. It intercepts and records the dynamic library calls which are
    called by the executed process and the signals which are received by
    that process. It can also intercept and print the system calls exe‐
    cuted by the program.

    Its use is very similar to strace(1).

    Source: man ltrace

Не всегда программы в Linux запускаются как положено. Иногда, в силу разных причин программа вместо нормальной работы выдает ошибку. Но нам не нужна ошибка, нам нужна программа, вернее, та функция, которую она должна выполнять. Сегодня мы поговорим об одной из самых серьезных и непонятных ошибок. Это ошибка сегментации Ubuntu. Если такая ошибка происходит только один раз, то на нее можно не обращать внимания, но если это регулярное явление нужно что-то делать.

Конечно, случается эта проблема не только в Ubuntu, а во всех Linux дистрибутивах, поэтому наша инструкция будет актуальна для них тоже. Но сосредоточимся мы в основном на Ubuntu. Рассмотрим что такое ошибка сегментирования linux, почему она возникает, а также как с этим бороться и что делать.

Что такое ошибка сегментации?

Ошибка сегментации, Segmentation fault, или Segfault, или SIGSEGV в Ubuntu и других Unix подобных дистрибутивах, означает ошибку работы с памятью. Когда вы получаете эту ошибку, это значит, что срабатывает системный механизм защиты памяти, потому что программа попыталась получить доступ или записать данные в ту часть памяти, к которой у нее нет прав обращаться.

Чтобы понять почему так происходит, давайте рассмотрим как устроена работа с памятью в Linux, я попытаюсь все упростить, но приблизительно так оно и работает.

Допустим, в вашей системе есть 6 Гигабайт оперативной памяти, каждой программе нужно выделить определенную область, куда будет записана она сама, ее данные и новые данные, которые она будет создавать. Чтобы дать возможность каждой из запущенных программ использовать все шесть гигабайт памяти был придуман механизм виртуального адресного пространства. Создается виртуальное пространство очень большого размера, а из него уже выделяется по 6 Гб для каждой программы. Если интересно, это адресное пространство можно найти в файле /proc/kcore, только не вздумайте никуда его копировать.

Выделенное адресное пространство для программы называется сегментом. Как только программа попытается записать или прочитать данные не из своего сегмента, ядро отправит ей сигнал SIGSEGV и программа завершится с нашей ошибкой. Более того, каждый сегмент поделен на секции, в некоторые из них запись невозможна, другие нельзя выполнять, если программа и тут попытается сделать что-то запрещенное, мы опять получим ошибку сегментации Ubuntu.

Почему возникает ошибка сегментации?

И зачем бы это порядочной программе лезть, куда ей не положено? Да в принципе, незачем. Это происходит из-за ошибки при написании программ или несовместимых версиях библиотек и ПО. Часто эта ошибка встречается в программах на Си или C++. В этом языке программисты могут вручную работать с памятью, а язык со своей стороны не контролирует, чтобы они это делали правильно, поэтому одно неверное обращение к памяти может обрушить программу.

Почему может возникать эта ошибка при несовместимости библиотек? По той же причине — неверному обращению к памяти. Представим, что у нас есть библиотека linux (набор функций), в которой есть функция, которая выполняет определенную задачу. Для работы нашей функции нужны данные, поэтому при вызове ей нужно передать строку. Наша старая версия библиотеки ожидает, что длина строки будет до 256 символов. Но программа была обновлена формат записи поменялся, и теперь она передает библиотеке строку размером 512 символов. Если обновить программу, но оставить старую версию библиотеки, то при передаче такой строки 256 символов запишутся нормально в подготовленное место, а вот вторые 256 перезапишут данные программы, и возможно, попытаются выйти за пределы сегмента, тогда и будет ошибка сегментирования linux.

Что делать если возникла ошибка сегментирования?

Если вы думаете, что это ошибка в программе, то вам остается только отправить отчет об ошибке разработчикам. Но вы все-таки еще можете попытаться что-то сделать.

Например, если падает с ошибкой сегментации неизвестная программа, то мы можем решить что это вина разработчиков, но если с такой ошибкой падает chrome или firefox при запуске возникает вопрос, может мы делаем что-то не так? Ведь это уже хорошо протестированные программы.

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

sudo apt update
sudo apt full-upgrade

Если это не помогло, нужно обнулить настройки программы до значений по умолчанию, возможно, удалить кэш. Настройки программ в Linux обычно содержатся в домашней папке, скрытых подкаталогах с именем программы. Также, настройки и кэш могут содержаться в каталогах ~/.config и ~/.cache. Просто удалите папки программы и попробуйте снова ее запустить. Если и это не помогло, вы можете попробовать полностью удалить программу, а потом снова ее установить, возможно, какие-нибудь зависимости были повреждены:

sudo apt remove пакет_программы
sudo apt autoremove
sudo apt install пакет_программы

Если есть возможность, попробуйте установить программу из другого источника, например, не из PPA, а более старую версию, из официальных репозиториев.

Когда вы все это выполнили, скорее всего, проблема не в вашем дистрибутиве, а в самой программе. Нужно отправлять отчет разработчикам. В Ubuntu это можно сделать с помощью программы apport-bug. Обычно Ubuntu предлагает это сделать сразу, после того как программа завершилась с ошибкой сегментирования. Если же ошибка сегментирования Ubuntu встречается не в системной программе, то вам придется самим искать разработчиков и вручную описывать что произошло.

Чтобы помочь разработчикам решить проблему, недостаточно отправить им только сообщение что вы поймали Segmentation Fault, нужно подробно описать проблему, действия, которые вы выполняли перед этим, так чтобы разработчик мог их воспроизвести. Также, желательно прикрепить к отчету последние функции, которые вызывала программа (стек вызовов функций), это может очень сильно помочь разработчикам.

Рассмотрим, как его получить. Это не так уж сложно. Сначала запустите вашу программу, затем узнайте ее PID с помощью команды:

pgrep программа

Дальше запускаем отладчик gdb:

sudo gdb -q

Подключаемся к программе:

(gdb) attach ваш_pid

После подключения программа станет на паузу, продолжаем ее выполнение командой:

(gdb) continue

segfault

Затем вам осталось только вызвать ошибку:

segfault1

И набрать команду, которая выведет стек последних вызовов:

(gdb) backtrace

Вывод этой команды и нужно отправлять разработчикам. Чтобы отключиться от программы и выйти наберите:

(gdb) detach
(gdb) quit

Дальше остается отправить отчет и ждать исправления ошибки. Если вы не уверены, что ошибка в программе, можете поспрашивать на форумах. Когда у вас есть стек вызовов, уже можно попытаться, если не понять в чем проблема, то попытаться узнать, не сталкивался ли с подобной проблемой еще кто-то.

Выводы

Теперь у вас есть приблизительный план действий, что нужно делать, когда появляется ошибка сегментирования сделан дамп памяти ubuntu. Если вы знаете другие способы решить эту проблему, напишите в комментариях!

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Содержание:

  • Handling
  • Overview
  • Causes
  • Что такое ошибка сегментации?
  • Additional Information
  • Examples
    • Writing to read-only memory
    • Null pointer dereference
    • Stack overflow

Handling

The default action for a segmentation fault or bus error is abnormal termination of the process that triggered it. A core file may be generated to aid debugging, and other platform-dependent actions may also be performed. For example, Linux systems using the grsecurity patch may log SIGSEGV signals in order to monitor for possible intrusion attempts using buffer overflows.

On some systems, like Linux and Windows, it is possible for the program itself to handle a segmentation fault.. Depending on the architecture and operating system, the running program can not only handle the event but may extract some information about its state like getting a stack trace, processor register values, the line of the source code when it was triggered, memory address that was invalidly accessed and whether the action was a read or a write.

Although a segmentation fault generally means that the program has a bug that needs fixing, it is also possible to intentionally cause such failure for the purposes of testing, debugging and also to emulate platforms were direct access to memory is needed. On the latter case, the system must be able to allow the program to run even after the fault occurs. In this case, when the system allows, it is possible to handle the event and increment the processor program counter to «jump» over the failing instruction to continue the execution.

Overview

Example of human generated signal

A null pointer dereference on Windows 8

A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system).

The term «segmentation» has various uses in computing; in the context of «segmentation fault», a term used since the 1950s, it refers to the address space of a program.[citation needed] With memory protection, only the program’s own address space is readable, and of this, only the stack and the read/write portion of the data segment of a program are writable, while read-only data and the code segment are not writable. Thus attempting to read outside of the program’s address space, or writing to a read-only segment of the address space, results in a segmentation fault, hence the name.

On systems using hardware memory segmentation to provide virtual memory, a segmentation fault occurs when the hardware detects an attempt to refer to a non-existent segment, or to refer to a location outside the bounds of a segment, or to refer to a location in a fashion not allowed by the permissions granted for that segment. On systems using only paging, an invalid page fault generally leads to a segmentation fault, and segmentation faults and page faults are both faults raised by the virtual memory management system. Segmentation faults can also occur independently of page faults: illegal access to a valid page is a segmentation fault, but not an invalid page fault, and segmentation faults can occur in the middle of a page (hence no page fault), for example in a buffer overflow that stays within a page but illegally overwrites memory.

At the hardware level, the fault is initially raised by the memory management unit (MMU) on illegal access (if the referenced memory exists), as part of its memory protection feature, or an invalid page fault (if the referenced memory does not exist). If the problem is not an invalid logical address but instead an invalid physical address, a bus error is raised instead, though these are not always distinguished.

At the operating system level, this fault is caught and a signal is passed on to the offending process, activating the process’s handler for that signal. Different operating systems have different signal names to indicate that a segmentation fault has occurred. On Unix-like operating systems, a signal called SIGSEGV (abbreviated from segmentation violation) is sent to the offending process. On Microsoft Windows, the offending process receives a STATUS_ACCESS_VIOLATION exception.

Causes

The conditions under which segmentation violations occur and how they manifest themselves are specific to hardware and the operating system: different hardware raises different faults for given conditions, and different operating systems convert these to different signals that are passed on to processes. The proximate cause is a memory access violation, while the underlying cause is generally a software bug of some sort. Determining the root cause – debugging the bug – can be simple in some cases, where the program will consistently cause a segmentation fault (e.g., dereferencing a null pointer), while in other cases the bug can be difficult to reproduce and depend on memory allocation on each run (e.g., dereferencing a dangling pointer).

The following are some typical causes of a segmentation fault:

  • Attempting to access a nonexistent memory address (outside process’s address space)
  • Attempting to access memory the program does not have rights to (such as kernel structures in process context)
  • Attempting to write read-only memory (such as code segment)

These in turn are often caused by programming errors that result in invalid memory access:

  • Dereferencing a null pointer, which usually points to an address that’s not part of the process’s address space
  • Dereferencing or assigning to an uninitialized pointer (wild pointer, which points to a random memory address)
  • Dereferencing or assigning to a freed pointer (dangling pointer, which points to memory that has been freed/deallocated/deleted)
  • A buffer overflow
  • A stack overflow
  • Attempting to execute a program that does not compile correctly. (Some compilers will output an executable file despite the presence of compile-time errors.)

In C code, segmentation faults most often occur because of errors in pointer use, particularly in C dynamic memory allocation. Dereferencing a null pointer will always result in a segmentation fault, but wild pointers and dangling pointers point to memory that may or may not exist, and may or may not be readable or writable, and thus can result in transient bugs. For example:

char *p1 = NULL;           // Null pointer
char *p2;                  // Wild pointer: not initialized at all.
char *p3  = malloc(10 * sizeof(char));  // Initialized pointer to allocated memory
                                        // (assuming malloc did not fail)
free(p3);                  // p3 is now a dangling pointer, as memory has been freed

Now, dereferencing any of these variables could cause a segmentation fault: dereferencing the null pointer generally will cause a segfault, while reading from the wild pointer may instead result in random data but no segfault, and reading from the dangling pointer may result in valid data for a while, and then random data as it is overwritten.

Что такое ошибка сегментации?

Ошибка сегментации, Segmentation fault, или Segfault, или SIGSEGV в Ubuntu и других Unix подобных дистрибутивах, означает ошибку работы с памятью. Когда вы получаете эту ошибку, это значит, что срабатывает системный механизм защиты памяти, потому что программа попыталась получить доступ или записать данные в ту часть памяти, к которой у нее нет прав обращаться.

Чтобы понять почему так происходит, давайте рассмотрим как устроена работа с памятью в Linux, я попытаюсь все упростить, но приблизительно так оно и работает.

Допустим, в вашей системе есть 6 Гигабайт оперативной памяти, каждой программе нужно выделить определенную область, куда будет записана она сама, ее данные и новые данные, которые она будет создавать. Чтобы дать возможность каждой из запущенных программ использовать все шесть гигабайт памяти был придуман механизм виртуального адресного пространства. Создается виртуальное пространство очень большого размера, а из него уже выделяется по 6 Гб для каждой программы. Если интересно, это адресное пространство можно найти в файле /proc/kcore, только не вздумайте никуда его копировать.

Выделенное адресное пространство для программы называется сегментом. Как только программа попытается записать или прочитать данные не из своего сегмента, ядро отправит ей сигнал SIGSEGV и программа завершится с нашей ошибкой. Более того, каждый сегмент поделен на секции, в некоторые из них запись невозможна, другие нельзя выполнять, если программа и тут попытается сделать что-то запрещенное, мы опять получим ошибку сегментации Ubuntu.

Additional Information

BackgroundModern general purpose hardware includes a «memory management unit» (or MMU). This hardware feature is used by operating systems like Linux to implement memory protection, i.e. to prevent different processes from accessing or modifying each other’s memory (except in a strictly controlled fashion through specific APIs). This simplifies troubleshooting and increases resilience as processes are carefully contained and separated from one another.A «segmentation violation» signal is sent to a process of which the memory management unit detected an attempt to use a memory address that does not belong to it.Common cause: programming errorIf a process tries to access memory through a pointer which has not been properly initialised, or which is pointing to memory that has previously been deallocated, this will likely result in a segfault. In this case, the segfault is occurring with a specific process or binary, possibly under a specific set of circumstances.To deal with this type of segfault, begin by applying all relevant service packs and maintenance updates. Next, if the problem is still reproducible with current code, try to capture an application core dump for analysis. Details for this are found in TID 3054866 — How to obtain application core dumps.If the problematic binary is shipped by Novell as part of the product, open a service request with Novell Technical services, supplying

  • a description of the circumstances under which the core dump was generated,
  • a supportconfig -v report for the affected system (supportconfig home page), and
  • the core dump file itself, if smaller than 50 MB. If it is larger, wait for the service request to be assigned to an engineer and then work with the engineer to transfer it.

If the problematic binary was supplied by a third party, contact that party’s support department for assistance.Common cause: mismatched binary and librariesSegfaults can occur with processes that combine binaries and shared libraries which aren’t (fully) compatible. This can occur, for instance, when a library is updated in a way that changes the library’s ABI (application binary interface), but the library’s internal version number is not updated to reflect this. A binary that was built against an older version of the library may start to segfault when loaded against the newer version.This case may be difficult to recognise, and there is no step list for dealing with it. When this case is suspected, some things to consider are:

  • Checking the system for file corruption (e.g. using the rpm-verify.txt file in a supportconfig -v report)
  • Checking the system’s settings that relate to shared libraries, like the /etc/ld.so.conf and /etc/ld.so.conf.d/* configuration files and the LD_LIBRARY_PATH and LD_PRELOAD environment variables.
  • Using the objdump tool to check the binary for a built-in library search path override (RPATH).

Common cause: hardware or hardware configuration issueWhen segfaults are occurring frequently, or with different processes or without a clear pattern to them, this can indicate that a system’s hardware (memory subsystem) is problematic, or that low-level system configuration settings are inappropriate. Please refer to TID 3301593 — Linux system hangs or is unstable for more information on how to handle this situation.

+ Upgrading to Open Enterprise Server 2 SP1 Linux

+ Open Enterprise Server 2 SP1 Migration Strategies

Examples

Segmentation fault on an EMV keypad

Writing to read-only memory

Writing to read-only memory raises a segmentation fault. At the level of code errors, this occurs when the program writes to part of its own code segment or the read-only portion of the data segment, as these are loaded by the OS into read-only memory.

Here is an example of ANSI C code that will generally cause a segmentation fault on platforms with memory protection. It attempts to modify a string literal, which is undefined behavior according to the ANSI C standard. Most compilers will not catch this at compile time, and instead compile this to executable code that will crash:

int main(void)
{
    char *s = "hello world";
    *s = 'H';
}

When the program containing this code is compiled, the string «hello world» is placed in the rodata section of the program executable file: the read-only section of the data segment. When loaded, the operating system places it with other strings and constant data in a read-only segment of memory. When executed, a variable, s, is set to point to the string’s location, and an attempt is made to write an H character through the variable into the memory, causing a segmentation fault. Compiling such a program with a compiler that does not check for the assignment of read-only locations at compile time, and running it on a Unix-like operating system produces the following runtime error:

$ gcc segfault.c -g -o segfault
$ ./segfault
Segmentation fault

Backtrace of the core file from GDB:

Program received signal SIGSEGV, Segmentation fault.
0x1c0005c2 in main () at segfault.c6
6               *s = 'H';

This code can be corrected by using an array instead of a character pointer, as this allocates memory on stack and initializes it to the value of the string literal:

char s[] = "hello world";
s = 'H';  // equivalently, *s = 'H';

Even though string literals should not be modified (this has undefined behavior in the C standard), in C they are of type, so there is no implicit conversion in the original code (which points a at that array), while in C++ they are of type, and thus there is an implicit conversion, so compilers will generally catch this particular error.

Null pointer dereference

In C and C-like languages, null pointers are used to mean «pointer to no object» and as an error indicator, and dereferencing a null pointer (a read or write through a null pointer) is a very common program error. The C standard does not say that the null pointer is the same as the pointer to memory address 0, though that may be the case in practice. Most operating systems map the null pointer’s address such that accessing it causes a segmentation fault. This behavior is not guaranteed by the C standard. Dereferencing a null pointer is undefined behavior in C, and a conforming implementation is allowed to assume that any pointer that is dereferenced is not null.

int *ptr = NULL;
printf("%d", *ptr);

This sample code creates a null pointer, and then tries to access its value (read the value). Doing so causes a segmentation fault at runtime on many operating systems.

Dereferencing a null pointer and then assigning to it (writing a value to a non-existent target) also usually causes a segmentation fault:

int *ptr = NULL;
*ptr = 1;

The following code includes a null pointer dereference, but when compiled will often not result in a segmentation fault, as the value is unused and thus the dereference will often be optimized away by dead code elimination:

int *ptr = NULL;
*ptr;

Stack overflow

Another example is recursion without a base case:

int main(void)
{
    main();
    return ;
}

which causes the stack to overflow which results in a segmentation fault. Infinite recursion may not necessarily result in a stack overflow depending on the language, optimizations performed by the compiler and the exact structure of a code. In this case, the behavior of unreachable code (the return statement) is undefined, so the compiler can eliminate it and use a tail call optimization that might result in no stack usage. Other optimizations could include translating the recursion into iteration, which given the structure of the example function would result in the program running forever, while probably not overflowing its stack.

The segmentation fault, also known as segfault, is a type of computer error that occurs whenever an unexpected condition causes the processor to attempt to access a memory location that’s outside its own program storage area. The term “segmentation” refers to a memory protection mechanism used in virtual memory operating systems.

This specific error arises because data is typically shared on a system using different memory sections, and the program storage space is shared among applications.

Segmentation faults are usually triggered by an access violation, which occurs when the CPU attempts to execute instructions outside its memory area or tries to read or write into some reserved address that does not exist. This action results in halting the current application and generates an output known as Segmentation Fault.

#1. What are the Symptoms of Segmentation Fault?

The symptoms of segmentation faults may vary depending on how and where they’re generated. Typically, this error is generated due to one of the following conditions:

#a. Dereferencing a null pointer

Programming languages offer references, which are pointers that identify where in memory an item is located. A null pointer is a special pointer that doesn’t point to any valid memory location. Dereferencing (accessing) null pointer results in segmentation faults or null pointer exceptions.

/**
 * @file main.c
 * @author freecoder
 * @brief this program allow to handle a segmentation fault error
 *
 * @version 1.0
 * @date 8 Jan. 2022
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>

/* main program entry */
int main(int argc, char **argv)
{
	/* local variables */
	unsigned int *puiPointer = NULL;
	/* body program */
	*puiPointer = 20;
	return 0;
}

after compiling and running the program with the gdb command, the segmentation fault error appears:

➜  Article-XX gcc -g main.c -o main
➜  Article-XX ./main               
[1]    7825 segmentation fault  ./main
➜  Article-XX gdb ./main           
GNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./main...
(gdb) start
Temporary breakpoint 1 at 0x401111: file main.c, line 20.
Starting program: /home/others/Article-XX/main 
warning: Error disabling address space randomization: Operation not permitted
Temporary breakpoint 1, main (argc=1, argv=0x7ffc9c096258) at main.c:20
20              unsigned int *puiPointer = NULL;
(gdb) list
15
16      /* main program entry */
17      int main(int argc, char **argv)
18      {
19              /* local variables */
20              unsigned int *puiPointer = NULL;
21
22              /* body program */
23
24              *puiPointer = 20;
(gdb) s
24              *puiPointer = 20;
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x000000000040111d in main (argc=1, argv=0x7ffc9c096258) at main.c:24
24              *puiPointer = 20;
(gdb) 
segmentation fault Dereferencing a null pointer

#b. Trying to access memory not initialized

Programs using uninitialized variables may crash when attempting to access uninitialized memory or may expose data stored in the uninitialized variables by writing to them. Also in the case when the program attempts to read or write to an area of memory not allocated with malloc(), calloc() or realloc().

An example of a simple segmentation fault is trying to read from a variable before it has been set:

/**
 * @file main.c
 * @author freecoder
 * @brief this program allow to handle a segmentation fault error
 *
 * @version 1.0
 * @date 8 Jan. 2022
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>

/* main program entry */
int main(int argc, char **argv)
{
	/* local variables */
	unsigned int *puiPointer;
	/* body program */
	*puiPointer = 20;
	return 0;
}

In this case, the pointer puiPointer will be pointing to a random location in memory, so when the program attempts to read from it (by dereferencing *puiPointer), a segmentation fault will be triggered:

➜  Article-XX gcc -g main.c -o main
➜  Article-XX gdb ./main           
GNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./main...
(gdb) start
Temporary breakpoint 1 at 0x401111: file main.c, line 24.
Starting program: /home/others/Article-XX/main 
warning: Error disabling address space randomization: Operation not permitted
Temporary breakpoint 1, main (argc=1, argv=0x7fff6df4f038) at main.c:24
24              *puiPointer = 20;
(gdb) list
19              /* local variables */
20              unsigned int *puiPointer;
21
22              /* body program */
23
24              *puiPointer = 20;
25
26              return 0;
27      }
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401115 in main (argc=1, argv=0x7fff6df4f038) at main.c:24
24              *puiPointer = 20;
(gdb) 
segmentation fault - Trying to access memory not initialized

#c. Trying to access memory out of bounds for the program

In most situations, if a program attempts to access (read or write) memory outside of its boundaries, a segmentation fault error will occur. A code example of a simple segmentation fault error is below:

/**
 * @file main.c
 * @author freecoder
 * @brief this program allow to handle a segmentation fault error
 *
 * @version 1.0
 * @date 8 Jan. 2022
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>

/* main program entry */
int main(int argc, char **argv)
{
	/* local variables */
	unsigned int uiArray[20];
	/* body program */
	uiArray[5000] = 1;
	return 0;
}

As shown bellow, the segmentation fault occurs after executing the out of bounds statement:

➜  Article-XX gcc -g main.c -o main
➜  Article-XX gdb ./main           
GNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./main...
(gdb) start
Temporary breakpoint 1 at 0x401111: file main.c, line 23.
Starting program: /home/others/Article-XX/main 
warning: Error disabling address space randomization: Operation not permitted
Temporary breakpoint 1, main (argc=1, argv=0x7ffdb68620f8) at main.c:23
23              uiArray[5000] = 1;
(gdb) list
18      {
19              /* local variables */
20              unsigned int uiArray[20];
21
22              /* body program */
23              uiArray[5000] = 1;
24
25              return 0;
26      }
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
main (argc=1, argv=0x7ffdb68620f8) at main.c:23
23              uiArray[5000] = 1;
(gdb) 
segmentation fault memory out of bounds

#d. Trying to modify string literals

/**
 * @file main.c
 * @author freecoder
 * @brief this program allow to handle a segmentation fault error
 *
 * @version 1.0
 * @date 8 Jan. 2022
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>

/* main program entry */
int main(int argc, char **argv)
{
	/* local variables */
	char* pucString = "Sample String 1";
	/* body program */
	pucString[14] = '2';
	return 0;
}

As shown bellow, we got a segmentation error because the compiler put the string constant “Sample String 1” in read-only memory while trying to modify the contents of that memory which fails as a result:

➜  Article-XX gcc -g main.c -o main
➜  Article-XX gdb ./main           
GNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./main...
(gdb) start
Temporary breakpoint 1 at 0x401111: file main.c, line 20.
Starting program: /home/others/Article-XX/main 
warning: Error disabling address space randomization: Operation not permitted
Temporary breakpoint 1, main (argc=1, argv=0x7ffc2ea212e8) at main.c:20
20              char* pucString = "Sample String 1";
(gdb) list
15
16      /* main program entry */
17      int main(int argc, char **argv)
18      {
19              /* local variables */
20              char* pucString = "Sample String 1";
21
22              /* body program */
23              pucString[14] = '2';
24
(gdb) n
23              pucString[14] = '2';
(gdb) 
Program received signal SIGSEGV, Segmentation fault.
main (argc=1, argv=0x7ffc2ea212e8) at main.c:23
23              pucString[14] = '2';
(gdb) 

segmentation fault modify string

#e. Using variable’s value as an address

A segmentation fault occurs when accidentally you are using a variable’s value as an address as you can see through the code example bellow:

/**
 * @file main.c
 * @author freecoder
 * @brief this program allow to handle a segmentation fault error
 *
 * @version 1.0
 * @date 8 Jan. 2022
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>

/* main program entry */
int main(int argc, char **argv)
{
	/* local variables */
	int iVariable;
	/* body program */
	scanf("%d", iVariable);
	return 0;
}

As shown in the terminal consol bellow, the segmentation occurs after the scans statement:

➜  Article-XX gcc -g main.c -o main
➜  Article-XX gdb ./main           
GNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./main...
(gdb) start
Temporary breakpoint 1 at 0x401135: file main.c, line 23.
Starting program: /home/others/Article-XX/main 
warning: Error disabling address space randomization: Operation not permitted
Temporary breakpoint 1, main (argc=1, argv=0x7fff418f9658) at main.c:23
23              scanf("%d", iVariable);
(gdb) list
18      {
19              /* local variables */
20              int iVariable;
21
22              /* body program */
23              scanf("%d", iVariable);
24
25              return 0;
26      }
(gdb) n
1
Program received signal SIGSEGV, Segmentation fault.
0x00007ff3e1d2201a in __vfscanf_internal (s=<optimized out>, format=<optimized out>, [email protected]=0x7fff418f9460, [email protected]=2)
    at vfscanf-internal.c:1895
1895    vfscanf-internal.c: No such file or directory.
(gdb) 
segmentation fault gemination fault using variable's value as address

#f. Stack overflow

The segmentation fault error may occur if the call stack pointer exceeds the stack bound in case of an infinite recursive function call:

/**
 * @file main.c
 * @author freecoder
 * @brief this program allow to handle a segmentation fault error
 *
 * @version 1.0
 * @date 8 Jan. 2022
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>

/* main program entry */
int main(void)
{
	/* local variables */
	/* body program */
	main();
	return 0;
}

As shown bellow, the segmentation fault error happened, due to a stack oveflow after calling the main function:

➜  Article-XX gcc -g main.c -o main
➜  Article-XX gdb ./main                                
GNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./main...
(gdb) start
Temporary breakpoint 1 at 0x40110a: file main.c, line 22.
Starting program: /home/others/Article-XX/main 
warning: Error disabling address space randomization: Operation not permitted
Temporary breakpoint 1, main () at main.c:22
22              main();
(gdb) list
17      int main(void)
18      {
19              /* local variables */
20
21              /* body program */
22              main();
23
24              return 0;
25      }
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
main () at main.c:22
22              main();
(gdb) 

segmentation fault Stack overflow

#2. How do you Fix Segmentation Faults?

Because segmentation faults are often associated with memory management issues or problematic pointer assignments, they can be fixed by making sure that the target application correctly handles these errors and does not attempt to read or write memory locations outside its own address space.

There are also certain procedures which you can follow in order to prevent and fix segmentation faults:

#a. How to Prevent Segmentation Faults?

Most segmentation faults occur due to memory access errors, so it’s important to make sure that pointers used by an application always reference valid data areas.

  • Check the reference of null memory.
  • Testing the code with Valgrind or Electric Fence
  • Assert() before dereferencing a suspective pointer, mainly a pointer embedded in a struct that is maintained in a container in a list or an array.
  • Always remember to initialize pointers properly.
  • Protect shared resources against concurrent access in multithreading by using a mutex or a semaphore.
  • Use of free() routine

#b. How to Fix Segmentation Faults?

There are some tools that you can use in order to fix the segmentation faults:

  • Gdb and core dump file
  • Gdb and backtrace.
  • Debugfs and Dmesg for kernel debugging

Conclusion

A segmentation fault is generally caused by a programming bug that tries to access either non-existent or protected memory. It can also happen as a result of dividing an integer by zero (causing the program counter to be redirected to nowhere), accessing memory that is out of bounds at an address that does not contain valid data or code.

Finally, when enabled on some operating systems (and in some embedded programming environments), the processor may issue an exception if a memory address contains a non-mapped machine code instruction.

I hope this post has clarified what segmentation faults on the x86 architecture imply and how to avoid them. Do not forget to share the information on social networks if you believe it is useful for others. If you have any queries, please do not hesitate to leave a comment and subscribe to our newsletter. Best of luck with your coding and see you in the next article!

The core file is normally called core and is located in the current working directory of the process. However, there is a long list of reasons why a core file would not be generated, and it may be located somewhere else entirely, under a different name. See the core.5 man page for details:

DESCRIPTION

The default action of certain signals is to cause a process to
terminate and produce a core dump file, a disk file containing an
image of the process’s memory at the time of termination. This image
can be used in a debugger (e.g., gdb(1)) to inspect the state of the
program at the time that it terminated.
A list of the signals which
cause a process to dump core can be found in signal(7).

There are various circumstances in which a core dump file is not produced:

   *  The process does not have permission to write the core file.  (By
      default, the core file is called core or core.pid, where pid is
      the ID of the process that dumped core, and is created in the
      current working directory.  See below for details on naming.) 
      Writing the core file will fail if the directory in which it is to
      be created is nonwritable, or if a file with the same name exists
      and is not writable or is not a regular file (e.g., it is a
      directory or a symbolic link).
   *  A (writable, regular) file with the same name as would be used for
      the core dump already exists, but there is more than one hard link
      to that file.
   *  The filesystem where the core dump file would be created is full;
      or has run out of inodes; or is mounted read-only; or the user has
      reached their quota for the filesystem.
   *  The directory in which the core dump file is to be created does
      not exist.
   *  The RLIMIT_CORE (core file size) or RLIMIT_FSIZE (file size)
      resource limits for the process are set to zero; see getrlimit(2)
      and the documentation of the shell's ulimit command (limit in
      csh(1)).
   *  The binary being executed by the process does not have read
      permission enabled.
   *  The process is executing a set-user-ID (set-group-ID) program that
      is owned by a user (group) other than the real user (group) ID of
      the process, or the process is executing a program that has file
      capabilities (see capabilities(7)).  (However, see the description
      of the prctl(2) PR_SET_DUMPABLE operation, and the description of
      the /proc/sys/fs/suid_dumpable file in proc(5).)
   *  (Since Linux 3.7) The kernel was configured without the
      CONFIG_COREDUMP option.

In addition, a core dump may exclude part of the address space of the
process if the madvise(2) MADV_DONTDUMP flag was employed.

Naming of core dump files

By default, a core dump file is named core, but the
/proc/sys/kernel/core_pattern file (since Linux 2.6 and 2.4.21) can
be set to define a template that is used to name core dump files.
The template can contain % specifiers which are substituted by the
following values when a core file is created:

       %%  a single % character
       %c  core file size soft resource limit of crashing process (since
           Linux 2.6.24)
       %d  dump mode—same as value returned by prctl(2) PR_GET_DUMPABLE
           (since Linux 3.7)
       %e  executable filename (without path prefix)
       %E  pathname of executable, with slashes ('/') replaced by
           exclamation marks ('!') (since Linux 3.0).
       %g  (numeric) real GID of dumped process
       %h  hostname (same as nodename returned by uname(2))
       %i  TID of thread that triggered core dump, as seen in the PID
           namespace in which the thread resides (since Linux 3.18)
       %I  TID of thread that triggered core dump, as seen in the
           initial PID namespace (since Linux 3.18)
       %p  PID of dumped process, as seen in the PID namespace in which
           the process resides
       %P  PID of dumped process, as seen in the initial PID namespace
           (since Linux 3.12)
       %s  number of signal causing dump
       %t  time of dump, expressed as seconds since the Epoch,
           1970-01-01 00:00:00 +0000 (UTC)
       %u  (numeric) real UID of dumped process

Понравилась статья? Поделить с друзьями:
  • Как найти поставщиков товара для маркетплейса
  • Как составить свой план работы на месяц
  • Как найти медиану прямоугольного прямоугольника
  • Как составить определение галактика
  • Область значения функции гиперболы как найти