LLDB - count the number of steps to execute a thread or to execute a function eg. main(), and skip to Xth step - lldb

(1)
Is there a way to count the number of steps it takes to execute a function or a thread with LLDB?
As an example,
#include<stdio.h>
int main()
{
printf("\n\n\t\tStudytonight - Best place to learn\n\n\n"); // step count: 1
int number;
int number2;
int number3;
number = 50; // step count: 2 (lldb skips declarations)
number = 60; // step count: 3
/*
Comment comment
*/
if(number < 100) // step count: 4 (lldb skips comments)
printf("Number is less than 100!\n"); // step count: 5
else if(number == 100)
printf("Number is 100!\n");
else
printf("Number is greater than 100!\n");
printf("\n\n\t\t\tCoding is Fun !\n\n\n"); // step count: 6 (the lines that are not executed bec of branching are not counted.)
return 0; // step count: 7
}
The step count is provided in the comments in the code above. And I only count step-overs.
The step count is unique to each execution of the code, and is expected to change if command line arguments and environment variables change and affect the control flow of the program.
If there are loops, each iteration will mean counting the lines in the loop again. So if there are 2 steps per iteration and there are 10 iterations, then there are 20 steps for that loop.
(2)
(Although I only count step-overs, I appreciate answers that also tell me how I can configure to include step-ins when I need them, or exclude them when I don't need them.)
(3)
In addition, is there a way to jump to a specific step in that step count? By this, I think of the jump command and How to skip a couple of lines code with lldb?.
However, what if the code has loops? Say:
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}
There are 6 static lines of code (counting all those with only the curly brackets as well). However, the number of steps is probably 21. I wish I could jump to the 10th step, for example. Is it possible with lldb?

Another way to count steps is to write a scripted stepping plan that just keeps pushing new "step in" or "step over" plans till you reach whatever your terminating condition is, and updates some python variable each time an individual step is concluded. For more info on writing scripted thread plans, see:
https://lldb.llvm.org/use/python-reference.html#using-the-python-api-to-create-custom-stepping-logic
and there are several examples of scripted stepping plans here:
https://github.com/llvm/llvm-project/blob/master/lldb/examples/python/scripted_step.py
I'm not quite sure what you mean by "jumping to a specific step". If you mean you just what to stop at that point without having to manually intervene, it would be fairly straightforward to make a scripted stepping plan with whatever end conditions you want (the 10th time you hit line 20, or whatever).
But if you mean "get to that stage in the execution w/o going through the intervening code" that's not a trivial problem. How would lldb know what state was modified along the way to that point? For instance to get to a certain iteration of a loop, lldb would have to know to set the loop counter to whatever value it has at that point, which it has no way of knowing.

Instead of counting steps, and executing a counted number of steps, you can use breakpoints in most cases. For example, in the for loop example, a breakpoint can be configured to stop only under the right conditions.
For these examples, I'll assume the printf is on line 23 of file.c.
To stop part way through the loop, instead of executing a number of next commands, a breakpoint condition can be used to stop only when the loop index i is the desired number:
b file.c:23
breakpoint modify --condition 'i == 5'
The condition expression is a evaluated by lldb, so it can be more complex as needed.
In this case, since the condition is a count, another way of doing this is to set an ignore count on the breakpoint:
b file.c:23
breakpoint modify --ignore-count 5
Note: instead of --condition and --ignore-count, you can alternatively use -c and -i.

Related

Why does this for-loop and while-loop produce different outcomes, even though their values are the same? Btw I am using Javascript

