Dump stack in linux

Linux: создание coredump памяти процесса, systemd-coredump и Debian

Возникла необходимость получить дамп РНР-процесса на Debian 9.

Рассмотрим механизм ядра, позволящий создать дамп, и настройку создания дампов в Linux.

Ниже будем говорить о создании дампа памяти процесса в Linux, а не дампа ядра при kernel panic — там он иной, см. Kdump на Arch Wiki.

Linux Core Dump

Ядро создаёт дамп памяти процесса, если он выполнил недопустимую операцию, и должен быть остановлен.

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

Список таких сигналов задаётся в макросе SIG_KERNEL_COREDUMP_MASK :

Который используется в другом макросе — sig_kernel_coredump :

Который срабывает в случае Fatal-ошибок, и вызывает do_coredump() :

Ну а сама do_coredump() создаёт дамп.

Сигналы и создание дампа

Проверим работу дампа.

Берём простой код на Си:

Собираем, и запускаем:

Во второй консоли — отправляем один из сигналов, например SIGSEGV (Segmentation violation), код 11:

В окне с приложением проверяем:

Проверяем файл дампа:

Аналогично можно создать дамп практически любого процесса, например — запустим sleep :

GDB — создать core dump

Кроме отправки сигнала — с помощью gdb , а именно gcore , можно создать дамп работающего процесса:

GDB — прочитать core dump

Что бы просмотреть содержимое — можем использовать gdb , которому передаём путь к исполняемому файлу, процесс которого сгенерировал дамп, и путь к самому файлу дампа:

kernel.core_pattern

Во время создания дампа — ядро проверяет параметр kernel.core_pattern , который определяет то, как будет обработан дамп.

Тут можно задать путь и имя файла, в который будет записан дамп, либо передать создание дампа внешнему обработчику, например systemd-coredump (рассмотрим ниже).

См. документацию Naming of core dump files тут>>>.

Из наиболее используемых опций тут:

  • %e executable filename (without path prefix)
  • %p PID of dumped process, as seen in the PID namespace in which the process resides
  • %t time of dump, expressed as seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC)

Собственно файл /tmp/coredump-make_dump.2714790, который мы открыли в GDB, и состоит из kernel.core_pattern = /tmp/coredump-%e.%p :

  1. /tmp каталог
  2. %e — имя файла начинается с coredump + имя исполняемого файла make_dump
  3. %p — и PID убитого процесса — 2714790

Помимо указания на путь к файлу и созданию его имени — в core_pattern можно указать пайп | , и передать данные через него, например в /dev/null или в хендлер типа systemd-coredump .

limits.conf

Кроме имени файла — ядро проверит значение soft и hard лимитов для core в /etc/security/limits.conf :

Либо проверяем в рабочем окружении:

Лимиты конкретного процесса можно получить через его дескриптор в /proc :

fs.suid_dumpable

Иногда дамп может не создаваться, если процесс в процессе выполнения выполнил запрос на смену UID, например через вызов setuid() .

Определяется флагом fs.suid_dumpable :

Может принимать значение 0, 1 или 2, см. man proc:

  • 0: (default) This provides the traditional (pre-Linux 2.6.13) behaviour. A core dump will NOT be produced for a process which has changed credentials (by calling seteuid or similar) or whose binary does not have read permission enabled.
  • 1: («debug«) All processes dump core when possible.
  • 2: («suidsafe«) Any binary which normally would not be dumped (see «0» above) is dumped readable by root only.

systemd-coredump

В systemd , разумеется, добавлен свой обработчик дампов — уже упомянутый systemd-coredump .

Читайте также:  Чем операционная система windows отличается от системы ms dos

На Arch Linux он используется по-умолчанию, на Debian 9 ставим из репозитория:

Файл параметров — /etc/systemd/coredump.conf .

После установки настраиваем ядро — через пайп передаём создание дампа в systemd-coredump :

