Creating a Backtrace with GDB/ru

From Lazarus wiki
Jump to navigationJump to search

Deutsch (de) English (en) 日本語 (ja) русский (ru)

Причины для создания обратной трассировки

Отчеты об ошибках

Файлы обратной трассировки могут быть очень полезны при отправке отчетов об ошибках. Они, несомненно, повысят вероятность того, что ошибка будет исправлена раньше.

Помоги себе найти проблему

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

Это просто весело!!!

Хорошо, это может быть преувеличением, но делать обратную трассировку просто весело!

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

Создание Backtrace

Light bulb  Примечание: Mac-пользователям следует использовать lldb вместо gdb.

Чтобы создать обратную трассировку с помощью GDB (Gnu DeBugger):

  1. У вас должна быть программа GDB. Она доступна на большинстве установленных ОС-*nix. Если вы скачали версию fpc или Lazarus для Windows, GDB уже включен в поставку. В Lazarus он установлен, как отладчик, по умолчанию. Посмотрите в Tools (Сервис) -> Options (Параметры) -> Debugger (Отладчик) -> General Tab (Общие). Путь по умолчанию для GDB в Windows: c:\lazarus\mingw\bin\gdb.exe.
  2. GDB должен быть прописан в переменной окружения PATH. Если это Windows, из командной строки введите (пример): установите PATH =% PATH%; set PATH=%PATH%;c:\lazarus\mingw\bin\
  3. Программа, которую вы хотите отладить, ДОЛЖНА иметь отладочную информацию, включенную в исполняемый файл. Если вы используете "strip", "upx", компилируете с "Xs" или использовали какой-либо другой exe-упаковщик, это не сработает!

Прим.перев.: если вы используете транковые svn-сборки FPC для Windows, то после компиляции gdb.exe в них отсутствует.Его необходимо скопировать (вместе с некоторыми другими утилитами) из папки <Stable-FPC RootDir>\bin\ дистрибутива стабильной версии компилятора (при помощи которой вы и собираете транк FPC, например, на момент перевода статьи это fpc 3.0.4) в папку <Trank-FPC RootDir>/bin/$(TargetCPU)-$(TargetOS)/, где находится fpc.exe.


Очень короткая инструкция

Linux терминал:

  $ cd program_folder
  $ gdb program_name
  run

Если случилась AV. Пишем:

  bt

Напрямую из окна стека вызовов

Чтобы захватить Backtrace изнутри Lazarus, убедитесь, что вы скомпилировали программу, включающую оба параметра "Generate debug info for GDB" (Генерировать отладочную информацию для GDB) и "Display line numbers in run-time error backtraces (-gl)" (Выдавать номера строк в ошибках времени исполнения (-gl)), и вы правильно настроили GDB в параметрах отладчика.

  1. Запускайте ваше приложение, пока не появится проблема
  2. Если появится диалоговое окно с предупреждением о проблеме, показывающее пару кнопок: "Break" (Прервать) и "Continue" (Продолжить), нажмите кнопку "Break".
  3. Откройте окно Call Stack (Стек вызовов) (Menu View (Вид) -> Debug Windows (Окна отладки) ->Call Stack (Стек вызовов)).
  4. Просмотрите список вызовов, при необходимости нажимая "(+)More" (Подробнее)
  5. Нажмите кнопку "Copy All" (Копировать все).
  6. Backtrace теперь в вашем буфере обмена и готов к вставке.

Пользователи Windows

1. Откройте окно приглашения MS-DOS

2. Перейдите на диск, на котором у вас есть exe:

C: {нажмите enter}

3. Перейдите в каталог, содержащий exe:

cd \myprograms\Project1 {нажмите enter}

4. Загрузите вашу программу с использованием GDB:

gdb Project1.exe {нажмите enter}

Пользователи Linux/BSD

1. Откройте вашу любимую программу Terminal

2. Перейдите в каталог, содержащий исполняемый файл:

cd $HOME/myprograms/project1 {нажмите enter}

