Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting a pointer to integer issues warning on 64bit arch

I'm writing a linux kernel module that makes use of the exported symbol open_exec

struct file *open_exec(const char *name)

It returns a pointer, and I can check for an error with the IS_ERR macro:

if (IS_ERR(file))
    return file;

During compile time, I get this warning:

warning: return makes integer from pointer without a cast

This is because my function here returns an integer. If I try to cast it:

return (int) file;

I don't get a warning on my 32bit machine, but I do on my 64bit machine:

warning: cast from pointer to integer of different size

This is because the sizeof of an int and a pointer are the same on 32bit, but they differ on a 64bit machine.

Casting it or not, the code appears to work. I'd just like to get rid of the warning.

How do I properly cast a pointer to an integer and get the value I expect, while not getting a compiler warning? The value I expect is essentially an integer listed in include/asm-generic/errno-base.h of the linux kernel code base.

Since I'm only looking at the pointer as if it was an integer in the case where IS_ERR() is true, I can be sure that it does in-fact only hold an integer value.

like image 444
Corey Henderson Avatar asked Jan 20 '23 03:01

Corey Henderson


1 Answers

The PTR_ERR() macro in linux/err.h, which is where IS_ERR() is also defined, converts a pointer that's really an error code into the appropriate type (a long).

You should use something like:

if (IS_ERR(file))
    return PTR_ERR(file);

Search for existing uses of PTR_ERR() in the source and you'll see this is a common pattern.

It might be appropriate for your function to return a long rather than an int - but all error codes should be representable in an int.

like image 77
Michael Burr Avatar answered Jan 21 '23 17:01

Michael Burr