24th
AUG

Operating Systems design homeworks

Posted by Strainu | Filed under C, Software

Operating Systems design homeworks from the Automatics and Computer Science Faculty, UPB, 4th year, prof. Octavian Purdilă. Themes: system calls, UART driver, file system driver, firewall, RAID software.
(more…)

Share and Enjoy:
  • Facebook
  • Twitter
  • Identi.ca
  • email
  • Add to favorites
  • Digg
  • StumbleUpon

Tags: , , ,

17th
MAY

Simple debugging in kernel programming

Posted by Strainu | Filed under C

When programming Linux kernel modules, you have limited debugging options. The main way is to use the printk function (the kernel equivalent of printf). If you want to give as much information as possible, you could use some of the macros that the language offers you, such as __FILE__ or __line__. Here is a small snippet you could use in your modules:

#define DEBUG 1
#if DEBUG
#define Dprintk(format, ...) \
printk (KERN_ALERT "[%s]:FUNC:%s:line:%d: " format, __FILE__, \
__func__, __LINE__, __VA_ARGS__)
#else
#define Dprintk(format, ...) do {}while(0)
#endif

You can use the same code in userspace programs by replacing printk with printf. And just in case you’re wondering what’s with the empty do-while, you might want to take a look at this older article.

Share and Enjoy:
  • Facebook
  • Twitter
  • Identi.ca
  • email
  • Add to favorites
  • Digg
  • StumbleUpon

Tags: , ,

4th
MAY

Macros using do{}while(0);

Posted by Strainu | Filed under C

If you ever had the chance to look in the Linux kernel sources, you might have seen macros defined like this:

#define foo(params) \
do{ \
    //instructions \
}while(0)

This basicly means that the code is executed exactly once, so the first idea is that do{}while(0); is useless.
In fact, there are a number of reasons for writing the macros this way:

  • Empty statements give warnings from the compilers, so rather than writing
    #define FOO

    you might want to write

    #define FOO do{}while(0)
  • It gives you a basic block in which to declare local variables. You could simply use curly brackets, but this could cause serious problems in conditional statements. Let’s take the following example:
    #define exch(a,b) {int t; t = a; a = b; b = t;}

    You then use the macro in the following code:

    if(a[i]<a [i+1])
        exch(a[i],a[i+1]);
    else
        ready = 1;

    This is what the copiler will get:

    if(a[i]<a [i+1]){
        int t;
        t = a[i];
        a[i] = a[i+1];
        a[i+1] = t;
    };
    else
        ready = 1;

    This is interpreted as an if statement whithout else and you will get an error like “else without matching if”. However, if you write the macro like this:

    #define exch(a,b) do{int t; t = a; a = b; b = t;}while(0)

    the code will behave as expected.

You can find more informations about this in the Kernelnewbies FAQ.

Share and Enjoy:
  • Facebook
  • Twitter
  • Identi.ca
  • email
  • Add to favorites
  • Digg
  • StumbleUpon

Tags: ,