Wednesday, March 7, 2018

Using electric-fence to debug malloc allocated memory issues

    While using malloc often we end up with some memory over run or under run issues. The compiler and OS can not detect these flaws most of the times when we build our application with standard libc.  However there is a handy tool available to catch up these flaws in run time.

    "electric-fence" or "efence" is a library and a malloc debugging tool which we can use to debug such buggy applications. It uses the virtual memory hardware of your computer to place an inaccessible memory page immediately after (or before, at the user's option) each memory allocation. When software reads or writes this inaccessible page, the hardware issues a segmentation fault, stopping the program at the offending instruction.



For example:


Check out the below program:


#include <stdio.h>

#include <string.h>
#include <stdlib.h>

int main(void)

{
    char *ptr;
    ptr = (char *)malloc(5 * sizeof(char));
    strcpy(ptr, "Welcome to Little Embedded Things");
    printf("%s\n", ptr);
    return 0;
}

    This program over runs the memory allocated by malloc. But if we will build this program with standard libc (gcc prog.c -o prog) then the program runs without any error. It may or may not print the entire string but it runs without any error.


    We can catch up such over run condition by building the program with "efence" library.


For example:

    gcc prog.c -o prog -lefence

    One thing to note down that "efence" can only check either under run or over run one at a time.


    So we need to set the parameter by setting or resetting the variable "EF_PROTECT_BELOW"


For example:

    export EF_PROTECT_BELOW=0 (To check overrun)
    export EF_PROTECT_BELOW=1 (To check under run)

    Once we build the application with "efence" library and run the application, now the hardware issues a segmentation fault, stopping the program at the offending instruction.


You can check "man 3 efence" for more details.

Or you can check out the below links:


https://www.systutorials.com/docs/linux/man/3-efence/

https://linux.die.net/man/3/efence

Monday, March 5, 2018

Common error in makefile

If you're getting an error saying : 

"*** missing separator.  Stop."

then you should check the rules should be started by a tab instead of spaces. Sometimes people configured their editor like Vim to use 4 spaces instead of tabs. So if you are using Vim then you need to check your Vim configuration also.

Base and Bounds, Segmentation

Base & bounds relocation: Two hardware registers: base address for process, bounds register that indicates the last valid address t...