오랫만에 쓰려니 다 까먹어서 다시 조사

 

빌드

-g 옵션을 통해 디버깅 심볼을 넣어준다.

$ gcc -g tt.c

 

이거 안하면 소스코드가 안나옴

Reading symbols from ./a.out...
(No debugging symbols found in ./a.out)
(gdb) l
No symbol table is loaded.  Use the "file" command.

 

gdb 실행 (인자 없이)

$ gdb ./a.out

$ gdb
(gdb) file ./a.out

 

gdb 실행 (인자 필요시)

$ gdb --args ./a.out arg1 arg2

[링크 : https://stackoverflow.com/questions/6121094/how-do-i-run-a-program-with-commandline-arguments-using-gdb-within-a-bash-script]

 

브레이크 포인트 설정 및 소스 보기

소스는 list (혹은 소문자 l) 과 라인수를 넣고

브레이크 포인트는 b로 추가한다. b 뒤에는 라인수 혹은 함수 명을 넣으면 된다.

브레이크 포인트 목록 확인은 info b를 통해 가능하다.

clear 를 통해 b 명령을 통해 추가하는 것과 정반대로 삭제가 가능하고

delete(소문자 d) 명령은 info b의 num 을 이용하여 삭제한다.

(gdb) l
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 void main()
5 {
6 int *arr = NULL;
7 arr = (int*)malloc(10 * sizeof(int));
8 int idx = 0;
9 for(idx = 0; idx < 10000; idx++)
10 arr[idx] = idx;
(gdb) l 10
5 {
6 int *arr = NULL;
7 arr = (int*)malloc(10 * sizeof(int));
8 int idx = 0;
9 for(idx = 0; idx < 10000; idx++)
10 arr[idx] = idx;
11
12 // iprintf("before\n");
13 // fflush(stdout);
14
(gdb) l 14
9 for(idx = 0; idx < 10000; idx++)
10 arr[idx] = idx;
11
12 // iprintf("before\n");
13 // fflush(stdout);
14
15 free(arr);
16
17 printf("after\n");
18 fflush(stdout);
(gdb) b 15
Breakpoint 1 at 0x1201: file t2.c, line 15.
(gdb) b
No default breakpoint address now.
(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x0000000000001201 in main at t2.c:15
(gdb) b main
Breakpoint 2 at 0x11b5: file t2.c, line 6.
(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x0000000000001201 in main at t2.c:15
2       breakpoint     keep y   0x00000000000011b5 in main at t2.c:6
(gdb) d
Delete all breakpoints? (y or n) n
(gdb) clear main
Deleted breakpoint 2 
(gdb) d 1
(gdb) info b
No breakpoints or watchpoints.
(gdb) b main
Breakpoint 3 at 0x11b5: file t2.c, line 6.
(gdb) b 15
Breakpoint 4 at 0x1201: file t2.c, line 15.
(gdb) b 10 if idx = 200
Breakpoint 5 at 0x11db: file t2.c, line 10.
(gdb) info b
Num     Type           Disp Enb Address            What
3       breakpoint     keep y   0x00000000000011b5 in main at t2.c:6
4       breakpoint     keep y   0x0000000000001201 in main at t2.c:15
5       breakpoint     keep y   0x00000000000011db in main at t2.c:10
stop only if idx = 200

[링크 : https://dining-developer.tistory.com/13]

 

디버깅 시작, 디버깅 제어

run을 통해 시작하고 인자가 필요할땐 

(gdb) r 1 2 3 

처럼 인자를 공백으로 띄워서 넣어준다.

c는 break 포인트 까지 실행(continue)

print 를 이용하여 변수 값을 출력할수 있다.

r을 눌러 실행하나 main() 함수에서 한번 브레이크 걸리고

c를 눌러 진행하지만 10 라인에 브레이크가 걸려있어 한번 멈추고

c를 눌러 진행하지만 조건부 브레이크에 의해 idx가 200인 경우에 멈춘다.

(gdb) r
Starting program: /home/minimonk/work/src/malloc/a.out 
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Breakpoint 3, main () at t2.c:6
6 int *arr = NULL;
(gdb) c
Continuing.

Breakpoint 5, main () at t2.c:10
10 arr[idx] = idx;
(gdb) c
Continuing.

Breakpoint 5, main () at t2.c:10
10 arr[idx] = idx;
(gdb) print idx
$1 = 200

 

next는 한줄 실행 (함수 진입 x)

step은 한줄 실행 (함수 진입)

finish는 함수 종료까지 실행(함수에서 벗어날때 까지)

 

[링크 : https://lacti.github.io/2008/04/01/gdb-simple-help/]

'프로그램 사용 > gdb & insight' 카테고리의 다른 글

gdb attach  (0) 2025.11.11
gdbserver taget  (0) 2023.07.19
gdb conditional break  (0) 2023.07.19
gdb 디버깅 타겟을 인자와 함께 실행하기  (0) 2022.10.17
gdb break  (0) 2021.04.09
Posted by 구차니

stm32도 붙이는데 리눅스에서도 작동중인 녀석을 디버그 할 수 있나 찾는데

그냥 pid 옵션주면 된다고

 

12년전 글이라서 한번 해봐야겠다.

-p는 gdb 옵션

attach 는 gdb 인터프리터내 명령어

gdb -p 12271
gdb /path/to/exe 12271

gdb /path/to/exe
(gdb) attach 12271

[링크 : https://stackoverflow.com/questions/14370972/how-to-attach-a-process-in-gdb]

   [링크 : https://kukuta.tistory.com/202]

'프로그램 사용 > gdb & insight' 카테고리의 다른 글

gdb 사용법  (0) 2026.01.16
gdbserver taget  (0) 2023.07.19
gdb conditional break  (0) 2023.07.19
gdb 디버깅 타겟을 인자와 함께 실행하기  (0) 2022.10.17
gdb break  (0) 2021.04.09
Posted by 구차니

target remote를 이용하여 접속을 할때 사용하는 명령인데

target remote 이후에 포트를 적어주면 된다.

(gdb) help target
Connect to a target machine or process.
The first argument is the type or protocol of the target machine.
Remaining arguments are interpreted by the target protocol.  For more
information on the arguments for a particular protocol, type
`help target ' followed by the protocol name.

List of target subcommands:

target core -- Use a core file as a target.
target ctf -- (Use a CTF directory as a target.
target exec -- Use an executable file as a target.
target extended-remote -- Use a remote computer via a serial line, using a gdb-specific protocol.
target native -- Native process (started by the "run" command).
target record-btrace -- Collect control-flow trace and provide the execution history.
target record-core -- Log program while executing and replay execution from log.
target record-full -- Log program while executing and replay execution from log.
target remote -- Use a remote computer via a serial line, using a gdb-specific protocol.
target tfile -- Use a trace file as a target.

Type "help target" followed by target subcommand name for full documentation.
Type "apropos word" to search for commands related to "word".
Type "apropos -v word" for full documentation of commands related to "word".
Command name abbreviations are allowed if unambiguous.

(gdb) help target remote
Use a remote computer via a serial line, using a gdb-specific protocol.
Specify the serial device it is connected to
(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).

(gdb) help monitor
Send a command to the remote monitor (remote targets only).

 

monitor는 remote로 붙었을때만 보내는 명령인데 reset은 검색되진 않는다.

(gdb) file C:/temp/Blinky.elf
Reading symbols from C:/temp/Blinky.elf...done.
(gdb) target remote localhost:2331
Remote debugging using localhost:2331
0x00000000 in ?? ()
(gdb) monitor reset
Resetting target
(gdb) load

[링크 : https://wiki.segger.com/J-Link_GDB_Server]

'프로그램 사용 > gdb & insight' 카테고리의 다른 글

gdb 사용법  (0) 2026.01.16
gdb attach  (0) 2025.11.11
gdb conditional break  (0) 2023.07.19
gdb 디버깅 타겟을 인자와 함께 실행하기  (0) 2022.10.17
gdb break  (0) 2021.04.09
Posted by 구차니

 

Set a breakpoint
The first step in setting a conditional breakpoint is to set a breakpoint as you normally would. I.e.

(gdb) break <file_name> : <line_number>
(gdb) break <function_name>
This will set a breakpoint and output the breakpoint number

Check breakpoints
If you forget which breakpoints you can add a condition to, you can list the breakpoints using:

(gdb) info breakpoints
Set a condition for a breakpoint
Set an existing breakpoint to only break if a certain condition is true:

(gdb) condition <breakpoint_number> condition
The condition is written in syntax similar to c using operators such as == != and <.

 

break 줄여서 br

$ gdb factorial
Reading symbols from factorial...done.
(gdb) br 28
Breakpoint 1 at 0x11bf: file factorial.c, line 28.
(gdb) condition 1 i > 5

 

아래 소스에서 28라인 i++ 에 break를 걸고, 해당 라인에서 i > 5 인 조건에서 잡히게 한다.

반복문의 경우 확실히 디버깅 할 때 편할 듯.

//This program calculates and prints out the factorials of 5 and 17


#include <stdio.h>
#include <stdlib.h>

int factorial(int n);

int main(void) {

int n = 5;
int f = factorial(n);
printf("The factorial of %d is %d.\n", n, f);
n = 17;
f = factorial(n);
printf("The factorial of %d is %d.\n", n, f);

return 0;

}
//A factorial is calculated by n! = n * (n - 1) * (n - 2) * ... * 1
//E.g. 5! = 5 * 4 * 3 * 2 * 1 = 120
int factorial(int n) {
int f = 1;
int i = 1;
while (i <= n) {
f = f * i;
i++; // 28 line
}
return f;
}

 

[링크 : https://www.cse.unsw.edu.au/~learn/debugging/modules/gdb_conditional_breakpoints/]

'프로그램 사용 > gdb & insight' 카테고리의 다른 글

gdb attach  (0) 2025.11.11
gdbserver taget  (0) 2023.07.19
gdb 디버깅 타겟을 인자와 함께 실행하기  (0) 2022.10.17
gdb break  (0) 2021.04.09
gdb/insight target window  (0) 2010.05.19
Posted by 구차니

예를 들어 ls -al을 하려면 아래와 같이 하면 된다.

$ gdb --args ls -al

 

그냥 넣으면 gdb의 옵션으로 해석한다.

$ gdb ls -al
gdb: 인식할 수 없는 옵션 '-al'
Use `gdb --help' for a complete list of options.

 

$ gdb --args executablename arg1 arg2 arg3

[링크 : https://stackoverflow.com/questions/6121094]

'프로그램 사용 > gdb & insight' 카테고리의 다른 글

gdbserver taget  (0) 2023.07.19
gdb conditional break  (0) 2023.07.19
gdb break  (0) 2021.04.09
gdb/insight target window  (0) 2010.05.19
insight/gdb 우분투에서 컴파일하기 실패 - insight/gdb compiling on ubuntu failed  (2) 2010.05.18
Posted by 구차니

귀찮아서 b main 으로만 쓰는건 함정 ㅋㅋ

for 반복문으로 인해서 귀찮아서 결국에는 라인으로 브레이크 잡는법 찾은것도 함정

 

gdb> break filename:line
gdb> b filename:line
gdb> b function

[링크 : https://stackoverflow.com/questions/5276988/]

 

브레이크 목록보기

gdb> info break
gdb> i b

[링크 : https://ccrma.stanford.edu/~jos/stkintro/Useful_commands_gdb.html]

Posted by 구차니
결론만 간단히 내자면, insight 컴파일시 환경설정에 따라서, target/TCP target/Serial이 추가된다.
그러니 신경쓰지 말고
GDBServer/TCP 나 Remote/TCP 둘중에 하나 골라서 쓰면된다.



Selecting a Target
Selecting a target involves choosing a target for debugging and setting connection interface options for the target.

Common targets include: "Exec" for native debuggers, "Remote/Serial" for establishing a connection to a target board via a serial line, "Remote/TCP" for TCP connections, and "Simulator" for connections to the simulator. There may be more depending on the configuration of the debugger being used.

In general, "remote" targets are always serial connections which require the user to specify the serial port and baud rate to be used for the connection and "remote/tcp" targets are always TCP connections which require specifying the hostname and port number of the machine to which to connect. Depending upon configuration, there may be numerous serial- and TCP-based connections. These always follow the naming convention target/Serial and target/TCP.

To select a target, choose one of the available targets from the dropdown menu in the Connection Frame. Then specify the interface options for this target: selecting the baudrate and serial port from the dropdown menus (serial targets only) or entering the hostname and port number (TCP targets only).

[출처 : insight - About GDB - target window]


Posted by 구차니
우분투에서 insight 소스를 받아서 컴파일 하는데 에러를 뱉어낸다 ㄱ-

WARNING: `makeinfo' is missing on your system.  You should only need it if
         you modified a `.texi' or `.texinfo' file, or any other file
         indirectly affecting the aspect of the manual.  The spurious
         call might also be the consequence of using a buggy `make' (AIX,
         DU, IRIX).  You might want to install the `Texinfo' package or
         the `GNU make' package.  Grab either from any GNU archive site.

$ makeinfo
'makeinfo' 프로그램은 현재 설치되어 있지 않습니다.  다음을 입력하여 이를 설치할 수 있습니다:
sudo apt-get install texinfo
머.. texinfo 패지키를 깔면 해결된다.

그리고, make distcelan 이후 다시 configure를 하고 해주니, 요런 에러가 발생한다.
configure: error: no termcap library found
이녀석은 libncurses5-dev 패키지를 설치하면 해결된다.
[링크 : http://leoric99.tistory.com/entry/Ubuntutermcap-라이브러리-해결-방법]

그런데.. 이 에러는 도대체 어떻게 잡아야 하나...
gcc -c -g -O2   -I. -I.././gdb -I.././gdb/config -DLOCALEDIR="\"/usr/local/share/locale\"" -DHAVE_CONFIG_H -I.././gdb/../include/opcode -I.././gdb/../readline/.. -I../bfd -I.././gdb/../bfd -I.././gdb/../include -I../libdecnumber -I.././gdb/../libdecnumber   -DMI_OUT=1 -DGDBTK -DTUI=1  -Wall -Wdeclaration-after-statement -Wpointer-arith -Wformat-nonliteral -Wno-pointer-sign -Wno-unused -Wno-switch -Wno-char-subscripts -Werror linux-nat.c
cc1: warnings being treated as errors
linux-nat.c: In function ‘linux_nat_info_proc_cmd’:
linux-nat.c:2879: error: ignoring return value of ‘fgets’, declared with attribute warn_unused_result
gdb/Makefile 에서 -Werror 부분을 주석처리 해준다.

WARNING: `bison' missing on your system.  You should only need it if
         you modified a `.y' file.  You may need the `Bison' package
         in order for those modifications to take effect.  You can get
         `Bison' from any GNU archive site.
머.. bison 패키지를 깔면 해결된다.

ada-lex.c missing and flex not available.
... 정말로 파일이 없다.
일단 flex 패키지를 설치해준다.
[링크 : http://kldp.org/node/55249]

그런데.. 또 클린하고 해도..
gcc -g -O2      \
                -o gdb gdb.o libgdb.a \
                   ../readline/libreadline.a ../opcodes/libopcodes.a ../bfd/libbfd.a  ../libiberty/libiberty.a ../libdecnumber/libdecnumber.a    ../libgui/src/libgui.a -L/home/morpheuz/src/insight/itcl/itcl -litcl3.2 -L/home/morpheuz/src/insight/itcl/itk -litk3.2 -L/home/morpheuz/src/insight/tk/unix -ltk8.4 -Wl,-rpath,/usr/local/lib -L/home/morpheuz/src/insight/tcl/unix -ltcl8.4   -lX11 -ldl  -lieee -lm -lncurses -lm   ../libiberty/libiberty.a  -ldl -rdynamic
libgdb.a(ada-lang.o): In function `parse':
/home/morpheuz/src/insight/gdb/ada-lang.c:10972: undefined reference to `ada_parse'
libgdb.a(ada-lang.o):(.rodata+0xda0): undefined reference to `ada_error'

... ada 가 날 열받게 하는구나~ ㄱ-
아놔 안해안해 ㄱ-


+
2016.08.29
[링크 : http://decdream.tistory.com/370] 이분은 성공하셨네 ㅠㅠ


'프로그램 사용 > gdb & insight' 카테고리의 다른 글

gdb break  (0) 2021.04.09
gdb/insight target window  (0) 2010.05.19
gdb / gdbserver 접속명령어  (0) 2010.05.18
insight(gdb) 아키텍쳐별 차이점(?)  (0) 2010.05.18
gdb cross compile 관련  (0) 2010.05.18
Posted by 구차니
gdbserver는 gdb를 돌릴만한 사정이 안되는 시스템을 위한 프로그램으로
단순하게 gdb의 앞단에서 데이터를 TCP나 시리얼 등으로 전송해 주는 역활을 한다.
그런 이유로 gdbserver 만으로는 아무런 것도 할수 없으며

크로스 컴파일 환경이라면, 내부적으로 크로스 환경에 맞추어진 gdb가 별도로 존재해야 한다.
gdbserver는 아래와 같이 host:port 식으로 선언을 하는데 현재까지는 host는 무시를 하고 port만을 받아들인다고 한다.

To use a TCP connection instead of a serial line:

     target> gdbserver host:2345 emacs foo.txt

The only difference from the previous example is the first argument, specifying that you are communicating with the host gdb via TCP. The `host:2345' argument means that gdbserver is to expect a TCP connection from machine `host' to local TCP port 2345. (Currently, the `host' part is ignored.)

[링크 : http://sourceware.org/gdb/current/onlinedocs/gdb/Server.html#Server]

그리고 gdb 쪽에서는 target remote 라는 명령어를 통해 접속이 가능하며, 기본값으로는 TCP로 접속하도록 되어있다.

target remote host:port
target remote tcp:host:port
    Debug using a TCP connection to port on host. The host may be either a host name or a numeric IP address; port must be a decimal number. The host could be the target machine itself, if it is directly connected to the net, or it might be a terminal server which in turn has a serial line to the target.

target remote udp:host:port
    Debug using UDP packets to port on host. For example, to connect to UDP port 2828 on a terminal server named manyfarms:
              target remote udp:manyfarms:2828
    When using a UDP connection for remote debugging, you should keep in mind that the `U' stands for “Unreliable”. UDP can silently drop packets on busy or unreliable networks, which will cause havoc with your debugging session.

[링크 : http://sourceware.org/gdb/current/onlinedocs/gdb/Connecting.html#Connecting]


음.. 그런데 gdb/insight 에서 보이는
GDBserver/TCP , remote/TCP는 멀까?
Posted by 구차니
테스트 환경
SH4 target board / i686 linux machine

아래의 화면은
./configure --build=i686-linux --host=i686-linux --target=sh4-linux
옵션으로 크로스컴파일된 insight의 Run 메뉴화면이다.


아래의 화면은
./configure
옵션으로 i686용으로 컴파일된 insight의 Run 메뉴화면이다.


음.. 크로스 컴파일 된녀석만 메뉴상에 별도로 Connect to target이 생기고
로컬용으로 컴파일 된녀석은 메뉴상에 Attach to process가 생기는 것으로 보인다.


About GDB 다이얼로그 차이점

<< sh4 , i686 >>
About 다이얼로그의 내용은 gdb 에서 show version으로 나오는 정보이며

가장 아래줄의
This GDB was configured as "i686-pc-linux-gnu".
This GDB was configured as "--host=i686-linux --target=sh4-linux".
만 다르게 나온다.


Attach to Process 메뉴화면

Posted by 구차니