As part of my project, while reading the reports, I came to know about bugs where large stack variables were allocated on the fixed kernel stack. There were many in the versions 2.4.x and 2.6.x. I was also required to list FPs (false positives) by Coccinelle. This post will be about, what I found for the mentioned case.
What is Stack?
What is the stack? It’s a special region of your computer’s memory that stores temporary variables created by each function (including the main() function). The stack is a “FILO” (first in, last out) data structure, that is managed and optimized by the CPU quite closely. Every time a function declares a new variable, it is “pushed” onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other stack variables.
The advantage of using the stack to store variables, is that memory is managed for you. You don’t have to allocate memory by hand, or free it once you don’t need it any more. What’s more, because the CPU organizes stack memory so efficiently, reading from and writing to stack variables is very fast.
A key to understanding the stack is the notion that when a function exits, all of its variables are popped off of the stack (and hence lost forever). Thus stack variables are local in nature. This is related to a concept we saw earlier known as variable scope, or local vs global variables. A common bug in C programming is attempting to access a variable that was created on the stack inside some function, from a place in your program outside of that function (i.e. after that function has exited).
Another feature of the stack to keep in mind, is that there is a limit (varies with OS) on the size of variables that can be store on the stack. This is not the case for variables allocated on the heap.
What is a variable on stack?
All the local variables in the function are allocated on the stack. That’s why we say it goes out of scope as soon as we come out of the function, and to avoid this behavior we can use static with them.
Why allocating large stack variables (> 1K) on the fixed-size kernel stack a bug?
- If you allocate too much in the stack you might run out of stack
- The Linux kernel stack has a fixed size. So they limit the size to 1K.
Types I studied?
It had only single type.
What did I found?
Bugs were all about allocating a size > 1K on stack, in the reports.
In the FPs by Coccinelle, most were where a variable allocated on stack of X size, but was less than the threshold, so can not be counted as a bug.
You can find bugs of each type above in the report linked. Have a look at this, here block is of size 4096 and which is too large.
Look at this. here output is of size 512 which is less than the threshold, so no issues with this.
More are coming!.