Создаём дамп какого-то процесса:

coredumpctl

Для работы с дампами через systemd-coredump — используем coredumpctl :

В колонке SIG сразу видим код сигнала, с которым был убит процесс, в данном случае 11 == SIGSEGV .

Сами файлы дампов systemd-coredump сохраняет в /var/lib/systemd/coredump :

Просмотреть дамп — передаём условие для MATCH, например — PID:

Источник

Отладка дампов Linux

Эта статья относится к: ✔️ пакету SDK для .NET Core 3.0 и более поздних версий

Сбор дампов в Linux

Два рекомендуемых способа сбора дампов в Linux:

  • Средство CLI dotnet-dump
  • Переменные среды для сборки дампов при аварийном завершении

Управляемые дампы с помощью dotnet-dump

Средство dotnet-dump просто в использовании и не зависит от каких-либо отладчиков машинного кода. dotnet-dump работает на различных платформах Linux (например, Alpine или ARM32/ARM64), где традиционные средства отладки могут быть недоступны. Однако dotnet-dump фиксирует только управляемое состояние, поэтому его нельзя использовать для отладки в машинном коде. Дампы, собранные dotnet-dump , анализируются в среде с той же ОС и архитектурой, в которой был создан дамп. Средство dotnet-gcdump можно использовать в качестве альтернативного варианта, которое фиксирует только сведения о куче GC, но создает дампы, которые можно проанализировать в Windows.

Дампы ядра с помощью createdump

Вместо dotnet-dump , создающего только управляемые дампы, createdump рекомендуется для создания основных дампов в Linux, содержащих как собственные, так и управляемые данные. Другие средства, такие как gdb или gcore, можно также использовать для создания основных дампов, однако они могут не учитывать состояние, необходимое для управляемой отладки, что приводит к неизвестному типу или именам функций во время анализа.

Средство createdump устанавливается вместе со средой выполнения .NET Core. Его можно найти рядом с libcoreclr.so (обычно в папке /usr/share/dotnet/shared/Microsoft.NETCore.App/[версия]). Средство использует идентификатор процесса для получения дампа в качестве основного аргумента, а также может принимать необязательные параметры, указывающие, какой тип дампа следует сохранять (по умолчанию используется малый дамп с кучей). Возможны следующие значения.

Исходный файл трассировки для преобразования. По умолчанию используется значение trace.nettrace.

Параметры

-f|—name

Файл, в который записывается дамп. Значение по умолчанию — «/tmp/coredump.%p», где % p — это идентификатор целевого процесса.

-n|—normal

-h|—withheap

Создание минидампа с кучей (по умолчанию).

-t|—triage

Создание минидампа для рассмотрения.

-u|—full

Создайте полного дампа ядра.

-d|—diag

Включение диагностических сообщений.

Для сбора дампов ядра требуется либо возможность SYS_PTRACE , либо createdump необходимо запустить с помощью sudo или su.

Анализ дампов в Linux

Как управляемые дампы, собранные с помощью dotnet-dump , так и дампы ядра, собранные с помощью createdump , можно проанализировать с помощью средства dotnet-dump , используя команду dotnet-dump analyze . dotnet dump требует, чтобы среда, в которой анализируется дамп, использовала ту же ОС и архитектуру, что и среда, в которой был записан дамп.

Кроме того, LLDB можно использовать для анализа основных дампов в Linux, что позволяет выполнять анализ как управляемых, так и собственных кадров. LLDB использует расширение SOS для отладки управляемого кода. Средство dotnet-sos CLI можно использовать для установки SOS, в котором содержится много полезных команд для отладки управляемого кода. Чтобы проанализировать дампы .NET Core, для LLDB и SOS требуются следующие двоичные файлы .NET Core из среды, в которой был создан дамп.

  1. libmscordaccore.so
  2. libcoreclr.so
  3. dotnet (узел, используемый для запуска приложения)

