Providing a Stack Trace

Michael Schwendt, Rahul Sundaram, Ankur Sinha Version unspecified Last review: 2014

Esta página ha sido tomada de la documentación anterior de Fedora Wiki.

Se ha limpiado para publicarla aquí en el Portal Fedora Docs, pero todavía no se ha revisado su precisión técnica.

Es probablemente

  • Contenga problemas de formato

  • Fuera de fecha

  • Necesite un poco de amor

Se agradecen mucho las revisiones de precisión técnica. Si desea ayudar, consulte el archivo README en el repositorio fuente para obtener instrucciones.

Solicitudes de extracción aceptadas en https://pagure.io/fedora-docs/quick-docs

Una vez haya corregido esta página, borre este anuncio.

Una traza de pila (stack trace) es uno de los recursos más importantes que puede proporcionar para ayudar a otros a depurar el fallo de una aplicación. Esta página detalla la importancia de las trazas de pila y describe varios métodos para obtenerlas.

Si experimenta un fallo, los pasos básicos para generar una traza de pila útil para aplicaciones estándar del entorno de escritorio Gnome son:

  • Instale los paquetes RPM -debuginfo apropiados antes del fallo (consulte la sección "¿Qué son los RPM de información de depuración y cómo los obtengo?" a continuación).

  • Espere a que se produzca el fallo o realice los pasos necesarios para reproducirlo.

  • En Fedora, ABRT (Automatic Bug Reporting Tool o Herramienta de Informe Automático de Errores en español) detectará automáticamente el fallo y obtendrá la traza de pila.

  • Incluya la traza de pila en su informe de error (consulte el documento "Cómo Presentar un Error" para obtener instrucciones completas).

Si ABRT no se inicia automáticamente, deberá iniciar el programa de un modo especial, utilizando un depurador (como gdb). Vea la sección Obtaining a stack trace using just GDB a continuación.

Se aplican instrucciones especiales para programas Java y Firefox.

¿Qué es una traza de pila?

Una traza de pila es una lista de las llamadas a funciones que conducen a algún punto del programa. Herramientas de depuración como gdb o bug-buddy pueden obtener trazas de pila de aplicaciones fallidas para que los desarrolladores puedan descubrir qué salió mal.

¿Qué aspecto tiene una traza de pila?

Una traza de pila típica es parecida a lo siguiente:

[New Thread 8192 (LWP 15167)]

0x420ae169 in wait4 () from /lib/i686/libc.so.6
.
.
.

Una mejor traza de pila, con símbolos de información de depuración (ver más abajo) se ve así:

0x000000350a6c577f in *__GI___poll (fds=0xe27460, nfds=9, timeout=-1) at ../sysdeps/unix/sysv/linux/poll.c:83
83          return INLINE_SYSCALL (poll, 3, CHECK_N (fds, nfds), nfds, timeout);

.
.
.

Observe que aparecen los nombres de archivos y los números de línea donde se llaman las funciones.

¿Qué son los símbolos de depuración y por qué son importantes?

Cuando un programa se compila con modificaciones especiales para generar símbolos de depuración (el modificador -g del compilador), almacena información adicional en el archivo del programa. Esta información puede ser utilizada para generar una traza de pila que contenga mucha más información, como el número de línea exacto del archivo fuente donde algo salió mal. Sin esta información, es muy difícil determinar qué salió mal observando la traza de pila.

¿Qué son los RPM de información de depuración y cómo los obtengo?

Fedora incluye un tipo especial de RPM llamados RPMs de información de depuración (debuginfo). Estos RPM creados automáticamente que contienen la información de depuración de los archivos del programa pero almacenados en un archivo externo. Todas las herramientas que manejan información de depuración saben cómo buscar automáticamente en estos archivos. Esto le permite instalar fácilmente información de depuración cuando la necesite. Debe instalar la versión y arquitectura exactas de debuginfo correspondientes a la aplicación que está intentando depurar.

Ejemplo: Verificando Versión y Arquitectura Coincidentes

[warren@computer ~] $ rpm -q --qf '%{name}-%{version}-%{release}.%{arch}\n' gaim gaim-debuginfo
gaim-2.0.0-0.26.beta5.i386
gaim-debuginfo-2.0.0-0.26.beta5.i386

Cada paquete que contenga binarios en su distribución tiene un paquete debuginfo correspondiente.

Instalando RPMs debuginfo usando DNF.

debuginfo-install es un útil complemento, perteneciente al paquete dnf-plugins-core, que habilita automáticamente los repositorios de debuginfo y descarga todos los paquetes de debuginfo necesarios . Usted puede hacer:

$ dnf debuginfo-install <pkg-spec>

para instalar todos los paquetes debuginfo necesarios para el paquete <pkg-spec>.

Para instalar únicamente el conjunto mínimo de paquetes debuginfo, use la lista de paquetes del comando (sin instalar nada) para obtener los nombres de los paquetes debuginfo y sus respectivos repositorios. Luego, construya el comando de instalación de acuerdo con el siguiente ejemplo:

