linux function

I don't understand what this return means, the parenthesis mean casting
but what then would the braces mean. I am so confused. The code is from
https://elixir.bootlin.com/linux/latest/source/include/linux/file.h#L55

I am trying to understand why I'm getting an error in my code that uses sendfile
so I thought if I could figure out how sendfile worked I could see where it goes
wrong, or it'll make me able to replicate the program and put it in cgdb, and see where the error occurs but I'm getting stuck.


1
2
3
4
static inline struct fd __to_fd(unsigned long v)
{
return (struct fd){(struct file *)(v & ~3),v & 3};
}

Last edited on
The function is very low-level. It is, apparently, using an unsigned long to hold what is basically an address (pointer value) but where the least-significant two bits (perhaps always zeroes in the original pointer value) are being used for flags.

The syntax you are confused about is a cast to a struct with the initializers for the struct inside the braces. The struct has two elements. The first element in the comma-separated list in the braces is v with the lowest two bits zeroed and converted to a file*. This presumably recovers the original address, which is used to initialize the file* in fd. The second element is just the last two bits of v, which hold the flags.

struct fd looks like this:

1
2
3
4
5
6
struct fd {
	struct file *file;
	unsigned int flags;
};
#define FDPUT_FPUT       1
#define FDPUT_POS_UNLOCK 2 

Last edited on
wow, it makes complete sense now, thank you so much for your input.
No problem.

But the need to reverse-engineer a system library function in order to track down a bug is unusual. Do you suspect that sendfile itself has a bug? If not, you should carefully read its spec to ensure you're using it correctly and then concentrate on your own code.

sendfile: http://man7.org/linux/man-pages/man2/sendfile.2.html
It wasn't a bug in sendfile I used mkdir first, but I gave it 0644 as permission, which was incorrect. You should only use 0644 for files not for directories. And sendfile as a result didn't have the correct permissions to send the file
Topic archived. No new replies allowed.