3. Загрузите вашу программу с использованием GDB:

gdb project1 {нажмите enter}

Mac OS X

GDB по умолчанию недоступен для macOS. Вы можете рассмотреть возможность использования отладчика MacOS по умолчанию lldb.

Mac OS X: Графическое приложение

1. Если это еще не сделано: создайте комплект приложений (Project (Проект)/ Project Options (Параметры проекта)/ Application ()Приложение/ Create Application Bundle (Создать комплект приложений))

2. Open your favorite Terminal program

3. Change to the directory containing the application bundle / executable:

cd $HOME/myprograms/project1 {press enter}

4. Load your program with GDB:

gdb project1.app/Contents/MacOS/project1 {press enter}

Mac OS X: Non graphical application, command line program

1. Open your favorite Terminal program

2. Change to the directory containing the executable:

cd $HOME/myprograms/project1 {press enter}

3. Load your program with GDB:

gdb project1 {press enter}

GDB ready to accept commands

You should now see a prompt that looks something like this:

GNU gdb 6.3.50.20050217-cvs
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "i686-pc-linux-gnu".
(gdb) _

Let GDB stop when an exception is raised

(gdb) break fpc_raiseexception {press enter}

Now, run your program:

(gdb) run {press enter}

Your program will run normally, until it crashes or causes an error.

When your program crashes instead of the usual error "Access Violation" or "Division by Zero" your program will just seem to stop, not respond and not repaint itself. This is because gdb has caught the error and is waiting for you to tell it what to do.

Switch over to your MS-DOS window or Terminal and you should have a screen something like this:

Program received signal SIGFPE, Arithmetic exception.
0x080733aa in TFORM1__BUTTON1CLICK (SENDER=0x403d8bd8, this=0x403d77d8) at unit1.pas:36
Current language:  auto; currently pascal
(gdb) _

To create a backtrace now type:

backtrace {press enter}

or

bt {press enter}

You should now have a screen that looks something like this:

#0  0x080733aa in TFORM1__BUTTON1CLICK (SENDER=0x403d8bd8, this=0x403d77d8) at unit1.pas:36
#1  0x080ecd78 in TCONTROL__CLICK (this=0x403d8bd8) at control.inc:1768
#2  0x081274bd in TBUTTONCONTROL__CLICK (this=0x403d8bd8) at buttoncontrol.inc:57
#3  0x08129171 in TCUSTOMBUTTON__CLICK (this=0x403d8bd8) at buttons.inc:186
#4  0x08129198 in TCUSTOMBUTTON__WMDEFAULTCLICKED (MESSAGE={MSG = 1031, WPARAM = 
        136821192, LPARAM = -1073747812, RESULT = 1075866658, WPARAMLO = 47560, 
        WPARAMHI = 2087, LPARAMLO = 59548, LPARAMHI = 49151, RESULTLO = 27682, RESULTHI = 16416}, 
        this=0x403d8bd8) at buttons.inc:198
#5  0x0805bbf7 in SYSTEM_TOBJECT_$__DISPATCH$formal ()
#6  0x080ec6e0 in TCONTROL__WNDPROC (THEMESSAGE={MSG = 1031, WPARAM = 136821192, 
        LPARAM = -1073747812, RESULT = 1075866658, WPARAMLO = 47560, WPARAMHI = 2087, 
        LPARAMLO = 59548,  PARAMHI = 49151, RESULTLO = 27682, RESULTHI = 16416}, 
        this=0x403d8bd8) at control.inc:1447 
#7  0x080e4ed9 in TWINCONTROL__WNDPROC (MESSAGE={MSG = 1031, WPARAM = 136821192, 
        LPARAM = -1073747812, RESULT = 1075866658, WPARAMLO = 47560, WPARAMHI = 2087, 
        LPARAMLO = 59548,  PARAMHI = 49151, RESULTLO = 27682, RESULTHI = 16416}, 
        this=0x403d8bd8) at wincontrol.inc:2154
