Skip to content
Advertisement

How to use get_random_bytes() in linux kernel module?

I have made simple kernel module.

void cb_funct(unsigned long arg)    // callback function.
{
    int rand;
    get_random_bytes(&rand, sizeof(rand));
    rand%=250;

    seq_printf(m, "random number : %dn", rand);
    ...
}

I printed out rand variable using seq_printf function.

cb_funct function is called five times.

Below is the result.

random number : 66

random number : -5

random number : 135

random number : 178

random number : -42

Why negative variable is printed out?

How to use get_random_bytes function in linux?

Advertisement

Answer

It makes sense that you are seeing negative numbers. Assuming that sizeof(int) = 4 bytes, you are asking get_random_bytes to fill up 4 bytes of random numbers starting at address &rand. If the most significant bit for the most significant byte happens to get a 1, then rand will be a negative number. For signed variables (such as int), the most significant bit declares sign. There are multiple things that you can do if that is a problem:

  • Use an unsigned variable (unsigned int or uint32_t, for example). When you print it, remember to use %u or 0x%x.
  • Mask out the most significant bit after calling get_random_bytes. Something like this (again, assuming size(int) is 4 bytes): rand &= 0x7FFFFFFF. This will get you a positive random number.
  • ask get_random_bytes to fill up only three bytes, so it won’t fill up the most significant byte. But your random number will be in range 0 – 0xFFFFFF instead of 0 – 0xFFFFFFFF. And you should initialize your variable to 0 first. You could do: int rand = 0; get_random_bytes(&rand, sizeof(int)-1);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement