3

EX: Thread A creates Thread B. i wish to block thread A when it starts to create Thread B. but i do not know how to do it with GDB. Any help would be appreciated! Thanks

1 Answer 1

1

Use the GDB non-stop mode and put a breakpoint at the line after your program calls pthread_create().

Reading symbols from bad_thread...done.
(gdb) set target-async 1
(gdb) set pagination off
(gdb) set non-stop on
(gdb) b pthread_create
Breakpoint 1 at 0x400570
(gdb) r
Starting program: bad_thread 
[Thread debugging using libthread_db enabled]

Breakpoint 1, 0x0000000000400570 in pthread_create@plt ()
(gdb) bt
#0  0x0000000000400570 in pthread_create@plt ()
#1  0x00000000004006d8 in main () at bad_thread.c:21
(gdb) list   
12     pthread_mutex_unlock(&x_mutex);
13
14     pthread_exit(NULL);
15 }
16
17 int
18 main () {
19     pthread_t tid1, tid2;
20
21     pthread_create(&tid1, NULL, add_thread, NULL);
(gdb) b bad_thread.c:22 
Breakpoint 2 at 0x4006d8: file bad_thread.c, line 22.
(gdb) b add_thread
Breakpoint 3 at 0x400694: file bad_thread.c, line 10.
(gdb) c
Continuing.
[New Thread 0x40a00960 (LWP 26829)]

Breakpoint 2, main () at bad_thread.c:22
22     pthread_create(&tid2, NULL, add_thread, NULL);
(gdb) 
Breakpoint 3, add_thread (arg=0x0) at bad_thread.c:10
10     pthread_mutex_lock(&x_mutex);
bt
#0  main () at bad_thread.c:22
(gdb) 

To explain the above:

  • Turn on non-stop mode as per GDB docs
  • put a breakpoint at pthread_create() to determine where the program calls this
  • run and hit the breakpoint
  • backtrace and list to find the next line of code
  • put a breakpoint at the next line of code and at the thread start function (add_thread, in this case)
  • run
  • Notice we hit the breakpoint at the next line of code in the original thread. The new thread continues in the background and then hits the breakpoint at the thread start function.
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, Thanks for your answer. but it can totally solve my problem. My requeirment is: i have a library which i have no source code, so i just with to block the create thread event(such as block fork event)before a thread is created? how to do that?
@Dafan - phtread_create() is used to start a new thread. fork() is used to start a new process. In either case, you should be able to just put a breakpoint at the relevant symbol, e.g. break pthread_create. This should work even if your program/library doesn't have symbols, as these symbols exist in standard libraries, which hopefully should have the symbols. At least it worked on my Ubuntu VM.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.