В большинстве случаев эти двоичные файлы можно скачать с помощью средства dotnet-symbol . Если необходимые двоичные файлы невозможно загрузить с помощью dotnet-symbol (например, если используется частная версия .NET Core, построенная на основе источника), может потребоваться скопировать перечисленные выше файлы из среды, в которой был создан дамп. Если файлы не расположены вместе с файлом дампа, можно использовать команду LLDB/SOS setclrpath

, чтобы задать путь, из которого они должны быть загружены, и setsymbolserver -directory

, чтобы задать путь для поиска файлов символов.

После того как необходимые файлы будут доступны, можно загрузить дамп в LLDB, указав узел dotnet в качестве исполняемого файла для отладки:

В приведенной выше командной строке — это путь к дампу для анализа, а — это собственная программа, запускающая приложение .NET Core. Обычно это двоичный файл dotnet , если приложение не является автономным. В этом случае это имя приложения без расширения DLL.

Читайте также:  Проверить наличие библиотеки linux

После запуска LLDB может потребоваться использовать команду setsymbolserver , чтобы указать правильное расположение символов ( setsymbolserver -ms , чтобы использовать сервер символов корпорации Майкрософт, или setsymbolserver -directory

для указания локального пути). Собственные символы можно загрузить, запустив loadsymbols . На этом этапе для анализа дампа можно использовать команды SOS.

Источник

Red Hat Customer Portal

Log in to Your Red Hat Account

Your Red Hat account gives you access to your profile, preferences, and services, depending on your status.

If you are a new customer, register now for access to product evaluations and purchasing capabilities.

Need access to an account?

If your company has an existing Red Hat account, your organization administrator can grant you access.

Red Hat Account

Customer Portal

For your security, if you’re on a public computer and have finished using your Red Hat services, please be sure to log out.

Select Your Language

How do I generate a Java thread dump on Linux/Unix?

Environment

  • Java
  • Linux and most Unix-like environments

Issue

  • How do I generate a thread dump in JBoss while running on Linux?
  • How do I generate a JBoss stack trace on Linux?
  • How do I redirect output of kill -3 to a file?
  • JBoss has high cpu usage, freezes, hangs, or doesn’t release idle threads, how can I get a thread dump to troubleshoot?
  • JMS messages are getting lost, how can I generate a thread dump to investigate?
  • Unable to take thread dump using Kill -3 in server.log or console.log

Resolution

Disclaimer: Links contained herein to an external website(s) are provided for convenience only. Red Hat has not reviewed the links and is not responsible for the content or its availability. The inclusion of any link to an external website does not imply endorsement by Red Hat of the website or their entities, products or services. You agree that Red Hat is not responsible or liable for any loss or expenses that may result due to your use of (or reliance on) the external site or content.

Choose one of the following methods to generate a Java thread dump on Unix:

Note: Typically gc logging is provided whenever thread dumps are captured. Excessive gc can cause threading issues, so gc and thread dump analysis go hand in hand.

Option 1: OpenJDK / Sun JDK

Use jps -lv to find the Java process ID for issuing kill -QUIT or kill -3 .
Be sure the -Xrs JVM option is not being used, as it causes SIGQUIT and SIGWAITING signals to be ignored. Running kill -3 sends a SIGQUIT signal to the JVM, so using this option will cause kill -3 to be ignored. See Java Application launcher.

If using OpenJDK or Sun JDK 1.6 or later, using jstack is an option. This is useful when redirecting standard out to a file is problematic for some reason (e.g. it is not desirable to restart the JVM just to redirect standard out). Execute the following, passing in the Java process ID:

Note the process ID number of the Java process (e.g. using top , a grep on ps -axw , etc.) and send a QUIT signal to the process with the kill -QUIT or kill -3 command 1 . For example:

Option 2: kill -3 Linux script (not-continuous)