$ dnf --enablerepo=fedora-debuginfo --enablerepo=updates-debuginfo install <pkg-spec>-debuginfo

Esto es útil cuando no desea instalar paquetes debuginfo para todas las dependencias del paquete a depurar, ya que a menudo no se requieren.

Instalando RPMs debuginfo usando yum.

El comando debuginfo-install es una herramienta útil, perteneciente al paquete yum-utils, que habilita automáticamente los repositorios de debuginfo y descarga los paquetes debuginfo necesarios. Usted puede hacer:

$ debuginfo-install foo

para instalar todos los paquetes debuginfo necesarios para el paquete foo.

Para instalar únicamente el conjunto mínimo de paquetes debuginfo, use la salida de debuginfo-install (sin instalar nada) para obtener los nombres de los paquetes debuginfo y sus respectivos repositorios. Luego, construya el comando de instalación de acuerdo con el siguiente ejemplo:

$ yum --enablerepo fedora-debuginfo,updates-debuginfo install foo-debuginfo

Esto es útil cuando no desea instalar paquetes debuginfo para todas las dependencias del paquete a depurar, ya que a menudo no se requieren.

Instalando RPMs debuginfo manualmente.

Estos paquetes pueden descargarse desde los espejos normales de Fedora en el subdirectorio "debug" del directorio de la arquitectura. Por ejemplo, los paquetes debuginfo para la última versión de desarrollo están disponibles en http://mirrors.fedoraproject.org/publiclist/Fedora/development/ . Utilice el espejo más cercano a usted para realizar la descarga.

Empaquetadores.

Si usted es un empaquetador buscando información acerca de los RPMs debuginfo, consulte el documento Debuginfo packages.

How do I generate a backtrace?

First make sure that you have installed the debuginfo packages for the application you are debugging and all related libraries. A developer often tells you to install specific debuginfo packages because he can tell from a stack trace which libraries are involved in the crash. See below for recommended packages for some common type of applications.

There are several ways to get a stack trace:

What debuginfo packages should I install?

At the very least you will need to install the debuginfo package for the application that is crashing. You can find out what package this application is in by typing rpm -qf path-of-program.

For certain types of programs it is also very useful to install a couple of default packages that are useful for almost all stack traces:

  • Gnome applications and applications using Gtk+: glib2-debuginfo, pango-debuginfo, gtk2-debuginfo

  • KDE applications: qt-debuginfo, kdelibs-debuginfo

Obtaining a stack trace using just GDB

If you are running a Java program such as Eclipse or Tomcat, the situation is a bit more complicated - see Java programs for details.

First, run the following command to start gdb:

gdb name-of-program

Where name-of-program is the name of the program that crashed (for example: /usr/bin/gnome-panel).

Then, at the gdb prompt, type:

run

If you need to give any arguments to the program, give them after the run command, like:

run --argument

Once the program is running, reproduce the crash and go back to the terminal where you ran gdb. The gdb prompt should be shown - if not, hit Control+C to break into the debugger. At the gdb debugger prompt, type:

thread apply all bt full