#8  0x08161955 in DELIVERMESSAGE (TARGET=0x403d8bd8, AMESSAGE=void) at gtkproc.inc:3242
#9  0x0818897c in GTKWSBUTTON_CLICKED (AWIDGET=0x8285380, AINFO=0x40453794) at gtkwsbuttons.pp:112
... { Truncated for simplicity} Complete listing here
(gdb) _
Light bulb  Примечание: If the backtrace is too long you will be prompted to press enter for the next page of the backtrace until it is complete

The information displayed here has the sequence of events up to where the error occured. Understanding a Backtrace

To exit GDB (and your program) you may now type:

quit {press enter}

Or to continue running until the next exception type:

cont {press enter}

Hint: At any time while your program is running you may press Ctrl+C (from the Terminal or MS-DOS prompt) to get a "(gdb) _" prompt

Light bulb  Примечание: The use of an english keyboard layout can prevent problems with gdb (e.g. if you type special characters like ' \ ').

using lldb on Mac

start lldb

lldb

load your project

target create project1.app/MacOs/Contents/project1

set a breakpoint You may skip this, if the project crashes, rather than raising an fpc exception) If there are expected exceptions, that will be handled by try except, then use "c" to continue

breakpoint set --func fpc_raiseexception

run it

r

when it stops, get the backtrace

bt

show locals for different frames (replace 1 in frame select, with different frames, e.g. top 3 or top 5)

frame select 1
frame variable -P 1

Getting the Backtrace out of the terminal and into an email

Currently we have made a backtrace and seen it in the Terminal(or MS-DOS prompt) but how do I get it into an email? There are two ways that I know of:

  1. Use the copy/paste functionality of your Terminal(or MS-DOS prompt)
  2. Redirect the output of gdb to a file like so:
gdb project1 > output.txt

Now you can open the file and copy/paste it into your email.

Caveat: The second method requires that you type blindly. So you would type "run" to start the program and "backtrace" to make a backtrace like normal but nothing would show up on the screen.

Exception: On Linux you can get around not being able to see with the following command:

touch output.txt & tail output.txt -f & gdb project1 > output.txt

Understanding a Backtrace

The stack contains all calls at the moment when the division by zero error occured. At position #0 is the latest call "button1-click()". subproc-call #37 is the first call of main() of the whole app.


TODO: Write Me :)

(gdb) bt
#0  0x080733aa in TFORM1__BUTTON1CLICK (SENDER=0x403d8bd8, this=0x403d77d8) at unit1.pas:36
#1  0x080ecd78 in TCONTROL__CLICK (this=0x403d8bd8) at control.inc:1768
#2  0x081274bd in TBUTTONCONTROL__CLICK (this=0x403d8bd8) at buttoncontrol.inc:57
#3  0x08129171 in TCUSTOMBUTTON__CLICK (this=0x403d8bd8) at buttons.inc:186
#4  0x08129198 in TCUSTOMBUTTON__WMDEFAULTCLICKED (MESSAGE={MSG = 1031, WPARAM = 136821192, 
        LPARAM = -1073747812, RESULT = 1075866658, WPARAMLO = 47560, WPARAMHI = 2087, 
        LPARAMLO = 59548, LPARAMHI = 49151, RESULTLO = 27682, RESULTHI = 16416}, 
        this=0x403d8bd8) at buttons.inc:198
#5  0x0805bbf7 in SYSTEM_TOBJECT_$__DISPATCH$formal ()
#6  0x080ec6e0 in TCONTROL__WNDPROC (THEMESSAGE={MSG = 1031, WPARAM = 136821192, 
        LPARAM = -1073747812, RESULT = 1075866658, WPARAMLO = 47560, WPARAMHI = 2087, 
        LPARAMLO = 59548, LPARAMHI = 49151, RESULTLO = 27682, RESULTHI = 16416}, 
        this=0x403d8bd8) at control.inc:1447
