Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd gcc warning behavior

Tags:

c

linux

gcc

I'm working on a linux driver, and I got this warning message:

/home/andrewm/pivot3_scsif/pivot3_scsif.c:1090: warning: ignoring return value of ‘copy_from_user’, declared with attribute warn_unused_result

The offending line is:

  if (copy_from_user(tmp, buf, count) < 0)

After checking the declaration of copy_from_user, I found it returns an unsigned long, so obviously the comparison would always fail, so the return value wouldn't affect the comparison. That part makes sense, but why does gcc not also warn about the fact that it's a signed/unsigned comparison? Is that just a compiler peculiarity? Or does it avoid warning twice for the same expression?

The function containing the line is:

int proc_write(struct file *f, const char __user *buf, unsigned long count, void *data)
{
  char tmp[64];
  long value;
  struct proc_entry *entry;

  if (count >= 64)
    count = 64;
  if (copy_from_user(tmp, buf, count) < 0)
  {
    printk(KERN_WARNING "pivot3_scsif: failed to read from user buffer %p\n", buf);
    return (int)count;  
  }
  tmp[count - 1] = '\0';
  if (tmp[count - 2] == '\n')
    tmp[count - 2] = '\0';
  ...
}

Using gcc 4.4.1 on 64-bit Red Hat (on a company server, I don't really have a choice on upgrading).

like image 482
Drew McGowen Avatar asked Jun 28 '13 19:06

Drew McGowen


2 Answers

It seems it's a compiler option http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html:

-Wno-unused-result
    Do not warn if a caller of a function marked with attribute warn_unused_result (see Function Attributes) does not use its return value. The default is -Wunused-result. 

....

-Wtype-limits
    Warn if a comparison is always true or always false due to the limited range of the data type, but do not warn for constant expressions. For example, warn if an unsigned variable is compared against zero with ‘<’ or ‘>=’. This warning is also enabled by -Wextra. 
like image 78
Ast Derek Avatar answered Oct 25 '22 00:10

Ast Derek


Yes, it's probably just a compiler quirk. The warning was presumably generated after a few steps of syntax optimization wherein the if() expression was eliminated (because the condition was always true), leaving the bare function call. It's fairly routine to find this kind of behavior. There are likewise some warning conditions that are only emitted when compiling with optimization enabled.

You seem to have figured out the proper fix yourself.

like image 3
Andy Ross Avatar answered Oct 24 '22 23:10

Andy Ross