Download either threaddump_linux.sh.tar.gz or threaddump_solaris.sh.tar.gz , and extract the script. Make the script executable with chmod 755 .

The script will capture a series of 6 thread dumps spaced 20 seconds apart (this can be modified as needed), passing in the Java process ID as an argument. For example:

Be sure to test the script before the issue happens to make sure it runs properly in your environment.

Option 3: kill -3 Linux script (continuous)

Download either threaddump_linux-continuous.sh.tar.gz or threaddump_solaris-continuous.sh.tar.gz , and extract the script. Make the script executable with chmod 755 .

It will capture thread dumps spaced 20 seconds apart (modify as needed), passing in the Java process ID as an argument. For example:

Читайте также:  Как создать сценарий windows cmd

Be sure to test the script before the issue happens to make sure it runs properly in your environment.

Option 4: JBoss EAP Parameter

Use the below command to start JBoss instance and then use kill -3 to generate the thread dumps.

If the Java application is started with a service script that logs console output, the thread dumps will be in the console log. Otherwise, redirect stdout to a file on startup.

This will redirect your output/dump to the file console specified in the above command.

Option 5: jstack linux script (continuous)

Download linux_jstack-continuous.tar.gz , and extract the script. Make the script executeable with chmod 755
It will use jstack to capture a series of 6 thread dumps spaced 20 seconds apart (modify as needed), passing in the Java process ID as an argument. Make sure you set JAVA_HOME in this script. It generates a file called jstack_threaddump.out in the directory where this script is executed. For example:

Option 6: IBM J9

IBM J9 has it own monitoring tool, IBM Thread and Monitor Dump Analyzer for Java — TMDA. However, kill -3 PID can still be used to generate a thread dump, as described in SeeOption 1: OpenJDK / Sun JDK kill -3 section.

More information can be found in OpenJ9 Docs — Java Dumps.

Notes

  • Verify that the Java process is still running with the ps aux command ( R or S state in STAT column) . For example, jstack -F

puts the target Java process in a «trace stop» (T) state. Threads in the (T) state will receive the signal for a thread dump; however, output will be delayed until the process continues.

  • You need to make sure to execute jstack command from the same user as the java process. Please see Getting «Unable to open socket file» message when executing jstack / jmap / jcmd and unable to generate a thread dump / heap dump for more details.
  • There are known bugs related to using other jstack options (e.g. -F , -m , etc.) and/or thread dump tools are not able to parse the output, so if any other options besides -l are proposed, be sure to test capturing and parsing the output.
  • In some circumstances running jstack might cause a performance impact. It is reported that a slowness in response time can be observed when running jstack in some scenarios.
  • If you want to take thread dumps to identify which Java threads consume high cpu, please see How do I identify high CPU utilization by Java threads on Linux/Solaris and use the attached sample script in the article.
  • JBoss EAP 5.x

    To redirect stdout to a file on startup:

    If having trouble redirecting stdout , modify $JBOSS_HOME/bin/run.sh and change the line:

    Save and restart JBoss normally. Now kill -3 or kill -QUIT should create a thread dump in the file console.log .

    JBoss EAP 7.x/6.x

    The recommendation is to use jstack . See Option 5: jstack Linux script(continuous).

    JBoss Fuse 6

    If you are capturing thread dumps from a child container, note that the process is different to the root container. Be sure to check the process ID (PID) using ‘ps’ or similar before selecting the PID to run the script against. eg:

    Note: kill -3 command does not produce output directly to a file from the command line. Instead, it produces output to the console output of the process it was invoked on. For a JBoss EAP domain mode server, its console output should be captured in the host controller log by default. ↩

    Attachments

    • Product(s)
    • Red Hat JBoss Enterprise Application Platform
    • Component
    • dump
    • Category
    • Troubleshoot
    • Tags
    • eap
    • java
    • jboss
    • jboss_eap
    • jvm
    • tomcat

    This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.

    Источник

    Оцените статью