11

While getting to know how to write device drivers I came across IS_ERR() macro. But I couldn't find how is it working. I have include the code below:

majorNumber = register_chrdev(0, DEVICE_NAME, &fops);

if (majorNumber<0)
{
    printk(KERN_ALERT "Failed to register a major number\n");
    return majorNumber;
}
printk(KERN_INFO "Registered correctly with major number %d\n", majorNumber);

// Register the device class
ebbcharClass = class_create(THIS_MODULE, CLASS_NAME);

if (IS_ERR(ebbcharClass))
{               
  unregister_chrdev(majorNumber, DEVICE_NAME);
  printk(KERN_ALERT "Failed to register device class\n");
  return PTR_ERR(ebbcharClass);          
}

So what does the IS_ERR() macro expand to and how it gets executed.

S.I.J
  • 979
  • 1
  • 10
  • 22
  • It is unclear what you are asking. If you only wish to see what the macro evaluates to, compile with `-E` option – Eregrith May 19 '15 at 08:38
  • I have edited my question to give a clear meaning of what I need to know. – S.I.J May 19 '15 at 09:01
  • Btw, use `pr_*()` macros for print and check the [CodingStyle](https://www.kernel.org/doc/Documentation/CodingStyle) just in case. – 0andriy Jun 14 '15 at 16:51

3 Answers3

9

Tests if the supplied pointer should be considered an error value.

It does not check if the pointer is valid.

In your code IS_ERR is used to check if class_create succeded creating ebbcharClass. If an error occurs unregister the char driver and signal the error.

You can find MACROs and inline funcs in err.h

mcsim
  • 1,647
  • 2
  • 16
  • 35
LPs
  • 16,045
  • 8
  • 30
  • 61
  • I would add that is defined in `err.h`. – 0andriy Jun 14 '15 at 16:50
  • I saw somewhere IS_ERR is used like this : if (IS_ERR(dev_ret = class_create(THIS_MODULE, "chardev"))) . so IS_ERR works both for the `return value of class_create function` and the `assignment operation of class_create return value`? from https://testkernel.tistory.com/91 – Chan Kim Apr 28 '21 at 11:53
8

Be careful for pitfall:

#define IS_ERR_VALUE(x) unlikely((x) >= (unsigned long)-MAX_ERRNO)
#define MAX_ERRNO       4095

This covers -1 to -4095, which represents error code, not number below 4096, nor NULL (0). Every value from 0 to 4294963201 (0xfffff001) is considered no error. Do not use it to cover NULL checking.

msrd0
  • 7,816
  • 9
  • 47
  • 82
bsd unix
  • 81
  • 1
  • 1
1

If you want to know what the macro expands to, just compile your file using the -E option of gcc, which will only do pre-processing. It will include all headers and expand all macros.

The macro does not "get executed" per se, it's just a "search and replace" type of thing.

Eregrith
  • 4,263
  • 18
  • 39