If that does not work (meaning that you don’t get any output—​this may be the case in programs which are not multi-threaded), type <code>bt</code> instead. If you still do not have any output, read [[#special| this note]] about obtaining a stack trace under special circumstances. The output is the stack trace. Cut and paste all of it into a text file.

You can quit gdb by typing quit.

Sometimes, the trace can be quite large and it is difficult to copy and paste it. In such situations, storing the trace to a file is convenient:

gdb
> run
# program crashes
> set logging file backtrace.log
> set logging on
> thread apply all bt full
> set logging off
> quit

Obtaining a stack trace from a core dump

If the program that crashes leaves a core dump, you can use GDB to obtain a stack trace. Core dumps are saved in a file on your hard disk and are usually named something along the lines of "core" or "core.3124". To obtain a stack trace from one of these files, run the following command:

gdb name-of-program core-file-name

Where name-of-program is the name of the program that crashed (for example: /usr/bin/gnome-panel), and core-file-name is the name of the core file that contains the core dump (for example: core.7812).

Then, at the gdb prompt, type:

thread apply all bt full

If that does not work (meaning that you don’t get any output—​this may be the case in programs which are not multi-threaded), type bt instead. If you still do not have any output, read this note about obtaining a stack trace under special circumstances. The output is the stack trace. Cut and paste all of it into a text file.

You can quit gdb by typing quit.

Note that creation of core files is disabled in Fedora by default (in /etc/profile). To enable them for a shell session, type at the shell prompt:

ulimit -c unlimited

How to install ABRT

If you installed Fedora via a LiveCD image, ABRT should already be installed. You should be able to start it in Applications → System Tools → Automatic Bug Reporting Tool. If ABRT is not installed, for whatever reason, you can install it manually by doing the following on a command line:

$ su -c 'dnf install abrt'

or go to SystemAdministrationAdd/Remove Software in Gnome, and type`abrt` in the search box and select Find. Select the abrt package and apply the changes.

Configuring ABRT for Bugzilla

Go to ApplicationSystem ToolsAutomated Bug Reporting Tool and select it to start it manually. Once the GUI window appears, choose EditPlugins and from the Settings window, scroll down, highlight Bugzilla and choose Configure Plugin. The Bugzilla URL should be https://bugzilla.redhat.com and enter your own Bugzilla login and password in the proper boxes.

If you do not yet have a Bugzilla account, now is the time to get one, just go to the URL as displayed on that page and create a new account.

Next time you have a program crash, and ABRT triggers, when you hit Report, ABRT will be able to automatically log in to Bugzilla and submit a Bug Report for you.

Using ABRT

(The following assumes Gnome as the desktop …​ someone else will have to update for KDE/Others)

If ABRT detects a crashed program, you will get an ABRT alert. This will be visually indicated by a flashing red light in the system tray. Left click on the alert light, and the Automatic Bug Reporting Tool should start, displaying all of the crashes it has registered. To report the bug, right click on it and choose report. ABRT will gather the logs it needs to submit with the bug and will then let you know it is going to submit a bug on your behalf. If you have configured ABRT as in the previous section, it will then ask you to verify whether or not to include the various logs, then will automatically go out to Bugzilla and open a bug, attaching the logs into the bug. It will then show you the bug number so that you can track the bug as it is worked on.

Configuring ABRT when missing Debuginfos

When you right click on a bug in ABRT and choose Report, ABRT will attempt to go out and retrieve the logs it will need to send as part of the bug report. The developers have added code to detect whether or not symbolic traces are included within the backtrace, and if it detects that there are none, ABRT will alert you of this, and will show you the command to run. This is the same as what is shown in the debuginfo section.

Special cases

Programs running as another user

If you do not get any output from gdb after typing thread apply all bt or bt, it may be because the program is run as root or as another user. In GNOME for example, this is the case when running gnome-games. In such cases, you will need to be root in order to capture a trace. So, quit gdb, login as root, and then repeat the steps to obtain a stack trace.

Firefox

  • Install Firefox and Xulrunner debug info packages - run ebuginfo-install firefox xulrunner as root on the command line.

  • Run firefox -g on the command line. That will start firefox running inside of gdb debugger.

  • In gdb, you should see gdb prompt (gdb). Issue the command run -safe-mode. A dialog window will pop up, disable all add-ons here and continue in safe mode.

  • Do whatever is necessary to make firefox crash and follow the instructions above for gdb usage.

  • When Firefox crashes, obtain the backtrace and attach it to bugzilla.

Thunderbird

It’s almost the same as for Firefox, just the debug info packages are different. Install them by "debuginfo-install thunderbird" command as root on the console.

Java programs

See document Troubleshooting Java Programs for info on getting stack traces from programs running in Java.

Daemons and their spawn

You will need to gather the backtrace from the core file.

Make sure your daemon’s initscript isn’t forbidding dumping core files to the disk. Add the line DAEMON_COREFILE_LIMIT=unlimited to its configuration file in /etc/sysconfig. For example, the Bluetooth daemon (hcid) uses /etc/sysconfig/bluetooth.

Then setup the kernel so that the core dump is written to a known location such as /tmp. As root, run:

echo /tmp/core > /proc/sys/kernel/core_pattern

To make this change permanent, add that line to /etc/sysctl.conf:

kernel.core_pattern = /tmp/core

And run sysctl -p to apply it straight away.

A full list of possible patterns for the core file are available at in the sysctl/kernel.txt kernel Documentation .

Finally, after reproducing your problem, you can double-check which binary created the core file with file /tmp/core.1234. Then run gdb on the file to create a post-mortem stack trace:

gdb /path/to/binary/file /tmp/core.1234

and follow the instructions above for gdb usage.

you can test whether dumping a core file would work by running kill -SEGV 1234 where 1234 is the PID of the program you’re testing.

Other tools

Valgrind

The brilliant tool valgrind is often able to say more about what is going wrong; it can give a strack trace to the point where things start to go wrong, which might be long time before the program actually crashes. Programs run through valgrind will run an order of magnitude slower and use more memory, but it will be buddyamazingly usable.

With valgrind installed (`dnf install valgrind) you can use it on a program:

valgrind name-of-program program-arguments

With debuginfo installed stacktraces will use symbolic names. See [http://valgrind.org/ valgrind.org] for more info and tips and tricks.

strace

strace can track all system calls made by a program, which can also be helpful in debugging, though it cannot produce stack traces. Install with dnf install strace, and see man strace for details.

The situation is a bit improved. Now stack trace feature is implemented (strace -k). Though it is disabled when building because the implementation is not stable on i386.

References