Skip innermost frames in backtrace - c++

I would like to create a backtrace in gdb (in a script). The command bt 2 prints only the 2 innermost frames, while bt -2 prints only the 2 outermost frames.
What I'd like to do is to skip the 2 innermost frames, and show all outer frames. I've tried
up 2
bt
(and similarly up-silently, frame, select-frame), but it doesn't affect the output of bt. To be clear, I want to get rid of the first to lines in this output:
#0 0x0000003167e0f33e in waitpid () from /lib64/libpthread.so.0
#1 0x00007f2779835de8 in print_trace() () at /path/to/MyAnalysis.cxx:385
#2 0x00007f2779836ec9 in MyAnalysis::getHistHolder(std::basic_string<char, std::char_traits<char>, std::allocator<char> >) () at /path/to/MyAnalysis.cxx:409
#3 0x00007f27798374aa in MyAnalysis::execute() () at /path/to/MyAnalysis.cxx:599
#4 0x00007f2783a9670f in EL::Worker::algsExecute() () from /blah/lib/libEventLoop.so
...
Any way to do this?
Calling return twice seems to work, but then the application is left in an invalid state afterwards, so I can't use it.

Your argument to "bt" depends on current number of frames present. Probably this can also be done in gdb directly (not sure), but this python script does exactly this:
import gdb
class TopBt (gdb.Command):
""" tbt n Shows backtrace for top n frames """
def __init__ (self):
super(TopBt, self).__init__ ("tbt", gdb.COMMAND_DATA)
def framecount():
n = 0
f = gdb.newest_frame()
while f:
n = n + 1
f = f.older()
return n
def invoke (self, arg, from_tty):
top = int(arg[0])
btarg = -(TopBt.framecount() - top)
if btarg < 0:
gdb.execute("bt " + str(btarg))
TopBt()
Save this to some file (tbt.py), source it in gdb (source tbt.py). Now you have new command tbt. tbt N will print backtrace for all but top N frames.

If it's ok for the stack to be capped at some pre-determined length, you can provide an explicit long list, like this for up to 40 frames starting at frame 4:
frame apply level 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 43 -q frame
Frame numbers beyond what's available appear to be ignored.

Related

Class constructor "eating" up values

So I'm trying to run this sim program for a class that makes us build a Bet class using sets.
Here's the class definition:
class Bet2{
private:
set<int> mainNumbers;
set<int> luckyNumbers;
public:
Bet2();
void show() const;
set<int> getMainNumbers();
set<int> getLuckyNumbers();
};
So I decided to use the random lib, since the rand() function that they gave us in class spat out the same values when creating a bunch of Bet2 objects at once, for the sim.
However, for some reason, it's not spitting out the number of values it's supposed to. Sometimes it spits out 4 main numbers (instead of 5), or just 1 lucky number (instead of 2)
Here's the code for the constructor:
Bet2::Bet2() {
random_device rd;
uniform_int_distribution<int> main(1, 50);
for (int i = 0; i < 5; i++)
mainNumbers.insert(main(rd));
uniform_int_distribution<int> star(1, 12);
for (int i = 0; i < 2; i++)
luckyNumbers.insert(star(rd));
}
I ran a few tests using the uniform_int_distribution and the random_device, in the main fucntion, and it ran without any problem. For some reason it eats up values when i initialize a Bet2 vector for my sim:
Main Numbers: 11 23 27 32 36
Star Numbers: 3 11
Main Numbers: 4 18 22 27 28
Star Numbers: 9 11
Main Numbers: 3 5 25 43 <-
Star Numbers: 1 <-
Main Numbers: 40 42 43 46 50
Star Numbers: 2 7
Main Numbers: 7 10 14 27 45
Star Numbers: 9 10
Main Numbers: 11 15 21 24 35
Star Numbers: 1 11
Main Numbers: 3 25 29 45 50
Star Numbers: 3 7
Main Numbers: 11 15 23 25 37
Star Numbers: 1 6
Main Numbers: 7 8 26 31 43
Star Numbers: 6 9
Main Numbers: 15 27 36 38 39
Star Numbers: 2 8
Tried to figure out of uniform_int_distribution can not generate a value, but didnt't find anything online.
Thanks in advance!
std::set can store only up to 1 copy of a given value.
The lack of numbers should be because the random numbers happened to become the same as the numbers that were previously seen.
If you want to store multiples of the same value, you should use std::multiset instead.
If you want to generate a unique set of defined number of values, it may be better to first generate a std::vector of candidate values, and then use std::sample() for that.

struct method partly changes the values of it's member array cpp