#7  0x080e4ed9 in TWINCONTROL__WNDPROC (MESSAGE={MSG = 1031, WPARAM = 136821192, 
        LPARAM = -1073747812, RESULT = 1075866658, WPARAMLO = 47560, WPARAMHI = 2087, 
        LPARAMLO = 59548, LPARAMHI = 49151, RESULTLO = 27682, RESULTHI =   16416},
        this=0x403d8bd8) at wincontrol.inc:2154
#8  0x08161955 in DELIVERMESSAGE (TARGET=0x403d8bd8, AMESSAGE=void) at gtkproc.inc:3242
#9  0x0818897c in GTKWSBUTTON_CLICKED (AWIDGET=0x8285380, AINFO=0x40453794) at gtkwsbuttons.pp:112
#10 0x401d7877 in gtk_marshal_NONE__NONE () from /usr/lib/libgtk-1.2.so.0
#11 0x40206e5a in gtk_signal_remove_emission_hook () from /usr/lib/libgtk-1.2.so.0
#12 0x4020616a in gtk_signal_set_funcs () from /usr/lib/libgtk-1.2.so.0
#13 0x40204234 in gtk_signal_emit () from /usr/lib/libgtk-1.2.so.0
#14 0x40176e1c in gtk_button_clicked () from /usr/lib/libgtk-1.2.so.0
#15 0x4017838a in gtk_button_get_relief () from /usr/lib/libgtk-1.2.so.0
#16 0x401d7877 in gtk_marshal_NONE__NONE () from /usr/lib/libgtk-1.2.so.0
#17 0x4020607b in gtk_signal_set_funcs () from /usr/lib/libgtk-1.2.so.0
#18 0x40204234 in gtk_signal_emit () from /usr/lib/libgtk-1.2.so.0
#19 0x40176d60 in gtk_button_released () from /usr/lib/libgtk-1.2.so.0
#20 0x40177d26 in gtk_button_get_relief () from /usr/lib/libgtk-1.2.so.0
#21 0x401d764d in gtk_marshal_BOOL__POINTER () from /usr/lib/libgtk-1.2.so.0
#22 0x4020619f in gtk_signal_set_funcs () from /usr/lib/libgtk-1.2.so.0
#23 0x40204234 in gtk_signal_emit () from /usr/lib/libgtk-1.2.so.0
#24 0x40239fd9 in gtk_widget_event () from /usr/lib/libgtk-1.2.so.0
#25 0x401d74d0 in gtk_propagate_event () from /usr/lib/libgtk-1.2.so.0
#26 0x401d65c1 in gtk_main_do_event () from /usr/lib/libgtk-1.2.so.0
#27 0x40065b44 in gdk_wm_protocols_filter () from /usr/lib/libgdk-1.2.so.0
#28 0x4003de75 in g_get_current_time () from /usr/lib/libglib-1.2.so.0
#29 0x4003e32c in g_get_current_time () from /usr/lib/libglib-1.2.so.0
#30 0x4003e4f5 in g_main_iteration () from /usr/lib/libglib-1.2.so.0
#31 0x401d6388 in gtk_main_iteration_do () from /usr/lib/libgtk-1.2.so.0
#32 0x080b4d26 in TGTKWIDGETSET__WAITMESSAGE (this=0x40473014) at gtkobject.inc:1427
#33 0x08070073 in TAPPLICATION__IDLE (this=0x4045b014) at application.inc:319
#34 0x08070ffb in TAPPLICATION__HANDLEMESSAGE (this=0x4045b014) at application.inc:827
#35 0x08071380 in RUNMESSAGE (parentfp=0xbffff5a4) at application.inc:933
#36 0x080712d7 in TAPPLICATION__RUN (this=0x4045b014) at application.inc:944
#37 0x080531c3 in main () at project1.lpr:13
(gdb)

This Backtrace was produced using this code:

30. procedure TForm1.Button1Click(Sender: TObject);
31. var
32.  X, Y, Z: Integer;
33. begin
34.   X := 0;
35.   Y := 0;
36.   Z := X div Y;   //   division by zero error
37. end;

See Also