My novice understanding of the difference between for-loops and while-loops is that they differ in format and we use for-loops when we know the exact number of iterations to complete and we use while-loops when we know what condition must be met to stop. That said could someone explain the difference in outcome of the following code?
let countDown = 2;
while(countDown>1){
countDown--;
console.log(countDown)
}
1
for(let countDown = 2; countDown>1; countDown--){
console.log(countDown)
}
2
As U. Windl had commented, for is just "syntactic sugar" for a while loop. The output of your program varied for for and while loop because in while loop countDown is decremented first and then logged, in for loop countDown is logged first and then decremented. With the below change in while loop the output would be same for both and its equivalent to for loop.
let countDown = 2;
while(countDown>1){
console.log(countDown)
countDown--;
}
Lets see what for and while loop says JavaScript For Loop
The For Loop
The for loop has the following syntax:
for (statement 1; statement 2 (condition); statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
While Loop
while (condition) {
// code block to be executed
}
In your program in for loop Statement 3 (i.e countDown--) is executed after the code block (i.e console.log) has been executed, that is the reason the output was 2.
In while loop we have to take care when to execute Statement 3 (i.e countDown-- in this case) and in for loop Statement 3 is always executed after executing code block
for equivalent for while
for (; condition; ) {
// code block to be executed
}
while equivalent for for
Statement 1
while (Statement 2) {
// code block to be executed
Statement 3
}

How to read one line at a time from a data file and to perform calculations in it before moving to the next line in C Programming?

I'm a beginner at C programming and I would appreciate some help in order to understand the problem.
Alright so, I have a data file (input.dat) with data like this: (first line) 0 2 3 4 5; (second line) 1 2 3 5 4, (third line and so on...). I'm required to read the data one line at a time until the end of file and print it. This is what I have done so far:
int main(void)
{
float coeffs[5];
FILE *input; /* File pointer to the input file */
fopen_s(&input, "input.dat", "r"); /* Location of the input file */
int count = 0;
/* Loops to read data set*/
while (fscanf_s(input, "%f %f %f %f %f ", &coeffs[0], &coeffs[1], &coeffs[2], &coeffs[3], &coeffs[4]) != EOF)
{
printf("a=%.4f; b=%.4f; c=%.4f; d=%.4f; e=%.4f\n", coeffs[0], coeffs[1], coeffs[2], coeffs[3], coeffs[4]);
count++;
}
return 0;
}
This is showing all of the lines in the data file at once. But this is not what I want. I need to read one line at a time and perform some calculations and conditions for that one line first before I move to the next line. So how can I do that?
Next problem is, for the first line, I need to implement a loop from -10 to +10 with increment of 2 (to get 11 results in total). For example the program will read the first line, display it on the screen, then for the first value -10, the program will calculate and again display something . Then it will do the same for -8, then for -6 and so on until +10. After the 11 results are displayed, the program will then and ONLY then, move to the second line and so on. Hence for each line in the data file, the program will have 11 results. How can I use the loop function with increment of 2 to achieve these 11 results?
I would appreciate if anyone can provide me a simple layout of the structure of the codes which I've to write. NOTE: The formats are a bit different than other compilers as I must use Microsoft Visual Studio to do it.
Add your calculations to your while loop. You are reading one line at a time anyway.
If you want to loop from -10 to 10 with increments of 2, use a for loop.
for(count = -10; count <= 10; count = count + 2)
{
// Calculations
}

How do I create a "twirly" in a C program task?

Hey guys I have created a program in C that tests all numbers between 1 and 10000 to check if they are perfect using a function that determines whether a number is perfect. Once it finds these it prints them to the user, they are 6, 28, 496 and 8128. After this the program then prints out all the factors of each perfect number to the user. This is all fine. Here is my problem.
The final part of my task asks me to:
"Use a "twirly" to indicate that your program is happily working away. A "twirly" is the following characters printed over the top of each other in the following order: '|' '/' '-' '\'. This has the effect of producing a spinning wheel - ie a "twirly". Hint: to do this you can use \r (instead of \n) in printf to give a carriage return only (instead of a carriage return linefeed). (Note: this may not work on some systems - you do not have to do it this way.)"
I have no idea what a twirly is or how to implement one. My tutor said it has something to do with the sleep and delay functions which I also don't know how to use. Can anyone help me with this last stage, it sucks that all my coding is complete but I can't get this "twirly" thing to work.
if you want to simultaneously perform the task of
Testing the numbers and
Display the twirly on screen
while the process goes on then you better look into using threads. using POSIX threads you can initiate the task on a thread and the other thread will display the twirly to the user on terminal.
#include<stdlib.h>
#include<pthread.h>
int Test();
void Display();
int main(){
// create threads each for both tasks test and Display
//call threads
//wait for Test thread to finish
//terminate display thread after Test thread completes
//exit code
}
Refer chapter 12 for threads
beginning linux programming ebook
Given the program upon which the user is "waiting", I believe the problem as stated and the solutions using sleep() or threads are misguided.
To produce all the perfect numbers below 10,000 using C on a modern personal computer takes about 1/10 of a second. So any device to show the computer is "happily working away" would either never be seen or would significanly intefere with the time it takes to get the job done.
But let's make a working twirly for perfect number search anyway. I've left off printing the factors to keep this simple. Since 10,000 is too low to see the twirly in action, I've upped the limit to 100,000:
#include <stdio.h>
#include <string.h>
int main()
{
const char *twirly = "|/-\\";
for (unsigned x = 1; x <= 100000; x++)
{
unsigned sum = 0;
for (unsigned i = 1; i <= x / 2; i++)
{
if (x % i == 0)
{
sum += i;
}
}
if (sum == x)
{
printf("%d\n", x);
}
printf("%c\r", twirly[x / 2500 % strlen(twirly)]);
}
return 0;
}
No need for sleep() or threads, just key it into the complexity of the problem itself and have it update at reasonable intervals.
Now here's the catch, although the above works, the user will never see a fifth perfect number pop out with a 100,000 limit and even with a 100,000,000 limit, which should produce one more, they'll likely give up as this is a bad (slow) algorithm for finding them. But they'll have a twirly to watch.
i as integer
loop i: 1 to 10000
loop j: 1 to i/2
sum as integer
set sum = 0
if i%j == 0
sum+=j
return sum==i
if i%100 == 0
str as character pointer
set *str = "|/-\\"
set length = 4
print str[p] using "%c\r" as format specifier
Increment p and assign its modulo by len to p

C program freezes after scanf input

I'm working on a homework assignment to calculate the nth prime number as chosen by the user. I had this working just fine, and fairly quickly, but I decided to add in an error message if the user put in anything greater than 50000. For some reason, that decided not to work, so I took it out. After that, my program freezes once the user inputs which prime number they want.
#include <stdio.h>
int main(void)
{
long int pFactor,test,nthCount,target,result,notPrime;
test=2;
nthCount=0;
printf("Which prime number do you want to know?");
scanf("%li",&target);
while (nthCount<target)
{
for(pFactor=test/2;pFactor>1;pFactor--)
{
notPrime=0;
result=(test%pFactor);
if(result==0)
{
notPrime=1;
break;
}
if(notPrime!=1)
{
nthCount++;
notPrime=0;
test++;
}
}
}
test--;
printf("The %li prime number is %li.\n",target,test);
return 0;
}
I think it's something scanf related, as anything I try to print after that doesn't come out.
for(pFactor=test/2;pFactor>1;pFactor--) // where test = 2
deduces to, pFactor>1 is always false (1>1)
So, the flow never enters the for loop and thus, nthCount always remains 0.
while (nthCount<target) // becomes an infinite loop
Your program is stuck within an infinite loop. Body of the for loop is unreachable for all cases and that causing the while-loop to run for infinite time. Modify your program and debug your program yourself next time.
In such cases (program freezes) you can normally quickly get to the root of the problem by making some observations.
First, find out if it's an infinite loop or some function blocking the program flow. 100% CPU usage is a good indicator for an out-of-control loop and 0% CPU usage is a good indicator that your program is blocking, i.e. is waiting for some event to happen. In your case you could have noted that it's the first: an infinite loop.
Then try to find out where and why this happens. You can for example add debug output at strategic positions in suspected loops. You could have adapted your loop body to this:
while (nthCount<target)
{
/* added debug output: */
printf("%ld, %ld, %ld\n", target, nthCount, pFactor);
for(pFactor=test/2;pFactor>1;pFactor--)
{
/* omitted for the sake of brevity */
}
}
Running this, you would have seen something like this:
$ gcc test.cc && echo 1 | ./a.out | head
Which prime number do you want to know?1
1, 0, 0
1, 0, 1
1, 0, 1
1, 0, 1
1, 0, 1
1, 0, 1
1, 0, 1
1, 0, 1
1, 0, 1
Here you can see that the outer loop is spinning infinitely because the inner loop never executes (the last number is always less or equal to one) and thus the loop condition of the outer loop is never changed (and thus never false). And this is where you can start fixing it.

GDB: Force through an if statement

This is the structure of my code
if(someFunction())
{
// Some code
}
where someFunction() evaluates to 0 most of the time
When GDB is at line 1 above, if I do next then // Some code will not be executed.
Is there a way to tell GDB to execute the code inside the if statement?
I can just propose you a workaround. Have a temporary variable int i=0 and then do the if as
if(i==1){
//some code
}
When you reach the desired position with gdb. Set i to 1 using
set i = 1
and then your loop will be executed. Of course after the loop you will have to reset you i if you don't want it executed every time.
You can jump to // Some code after stopping on if statement in gdb, unless // Some code was not optimized out, see 17.2 Continuing at a Different Address. Assuming you stopped on if, you can:
jump +2
0 means false, so it will not entering into if loop, use
if(1)

Resources