Some information about the overall project:
I have to find if specific nodes remain connected if i start removing the lowest width edges from a graph. I have a struct solve, which has a member array called connected. In a method of this struct , FindConnections I go over some of the edges, from the Kth till the last and see which nodes are connected. The way I keep track of the connected nodes is to have an array that for each node points to the lowest id node it is connected, with the lowest pointing to itself
for example
if nodes 2 5 6 12 are directly connected
connected[2] =connected[5] =connected[6] =connected[12] = 2
so now if 12 and 23 are connected (and 12 is the lowest connection of 23)
connected [23] = 12 and connected[connected[23]] = 2 so i can reach 2 from 23 with recursion
My problem is that after finishing modifying the connected array inside FindConnections, some of the changes are preserved while other not
Here is the code:
void FindConnections(int index)
{
for (int temp, i = index; i < NumberOfPortals; i++)
{
temp = min(first[i], second[i]); // the nodes which edge i connects
connected[first[i]] = temp;
connected[second[i]] = temp;
}
}
which is called by
void seeAllConnections() // this function is for visualization it will not be included
{
for (int i = NumberOfPortals - 1; i >= 0; --i)
{
printf("Only using %d Portals:\n", NumberOfPortals - i);
FindConnections(i);
seeconnected(); // prints connected array
for (int i = 0; i < NumberOfUniverses; i++) //resets connected array
{
connected[i] = i;
}
}
}
In the two first iterations of the for loop in seeAllConnections, everything is good, the edges that are examined are
first second width(irrelevant for now)
6 7 255
26 2 111
11 7 36
in the beginning everyone is connected with himself
in the first one we get the output
(I am placing ** around the values that are changed and !! around the one that was supposed to change but didn't , just so you can see it better, the program prints just the numbers)
Only using 1 Portals:
connected are:
0 1 2 3 4 5 6 7 8 9 10 *7* 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
and we can see that connected[11] = 7 just like we wanted to
in the second one
Only using 2 Portals:
connected are:
0 1 2 3 4 5 6 7 8 9 10 *7* 12 13 14 15 16 17 18 19 20 21 22 23 24 25 *2* 27 28 29
connected[11] =7 just like before
connected[26] = 2 just like we wanted
in the third one
Only using 3 Portals:
connected are:
0 1 2 3 4 5 6 !7! 8 9 10 *7* 12 13 14 15 16 17 18 19 20 21 22 23 24 25 *2* 27 28 29
connected [7] = 7 , not 6
moreover, when i use gdb, inside the FindConnections loop, connected[7] = 6 like we wanted
(gdb) print first[i]
$10 = 6
(gdb) print second[i]
$11 = 7
(gdb) print connected[first[i]]
$12 = 6
(gdb) print connected[second[i]]
$13 = 6
but when it exits the function and returns to seeAllConnected
connected[7] = 7
What Am I doing wrong? how can the first two changes be preserved form the same function in the same struct in the same loop, while the second one isn't?
Also after every time I call FindConnections I reset the array to it's original values, so the changes couldn't have been preserved from before
Thank you in advance
I found out what was wrong, as it was a reverse iteration connected[7] got overwritten.

Bubble-sorting rows of Fortran 2D array

I am working on the second part of an assignment which asks me to reorder a matrix such that each row is in monotonically increasing order and so that the first element of each row is monotonically increasing. If two rows have the same initial value, the rows should be ordered by the second element in the row. If those are both the same, it should be the third element, continuing through the last element.
I have written a bubble sort that works fine for the first part (reordering each row). I have written a bubble sort for the second part (making sure that the first element of each row is monotonically increasing). However, I am running into an infinite loop and I do not understand why.
I do understand that the issue is that my "inorder" variable is not eventually getting set to true (which would end the while loop). However, I do not understand why inorder is not getting set to true. My logic is the following: once the following code has swapped rows to the point that the rows are all in order, we will pass through the while loop one more time (and inorder will get set to true), which will cause the while loop to end. I am stumped as to why this isn't happening.
inorder = .false.
loopA: do while ( .not. inorder ) !While the rows are not ordered
inorder = .true.
loopB: do i = 1, rows-1 !Iterate through the first column of the array
if (arr(i,1)>arr(i+1,1)) then !If we find a row that is out of order
inorder = .false.
tempArr = arr(i+1,:) !Swap the corresponding rows
arr(i+1,:) = arr(i,:)
arr(i,:) = tempArr
end if
if (arr(i,1)==arr(i+1,1)) then !The first elements of the rows are the same
loopC: do j=2, cols !Iterate through the rest of the row to find the first element that is not the same
if (arr(i,j)>arr(i+1,j)) then !Found elements that are not the same and that are out of order
inorder = .false.
tempArr = arr(i+1,:) !Swap the corresponding rows
arr(i+1,:) = arr(i,:)
arr(i,:) = tempArr
end if
end do loopC
end if
end do loopB
end do loopA
Example input:
6 3 9 23 80
7 54 78 87 87
83 5 67 8 23
102 1 67 54 34
78 3 45 67 28
14 33 24 34 9
Example (correct) output (that my code is not generating):
1 34 54 67 102
3 6 9 23 80
3 28 45 67 78
5 8 23 67 83
7 54 78 87 87
9 14 24 33 34
It is also possible that staring at this for hours has made me miss something stupid, so I appreciate any pointers.
When you get to compare rows where the first element is identical, you then go through the whole array and compare every single item.
So if you have two arrays like this:
1 5 3
1 2 4
Then the first element is the same, it enters the second part of your code.
In second place, 5>2, so it swaps it:
1 2 4
1 5 3
But then it doesn't stop. In third place, 4>3, so it swaps it back
1 5 3
1 2 4
And now you're back to where you were.
Cheers

Mysterious write violation on my variable

I have an library that don't give correct output. I guess it is possibly an write violation, and focused it on this section of code:
void Page::build_default_frame(PosType genome_display_length)
{
Frame* frame = new Frame(*this,
margin_left,
margin_top,
width - margin_left - margin_right,
genome_display_length);
default_frame = frame;
frames.insert(default_frame);
}
The default_frame is a boost intrusive_ptr<Frame>.
Before execute the sentence default_frame = frame, the content of object frame was all right, but after that, its contents were modified to weird value. So I set two watches on two member variables of frame object:
(gdb) watch -l frame->genome_scale.genome_display_length
Hardware watchpoint 4: -location frame->genome_scale.genome_display_length
(gdb) watch -l frame->genome_scale.frame_width
Hardware watchpoint 5: -location frame->genome_scale.frame_width
and then continue. It suddenly reports write operation on these address:
(gdb) c
Continuing.
Hardware watchpoint 4: -location frame->genome_scale.genome_display_length
Old value = 1000
New value = 16
_dl_runtime_resolve () at ../sysdeps/x86_64/dl-trampoline.S:39
39 ../sysdeps/x86_64/dl-trampoline.S: No such file or directory.
(gdb) bt
#0 _dl_runtime_resolve () at ../sysdeps/x86_64/dl-trampoline.S:39
#1 0x00007ffff7b93dd0 in geno_eye::Page::build_default_frame (this=0x6071b0, genome_display_length=1000)
at /home/yangxi/projects/GenoEye/src/geno_eye/Page.cpp:127
#2 0x00007ffff7b93cc1 in geno_eye::Page::Page (this=0x6071b0, context=0x607750, width=300, height=300,
genome_display_length=1000) at /home/yangxi/projects/GenoEye/src/geno_eye/Page.cpp:29
#3 0x00000000004016b8 in geno_eye::__tester__::run (this=0x7fffffffe1c8)
at /home/yangxi/projects/GenoEye/t/t_page.cpp:15
#4 0x00000000004015d1 in main () at /home/yangxi/projects/GenoEye/t/t_page.cpp:36
(gdb) c
Continuing.
Hardware watchpoint 5: -location frame->genome_scale.frame_width
Old value = 240
New value = 3.1228427039313504e-317
_dl_runtime_resolve () at ../sysdeps/x86_64/dl-trampoline.S:40
40 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) bt
#0 _dl_runtime_resolve () at ../sysdeps/x86_64/dl-trampoline.S:40
#1 0x00007ffff7b93dd0 in geno_eye::Page::build_default_frame (this=0x6071b0, genome_display_length=1000)
at /home/yangxi/projects/GenoEye/src/geno_eye/Page.cpp:127
#2 0x00007ffff7b93cc1 in geno_eye::Page::Page (this=0x6071b0, context=0x607750, width=300, height=300,
genome_display_length=1000) at /home/yangxi/projects/GenoEye/src/geno_eye/Page.cpp:29
#3 0x00000000004016b8 in geno_eye::__tester__::run (this=0x7fffffffe1c8)
at /home/yangxi/projects/GenoEye/t/t_page.cpp:15
#4 0x00000000004015d1 in main () at /home/yangxi/projects/GenoEye/t/t_page.cpp:36
The two old values are the correct values for that two member variables. This write operation is happened before executing the = function of boost intrusive_ptr, as I pressed tens of "next", and the code is still in file dl-trampoline.S.
(gdb) n
41 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
42 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
43 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
44 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
45 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
46 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
47 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
48 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
49 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
50 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
51 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
52 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
53 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
54 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
56 in ../sysdeps/x86_64/dl-trampoline.S
(gdb) n
boost::intrusive_ptr<geno_eye::Frame>::operator= (this=0x6071b0, rhs=0x3e8)
at /usr/include/boost/smart_ptr/intrusive_ptr.hpp:134
134 {
What is dl-trampoline.S ? Why it silently write on the memory of my object?
In addition of that, I also run valgrind:
$ valgrind ./t_page
However, instead of invalid write, it reports invalid read to that object, which is happened after the object creation is finished.
This is caused by an reference-to-stack bug.
Object genome_scale holds two references to two member variables of frame object. When I reconstruct my code, it accidentally reference to two stack variables...
So, maybe I should avoid the use of reference types in this situation, as you can easily provide stack stuffs to them and don't get any warns.

buffer overflow that shouldnt happen (?)

I have the following program
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 int check_authentication(char *password){
6 char password_buffer[16];
7 int auth_flag =0;
8
9
10 strcpy(password_buffer, password);
11
12 if(strcmp(password_buffer, "brillig" ) == 0 )
13 auth_flag = 1;
14 if(strcmp(password_buffer, "outgrabe") == 0)
15 auth_flag = 1;
16
17 return auth_flag;
18 }
19
20 int main(int argc, char *argv[]){
21 if (argc<2){
22 printf("Usage: %s <password>\n", argv[0]);
23 exit(0);
24 }
25
26 if(check_authentication(argv[1])){
27 printf("\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n");
28 printf(" Access Granted.\n");
29 printf("\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n");
30 }
31 else {
32 printf("\n Access Denied. \n");
33 }
34 }
I am running it supplying 30 bytes of As through gdb... and I am setting the following breakpoints
(gdb) break 9
Breakpoint 1 at 0x80484c1: file auth_overflow2.c, line 9.
(gdb) break 16
Breakpoint 2 at 0x804850f: file auth_overflow2.c, line 16.
(gdb) run AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
So far so good. Everything goes as it was supposed to go even till the next breakpoint
Breakpoint 1, check_authentication (password=0xbffff6d2 'A' <repeats 30 times>)
at auth_overflow2.c:10
10 strcpy(password_buffer, password);
(gdb) x/s password_buffer
0xbffff484: "\364\237\374\267\240\205\004\b\250\364\377\277\245", <incomplete sequence \352\267>
(gdb) x/x &auth_flag
0xbffff494: 0x00
Now we see the following information:
variable auth_flag is in address 0xbffff494 and variable buffer is in the address 0xbffff484. Since address of var auth_flag is greater than the address of buffer and the stack grows towards lower addresses that means that additional (overrun of the buffer) bytes in the buffer variable WILL NOT OVERWRITE auth_flag. Right ?
But gdb has a different opinion...
(gdb) cont
Continuing.
Breakpoint 2, check_authentication (
password=0xbf004141 <Address 0xbf004141 out of bounds>)
at auth_overflow2.c:17
17 return auth_flag;
(gdb) x/s password_buffer
0xbffff484: 'A' <repeats 30 times>
(gdb) x/x &auth_flag
0xbffff494: 0x41
and ...
(gdb) x/16xw &auth_flag
0xbffff494: 0x41414141 0x41414141 0x41414141 0xbf004141
0xbffff4a4: 0x00000000 0xbffff528 0xb7e8bbd6 0x00000002
0xbffff4b4: 0xbffff554 0xbffff560 0xb7fe1858 0xbffff510
0xbffff4c4: 0xffffffff 0xb7ffeff4 0x080482bc 0x00000001
We see that auth_flag was overwritten with these 0x41 (=A) although this variable was in a lower position in stack. Why this happened?
Stack growth direction has nothing to do with where the extra bytes go when you overrun a buffer. Overruns from strcpy are always going to be into higher addresses (unless overrun so far that you wrap around to address 0, which is pretty unlikely)
Objects are stored in memory from lower udresses up to higher addresses. As you can not guarantee that the length of the string refered to by parameter password is less than 16 then your code is invalid.
In fact there is no any need in the local buffer password_buffer.
The function could be written the following way
_Bool check_authentication( const char *password )
{
return ( strcmp( password, "brillig" ) == 0 || strcmp( password, "outgrabe" ) == 0 );
}
Instead of the return type _Bool you may use type int as in your function realization. In any case either 1 or 0 will be returned.
the compiler can freely reorder the stack of variables therefore in this case it's always char array before int variable. This makes the program vulnerable for stack-based buffer overflow.
In order to change the following:
(gdb) x/s password_buffer
0xbffff484: 'A' <repeats 30 times>
(gdb) x/x &auth_flag
0xbffff494: 0x41
into expected answer as below:
(gdb) x/s password_buffer
0xbffff494: 'A' <repeats 30 times>
(gdb) x/x &auth_flag
0xbffff484: 0x00
We simply add a -fstack-protector-all argument during compilation and the result will be as expected. To be vice-versa, perhaps you can use -O0 or -fno-stack-protector.
Answer from: https://stackoverflow.com/a/21215205/3205268
If you are reading in more then 15 bytes you will get that. strcpy will look for the end of the string. You could use something like strncpy to only copy a limited number of characters.