3

I was debugging a C++ program in the gdb debugger and tried to access the 5th element of vector which only contains 4 element. After trying this error was on the screen:

(gdb) list main
1   #include <memory>
2   #include <vector>
3   
4   int main(int argc, char *argv[]){
5   
6   
7       std::vector<int> v_num = {1, 3, 5, 67};
8       std::unique_ptr<std::vector<int>> p(&v_num);
9   
10  
(gdb) p v_num.at (5)
Python Exception <class 'IndexError'> Vector index "5" should not be >= 4.: 
Error while executing Python code.
(gdb) 

I didn't except to see a Python exception inside the the gdb. Can someone explain why I encountered such error? Does gdb uses python internally?

Amir reza Riahi
  • 1,540
  • 2
  • 8
  • 34
  • 2
    I guess it is Python Xmethods for `std::vector` https://sourceware.org/gdb/onlinedocs/gdb/Xmethods-In-Python.html. – ks1322 Jul 18 '22 at 17:49

1 Answers1

3

Does gdb uses python internally?

Yes, it uses Python a lot to extend itself in many ways, see https://sourceware.org/gdb/onlinedocs/gdb/Python.html#Python.

What you discovered is called Python Xmethods, see https://sourceware.org/gdb/onlinedocs/gdb/Xmethods-In-Python.html. Xmethods are used as a replacement of inlined or optimized out method defined in C++ source code. libstdc++ has a number of xmethods for standard containers. You can see them with info xmethod command. For std::vector there are 6 xmethods defined on my box:

  libstdc++::vector
    size
    empty
    front
    back
    at
    operator[]

You can disable all xmethods with disable xmethod command. If you do it, GDB will unable to call at method:

(gdb) p v_num.at (5)
Cannot evaluate function -- may be inlined
ks1322
  • 33,961
  • 14
  • 109
  • 164
  • Thanks for your answer. Does this apply only to libstdc++? If my own member classes become inline by decision of the compiler, there is no way to use xmethods to recover them in gdb? – Amir reza Riahi Jul 20 '22 at 05:22
  • 1
    You can use xmethods for your class the same way as you do it for libstdc++, but you have to write them yourself. For libstdc++ they are already written by libstdc++ developers. – ks1322 Jul 20 '22 at 10:06
  • When I create an 'xmethod' how do I activate it in GDB? I tried 'enable xmethod /home/me/xmethods MyClass'. I gave me an error, complaining about the locus not being a regexp. Any advice on how to specify the locus? I will open a new issue about this. – phreed Jul 28 '22 at 15:34