Skip to contentSkip to conversation

script to find incorrect tests on unsigneds

DISCUSSION Roel Kluin 6 participants 30 messages Apr 18, 2008 – Apr 23, 2008 1 message not in the archive

Subsystems (6)
VFS SCSI Kernel janitors SPI +2 more subsystems
lore
Share & tools
lore

Roel Kluin

author
#0 lore raw

A bash script to find incorrect tests on unsigned values. for instance:

unsigned int i;
...
i = neg_ret_function();
...
if (i < 0) ...

#!/bin/bash
# (c) roel kluin 2008 GPL v2
#
# TODO: make this working also for

#                              ... $unsigned_var = $signed_var ...
#                              ... $unsigned_var = \(-POSITIVE_DEF\|NEGATIVE_DEF\) ...
#                              ... ( $unsigned_var [+*/%^&~-]?= ... ) < 0 ...
# a number
int="[0-9]"
hex="[a-f0-9]"
hEx="[A-Fa-f0-9]"
HEX="[A-F0-9]"
upp="[A-Z]"
up_="[A-Z_]"
low="[a-z0-9]"
lo_="[a-z0-9_]"
alp="[A-Za-z]"
al_="[A-Za-z_]"
ALN="[A-Z0-9]"
AN_="[A-Z0-9_]"
aln="[A-Za-z0-9]"
an_="[A-Za-z0-9_]"
# to match something like 1ul, floats or hexes as well:
D="$int*\.\?$int\+x\?$hex*[uUlL]\{0,3\}[fF]\?"
# more strict and catches it (costs one backreference for (git-)grep)
d="\($int\+[uUlLfF]\?\|$int\+[uU]\?[lL][lL]\?\|0x$hex\+\|0x$HEX\+\|$i\+[lL][lL][uU]\|$i*\.$i\+[fF]\?\)"

# capital: can be used to catch a definition or config option K="$UP_\+$AN_*";

# can be used for a variable/function name:
V="$an_\+$an_*"
# works the same as above, but also for members and arrays: one backreference
# is more strict
W="$V\(\[$s$V$s\]\|\[$s$D$s\]\|\.$V\|->$V\)*"
# catches it at once (less strict)
w="\($V\|${V}\[$s$an_*${s}\]\|$V\.\|$V->\)\+"

# seperators:
s="[[:space:]]*";
S="[[:space:]]\+"

# useful to delimit a variable name:
Q="[^[:alnum:]_]"
# match the end of the line, including comments: one backreference (but at eol)
cendl="$s\(\/[\*\/].*\)\?$"
# match something that is not comment, string or character: 2 backreferences
ccode="\([^\/\"']*\|\/[^\*\/]\|\/\*\([^\*]*\|\**[^\/\*]\)*\*\+\/\|'[^']*'\|\"[^\"]*\"\)*"
# resp function open and end (only works when indentation is correct.
fo="^[\{]$cendl"
fe="^[\}]$cendl"
se="^[\}];$cendl"
# to match nested parentheses
nps="[^()]*"
nstdps="\(($nps\(($nps\(($nps\(($nps\(($nps)$nps\)*)$nps\)*)$nps\)*)$nps\)*)$nps\)*"
# first determine unsigned typedefs
arr="\(\[[^\]]*\]$s\)*"
attr="__attribute__$s(([^;]*))"
utype="${s}typedef${S}unsigned$S\($V$S\)*"
uns="unsigned$(
git-grep "^$utype\($V$s$arr\|$attr$S$V$s$arr\|$V$s$arr$S$attr\)$s;$cendl" | sed -n "s/^[^.]*\.[hc]:$utype\(\($V\)$s$arr\|$attr$S\($V\)$s$arr\|\($V\)$s$arr$S$attr\)$s;$cendl/\\\\|\3\5\7/p" | sort | uniq | tr -d "\n")"
# define left and right operators
# to decrease the number backrefences, these are assigned in loops
oplfor op in "[;,|^?:(]" "[\!+*/%&|~^-]=" ">>=" "<<=" "\[" "&&" "$an_$s&"; do 
 opl="$opl$op\|$op$s++\|$op$s--\|"
done
opl="\(${opl%|})"
oprfor op in "[;,&|^?:)]" "[\!+*/%&|~^<>-]=" ">>=" "<<=" ">[^>]" "<[^<]" "\]"; do 
 opr="$opr$op\|$op$s++\|$op$s--\|"
done
opr="\(${opr%|})"
# string catches invalid comparison
q1="$opl$s\($w$s\(>=${s}0\|<${s}0\|[><\!=]=$s-$s$D\|[<>]$s-$s$D\)\|\(0$s>\|0$s<=\|-$s$D${s}[><\!=]=\|-$s$D${s}[<>]\)$s$w\)$s$opr"

start=0
end=$(echo $uns | tr -cd "|" | wc -c)

# main function
while [ $start -lt $end ]; do
  # we match 30 typedefs at a time
  tuns="$(echo $uns | cut -d "\\" -f$start-$(($start+29)))"
  # catch candidate files 
  for f in $(git-grep -l "^\(${ccode}[,;]$s\)\?\($tuns\)$S" | grep "[^.]*\.[ch]" | xargs grep -l "$q1"); do
    for n in $(sed -n "/^.*$q1/=" $f); do # lines
      for v in $(sed -n "${n}s/^.*$q1.*$/\3\6/p" $f); do
        # n2 = wine there
        head -n$n $f | tac | sed -n "/^[{]/q; /^\(.*$Q\)\?\($tuns\)$S\($V$S\)*$v$Q.*$/=" | while read n2;        
        do
          echo "# --- invalid test on unsigned variable '$v' --- #"
          echo "vi $f +$n2 # unsigned declaration"
          echo "vi $f +$n # invalid test"
        done
      done
    done
  done
  start=$(($start+30))
done | less
#1 lore raw

I found 63 occurrences of this problem with the following semantic match
(http://www.emn.fr/x-info/coccinelle/):

@@ unsigned int i; @@

* i < 0

I looked through all of the results by hand, and they all seem to be problems. In many cases, it seems like the variable should not be unsigned as it is used to hold the return value of a function that might return a negative error code, but I haven't looked into this in detail.

In the output below, the lines that begin with a single start contain a test of whether an unsigned variable or structure field is less than 0. The output is actually generated with diff, but I converted the -s to *s to avoid confusion.

julia

diff -u -p a/arch/arm/mach-davinci/psc.c b/arch/arm/mach-davinci/psc.c *** a/arch/arm/mach-davinci/psc.c 2008-03-12 14:13:12.000000000 +0100 @@ -70,7 +70,7 @@ void davinci_psc_config(unsigned int dom
{
u32 epcpr, ptcmd, ptstat, pdstat, pdctl1, mdstat, mdctl, mdstat_mask;

* if (id < 0)
return;

mdctl = davinci_readl(DAVINCI_PWR_SLEEP_CNTRL_BASE + MDCTL + 4 * id);
diff -u -p a/arch/cris/arch-v10/kernel/dma.c b/arch/cris/arch-v10/kernel/dma.c *** a/arch/cris/arch-v10/kernel/dma.c 2008-03-12 14:13:12.000000000 +0100 @@ -24,7 +24,7 @@ int cris_request_dma(unsigned int dmanr,
unsigned long int gens;
int fail = -EINVAL;

* if ((dmanr < 0) || (dmanr >= MAX_DMA_CHANNELS)) {
printk(KERN_CRIT "cris_request_dma: invalid DMA channel %u\n", dmanr); return -EINVAL;
}
@@ -213,7 +213,7 @@ int cris_request_dma(unsigned int dmanr,
void cris_free_dma(unsigned int dmanr, const char * device_id)
{
unsigned long flags;
* if ((dmanr < 0) || (dmanr >= MAX_DMA_CHANNELS)) {
printk(KERN_CRIT "cris_free_dma: invalid DMA channel %u\n", dmanr); return;
}
diff -u -p a/arch/mips/sgi-ip27/ip27-timer.c b/arch/mips/sgi-ip27/ip27-timer.c *** a/arch/mips/sgi-ip27/ip27-timer.c 2008-03-12 14:13:12.000000000 +0100 @@ -228,7 +228,7 @@ static void __init hub_rt_clock_event_gl
break;

irq = allocate_irqno();
* if (irq < 0)
panic("Allocation of irq number for timer failed");
} while (xchg(&rt_timer_irq, irq));

diff -u -p a/arch/mips/vr41xx/common/irq.c b/arch/mips/vr41xx/common/irq.c *** a/arch/mips/vr41xx/common/irq.c 2008-03-12 14:13:12.000000000 +0100 @@ -80,7 +80,7 @@ static void irq_dispatch(unsigned int ir
desc->chip->ack(source_irq);
}
irq = cascade->get_irq(irq);
* if (irq < 0)
atomic_inc(&irq_err_count);
else
irq_dispatch(irq);
diff -u -p a/arch/powerpc/kernel/udbg_16550.c b/arch/powerpc/kernel/udbg_16550.c *** a/arch/powerpc/kernel/udbg_16550.c 2008-03-12 14:13:12.000000000 +0100 @@ -142,7 +142,7 @@ unsigned int udbg_probe_uart_speed(void
speed = (clock / prescaler) / (divisor * 16);

/* sanity check */
* if (speed < 0 || speed > (clock / 16))
speed = 9600;

return speed;
diff -u -p a/arch/powerpc/oprofile/cell/vma_map.c b/arch/powerpc/oprofile/cell/vma_map.c *** a/arch/powerpc/oprofile/cell/vma_map.c 2008-04-10 08:32:55.000000000 +0200 @@ -232,7 +232,7 @@ struct vma_to_fileoffset_map *create_vma
*/
overlay_tbl_offset = vma_map_lookup(map, ovly_table_sym,
aSpu, &grd_val);
* if (overlay_tbl_offset < 0) {
printk(KERN_ERR "SPU_PROF: "
"%s, line %d: Error finding SPU overlay table\n", __FUNCTION__, __LINE__);
diff -u -p a/arch/s390/appldata/appldata_base.c b/arch/s390/appldata/appldata_base.c *** a/arch/s390/appldata/appldata_base.c 2008-03-12 14:13:13.000000000 +0100 @@ -438,7 +438,7 @@ out:
*/
int appldata_register_ops(struct appldata_ops *ops)
{
* if ((ops->size > APPLDATA_MAX_REC_SIZE) || (ops->size < 0))
return -EINVAL;

ops->ctl_table = kzalloc(4 * sizeof(struct ctl_table), GFP_KERNEL);
diff -u -p a/arch/sh/kernel/cpu/irq/intc.c b/arch/sh/kernel/cpu/irq/intc.c *** a/arch/sh/kernel/cpu/irq/intc.c 2008-03-12 14:13:13.000000000 +0100 @@ -415,7 +415,7 @@ static unsigned int __init intc_prio_dat
fn += (pr->reg_width >> 3) - 1;
bit = pr->reg_width - ((j + 1) * pr->field_width);

* BUG_ON(bit < 0);

return _INTC_MK(fn, mode,
intc_get_reg(d, reg_e),
@@ -448,7 +448,7 @@ static unsigned int __init intc_sense_da
fn += (sr->reg_width >> 3) - 1;
bit = sr->reg_width - ((j + 1) * sr->field_width);

* BUG_ON(bit < 0);

return _INTC_MK(fn, 0, intc_get_reg(d, sr->reg),
0, sr->field_width, bit);
diff -u -p a/arch/sh/kernel/cpu/sh2a/fpu.c b/arch/sh/kernel/cpu/sh2a/fpu.c *** a/arch/sh/kernel/cpu/sh2a/fpu.c 2008-03-12 14:13:13.000000000 +0100 @@ -299,7 +299,7 @@ static int denormal_addf(int hx, int hy)
iy = hy & 0x7fffffff;
if (iy < 0x00800000) {
ix = denormal_subf1(ix, iy);
* if (ix < 0) {
ix = -ix;
sign ^= 0x80000000;
}
diff -u -p a/arch/x86/mm/ioremap.c b/arch/x86/mm/ioremap.c
*** a/arch/x86/mm/ioremap.c 2008-03-12 14:13:13.000000000 +0100 @@ -470,7 +470,7 @@ void __init early_iounmap(void *addr, un
unsigned int nesting;

nesting = --early_ioremap_nested;
* WARN_ON(nesting < 0);

if (early_ioremap_debug) {
printk(KERN_INFO "early_iounmap(%p, %08lx) [%d]\n", addr,
diff -u -p a/drivers/char/esp.c b/drivers/char/esp.c
*** a/drivers/char/esp.c 2008-03-12 14:13:13.000000000 +0100 @@ -2382,7 +2382,7 @@ static int __init espserial_init(void)
if ((flow_on < 1) || (flow_on > 1023))
flow_on = 944;

* if ((rx_timeout < 0) || (rx_timeout > 255))
rx_timeout = 128;

if (flow_on >= flow_off)
diff -u -p a/drivers/char/hvc_console.c b/drivers/char/hvc_console.c *** a/drivers/char/hvc_console.c 2008-03-12 14:13:13.000000000 +0100 @@ -423,7 +423,7 @@ static void hvc_close(struct tty_struct
free_irq(irq, hp);

} else {
* if (hp->count < 0)
printk(KERN_ERR "hvc_close %X: oops, count is %d\n",
hp->vtermno, hp->count);
spin_unlock_irqrestore(&hp->lock, flags);
diff -u -p a/drivers/char/hvcs.c b/drivers/char/hvcs.c
*** a/drivers/char/hvcs.c 2008-03-12 14:13:13.000000000 +0100
@@ -1248,7 +1248,7 @@ static void hvcs_close(struct tty_struct
free_irq(irq, hvcsd);
kref_put(&hvcsd->kref, destroy_hvcs_struct); return;
* } else if (hvcsd->open_count < 0) {
printk(KERN_ERR "HVCS: vty-server@%X open_count: %d"
" is missmanaged.\n",
hvcsd->vdev->unit_address, hvcsd->open_count);
diff -u -p a/drivers/char/hvsi.c b/drivers/char/hvsi.c
*** a/drivers/char/hvsi.c 2008-03-12 14:13:13.000000000 +0100
@@ -908,7 +908,7 @@ static void hvsi_close(struct tty_struct

spin_lock_irqsave(&hp->lock, flags);
}
* } else if (hp->count < 0)
printk(KERN_ERR "hvsi_close %lu: oops, count is %d\n",
hp - hvsi_ports, hp->count);

diff -u -p a/drivers/gpio/mcp23s08.c b/drivers/gpio/mcp23s08.c *** a/drivers/gpio/mcp23s08.c 2008-03-12 14:13:13.000000000 +0100 @@ -178,7 +178,7 @@ static void mcp23s08_dbg_show(struct seq

mutex_lock(&mcp->lock);
t = mcp23s08_read_regs(mcp, 0, mcp->cache, sizeof mcp->cache);
* if (t < 0) {
seq_printf(s, " I/O ERROR %d\n", t);
goto done;
}
diff -u -p a/drivers/ieee1394/dv1394.c b/drivers/ieee1394/dv1394.c *** a/drivers/ieee1394/dv1394.c 2008-03-12 14:13:13.000000000 +0100 @@ -918,7 +918,7 @@ static int do_dv1394_init(struct video_c
/* default SYT offset is 3 cycles */ init->syt_offset = 3;

* if ( (init->channel > 63) || (init->channel < 0) )
init->channel = 63;

chan_mask = (u64)1 << init->channel;
diff -u -p a/drivers/ieee1394/video1394.c b/drivers/ieee1394/video1394.c *** a/drivers/ieee1394/video1394.c 2008-03-12 14:13:13.000000000 +0100 @@ -893,7 +893,7 @@ static long video1394_ioctl(struct file
if (unlikely(d = NULL))
return -EFAULT;

* if (unlikely((v.buffer<0) || (v.buffer>=d->num_desc - 1))) {
PRINT(KERN_ERR, ohci->host->id,
"Buffer %d out of range",v.buffer);
return -EINVAL;
@@ -959,7 +959,7 @@ static long video1394_ioctl(struct file
if (unlikely(d = NULL))
return -EFAULT;

* if (unlikely((v.buffer<0) || (v.buffer>d->num_desc - 1))) {
PRINT(KERN_ERR, ohci->host->id,
"Buffer %d out of range",v.buffer);
return -EINVAL;
@@ -1030,7 +1030,7 @@ static long video1394_ioctl(struct file
d = find_ctx(&ctx->context_list, OHCI_ISO_TRANSMIT, v.channel); if (d = NULL) return -EFAULT;

* if ((v.buffer<0) || (v.buffer>=d->num_desc - 1)) {
PRINT(KERN_ERR, ohci->host->id,
"Buffer %d out of range",v.buffer);
return -EINVAL;
@@ -1137,7 +1137,7 @@ static long video1394_ioctl(struct file
d = find_ctx(&ctx->context_list, OHCI_ISO_TRANSMIT, v.channel); if (d = NULL) return -EFAULT;

* if ((v.buffer<0) || (v.buffer>=d->num_desc-1)) {
PRINT(KERN_ERR, ohci->host->id,
"Buffer %d out of range",v.buffer);
return -EINVAL;
diff -u -p a/drivers/macintosh/windfarm_smu_sat.c b/drivers/macintosh/windfarm_smu_sat.c *** a/drivers/macintosh/windfarm_smu_sat.c 2008-03-12 14:13:13.000000000 +0100 @@ -88,7 +88,7 @@ struct smu_sdbp_header *smu_sat_get_sdb_
}

len = i2c_smbus_read_word_data(&sat->i2c, 9);
* if (len < 0) {
printk(KERN_ERR "smu_sat_get_sdb_part rd len error\n");
return NULL;
}
diff -u -p a/drivers/media/video/bt8xx/bttv-driver.c b/drivers/media/video/bt8xx/bttv-driver.c *** a/drivers/media/video/bt8xx/bttv-driver.c 2008-03-12 14:13:13.000000000 +0100 @@ -1287,7 +1287,7 @@ set_tvnorm(struct bttv *btv, unsigned in
const struct bttv_tvnorm *tvnorm;
v4l2_std_id id;

* if (norm < 0 || norm >= BTTV_TVNORMS)
return -EINVAL;

tvnorm = &bttv_tvnorms[norm];
@@ -4607,7 +4607,7 @@ static int __init bttv_init_module(void)
#endif
if (gbuffers < 2 || gbuffers > VIDEO_MAX_FRAME)
gbuffers = 2;
* if (gbufsize < 0 || gbufsize > BTTV_MAX_FBUF)
gbufsize = BTTV_MAX_FBUF;
gbufsize = (gbufsize + PAGE_SIZE - 1) & PAGE_MASK;
if (bttv_verbose)
diff -u -p a/drivers/media/video/meye.c b/drivers/media/video/meye.c *** a/drivers/media/video/meye.c 2008-03-12 14:13:13.000000000 +0100 @@ -2020,7 +2020,7 @@ static struct pci_driver meye_driver = {
static int __init meye_init(void)
{
gbuffers = max(2, min((int)gbuffers, MEYE_MAX_BUFNBRS));
* if (gbufsize < 0 || gbufsize > MEYE_MAX_BUFSIZE)
gbufsize = MEYE_MAX_BUFSIZE;
gbufsize = PAGE_ALIGN(gbufsize);
printk(KERN_INFO "meye: using %d buffers with %dk (%dk total) "
diff -u -p a/drivers/media/video/mt20xx.c b/drivers/media/video/mt20xx.c *** a/drivers/media/video/mt20xx.c 2008-03-12 14:13:13.000000000 +0100 @@ -150,7 +150,7 @@ static int mt2032_compute_freq(struct dv
tuner_dbg("mt2032: rfin=%d lo2=%d lo2n=%d lo2a=%d num=%d lo2freq=%d\n",
rfin,lo2,lo2n,lo2a,lo2num,lo2freq);

* if(lo1a<0 || lo1a>7 || lo1n<17 ||lo1n>48 || lo2a<0 ||lo2a >7 ||lo2n<17 || lo2n>30) {
tuner_info("mt2032: frequency parameters out of range: %d %d %d %d\n",
lo1a, lo1n, lo2a,lo2n);
return(-1);
diff -u -p a/drivers/media/video/planb.c b/drivers/media/video/planb.c *** a/drivers/media/video/planb.c 2008-03-12 14:13:13.000000000 +0100
@@ -878,7 +878,7 @@ static int vgrab(struct planb *pb, struc

if(pb->grabbing >= MAX_GBUFFERS)
return -ENOBUFS;
* if(fr > (MAX_GBUFFERS - 1) || fr < 0)
return -EINVAL;
if(mp->height <= 0 || mp->width <= 0)
return -EINVAL;
@@ -1934,7 +1934,7 @@ chk_grab:

if(copy_from_user(&any, arg, sizeof(any)))
return -EFAULT;
* if(any.offset < 0 || any.offset + any.bytes > 0x400)
return -EINVAL;
if(any.bytes > 128)
return -EINVAL;
diff -u -p a/drivers/media/video/saa7134/saa7134-video.c b/drivers/media/video/saa7134/saa7134-video.c *** a/drivers/media/video/saa7134/saa7134-video.c 2008-03-12 14:13:13.000000000 +0100 @@ -1742,7 +1742,7 @@ static int saa7134_s_input(struct file *
if (0 != err)
return err;

* if (i < 0 || i >= SAA7134_INPUT_MAX)
return -EINVAL;
if (NULL = card_in(dev, i).name)
return -EINVAL;
@@ -2427,7 +2427,7 @@ int saa7134_video_init1(struct saa7134_d
/* sanitycheck insmod options */
if (gbuffers < 2 || gbuffers > VIDEO_MAX_FRAME)
gbuffers = 2;
* if (gbufsize < 0 || gbufsize > gbufsize_max)
gbufsize = gbufsize_max;
gbufsize = (gbufsize + PAGE_SIZE - 1) & PAGE_MASK;

diff -u -p a/drivers/media/video/usbvision/usbvision-video.c b/drivers/media/video/usbvision/usbvision-video.c *** a/drivers/media/video/usbvision/usbvision-video.c 2008-03-12 14:13:13.000000000 +0100
@@ -644,7 +644,7 @@ static int vidioc_s_input (struct file *
struct usb_usbvision *usbvision (struct usb_usbvision *) video_get_drvdata(dev);

* if ((input >= usbvision->video_inputs) || (input < 0) )
return -EINVAL;

mutex_lock(&usbvision->lock);
diff -u -p a/drivers/media/video/videodev.c b/drivers/media/video/videodev.c *** a/drivers/media/video/videodev.c 2008-03-12 14:13:13.000000000 +0100 @@ -1213,7 +1213,7 @@ static int __video_do_ioctl(struct inode
v4l2_std_id id = vfd->tvnorms,curr_id=0; unsigned int index = p->index,i;

* if (index<0) {
ret=-EINVAL;
break;
}
diff -u -p a/drivers/mfd/sm501.c b/drivers/mfd/sm501.c *** a/drivers/mfd/sm501.c 2008-03-12 14:13:13.000000000 +0100 @@ -1041,7 +1041,7 @@ static int sm501_plat_probe(struct platf
sm->mem_res = platform_get_resource(dev, IORESOURCE_MEM, 0); sm->platdata = dev->dev.platform_data;

* if (sm->irq < 0) {
dev_err(&dev->dev, "failed to get irq resource\n"); err = sm->irq;
goto err_res;
diff -u -p a/drivers/net/gianfar.c b/drivers/net/gianfar.c
*** a/drivers/net/gianfar.c 2008-03-12 14:13:13.000000000 +0100 @@ -197,11 +197,11 @@ static int gfar_probe(struct platform_de
priv->interruptTransmit = platform_get_irq_byname(pdev, "tx"); priv->interruptReceive = platform_get_irq_byname(pdev, "rx"); priv->interruptError = platform_get_irq_byname(pdev, "error");
* if (priv->interruptTransmit < 0 || priv->interruptReceive < 0 || priv->interruptError < 0)
goto regs_fail;
} else {
priv->interruptTransmit = platform_get_irq(pdev, 0);
* if (priv->interruptTransmit < 0)
goto regs_fail;
}

diff -u -p a/drivers/net/r8169.c b/drivers/net/r8169.c
*** a/drivers/net/r8169.c 2008-03-12 14:13:14.000000000 +0100
@@ -1709,7 +1709,7 @@ rtl8169_init_one(struct pci_dev *pdev, c
if (tp->mac_version = rtl_chip_info[i].mac_version)
break;
}
* if (i < 0) {
/* Unknown chip: assume array element #0, original RTL-8169 */ if (netif_msg_probe(tp)) {
dev_printk(KERN_DEBUG, &pdev->dev,
diff -u -p a/drivers/net/wireless/hermes.c b/drivers/net/wireless/hermes.c *** a/drivers/net/wireless/hermes.c 2008-03-12 14:13:14.000000000 +0100 @@ -439,7 +439,7 @@ int hermes_read_ltv(hermes_t *hw, int ba
u16 rlength, rtype;
unsigned nwords;

* if ( (bufsize < 0) || (bufsize % 2) )
return -EINVAL;

err = hermes_docmd_wait(hw, HERMES_CMD_ACCESS, rid, NULL);
diff -u -p a/drivers/rtc/rtc-sh.c b/drivers/rtc/rtc-sh.c *** a/drivers/rtc/rtc-sh.c 2008-03-12 14:13:14.000000000 +0100 @@ -553,19 +553,19 @@ static int __devinit sh_rtc_probe(struct
spin_lock_init(&rtc->lock);

rtc->periodic_irq = platform_get_irq(pdev, 0);
* if (unlikely(rtc->periodic_irq < 0)) {
dev_err(&pdev->dev, "No IRQ for period\n"); goto err_badres;
}

rtc->carry_irq = platform_get_irq(pdev, 1);
* if (unlikely(rtc->carry_irq < 0)) {
dev_err(&pdev->dev, "No IRQ for carry\n"); goto err_badres;
}

rtc->alarm_irq = platform_get_irq(pdev, 2);
* if (unlikely(rtc->alarm_irq < 0)) {
dev_err(&pdev->dev, "No IRQ for alarm\n"); goto err_badres;
}
diff -u -p a/drivers/scsi/esp_scsi.c b/drivers/scsi/esp_scsi.c *** a/drivers/scsi/esp_scsi.c 2008-03-12 14:13:14.000000000 +0100 @@ -380,7 +380,7 @@ static void esp_advance_dma(struct esp *

p->cur_residue -= len;
p->tot_residue -= len;
* if (p->cur_residue < 0 || p->tot_residue < 0) {
printk(KERN_ERR PFX "esp%d: Data transfer overflow.\n",
esp->host->unique_id);
printk(KERN_ERR PFX "esp%d: cur_residue[%d] tot_residue[%d] "
diff -u -p a/drivers/scsi/u14-34f.c b/drivers/scsi/u14-34f.c
*** a/drivers/scsi/u14-34f.c 2008-03-12 14:13:14.000000000 +0100 @@ -1126,7 +1126,7 @@ static void map_dma(unsigned int i, unsi

    if (scsi_bufflen(SCpnt)) {

count = scsi_dma_map(SCpnt);
* BUG_ON(count < 0);

scsi_for_each_sg(SCpnt, sg, count, k) {
cpp->sglist[k].address = H2DEV(sg_dma_address(sg));
diff -u -p a/drivers/spi/spi_s3c24xx.c b/drivers/spi/spi_s3c24xx.c *** a/drivers/spi/spi_s3c24xx.c 2008-03-12 14:13:14.000000000 +0100 @@ -127,7 +127,7 @@ static int s3c24xx_spi_setupxfer(struct

div = (div / 2) - 1;

* if (div < 0)
div = 1;

if (div > 255)
diff -u -p a/drivers/usb/host/ehci-dbg.c b/drivers/usb/host/ehci-dbg.c *** a/drivers/usb/host/ehci-dbg.c 2008-03-12 14:13:14.000000000 +0100 @@ -454,7 +454,7 @@ static void qh_lines (
(scratch >> 16) & 0x7fff, scratch,
td->urb);
* if (temp < 0)
temp = 0;
else if (size < temp)
temp = size;
@@ -465,7 +465,7 @@ static void qh_lines (
}

temp = snprintf (next, size, "\n");
* if (temp < 0)
temp = 0;
else if (size < temp)
temp = size;
diff -u -p a/drivers/usb/misc/usbtest.c b/drivers/usb/misc/usbtest.c *** a/drivers/usb/misc/usbtest.c 2008-03-12 14:13:14.000000000 +0100 @@ -1556,8 +1556,8 @@ usbtest_ioctl (struct usb_interface *int
if (code != USBTEST_REQUEST)
return -EOPNOTSUPP;

* if (param->iterations <= 0 || param->length < 0
* || param->sglen < 0 || param->vary < 0)
return -EINVAL;

if (mutex_lock_interruptible(&dev->lock))
diff -u -p a/drivers/usb/serial/mos7840.c b/drivers/usb/serial/mos7840.c *** a/drivers/usb/serial/mos7840.c 2008-03-12 14:13:14.000000000 +0100 @@ -1741,7 +1741,7 @@ static int mos7840_tiocmset(struct usb_s

status = 0;
status = mos7840_set_uart_reg(port, MODEM_CONTROL_REGISTER, mcr);
* if (status < 0) {
dbg("setting MODEM_CONTROL_REGISTER Failed\n"); return -1;
}
diff -u -p a/drivers/watchdog/wdt285.c b/drivers/watchdog/wdt285.c *** a/drivers/watchdog/wdt285.c 2008-03-12 14:13:14.000000000 +0100 @@ -162,7 +162,7 @@ watchdog_ioctl(struct inode *inode, stru
break;

/* Arbitrary, can't find the card's limits */
* if (new_margin < 0 || new_margin > 60) {
ret = -EINVAL;
break;
}
diff -u -p a/fs/ext3/inode.c b/fs/ext3/inode.c
*** a/fs/ext3/inode.c 2008-03-12 14:13:14.000000000 +0100
@@ -1263,7 +1263,7 @@ static int ext3_ordered_write_end(struct
EXT3_I(inode)->i_disksize = new_i_size;
copied = ext3_generic_write_end(file, mapping, pos, len, copied,
page, fsdata);
* if (copied < 0)
ret = copied;
}
ret2 = ext3_journal_stop(handle);
@@ -1291,7 +1291,7 @@ static int ext3_writeback_write_end(stru

copied = ext3_generic_write_end(file, mapping, pos, len, copied,
page, fsdata);
* if (copied < 0)
ret = copied;

ret2 = ext3_journal_stop(handle);
diff -u -p a/fs/ext4/inode.c b/fs/ext4/inode.c
*** a/fs/ext4/inode.c 2008-03-12 14:13:14.000000000 +0100
@@ -1303,7 +1303,7 @@ static int ext4_ordered_write_end(struct
EXT4_I(inode)->i_disksize = new_i_size;
copied = ext4_generic_write_end(file, mapping, pos, len, copied,
page, fsdata);
* if (copied < 0)
ret = copied;
}
ret2 = ext4_journal_stop(handle);
@@ -1331,7 +1331,7 @@ static int ext4_writeback_write_end(stru

copied = ext4_generic_write_end(file, mapping, pos, len, copied,
page, fsdata);
* if (copied < 0)
ret = copied;

ret2 = ext4_journal_stop(handle);
diff -u -p a/kernel/relay.c b/kernel/relay.c
*** a/kernel/relay.c 2008-03-12 14:13:15.000000000 +0100 @@ -1134,7 +1134,7 @@ static int subbuf_splice_actor(struct fi
return 0;

ret = *nonpad_ret = splice_to_pipe(pipe, &spd);
* if (ret < 0 || ret < total_len)
return ret;

if (read_start + ret = nonpad_end)
diff -u -p a/mm/slab.c b/mm/slab.c
*** a/mm/slab.c 2008-03-12 14:13:15.000000000 +0100
@@ -3007,7 +3007,7 @@ retry:
* there must be at least one object available for
* allocation.
*/
* BUG_ON(slabp->inuse < 0 || slabp->inuse >= cachep->num);

while (slabp->inuse < cachep->num && batchcount--) {
STATS_INC_ALLOCED(cachep);
diff -u -p a/net/irda/ircomm/ircomm_tty.c b/net/irda/ircomm/ircomm_tty.c *** a/net/irda/ircomm/ircomm_tty.c 2008-03-12 14:13:15.000000000 +0100 @@ -371,7 +371,7 @@ static int ircomm_tty_open(struct tty_st
IRDA_DEBUG(2, "%s()\n", __FUNCTION__ );

line = tty->index;
* if ((line < 0) || (line >= IRCOMM_TTY_PORTS)) {
return -ENODEV;
}

diff -u -p a/net/netfilter/xt_TCPOPTSTRIP.c b/net/netfilter/xt_TCPOPTSTRIP.c *** a/net/netfilter/xt_TCPOPTSTRIP.c 2008-03-12 14:13:15.000000000 +0100 @@ -95,7 +95,7 @@ tcpoptstrip_tg6(struct sk_buff *skb, con

nexthdr = ipv6h->nexthdr;
tcphoff = ipv6_skip_exthdr(skb, sizeof(*ipv6h), &nexthdr);
* if (tcphoff < 0)
return NF_DROP;

return tcpoptstrip_mangle_packet(skb, targinfo, tcphoff,
diff -u -p a/sound/soc/codecs/cs4270.c b/sound/soc/codecs/cs4270.c *** a/sound/soc/codecs/cs4270.c 2008-03-12 14:13:15.000000000 +0100 @@ -399,7 +399,7 @@ static int cs4270_hw_params(struct snd_p
ret = snd_soc_write(codec, CS4270_PWRCTL, CS4270_PWRCTL_FREEZE |
CS4270_PWRCTL_PDN_ADC | CS4270_PWRCTL_PDN_DAC | CS4270_PWRCTL_PDN);
* if (ret < 0) {
printk(KERN_ERR "cs4270: I2C write failed\n"); return ret;
}
@@ -411,7 +411,7 @@ static int cs4270_hw_params(struct snd_p
reg |= cs4270_mode_ratios[i].speed_mode | cs4270_mode_ratios[i].mclk;

ret = snd_soc_write(codec, CS4270_MODE, reg);
* if (ret < 0) {
printk(KERN_ERR "cs4270: I2C write failed\n"); return ret;
}
@@ -434,7 +434,7 @@ static int cs4270_hw_params(struct snd_p
}

ret = snd_soc_write(codec, CS4270_FORMAT, reg);
* if (ret < 0) {
printk(KERN_ERR "cs4270: I2C write failed\n"); return ret;
}
@@ -445,7 +445,7 @@ static int cs4270_hw_params(struct snd_p
reg = snd_soc_read(codec, CS4270_MUTE);
reg &= ~CS4270_MUTE_AUTO;
ret = snd_soc_write(codec, CS4270_MUTE, reg);
* if (ret < 0) {
printk(KERN_ERR "cs4270: I2C write failed\n"); return ret;
}
@@ -453,7 +453,7 @@ static int cs4270_hw_params(struct snd_p
/* Thaw and power-up the codec */

ret = snd_soc_write(codec, CS4270_PWRCTL, 0);
* if (ret < 0) {
printk(KERN_ERR "cs4270: I2C write failed\n"); return ret;
}

#9 lore raw
In reply to Roel Kluin

Does the initialization of result in the following code serve any purpose?

sound/isa/sb/sb_common.c:

static int snd_sbdsp_version(struct snd_sb * chip)

 {
        unsigned int result = -ENODEV;

        snd_sbdsp_command(chip, SB_DSP_GET_VERSION);
        result = (short) snd_sbdsp_get_byte(chip) << 8;

If result is unsigned, its value will never be -ENODEV, and anyway the value is overwritten before it is ever used.

There are a couple of other cases like this. There are also initializations of unsigned variables to -1, which seem prevalent enough that perhaps they serve some purpose.

julia

#10 lore raw
In reply to Roel Kluin

i guess the idea of using unsigned int = -1 is to set all bit. so you do not need something linux =UINT_MAX. That would fail if someone changes int to long and not UINT_MAX.

IMHO the use of 'result' is not need. snd_sbdsp_get_byte will return int i am worried because snd_sbdsp_get_byte() may return -ENODEV. what will short do and why ?

maybe the autor wants this (not tested):

static int snd_sbdsp_version(sb_t * chip)

{
	int major,minor;
	if ( snd_sbdsp_command(chip, SB_DSP_GET_VERSION) =0)
	 return -ENODEV;

        major=snd_sbdsp_get_byte(chip) ;
	if( major<0)
		return -ENODEV;

	minor=snd_sbdsp_get_byte(chip) ;
	if( minor <0)
		return -ENODEV;

	return (major<<8)|minor ;

}

btw: is ANYONE using sb isa card these days ?

re,
wh

Quoted 27 lines · Julia Lawall

Does the initialization of result in the following code serve any purpose?

sound/isa/sb/sb_common.c:

static int snd_sbdsp_version(struct snd_sb * chip)

 {
        unsigned int result = -ENODEV;

        snd_sbdsp_command(chip, SB_DSP_GET_VERSION);
        result = (short) snd_sbdsp_get_byte(chip) << 8;

If result is unsigned, its value will never be -ENODEV, and anyway the value is overwritten before it is ever used.

There are a couple of other cases like this. There are also initializations of unsigned variables to -1, which seem prevalent enough that perhaps they serve some purpose.

julia

--
To unsubscribe from this list: send the line "unsubscribe kernel-janitors" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html

#11 lore raw
In reply to Roel Kluin
Quoted 6 lines · Julia Lawall

I found 63 occurrences of this problem with the following semantic match
(http://www.emn.fr/x-info/coccinelle/):

@@ unsigned int i; @@

* i < 0

Could you also look for unsigned long?

Quoted 4 lines

I looked through all of the results by hand, and they all seem to be problems. In many cases, it seems like the variable should not be unsigned as it is used to hold the return value of a function that might return a negative error code, but I haven't looked into this in detail.

The problem will be if the variable is supposed to be unsigned in some uses and signed in others. The IS_ERR_VALUE() macro from linux/err.h may be useful for this.

Quoted 4 lines

In the output below, the lines that begin with a single start contain a test of whether an unsigned variable or structure field is less than 0. The output is actually generated with diff, but I converted the -s to *s to avoid confusion.

I'll respond to some of these, cc'ing the appropriate people. Thanks for doing this.

Signature · 4 lines
Intel are signing my paycheques ... these opinions are still mine
"Bill, look, we understand that you're interested in selling us this
operating system, but compare it to ours.  We can't possibly take such
a retrograde step."
#2 lore raw

esp_scsi incorrect unsigned test

In reply to Julia Lawall
Quoted 20 lines · Julia Lawall

I found 63 occurrences of this problem with the following semantic match
(http://www.emn.fr/x-info/coccinelle/):

@@ unsigned int i; @@

* i < 0

I looked through all of the results by hand, and they all seem to be problems. In many cases, it seems like the variable should not be unsigned as it is used to hold the return value of a function that might return a negative error code, but I haven't looked into this in detail.

In the output below, the lines that begin with a single start contain a test of whether an unsigned variable or structure field is less than 0. The output is actually generated with diff, but I converted the -s to *s to avoid confusion.

diff -u -p a/drivers/scsi/esp_scsi.c b/drivers/scsi/esp_scsi.c *** a/drivers/scsi/esp_scsi.c 2008-03-12 14:13:14.000000000 +0100

Review static void esp_advance_dma(struct esp * · line 386

Quoted 7 lines
(quoted diff) +0 -0
@@ -380,7 +380,7 @@ static void esp_advance_dma(struct esp *
 
 	p->cur_residue -= len;
 	p->tot_residue -= len;
 *	if (p->cur_residue < 0 || p->tot_residue < 0) {
 		printk(KERN_ERR PFX "esp%d: Data transfer overflow.\n",
 		       esp->host->unique_id);
 		printk(KERN_ERR PFX "esp%d: cur_residue[%d] tot_residue[%d] "

This is clearly buggy. A residue is, though, inherently unsigned, so I don't think we should change the type of the variable. Rather, we should test it before subtraction. Dave, what do you think?

----

Fix ESP data transfer overflow checks

The current code attempts to detect data transfer overflow by checking whether an unsigned variable is negative. Instead, we should compare the two variables before subtracting them.

drivers/scsi/esp_scsi.c +5 -3
index bfdee59..b5e8a94 100644
@@ -378,9 +378,7 @@ static void esp_advance_dma(struct esp *esp, struct esp_cmd_entry *ent,
 		return;
 	}
 
-	p->cur_residue -= len;
-	p->tot_residue -= len;
-	if (p->cur_residue < 0 || p->tot_residue < 0) {
+	if (unlikely(p->cur_residue < len || p->tot_residue < len)) {
 		printk(KERN_ERR PFX "esp%d: Data transfer overflow.\n",
 		       esp->host->unique_id);
 		printk(KERN_ERR PFX "esp%d: cur_residue[%d] tot_residue[%d] "
@@ -389,7 +387,11 @@ static void esp_advance_dma(struct esp *esp, struct esp_cmd_entry *ent,
 		       p->cur_residue, p->tot_residue, len);
 		p->cur_residue = 0;
 		p->tot_residue = 0;
+	} else {
+		p->cur_residue -= len;
+		p->tot_residue -= len;
 	}
+
 	if (!p->cur_residue && p->tot_residue) {
 		p->cur_sg++;
 		p->cur_residue = sg_dma_len(p->cur_sg);
Signature · 4 lines
Intel are signing my paycheques ... these opinions are still mine
"Bill, look, we understand that you're interested in selling us this
operating system, but compare it to ours.  We can't possibly take such
a retrograde step."
maintainer
#3 lore raw

Re: esp_scsi incorrect unsigned test

Quoted 49 lines · Matthew Wilcox
Quoted 20 lines · Julia Lawall

I found 63 occurrences of this problem with the following semantic match
(http://www.emn.fr/x-info/coccinelle/):

@@ unsigned int i; @@

* i < 0

I looked through all of the results by hand, and they all seem to be problems. In many cases, it seems like the variable should not be unsigned as it is used to hold the return value of a function that might return a negative error code, but I haven't looked into this in detail.

In the output below, the lines that begin with a single start contain a test of whether an unsigned variable or structure field is less than 0. The output is actually generated with diff, but I converted the -s to *s to avoid confusion.

diff -u -p a/drivers/scsi/esp_scsi.c b/drivers/scsi/esp_scsi.c *** a/drivers/scsi/esp_scsi.c 2008-03-12 14:13:14.000000000 +0100

drivers/scsi/esp_scsi.c static void esp_advance_dma(struct esp * · line 386

Quoted 7 lines
drivers/scsi/esp_scsi.c +0 -0
@@ -380,7 +380,7 @@ static void esp_advance_dma(struct esp *
 
 	p->cur_residue -= len;
 	p->tot_residue -= len;
 *	if (p->cur_residue < 0 || p->tot_residue < 0) {
 		printk(KERN_ERR PFX "esp%d: Data transfer overflow.\n",
 		       esp->host->unique_id);
 		printk(KERN_ERR PFX "esp%d: cur_residue[%d] tot_residue[%d] "

This is clearly buggy. A residue is, though, inherently unsigned, so I don't think we should change the type of the variable. Rather, we should test it before subtraction. Dave, what do you think?

----

Fix ESP data transfer overflow checks

The current code attempts to detect data transfer overflow by checking whether an unsigned variable is negative. Instead, we should compare the two variables before subtracting them.

drivers/scsi/esp_scsi.c +0 -0
index bfdee59..b5e8a94 100644

drivers/scsi/esp_scsi.c static void esp_advance_dma(struct esp *esp, struct esp_cmd_entry *ent, · line 384

Quoted 10 lines
drivers/scsi/esp_scsi.c +1 -3
@@ -378,9 +378,7 @@ static void esp_advance_dma(struct esp *esp, struct esp_cmd_entry *ent,
 		return;
 	}
 
-	p->cur_residue -= len;
-	p->tot_residue -= len;
-	if (p->cur_residue < 0 || p->tot_residue < 0) {
+	if (unlikely(p->cur_residue < len || p->tot_residue < len)) {
 		printk(KERN_ERR PFX "esp%d: Data transfer overflow.\n",
 		       esp->host->unique_id);
 		printk(KERN_ERR PFX "esp%d: cur_residue[%d] tot_residue[%d] "

To be pedantic, this should be %u not %d for unsigned.

drivers/scsi/esp_scsi.c static void esp_advance_dma(struct esp *esp, struct esp_cmd_entry *ent, · line 397

Quoted 12 lines
drivers/scsi/esp_scsi.c +4 -0
@@ -389,7 +387,11 @@ static void esp_advance_dma(struct esp *esp, struct esp_cmd_entry *ent,
 		       p->cur_residue, p->tot_residue, len);
 		p->cur_residue = 0;
 		p->tot_residue = 0;
+	} else {
+		p->cur_residue -= len;
+		p->tot_residue -= len;
 	}
+
 	if (!p->cur_residue && p->tot_residue) {
 		p->cur_sg++;
 		p->cur_residue = sg_dma_len(p->cur_sg);

It look fine to me ... although an alternative (and possibly simpler) fix would just be to remove the unsigned from the two residue definitions in the struct.

James

#5 lore raw

u14-3f incorrect unsigned test

In reply to Julia Lawall
Quoted 20 lines · Julia Lawall

I found 63 occurrences of this problem with the following semantic match
(http://www.emn.fr/x-info/coccinelle/):

@@ unsigned int i; @@

* i < 0

I looked through all of the results by hand, and they all seem to be problems. In many cases, it seems like the variable should not be unsigned as it is used to hold the return value of a function that might return a negative error code, but I haven't looked into this in detail.

In the output below, the lines that begin with a single start contain a test of whether an unsigned variable or structure field is less than 0. The output is actually generated with diff, but I converted the -s to *s to avoid confusion.

diff -u -p a/drivers/scsi/u14-34f.c b/drivers/scsi/u14-34f.c *** a/drivers/scsi/u14-34f.c 2008-03-12 14:13:14.000000000 +0100

Review static void map_dma(unsigned int i, unsi · line 1132

Quoted 7 lines
(quoted diff) +0 -0
@@ -1126,7 +1126,7 @@ static void map_dma(unsigned int i, unsi
 
    if (scsi_bufflen(SCpnt)) {
 	   count = scsi_dma_map(SCpnt);
 *	   BUG_ON(count < 0);
 
 	   scsi_for_each_sg(SCpnt, sg, count, k) {
 		   cpp->sglist[k].address = H2DEV(sg_dma_address(sg));

----

u14-34f: Correct unsigned comparison against 0

scsi_dma_map() can return an error. The current situation of BUG_ON for an out of memory condition is far from ideal, but it's better than the current situation where running out of memory will lead to the driver trying to walk through 4 billion sg entries.

drivers/scsi/u14-34f.c +2 -2
index 58d7eee..11df071 100644
@@ -1110,7 +1110,7 @@ static int u14_34f_detect(struct scsi_host_template *tpnt) {
 
 static void map_dma(unsigned int i, unsigned int j) {
    unsigned int data_len = 0;
-   unsigned int k, count, pci_dir;
+   unsigned int k, pci_dir;
    struct scatterlist *sg;
    struct mscp *cpp;
    struct scsi_cmnd *SCpnt;
@@ -1125,7 +1125,7 @@ static void map_dma(unsigned int i, unsigned int j) {
    cpp->sense_len = SCSI_SENSE_BUFFERSIZE;
 
    if (scsi_bufflen(SCpnt)) {
-	   count = scsi_dma_map(SCpnt);
+	   int count = scsi_dma_map(SCpnt);
 	   BUG_ON(count < 0);
 
 	   scsi_for_each_sg(SCpnt, sg, count, k) {
Signature · 4 lines
Intel are signing my paycheques ... these opinions are still mine
"Bill, look, we understand that you're interested in selling us this
operating system, but compare it to ours.  We can't possibly take such
a retrograde step."
#7 lore raw
In reply to a message not in the archive
Quoted 20 lines · Julia Lawall

I found 63 occurrences of this problem with the following semantic match
(http://www.emn.fr/x-info/coccinelle/):

@@ unsigned int i; @@

* i < 0

I looked through all of the results by hand, and they all seem to be problems. In many cases, it seems like the variable should not be unsigned as it is used to hold the return value of a function that might return a negative error code, but I haven't looked into this in detail.

In the output below, the lines that begin with a single start contain a test of whether an unsigned variable or structure field is less than 0. The output is actually generated with diff, but I converted the -s to *s to avoid confusion.

diff -u -p a/drivers/spi/spi_s3c24xx.c b/drivers/spi/spi_s3c24xx.c *** a/drivers/spi/spi_s3c24xx.c 2008-03-12 14:13:14.000000000 +0100

Review static int s3c24xx_spi_setupxfer(struct · line 133

Quoted 7 lines
(quoted diff) +0 -0
@@ -127,7 +127,7 @@ static int s3c24xx_spi_setupxfer(struct 
 
 	div = (div / 2) - 1;
 
 *	if (div < 0)
 		div = 1;
 
 	if (div > 255)

Since this one's always in the range 0-255, it could probably be made signed, but it's just as easy to make it work unsigned.

drivers/spi/spi_s3c24xx.c +3 -3
index b7476b8..b398cc9 100644
@@ -125,10 +125,10 @@ static int s3c24xx_spi_setupxfer(struct spi_device *spi,
 	/* is clk = pclk / (2 * (pre+1)), or is it
 	 *    clk = (pclk * 2) / ( pre + 1) */
 
-	div = (div / 2) - 1;
+	div /= 2;
 
-	if (div < 0)
-		div = 1;
+	if (div > 0)
+		div -= 1;
 
 	if (div > 255)
 		div = 255;
Signature · 4 lines
Intel are signing my paycheques ... these opinions are still mine
"Bill, look, we understand that you're interested in selling us this
operating system, but compare it to ours.  We can't possibly take such
a retrograde step."
#8 lore raw
In reply to Julia Lawall
Quoted 46 lines · Julia Lawall

I found 63 occurrences of this problem with the following semantic match
(http://www.emn.fr/x-info/coccinelle/):

@@ unsigned int i; @@

* i < 0

I looked through all of the results by hand, and they all seem to be problems. In many cases, it seems like the variable should not be unsigned as it is used to hold the return value of a function that might return a negative error code, but I haven't looked into this in detail.

In the output below, the lines that begin with a single start contain a test of whether an unsigned variable or structure field is less than 0. The output is actually generated with diff, but I converted the -s to *s to avoid confusion.

diff -u -p a/fs/ext3/inode.c b/fs/ext3/inode.c *** a/fs/ext3/inode.c 2008-03-12 14:13:14.000000000 +0100

(quoted diff) +0 -0
@@ -1263,7 +1263,7 @@ static int ext3_ordered_write_end(struct
 			EXT3_I(inode)->i_disksize = new_i_size;
 		copied = ext3_generic_write_end(file, mapping, pos, len, copied,
 							page, fsdata);
 *		if (copied < 0)
 			ret = copied;
 	}
 	ret2 = ext3_journal_stop(handle);
@@ -1291,7 +1291,7 @@ static int ext3_writeback_write_end(stru
 
 	copied = ext3_generic_write_end(file, mapping, pos, len, copied,
 							page, fsdata);
 *	if (copied < 0)
 		ret = copied;
 
 	ret2 = ext3_journal_stop(handle);

diff -u -p a/fs/ext4/inode.c b/fs/ext4/inode.c *** a/fs/ext4/inode.c 2008-03-12 14:13:14.000000000 +0100

(quoted diff) +0 -0
@@ -1303,7 +1303,7 @@ static int ext4_ordered_write_end(struct
 			EXT4_I(inode)->i_disksize = new_i_size;
 		copied = ext4_generic_write_end(file, mapping, pos, len, copied,
 							page, fsdata);
 *		if (copied < 0)
 			ret = copied;
 	}
 	ret2 = ext4_journal_stop(handle);

Review static int ext4_writeback_write_end(stru · line 1337

Quoted 7 lines
(quoted diff) +0 -0
@@ -1331,7 +1331,7 @@ static int ext4_writeback_write_end(stru
 
 	copied = ext4_generic_write_end(file, mapping, pos, len, copied,
 							page, fsdata);
 *	if (copied < 0)
 		ret = copied;
 
 	ret2 = ext4_journal_stop(handle);

Fix comparisons of an unsigned int against 0

It's not really feasible to change 'copied' into a signed int, and while we could cast it for the purposes of this comparison, I think this rearrangement of the tests is actually clearer than the original.

fs/ext3/inode.c +6 -11
index eb95670..60f504b 100644
@@ -1261,18 +1261,16 @@ static int ext3_ordered_write_end(struct file *file,
 		new_i_size = pos + copied;
 		if (new_i_size > EXT3_I(inode)->i_disksize)
 			EXT3_I(inode)->i_disksize = new_i_size;
-		copied = ext3_generic_write_end(file, mapping, pos, len, copied,
+		ret = ext3_generic_write_end(file, mapping, pos, len, copied,
 							page, fsdata);
-		if (copied < 0)
-			ret = copied;
 	}
 	ret2 = ext3_journal_stop(handle);
-	if (!ret)
+	if (ret >= 0 && ret2)
 		ret = ret2;
 	unlock_page(page);
 	page_cache_release(page);
 
-	return ret ? ret : copied;
+	return ret;
 }
 
 static int ext3_writeback_write_end(struct file *file,
@@ -1289,18 +1287,15 @@ static int ext3_writeback_write_end(struct file *file,
 	if (new_i_size > EXT3_I(inode)->i_disksize)
 		EXT3_I(inode)->i_disksize = new_i_size;
 
-	copied = ext3_generic_write_end(file, mapping, pos, len, copied,
+	ret = ext3_generic_write_end(file, mapping, pos, len, copied,
 							page, fsdata);
-	if (copied < 0)
-		ret = copied;
-
 	ret2 = ext3_journal_stop(handle);
-	if (!ret)
+	if (ret >= 0 && ret2)
 		ret = ret2;
 	unlock_page(page);
 	page_cache_release(page);
 
-	return ret ? ret : copied;
+	return ret;
 }
 
 static int ext3_journalled_write_end(struct file *file,
fs/ext4/inode.c +6 -10
index 945cbf6..69b29c6 100644
@@ -1301,18 +1301,16 @@ static int ext4_ordered_write_end(struct file *file,
 		new_i_size = pos + copied;
 		if (new_i_size > EXT4_I(inode)->i_disksize)
 			EXT4_I(inode)->i_disksize = new_i_size;
-		copied = ext4_generic_write_end(file, mapping, pos, len, copied,
+		ret = ext4_generic_write_end(file, mapping, pos, len, copied,
 							page, fsdata);
-		if (copied < 0)
-			ret = copied;
 	}
 	ret2 = ext4_journal_stop(handle);
-	if (!ret)
+	if (ret >= 0 && ret2)
 		ret = ret2;
 	unlock_page(page);
 	page_cache_release(page);
 
-	return ret ? ret : copied;
+	return ret;
 }
 
 static int ext4_writeback_write_end(struct file *file,
@@ -1329,18 +1327,16 @@ static int ext4_writeback_write_end(struct file *file,
 	if (new_i_size > EXT4_I(inode)->i_disksize)
 		EXT4_I(inode)->i_disksize = new_i_size;
 
-	copied = ext4_generic_write_end(file, mapping, pos, len, copied,
+	ret = ext4_generic_write_end(file, mapping, pos, len, copied,
 							page, fsdata);
-	if (copied < 0)
-		ret = copied;
 
 	ret2 = ext4_journal_stop(handle);
-	if (!ret)
+	if (ret >= 0 && ret2)
 		ret = ret2;
 	unlock_page(page);
 	page_cache_release(page);
 
-	return ret ? ret : copied;
+	return ret;
 }
 
 static int ext4_journalled_write_end(struct file *file,
Signature · 4 lines
Intel are signing my paycheques ... these opinions are still mine
"Bill, look, we understand that you're interested in selling us this
operating system, but compare it to ours.  We can't possibly take such
a retrograde step."
#12 lore raw
In reply to Roel Kluin
Quoted 9 lines · Matthew Wilcox
Quoted 6 lines · Julia Lawall

I found 63 occurrences of this problem with the following semantic match
(http://www.emn.fr/x-info/coccinelle/):

@@ unsigned int i; @@

* i < 0

Could you also look for unsigned long?

Attached. Many of these are in the "a < X || a > Y" category.

julia

-----------------------

diff -u -p a/arch/m32r/kernel/ptrace.c b/arch/m32r/kernel/ptrace.c *** a/arch/m32r/kernel/ptrace.c 2008-03-12 14:13:12.000000000 +0100 @@ -78,7 +78,7 @@ static int ptrace_read_user(struct task_
struct user * dummy = NULL;
#endif

* if ((off & 3) || (off < 0) || (off > sizeof(struct user) - 3))
return -EIO;

off >>= 2;
@@ -140,7 +140,7 @@ static int ptrace_write_user(struct task
struct user * dummy = NULL;
#endif

* if ((off & 3) || off < 0 ||
off > sizeof(struct user) - 3)
return -EIO;

diff -u -p a/arch/mips/kernel/irixelf.c b/arch/mips/kernel/irixelf.c *** a/arch/mips/kernel/irixelf.c 2008-03-12 14:13:12.000000000 +0100 @@ -587,7 +587,7 @@ static void irix_map_prda_page(void)
v = do_brk(PRDA_ADDRESS, PAGE_SIZE); up_write(&current->mm->mmap_sem);

* if (v < 0)
return;

pp = (struct prda *) v;
diff -u -p a/drivers/atm/fore200e.c b/drivers/atm/fore200e.c *** a/drivers/atm/fore200e.c 2008-03-12 14:13:13.000000000 +0100 @@ -1031,7 +1031,7 @@ int bsq_audit(int where, struct host_bsq
where, scheme, magn, buffer->index, buffer->scheme);
}

* if ((buffer->index < 0) || (buffer->index >= fore200e_rx_buf_nbr[ scheme ][ magn ])) {
printk(FORE200E "bsq_audit(%d): queue %d.%d, out of range buffer index = %ld !\n",
where, scheme, magn, buffer->index);
}
diff -u -p a/drivers/char/dsp56k.c b/drivers/char/dsp56k.c
*** a/drivers/char/dsp56k.c 2008-03-12 14:13:13.000000000 +0100
@@ -395,7 +395,7 @@ static int dsp56k_ioctl(struct inode *in
return put_user(status, &hf->status);
}
case DSP56K_HOST_CMD:
* if (arg > 31 || arg < 0)
return -EINVAL;
dsp56k_host_interface.cvr = (u_char)((arg & DSP56K_CVR_HV_MASK) |
DSP56K_CVR_HC);
diff -u -p a/drivers/hid/usbhid/hiddev.c b/drivers/hid/usbhid/hiddev.c
*** a/drivers/hid/usbhid/hiddev.c 2008-03-12 14:13:13.000000000 +0100
@@ -420,7 +420,7 @@ static int hiddev_ioctl(struct inode *in
return put_user(HID_VERSION, (int __user *)arg);

case HIDIOCAPPLICATION:
* if (arg < 0 || arg >= hid->maxapplication)
return -EINVAL;

for (i = 0; i < hid->maxcollection; i++)
diff -u -p a/drivers/hwmon/fscpos.c b/drivers/hwmon/fscpos.c *** a/drivers/hwmon/fscpos.c 2008-03-12 14:13:13.000000000 +0100 @@ -230,7 +230,7 @@ static ssize_t set_pwm(struct i2c_client
unsigned long v = simple_strtoul(buf, NULL, 10);

/* Range: 0..255 */
* if (v < 0) v = 0;
if (v > 255) v = 255;

mutex_lock(&data->update_lock);
diff -u -p a/drivers/i2c/chips/tsl2550.c b/drivers/i2c/chips/tsl2550.c *** a/drivers/i2c/chips/tsl2550.c 2008-03-12 14:13:13.000000000 +0100 @@ -221,7 +221,7 @@ static ssize_t tsl2550_store_power_state
unsigned long val = simple_strtoul(buf, NULL, 10); int ret;

* if (val < 0 || val > 1)
return -EINVAL;

mutex_lock(&data->update_lock);
@@ -253,7 +253,7 @@ static ssize_t tsl2550_store_operating_m
unsigned long val = simple_strtoul(buf, NULL, 10); int ret;

* if (val < 0 || val > 1)
return -EINVAL;

if (data->power_state = 0)
diff -u -p a/drivers/ide/ide-cd.c b/drivers/ide/ide-cd.c
*** a/drivers/ide/ide-cd.c 2008-03-12 14:13:13.000000000 +0100 @@ -182,7 +182,7 @@ void cdrom_analyze_sense_data(ide_drive_
sector &= ~(bio_sectors -1);
valid = (sector - failed_command->sector) << 9;

* if (valid < 0)
valid = 0;
if (sector < get_capacity(info->disk) &&
drive->probed_capacity - sector < 4 * 75) {
diff -u -p a/drivers/message/i2o/i2o_block.c b/drivers/message/i2o/i2o_block.c *** a/drivers/message/i2o/i2o_block.c 2008-03-12 14:13:13.000000000 +0100 @@ -670,7 +670,7 @@ static int i2o_block_ioctl(struct inode
case BLKI2OGWSTRAT:
return put_user(dev->wcache, (int __user *)arg);
case BLKI2OSRSTRAT:
* if (arg < 0 || arg > CACHE_SMARTFETCH)
return -EINVAL;
dev->rcache = arg;
break;
diff -u -p a/drivers/misc/intel_menlow.c b/drivers/misc/intel_menlow.c *** a/drivers/misc/intel_menlow.c 2008-03-12 14:13:13.000000000 +0100 @@ -121,7 +121,7 @@ static int memory_set_cur_bandwidth(stru
if (memory_get_int_max_bandwidth(cdev, &max_state))
return -EFAULT;

* if (max_state < 0 || state > max_state)
return -EINVAL;

arg_list.count = 1;
diff -u -p a/drivers/mtd/devices/slram.c b/drivers/mtd/devices/slram.c *** a/drivers/mtd/devices/slram.c 2008-03-12 14:13:13.000000000 +0100 @@ -270,7 +270,7 @@ static int parse_cmdline(char *devname,
}
T("slram: devname=%s, devstart=0x%lx, devlength=0x%lx\n",
devname, devstart, devlength);
* if ((devstart < 0) || (devlength < 0) || (devlength % SLRAM_BLK_SZ != 0)) {
E("slram: Illegal start / length parameter.\n"); return(-EINVAL);
}
diff -u -p a/drivers/mtd/ubi/build.c b/drivers/mtd/ubi/build.c *** a/drivers/mtd/ubi/build.c 2008-03-12 14:13:13.000000000 +0100 @@ -1059,7 +1059,7 @@ static int __init bytes_str_to_int(const
unsigned long result;

result = simple_strtoul(str, &endp, 0);
* if (str = endp || result < 0) {
printk(KERN_ERR "UBI error: incorrect bytes count: \"%s\"\n",
str);
return -EINVAL;
diff -u -p a/drivers/telephony/ixj.c b/drivers/telephony/ixj.c *** a/drivers/telephony/ixj.c 2008-03-12 14:13:14.000000000 +0100 @@ -6598,7 +6598,7 @@ static int ixj_ioctl(struct inode *inode
retval = ixj_init_filter_raw(j, &jfr);
break;
case IXJCTL_GET_FILTER_HIST:
* if(arg<0||arg>3)
retval = -EINVAL;
else
retval = j->filter_hist[arg];
@@ -6633,7 +6633,7 @@ static int ixj_ioctl(struct inode *inode
}
break;
case IXJCTL_INTERCOM_STOP:
* if(arg < 0 || arg >= IXJMAX)
return -EINVAL;
j->intercom = -1;
ixj_record_stop(j);
@@ -6645,7 +6645,7 @@ static int ixj_ioctl(struct inode *inode
idle(get_ixj(arg));
break;
case IXJCTL_INTERCOM_START:
* if(arg < 0 || arg >= IXJMAX)
return -EINVAL;
j->intercom = arg;
ixj_record_start(j);
diff -u -p a/drivers/usb/misc/usbtest.c b/drivers/usb/misc/usbtest.c *** a/drivers/usb/misc/usbtest.c 2008-03-12 14:13:14.000000000 +0100 @@ -212,7 +212,7 @@ static struct urb *simple_alloc_urb (
{
struct urb *urb;

* if (bytes < 0)
return NULL;
urb = usb_alloc_urb (0, GFP_KERNEL);
if (!urb)
diff -u -p a/drivers/video/atmel_lcdfb.c b/drivers/video/atmel_lcdfb.c *** a/drivers/video/atmel_lcdfb.c 2008-03-12 14:13:14.000000000 +0100 @@ -743,7 +743,7 @@ static int __init atmel_lcdfb_probe(stru
}

sinfo->irq_base = platform_get_irq(pdev, 0);
* if (sinfo->irq_base < 0) {
dev_err(dev, "unable to get irq\n");
ret = sinfo->irq_base;
goto stop_clk;
diff -u -p a/kernel/softlockup.c b/kernel/softlockup.c
*** a/kernel/softlockup.c 2008-03-12 14:13:15.000000000 +0100 @@ -154,7 +154,7 @@ static void check_hung_task(struct task_
if ((long)(now - t->last_switch_timestamp) <
sysctl_hung_task_timeout_secs)
return;
* if (sysctl_hung_task_warnings < 0)
return;
sysctl_hung_task_warnings--;

diff -u -p a/kernel/sys.c b/kernel/sys.c
*** a/kernel/sys.c 2008-03-12 14:13:15.000000000 +0100
@@ -1647,7 +1647,7 @@ asmlinkage long sys_prctl(int option, un
error = get_dumpable(current->mm); break;
case PR_SET_DUMPABLE:
* if (arg2 < 0 || arg2 > 1) {
error = -EINVAL;
break;
}
diff -u -p a/sound/oss/dmabuf.c b/sound/oss/dmabuf.c
*** a/sound/oss/dmabuf.c 2008-03-12 14:13:15.000000000 +0100 @@ -797,7 +797,7 @@ static int find_output_space(int dev, ch
#else
active_offs = DMAbuf_get_buffer_pointer(dev, dmap, DMODE_OUTPUT); /* Check for pointer wrapping situation */
* if (active_offs < 0 || active_offs >= dmap->bytes_in_use)
active_offs = 0;
active_offs += dmap->byte_counter;
#endif
diff -u -p a/sound/oss/trident.c b/sound/oss/trident.c
*** a/sound/oss/trident.c 2008-03-12 14:13:15.000000000 +0100 @@ -4039,7 +4039,7 @@ ali_write_proc(struct file *file, const
unsigned long flags;
char c;

* if (count < 0)
return -EINVAL;
if (count = 0)
return 0;
diff -u -p a/sound/spi/at73c213.c b/sound/spi/at73c213.c *** a/sound/spi/at73c213.c 2008-03-12 14:13:15.000000000 +0100 @@ -174,7 +174,7 @@ static int snd_at73c213_set_bitrate(stru
dac_rate_new = 8 * (ssc_rate / ssc_div);

status = clk_round_rate(chip->board->dac_clk, dac_rate_new);
* if (status < 0)
return status;

/* Ignore difference smaller than 256 Hz. */
@@ -189,7 +189,7 @@ static int snd_at73c213_set_bitrate(stru

set_rate:
status = clk_set_rate(chip->board->dac_clk, status);
* if (status < 0)
return status;

/* Set divider in SSC device. */

#13 lore raw
In reply to Roel Kluin
Quoted 9 lines · Matthew Wilcox
Quoted 6 lines · Julia Lawall

I found 63 occurrences of this problem with the following semantic match
(http://www.emn.fr/x-info/coccinelle/):

@@ unsigned int i; @@

* i < 0

Could you also look for unsigned long?

A few more...

julia

------------------------------

diff -u -p a/drivers/video/amifb.c b/drivers/video/amifb.c *** a/drivers/video/amifb.c 2008-03-12 14:13:14.000000000 +0100 @@ -2053,7 +2053,7 @@ static void amifb_copyarea(struct fb_inf
sy = area->sy + (dy - area->dy);

/* the source must be completely inside the virtual screen */
* if (sx < 0 || sy < 0 || (sx + width) > info->var.xres_virtual ||
(sy + height) > info->var.yres_virtual)
return;

diff -u -p a/drivers/video/atafb.c b/drivers/video/atafb.c *** a/drivers/video/atafb.c 2008-03-12 14:13:14.000000000 +0100 @@ -2598,7 +2598,7 @@ static void atafb_copyarea(struct fb_inf
sy = area->sy + (dy - area->dy);

/* the source must be completely inside the virtual screen */
* if (sx < 0 || sy < 0 || (sx + width) > info->var.xres_virtual ||
(sy + height) > info->var.yres_virtual)
return;

diff -u -p a/drivers/video/aty/aty128fb.c b/drivers/video/aty/aty128fb.c *** a/drivers/video/aty/aty128fb.c 2008-03-12 14:13:14.000000000 +0100 @@ -1350,7 +1350,7 @@ static int aty128_var_to_pll(u32 period_
}
}

* if (pll->post_divider < 0)
return -EINVAL;

/* calculate feedback divider */

#4 lore raw

Re: esp_scsi incorrect unsigned test

In reply to James Bottomley

From: James Bottomley <[email protected]>
Date: Sat, 19 Apr 2008 09:16:38 -0500

Quoted 3 lines

It look fine to me ... although an alternative (and possibly simpler) fix would just be to remove the unsigned from the two residue definitions in the struct.

I think that's the better approach too. James, please apply.

esp_scsi: Make cur_residue and tot_residue signed.

Many of the overflow checks test whether the value has gone negative, and we want to retain such checks.

Reported by Julia Lawall.

drivers/scsi/esp_scsi.h +2 -2
index d5576d5..9367a88 100644
@@ -240,9 +240,9 @@ struct esp_cmd_priv {
 		int		num_sg;
 	} u;
 
-	unsigned int		cur_residue;
+	int			cur_residue;
 	struct scatterlist	*cur_sg;
-	unsigned int		tot_residue;
+	int			tot_residue;
 };
 #define ESP_CMD_PRIV(CMD)	((struct esp_cmd_priv *)(&(CMD)->SCp))
 
#14 lore raw
In reply to Roel Kluin

Some functions have return type unsigned int, but return a negative integer anyway. I don't know whether this is a problem in practice, because the integer will get its proper value back if stored in a variable of type int, but at least it gives the wrong impression.

A list of these functions is below.

A simplified version of the semantic match used to find these functions is as follows (http://www.emn.fr/x-info/coccinelle/):

@@
identifier f;
expression E, E1;
constant C;
position p;
@@

unsigned f@p(...) {
... when any
(
* return -C;
|
E = -C;
... when != E = E1
* return E;
)
}

julia

----------------------------------------

powernowk8_get:            arch/x86/kernel/cpu/cpufreq/powernow-k8.c::1232
nforce2_detect_chipset:    arch/x86/kernel/cpu/cpufreq/cpufreq-nforce2.c::391
longrun_determine_freqs:   arch/x86/kernel/cpu/cpufreq/longrun.c::168
speedstep_get_freqs:       arch/x86/kernel/cpu/cpufreq/speedstep-lib.c::346
speedstep_get:             arch/x86/kernel/cpu/cpufreq/speedstep-smi.c::320
ia32_poke:                 arch/ia64/ia32/sys_ia32.c::1446
prom_claim:                arch/powerpc/kernel/prom_init.c::361
bfin_gpio_irq_startup:     arch/blackfin/mach-common/ints-priority.c::698
make_rate:                 drivers/atm/firestream.c::446
r3964_poll:                drivers/char/n_r3964.c::1213
FAN_FROM_REG:              drivers/hwmon/adm9240.c::111
amd_ec_wait_read:          drivers/i2c/busses/i2c-amd8111.c::86
amd_ec_read:               drivers/i2c/busses/i2c-amd8111.c::102
amd_ec_wait_write:         drivers/i2c/busses/i2c-amd8111.c::70
amd_ec_write:              drivers/i2c/busses/i2c-amd8111.c::120
pasemi_smb_waitready:      drivers/i2c/busses/i2c-pasemi.c::90
init_chipset_cs5530:       drivers/ide/pci/cs5530.c::135
init_chipset_hpt366:       drivers/ide/pci/hpt366.c::967
init_chipset_pdcnew:       drivers/ide/pci/pdc202xx_new.c::327
pci_init_sgiioc4:          drivers/ide/pci/sgiioc4.c::669
init_chipset_sis5513:      drivers/ide/pci/sis5513.c::362
sl82c105_bridge_revision:  drivers/ide/pci/sl82c105.c::235
init_chipset_via82cxxx:    drivers/ide/pci/via82cxxx.c::269
cinergyt2_poll:            drivers/media/dvb/cinergyT2/cinergyT2.c::555
dvb_demux_poll:            drivers/media/dvb/dvb-core/dmxdev.c::943
radio_poll:                drivers/media/video/bt8xx/bttv-driver.c::3599
saa_geo_setup:             drivers/media/video/planb.c::204
pwc_video_poll:            drivers/media/video/pwc/pwc-if.c::1381
v4l_stk_poll:              drivers/media/video/stk-webcam.c::794
xc2028_get_reg:            drivers/media/video/tuner-xc2028.c::130
scc_set_param:             drivers/net/hamradio/scc.c::1299
tun_chr_poll:              drivers/net/tun.c::262
calc_L1_latency:           drivers/pci/pcie/aspm.c::243
calc_L0S_latency:          drivers/pci/pcie/aspm.c::226
tiqdio_check_chsc_availability:         drivers/s390/cio/qdio.c::2352
tiqdio_set_subchannel_ind:              drivers/s390/cio/qdio.c::2396
tiqdio_set_delay_target:                drivers/s390/cio/qdio.c::2503
jsm_tty_get_mctrl:                      drivers/serial/jsm/jsm_tty.c::74
uio_poll:                               drivers/uio/uio.c::360
nfsacl_encode:                          fs/nfs_common/nfsacl.c::75
nfsacl_decode:                          fs/nfs_common/nfsacl.c::227
tipc_k_signal:                          net/tipc/handler.c::55
p9_fd_poll:                             net/9p/trans_fd.c::1255
snd_pcm_hw_param_value_min:             sound/core/oss/pcm_oss.c::149
snd_pcm_hw_param_value_max:             sound/core/oss/pcm_oss.c::175
azx_rirb_get_response:                  sound/pci/hda/hda_intel.c::556
wm8731_read_reg_cache:                  sound/soc/codecs/wm8731.c::75
wm8750_read_reg_cache:                  sound/soc/codecs/wm8750.c::80
wm8753_read_reg_cache:                  sound/soc/codecs/wm8753.c::117
ac97_read:                              sound/soc/codecs/wm9712.c::471
cs4270_read_reg_cache:                  sound/soc/codecs/cs4270.c::316
aic3x_read_reg_cache:                   sound/soc/codecs/tlv320aic3x.c::98

----------------------------------------

author
#15 lore raw
In reply to Roel Kluin
Quoted 7 lines · Julia Lawall

I found 63 occurrences of this problem with the following semantic match
(http://www.emn.fr/x-info/coccinelle/):

@@ unsigned int i; @@

* i < 0

Spatch did find some that my script didn't, and mine had a few false positives.
However, your spatch script did not catch some that my script covered. Below are the results of my script (after a few modifications) and below that yours for comparison. for instance not caught were:
* unsigned (or any unsigned typedef) i;

and besides your evaluated the tests:

* i < [any negative value]
* i >= [0 or any negative value]
* i = [any negative value]
* i != [any negative value]
* [0 or any negative value] <= i
* [0 or any negative value] > i

You could create a spatch script for all cases, but I think it'd be better to write a script to create spatch scripts dependent on matches in source. I may write this when I have time, Is there some reference on spatch syntax? And is spatch open source? if so, how can I obtain its source code?

Roel
---
My matches:

vi arch/alpha/math-emu/math.c +186      # unsigned variable 'res'
vi arch/ia64/kernel/ptrace.c +2008      # unsigned variable 'pos'
vi arch/ia64/kernel/ptrace.c +2101      # unsigned variable 'pos'
vi arch/mips/kernel/irixelf.c +590      # unsigned variable 'v'

vi arch/mips/mm/sc-mips.c +84 # unsigned variable 'tmp'
vi arch/mips/mm/sc-mips.c +90 # unsigned variable 'tmp'
vi arch/mips/sgi-ip27/ip27-timer.c +231 # unsigned variable 'irq'
vi arch/powerpc/boot/oflib.c +159 # unsigned variable 'result'
vi arch/powerpc/kernel/iommu.c +152 # unsigned variable 'n'
vi arch/powerpc/oprofile/cell/vma_map.c +232 # unsigned variable 'overlay_tbl_offset'
vi arch/powerpc/platforms/pseries/lpar.c +528 # unsigned variable 'slot'

vi arch/ppc/boot/of1275/claim.c +84     # unsigned variable 'result'
vi arch/sh/kernel/cpu/sh2a/fpu.c +303   # unsigned variable 'ix'
vi arch/sh/kernel/cpu/sh2a/fpu.c +388   # unsigned variable 'ix'
vi arch/sparc64/kernel/iommu.c +140     # unsigned variable 'n'
vi arch/x86/kernel/cpu/cpufreq/longhaul.c +486  # unsigned variable 'ratio'
vi arch/x86/kernel/io_apic_32.c +249    # unsigned variable 'pin'
vi arch/x86/kernel/pci-gart_64.c +100   # unsigned variable 'offset'
vi arch/x86/kernel/pci-gart_64.c +105   # unsigned variable 'offset'
vi arch/x86/kernel/pci-gart_64.c +249   # unsigned variable 'iommu_page'
vi arch/x86/kernel/pci-gart_64.c +374   # unsigned variable 'iommu_start'
vi arch/x86/mm/init_64.c +831   # unsigned variable 'above'
vi arch/x86/mm/ioremap.c +554   # unsigned variable 'nesting'
vi arch/x86/mm/numa_64.c +179   # unsigned variable 'mem'
vi drivers/char/drm/drm_bufs.c +1540    # unsigned variable 'virtual'
vi drivers/gpio/mcp23s08.c +181 # unsigned variable 't'
vi drivers/ide/ide-cd.c +185    # unsigned variable 'valid'
vi drivers/lguest/page_tables.c +163    # unsigned variable 'pfn'
vi drivers/media/video/planb.c +881     # unsigned variable 'fr'
vi drivers/media/video/planb.c +885     # unsigned variable 'format'

vi drivers/media/video/videodev.c +1216 # unsigned variable 'index' vi drivers/media/video/videodev.c +1216 # unsigned variable 'index'
vi drivers/mtd/devices/slram.c +273 # unsigned variable 'devlength'
vi drivers/net/irda/stir4200.c +769 # unsigned variable 'new_speed'
vi drivers/net/r8169.c +1708 # unsigned variable 'i'
vi drivers/net/r8169.c +1712 # unsigned variable 'i'

vi drivers/usb/host/ehci-dbg.c +457     # unsigned variable 'temp'
vi drivers/usb/host/ehci-dbg.c +468     # unsigned variable 'temp'
vi drivers/usb/serial/mos7840.c +1744   # unsigned variable 'status'
vi drivers/usb/storage/sddr55.c +368    # unsigned variable 'pba'
vi drivers/usb/storage/sddr55.c +368    # unsigned variable 'pba'
vi drivers/video/sis/sis_main.c +4053   # unsigned variable 'temp'
vi drivers/video/sis/sis_main.c +4059   # unsigned variable 'temp'
vi drivers/video/sis/sis_main.c +4067   # unsigned variable 'temp'
vi drivers/watchdog/wdt285.c +165       # unsigned variable 'new_margin'

vi fs/proc/task_mmu.c +148 # unsigned variable 'last_addr'
vi lib/iommu-helper.c +61 # unsigned variable 'index'
vi net/decnet/af_decnet.c +1589 # unsigned variable 'val'
vi net/netfilter/xt_TCPOPTSTRIP.c +98 # unsigned variable 'tcphoff'
vi sound/oss/dmabuf.c +800 # unsigned variable 'active_offs'

vi sound/pci/emu10k1/emu10k1x.c +1044   # unsigned variable 'reg'
vi sound/pci/hda/hda_codec.c +158       # unsigned variable 'parm'
vi sound/pci/hda/hda_codec.c +1929      # unsigned variable 'val'
vi sound/pci/hda/hda_codec.c +2026      # unsigned variable 'val'
vi sound/pci/hda/hda_codec.c +2031      # unsigned variable 'val'
vi sound/pci/hda/hda_proc.c +56 # unsigned variable 'caps'
vi sound/pci/hda/hda_proc.c +139        # unsigned variable 'stream'
vi sound/soc/codecs/cs4270.c +402       # unsigned variable 'ret'
vi sound/soc/codecs/cs4270.c +414       # unsigned variable 'ret'
vi sound/soc/codecs/cs4270.c +437       # unsigned variable 'ret'
vi sound/soc/codecs/cs4270.c +448       # unsigned variable 'ret'
vi sound/soc/codecs/cs4270.c +456       # unsigned variable 'ret'
vi drivers/block/cciss.c +3063  # unsigned variable 'cfg_base_addr_index'
vi drivers/net/irda/ali-ircc.c +1452    # unsigned variable 'speed'
vi drivers/net/irda/ali-ircc.c +1978    # unsigned variable 'speed'
vi drivers/net/irda/via-ircc.c +834     # unsigned variable 'speed'
vi drivers/net/irda/via-ircc.c +910     # unsigned variable 'speed'

vi fs/ext4/mballoc.c +2621 # unsigned variable 'i'
vi fs/ext4/mballoc.c +2627 # unsigned variable 'i'
vi arch/powerpc/platforms/iseries/call_pci.h +303 # unsigned variable 'xRc'
vi arch/powerpc/sysdev/fsl_soc.c +843 # unsigned variable 'sysclk'
vi arch/powerpc/sysdev/fsl_soc.c +845 # unsigned variable 'sysclk'
vi drivers/atm/fore200e.c +2923 # unsigned variable 'media_index'
vi drivers/hwmon/lm93.c +1728 # unsigned variable 'val'
vi drivers/infiniband/core/user_mad.c +715 # unsigned variable 'id'
vi drivers/infiniband/hw/ipath/ipath_intr.c +1162 # unsigned variable 'istat'
vi drivers/infiniband/hw/ipath/ipath_qp.c +114 # unsigned variable 'ret'
vi drivers/infiniband/hw/ipath/ipath_stats.c +80 # unsigned variable 'val'

vi drivers/infiniband/hw/mthca/mthca_av.c +177  # unsigned variable 'index'
vi drivers/infiniband/hw/mthca/mthca_mr.c +187  # unsigned variable 'seg'
vi drivers/infiniband/hw/mthca/mthca_mr.c +437  # unsigned variable 'key'
vi drivers/infiniband/hw/mthca/mthca_mr.c +597  # unsigned variable 'key'
vi drivers/macintosh/therm_adt746x.c +503       # unsigned variable 'val'
vi drivers/media/video/saa7115.c +1216  # unsigned variable 'wss'
vi drivers/net/ehea/ehea_main.c +440    # unsigned variable 'tmp_addr'
vi drivers/net/ehea/ehea_qmr.c +618     # unsigned variable 'mapped_addr'

vi drivers/net/mlx4/mr.c +175 # unsigned variable 'seg'
vi drivers/net/mlx4/mr.c +261 # unsigned variable 'index'
vi drivers/net/wireless/ipw2200.c +9152 # unsigned variable 'target_rate' vi drivers/net/wireless/iwlwifi/iwl-3945.c +480 # unsigned variable 'rate'

vi drivers/net/wireless/iwlwifi/iwl-3945.c +1007        # unsigned variable 'data_retry_limit'
vi drivers/net/wireless/iwlwifi/iwl-4965.c +3001        # unsigned variable 'data_retry_limit'
vi drivers/net/wireless/iwlwifi/iwl-4965.c +3124        # unsigned variable 'num_tbs'
vi drivers/video/aty/mach64_gx.c +371   # unsigned variable 'program_bits'
vi fs/jfs/jfs_dtree.c +3070     # unsigned variable 'dir_index'
vi sound/pci/ca0106/ca0106_proc.c +307  # unsigned variable 'reg'
vi arch/ppc/syslib/open_pic.c +127      # unsigned variable 'ipi'
vi arch/ppc/syslib/open_pic.c +130      # unsigned variable 'timer'
vi arch/ppc/syslib/open_pic.c +130      # unsigned variable 'timer'
vi arch/ppc/syslib/open_pic.c +136      # unsigned variable 'pri'
vi arch/ppc/syslib/open_pic.c +136      # unsigned variable 'pri'
vi arch/ppc/syslib/open_pic.c +136      # unsigned variable 'pri'
vi arch/ppc/syslib/open_pic2.c +102     # unsigned variable 'timer'
vi arch/ppc/syslib/open_pic2.c +102     # unsigned variable 'timer'
vi arch/ppc/syslib/open_pic2.c +108     # unsigned variable 'pri'
vi arch/ppc/syslib/open_pic2.c +108     # unsigned variable 'pri'
vi arch/ppc/syslib/open_pic2.c +108     # unsigned variable 'pri'

vi drivers/mtd/rfd_ftl.c +255 # unsigned variable 'addr'
vi drivers/mtd/rfd_ftl.c +746 # unsigned variable 'old_addr'
vi arch/v850/kernel/ptrace.c +148 # unsigned variable 'addr'
vi arch/v850/kernel/ptrace.c +148 # unsigned variable 'addr'

yours (unsigned int)

Quoted 36 lines

diff -u -p a/arch/arm/mach-davinci/psc.c b/arch/arm/mach-davinci/psc.c
diff -u -p a/arch/cris/arch-v10/kernel/dma.c b/arch/cris/arch-v10/kernel/dma.c
diff -u -p a/arch/mips/sgi-ip27/ip27-timer.c b/arch/mips/sgi-ip27/ip27-timer.c
diff -u -p a/arch/mips/vr41xx/common/irq.c b/arch/mips/vr41xx/common/irq.c
diff -u -p a/arch/powerpc/kernel/udbg_16550.c b/arch/powerpc/kernel/udbg_16550.c
diff -u -p a/arch/powerpc/oprofile/cell/vma_map.c b/arch/powerpc/oprofile/cell/vma_map.c diff -u -p a/arch/s390/appldata/appldata_base.c b/arch/s390/appldata/appldata_base.c diff -u -p a/arch/sh/kernel/cpu/irq/intc.c b/arch/sh/kernel/cpu/irq/intc.c
diff -u -p a/arch/sh/kernel/cpu/sh2a/fpu.c b/arch/sh/kernel/cpu/sh2a/fpu.c
diff -u -p a/arch/x86/mm/ioremap.c b/arch/x86/mm/ioremap.c
diff -u -p a/drivers/char/esp.c b/drivers/char/esp.c
diff -u -p a/drivers/char/hvc_console.c b/drivers/char/hvc_console.c
diff -u -p a/drivers/char/hvcs.c b/drivers/char/hvcs.c
diff -u -p a/drivers/char/hvsi.c b/drivers/char/hvsi.c
diff -u -p a/drivers/gpio/mcp23s08.c b/drivers/gpio/mcp23s08.c
diff -u -p a/drivers/ieee1394/dv1394.c b/drivers/ieee1394/dv1394.c
diff -u -p a/drivers/ieee1394/video1394.c b/drivers/ieee1394/video1394.c
diff -u -p a/drivers/macintosh/windfarm_smu_sat.c b/drivers/macintosh/windfarm_smu_sat.c diff -u -p a/drivers/media/video/bt8xx/bttv-driver.c b/drivers/media/video/bt8xx/bttv-driver.c diff -u -p a/drivers/media/video/meye.c b/drivers/media/video/meye.c
diff -u -p a/drivers/media/video/mt20xx.c b/drivers/media/video/mt20xx.c
diff -u -p a/drivers/media/video/planb.c b/drivers/media/video/planb.c
diff -u -p a/drivers/media/video/saa7134/saa7134-video.c b/drivers/media/video/saa7134/saa7134-video.c diff -u -p a/drivers/media/video/usbvision/usbvision-video.c
diff -u -p a/drivers/media/video/videodev.c b/drivers/media/video/videodev.c
diff -u -p a/drivers/mfd/sm501.c b/drivers/mfd/sm501.c
diff -u -p a/drivers/net/gianfar.c b/drivers/net/gianfar.c
diff -u -p a/drivers/net/r8169.c b/drivers/net/r8169.c
diff -u -p a/drivers/net/wireless/hermes.c b/drivers/net/wireless/hermes.c
diff -u -p a/drivers/rtc/rtc-sh.c b/drivers/rtc/rtc-sh.c
diff -u -p a/drivers/scsi/esp_scsi.c b/drivers/scsi/esp_scsi.c
diff -u -p a/drivers/scsi/u14-34f.c b/drivers/scsi/u14-34f.c
diff -u -p a/drivers/spi/spi_s3c24xx.c b/drivers/spi/spi_s3c24xx.c
diff -u -p a/drivers/usb/host/ehci-dbg.c b/drivers/usb/host/ehci-dbg.c
diff -u -p a/drivers/usb/misc/usbtest.c b/drivers/usb/misc/usbtest.c
diff -u -p a/drivers/usb/serial/mos7840.c b/drivers/usb/serial/mos7840.c

Quoted 8 lines

diff -u -p a/drivers/watchdog/wdt285.c b/drivers/watchdog/wdt285.c diff -u -p a/fs/ext3/inode.c b/fs/ext3/inode.c
diff -u -p a/fs/ext4/inode.c b/fs/ext4/inode.c
diff -u -p a/kernel/relay.c b/kernel/relay.c
diff -u -p a/mm/slab.c b/mm/slab.c
diff -u -p a/net/irda/ircomm/ircomm_tty.c b/net/irda/ircomm/ircomm_tty.c diff -u -p a/net/netfilter/xt_TCPOPTSTRIP.c b/net/netfilter/xt_TCPOPTSTRIP.c diff -u -p a/sound/soc/codecs/cs4270.c b/sound/soc/codecs/cs4270.c

yours (unsigned long)

Quoted 20 lines

diff -u -p a/arch/m32r/kernel/ptrace.c b/arch/m32r/kernel/ptrace.c diff -u -p a/arch/mips/kernel/irixelf.c b/arch/mips/kernel/irixelf.c diff -u -p a/drivers/atm/fore200e.c b/drivers/atm/fore200e.c
diff -u -p a/drivers/char/dsp56k.c b/drivers/char/dsp56k.c
diff -u -p a/drivers/hid/usbhid/hiddev.c b/drivers/hid/usbhid/hiddev.c diff -u -p a/drivers/hwmon/fscpos.c b/drivers/hwmon/fscpos.c
diff -u -p a/drivers/i2c/chips/tsl2550.c b/drivers/i2c/chips/tsl2550.c diff -u -p a/drivers/ide/ide-cd.c b/drivers/ide/ide-cd.c
diff -u -p a/drivers/message/i2o/i2o_block.c b/drivers/message/i2o/i2o_block.c diff -u -p a/drivers/misc/intel_menlow.c b/drivers/misc/intel_menlow.c diff -u -p a/drivers/mtd/devices/slram.c b/drivers/mtd/devices/slram.c diff -u -p a/drivers/mtd/ubi/build.c b/drivers/mtd/ubi/build.c diff -u -p a/drivers/telephony/ixj.c b/drivers/telephony/ixj.c diff -u -p a/drivers/usb/misc/usbtest.c b/drivers/usb/misc/usbtest.c diff -u -p a/drivers/video/atmel_lcdfb.c b/drivers/video/atmel_lcdfb.c diff -u -p a/kernel/softlockup.c b/kernel/softlockup.c
diff -u -p a/kernel/sys.c b/kernel/sys.c
diff -u -p a/sound/oss/dmabuf.c b/sound/oss/dmabuf.c
diff -u -p a/sound/oss/trident.c b/sound/oss/trident.c
diff -u -p a/sound/spi/at73c213.c b/sound/spi/at73c213.c

#16 lore raw
In reply to Roel Kluin

Thanks for the interesting comparison.

Quoted 6 lines

Spatch did find some that my script didn't, and mine had a few false positives.
However, your spatch script did not catch some that my script covered. Below are the results of my script (after a few modifications) and below that yours for comparison. for instance not caught were:
* unsigned (or any unsigned typedef) i;

Actually, if I had written just "unsigned", it would have picked up on "unsigned" or "unsigned int". Spatch has something called an isomorphism, which replaces certain terms by a set of equivelant ones. But someone has to describe what the equivalent ones should be, and for unsigned it was described as "unsigned => unsigned int", probably because I thought going the other way around might be unsafe. Anyway, this problem is corrected in the semantic match for finding functions that return negative values but have unsigned as a return type.

With respect to typedefs, we do take them into account, but we only expand a (probably useful) subset of the include files to save time. Also without processing the makefile, it is not always possible to know which include file an include refers to. Of course we could run the preprocessor on the source code, but since our main goal is transformation, we would like to stay as close as possible to the structure of the source program. Of course this is less of an issue for this kind of searching, but we haven't explored this option.

I haven't had a chance to look through all of your examples yet. Were there any cases where you found a local typedef? I also wrote a rule for some of the standard things like u32, etc, but they didn't turn up much, and not much that looked significant.

Quoted 8 lines

and besides your evaluated the tests:

* i < [any negative value]
* i >= [0 or any negative value]
* i = [any negative value]
* i != [any negative value]
* [0 or any negative value] <= i
* [0 or any negative value] > i

We do 0 > i via the isomoprhisms. But I have never seen such code.

As you mention, we could consider more kinds of comparison to 0 by writing more patterns, eg;

(
i < 0
|
i <= 0
|
i = -C
|
i < -C
|
i <= -C
)

where C was previously declared to be any constant.

Quoted 2 lines

You could create a spatch script for all cases, but I think it'd be better to write a script to create spatch scripts dependent on matches in source.

I'm not sure what you mean here. Many of those cases are probably quite uncommon. It would probably take more work to find an instance of i <= [any negative number] than it would to just write the extra case in the pattern language. But perhaps I am misinterpreting your suggestion.

I have a PhD student who is working on inferring semantic patches from a few manually done changes, but then he has some diff files to start with. It seems more difficult to infer searches from source code, because it is not clear what to focus on.

Quoted 3 lines

I may
write this when I have time, Is there some reference on spatch syntax? And is spatch open source? if so, how can I obtain its source code?

Currently only the binary is available.
http://www.emn.fr/x-info/coccinelle/

julia

author
#17 lore raw
In reply to Roel Kluin
Quoted 9 lines · Julia Lawall

Thanks for the interesting comparison.

Quoted 6 lines

Spatch did find some that my script didn't, and mine had a few false positives.
However, your spatch script did not catch some that my script covered. Below are the results of my script (after a few modifications) and below that yours for comparison. for instance not caught were:
* unsigned (or any unsigned typedef) i;

Quoted 8 lines

Actually, if I had written just "unsigned", it would have picked up on "unsigned" or "unsigned int". Spatch has something called an isomorphism, which replaces certain terms by a set of equivelant ones. But someone has to describe what the equivalent ones should be, and for unsigned it was described as "unsigned => unsigned int", probably because I thought going the other way around might be unsafe. Anyway, this problem is corrected in the semantic match for finding functions that return negative values but have unsigned as a return type.

If the function returns a negative int, but it is stored in an unsigned and subsequently tested, We have a problem as well.
A test could either mean that the author was very pedantic, or that he/she forgot about the signedness.

Quoted 9 lines

With respect to typedefs, we do take them into account, but we only expand a (probably useful) subset of the include files to save time. Also without processing the makefile, it is not always possible to know which include file an include refers to. Of course we could run the preprocessor on the source code, but since our main goal is transformation, we would like to stay as close as possible to the structure of the source program. Of course this is less of an issue for this kind of searching, but we haven't explored this option.

Quoted 4 lines

I haven't had a chance to look through all of your examples yet. Were there any cases where you found a local typedef? I also wrote a rule for some of the standard things like u32, etc, but they didn't turn up much, and not much that looked significant.

Yes there were some, for instance in the -mm patch:
ext4-mballoc-fix-hot-spins-after-err_freebuddy-and-err_freemeta.patch

Quoted 10 lines
Quoted 8 lines

and besides your evaluated the tests:

* i < [any negative value]
* i >= [0 or any negative value]
* i = [any negative value]
* i != [any negative value]
* [0 or any negative value] <= i
* [0 or any negative value] > i

We do 0 > i via the isomoprhisms. But I have never seen such code.

not really a problem, but in arch/mips/mm/sc-mips.c:84, with tmp unsigned:
if (0 <= tmp && tmp <= 7)

	c->scache.sets = 64 << tmp;
else
	return 0;
Quoted 17 lines

As you mention, we could consider more kinds of comparison to 0 by writing more patterns, eg;

(
i < 0
|
i <= 0
|
i = -C
|
i < -C
|
i <= -C
)

where C was previously declared to be any constant.

Quoted 7 lines
Quoted 2 lines

You could create a spatch script for all cases, but I think it'd be better to write a script to create spatch scripts dependent on matches in source.

I'm not sure what you mean here. Many of those cases are probably quite uncommon. It would probably take more work to find an instance of i <= [any negative number] than it would to just write the extra case in the pattern language. But perhaps I am misinterpreting your suggestion.

I meant something like the bash script below. it isn't working, however. I suspect I did something wrong in the spatch patch or invocation.

# define what to search for
left_operator="\([;,|^?:(]\|[\!+*/%&|~^-]=\|>>=\|<<=\|\[\|&&\|$an_$s&\)\(++\|--\)\?"
right_operator="\([;,&|^?:)]\|[\!+*/%&|~^<>-]=\|>>=\|<<=\|>[^>]\|<[^<]\|\]\)\(++\|--\)\?"
variable="$s\(\(++\|--\)$w\|$w\(++\|--\)\|$w\)$s"
comparison="\(\(>=\|<\)${s}0\|\([><\!=]=\|[<>]\)$s-$s$D\)$s"
query="$left_operator$variable$comparison$right_operator"

arr="\(\[[^\]]*\]$s\)*"
attr="__attribute__$s(([^;]*))"

# for each unsigned typedefs
for ut in "unsigned" "unsigned long" $(
git-grep -l "^${s}typedef${S}unsigned$S\($V$S\)*\($V$s$arr\|$attr$S$V$s$arr\|$V$s$arr$S$attr\)$s;$cendl" | 
sed -n "s/^${s}typedef${S}unsigned$S\($V$S\)*\(\($V\)$s$arr\|$attr$S\($V\)$s$arr\|\($V\)$s$arr$S$attr\)$s;$cendl/ \3\5\7/p" |
sort | uniq); do
# create the spatch
  cat > ../spatches/negative_unsigned.cocci << EOF
@@
constant C;
$ut i;
@@
(
* i < 0
|
* i <= 0
|
* i = -C
|
* i < -C
|
* i <= -C
)
EOF
  # find
  for f in $(git-grep -l "$ut" | grep "[^.]*\.[ch]" | xargs grep -l "$ut"); do
    spatch -sp_file ../spatches/negative_unsigned $f;
  done
done

Any suggestions?

Quoted 11 lines

I have a PhD student who is working on inferring semantic patches from a few manually done changes, but then he has some diff files to start with. It seems more difficult to infer searches from source code, because it is not clear what to focus on.

Quoted 3 lines

I may
write this when I have time, Is there some reference on spatch syntax? And is spatch open source? if so, how can I obtain its source code?

Currently only the binary is available.
http://www.emn.fr/x-info/coccinelle/

I think this community would more easily embrace it if it was open source.

Quoted 1 line

julia

thanks,

Roel

author
#18 lore raw
In reply to Roel Kluin

Forgot to add these on top of my script,

int="[0-9]"
hEx="[A-Fa-f0-9]"
an_="[A-Za-z0-9_]"
D="$int*\.\?$int\+x\?$hEx*[uUlL]\{0,3\}[fF]\?"
V="$an_\+$an_*"
w="\($V\|${V}\[$s$an_*${s}\]\|$V\.\|$V->\)\+"
s="[[:space:]]*";
S="[[:space:]]\+"
cendl="$s\(\/[\*\/].*\)\?$"

Roel

#19 lore raw
In reply to Roel Kluin
Quoted 19 lines · Roel Kluin
Quoted 9 lines · Julia Lawall

Thanks for the interesting comparison.

Quoted 6 lines

Spatch did find some that my script didn't, and mine had a few false positives.
However, your spatch script did not catch some that my script covered. Below are the results of my script (after a few modifications) and below that yours for comparison. for instance not caught were:
* unsigned (or any unsigned typedef) i;

Quoted 8 lines

Actually, if I had written just "unsigned", it would have picked up on "unsigned" or "unsigned int". Spatch has something called an isomorphism, which replaces certain terms by a set of equivelant ones. But someone has to describe what the equivalent ones should be, and for unsigned it was described as "unsigned => unsigned int", probably because I thought going the other way around might be unsafe. Anyway, this problem is corrected in the semantic match for finding functions that return negative values but have unsigned as a return type.

Quoted 4 lines

If the function returns a negative int, but it is stored in an unsigned and subsequently tested, We have a problem as well.
A test could either mean that the author was very pedantic, or that he/she forgot about the signedness.

Sorry, but I'm missing the point here. We have already checked for unsigned things that are compared to 0. Doesn't that address the case you mention?

Quoted 9 lines
Quoted 9 lines

With respect to typedefs, we do take them into account, but we only expand a (probably useful) subset of the include files to save time. Also without processing the makefile, it is not always possible to know which include file an include refers to. Of course we could run the preprocessor on the source code, but since our main goal is transformation, we would like to stay as close as possible to the structure of the source program. Of course this is less of an issue for this kind of searching, but we haven't explored this option.

Quoted 7 lines
Quoted 4 lines

I haven't had a chance to look through all of your examples yet. Were there any cases where you found a local typedef? I also wrote a rule for some of the standard things like u32, etc, but they didn't turn up much, and not much that looked significant.

Yes there were some, for instance in the -mm patch:
ext4-mballoc-fix-hot-spins-after-err_freebuddy-and-err_freemeta.patch

OK, thanks for the pointer.

Quoted 2 lines

I meant something like the bash script below. it isn't working, however. I suspect I did something wrong in the spatch patch or invocation.

OK, now I see what you mean. I have indeed made scripts to do this sort of thing - eg first you write a semantic match to find the names of all of the functions that might return a negative constant, and then you use those names to instantiate another semantic patch that searches for uses of each one of them. Finally, you run each of those semantic matches on the Linux kernel.

Your script worked fine for me. I did the following from my directory containing the Linux sources:

bash ~/the_script > ~/the_script.output

I modified the script though to give -quiet as an argument to spatch, since otherwise it is quite verbose. Normally with -quiet, you have only the output you are interested in.

I didn't let it run all the way, but I got the following output, that looks reasonable:

--- arch/arm/mach-davinci/psc.c 2008-04-07 13:50:25.000000000 +0200
@@ -70,7 +70,7 @@ void davinci_psc_config(unsigned int dom
{
u32 epcpr, ptcmd, ptstat, pdstat, pdctl1, mdstat, mdctl, mdstat_mask;

- if (id < 0)
return;

mdctl = davinci_readl(DAVINCI_PWR_SLEEP_CNTRL_BASE + MDCTL + 4 *
id);
--- arch/arm/mach-omap2/usb-tusb6010.c 2008-04-07 13:50:25.000000000 +0200
@@ -124,7 +124,7 @@ static int tusb_set_sync_mode(unsigned s
tmp = (t.sync_clk * 1000 + fclk_ps - 1) / fclk_ps; if (tmp > 4)
return -ERANGE;
- if (tmp <= 0)
tmp = 1;
t.page_burst_access = (fclk_ps * tmp) / 1000;

--- arch/arm/mach-sa1100/collie.c 2008-04-07 13:50:25.000000000 +0200
@@ -112,7 +112,7 @@ static u_int collie_uart_get_mctrl(struc
unsigned int r;

r = locomo_gpio_read_output(&collie_locomo_device.dev,
LOCOMO_GPIO_CTS & LOCOMO_GPIO_DSR);
- if (r = -ENODEV)
return ret;
if (r & LOCOMO_GPIO_CTS)
ret |= TIOCM_CTS;
--- arch/cris/arch-v10/kernel/dma.c 2008-04-16 13:27:54.000000000 +0200
@@ -24,7 +24,7 @@ int cris_request_dma(unsigned int dmanr,
unsigned long int gens;
int fail = -EINVAL;

- if ((dmanr < 0) || (dmanr >= MAX_DMA_CHANNELS)) {
printk(KERN_CRIT "cris_request_dma: invalid DMA channel
%u\n", dmanr);
return -EINVAL;
}
@@ -213,7 +213,7 @@ int cris_request_dma(unsigned int dmanr,
void cris_free_dma(unsigned int dmanr, const char * device_id) {
unsigned long flags;
- if ((dmanr < 0) || (dmanr >= MAX_DMA_CHANNELS)) {
printk(KERN_CRIT "cris_free_dma: invalid DMA channel
%u\n", dmanr);
return;
}

julia

#20 lore raw
In reply to Roel Kluin
Quoted 11 lines · Roel Kluin

Forgot to add these on top of my script,

int="[0-9]"
hEx="[A-Fa-f0-9]"
an_="[A-Za-z0-9_]"
D="$int*\.\?$int\+x\?$hEx*[uUlL]\{0,3\}[fF]\?"
V="$an_\+$an_*"
w="\($V\|${V}\[$s$an_*${s}\]\|$V\.\|$V->\)\+"
s="[[:space:]]*";
S="[[:space:]]\+"
cendl="$s\(\/[\*\/].*\)\?$"

With this I get an error from sed.

julia

author
#21 lore raw
In reply to Roel Kluin
Quoted 14 lines · Julia Lawall
Quoted 11 lines · Roel Kluin

Forgot to add these on top of my script,

int="[0-9]"
hEx="[A-Fa-f0-9]"
an_="[A-Za-z0-9_]"
D="$int*\.\?$int\+x\?$hEx*[uUlL]\{0,3\}[fF]\?"
V="$an_\+$an_*"
w="\($V\|${V}\[$s$an_*${s}\]\|$V\.\|$V->\)\+"
s="[[:space:]]*";
S="[[:space:]]\+"
cendl="$s\(\/[\*\/].*\)\?$"

Quoted 3 lines

With this I get an error from sed.

julia

Not due to this, but I had an error in my script. here's the updated script below. it's working now, I'll post the results shortly.

Thanks, and especially for the -quiet flag,

Roel

---
int="[0-9]"
hEx="[A-Fa-f0-9]"
an_="[A-Za-z0-9_]"
D="$int*\.\?$int\+x\?$hEx*[uUlL]\{0,3\}[fF]\?"
V="$an_\+$an_*"
w="\($V\|${V}\[$s$an_*${s}\]\|$V\.\|$V->\)\+"
s="[[:space:]]*";
S="[[:space:]]\+"
cendl="$s\(\/[\*\/].*\)\?$"

# define what to search for
left_operator="\([;,|^?:(]\|[\!+*/%&|~^-]=\|>>=\|<<=\|\[\|&&\|$an_$s&\)"
right_operator="\([;,&|^?:)]\|[\!+*/%&|~^<>-]=\|>>=\|<<=\|>[^>]\|<[^<]\|\]\)"
variable="$s\(\(++\|--\)$w\|$w\(++\|--\)\|$w\)$s"
comparison="\(\(>=\|<\)${s}0\|\([><\!=]=\|[<>]\)$s-$s$D\)$s"
query="$left_operator$variable$comparison$right_operator"

arr="\(\[[^\]]*\]$s\)*"
attr="__attribute__$s(([^;]*))"

# for each unsigned typedefs
for ut in "unsigned" "unsigned long" $(
git-grep "^${s}typedef${S}unsigned$S\($V$S\)*\($V$s$arr\|$attr$S$V$s$arr\|$V$s$arr$S$attr\)$s;$cendl" | 
sed -n "s/^[^.]*\.[hc]:${s}typedef${S}unsigned$S\($V$S\)*\(\($V\)$s$arr\|$attr$S\($V\)$s$arr\|\($V\)$s$arr$S$attr\)$s;$cendl/\3\5\7/p" | sort | uniq); do
# create the spatch
  cat > ../spatches/negative_unsigned.cocci << EOF
@@
constant C;
$ut i;
@@
(
* i < 0
|
* i <= 0
|
* i = -C
|
* i < -C
|
* i <= -C
)
EOF
  # find
  for f in $(git-grep -l "$ut" | grep "[^.]*\.[ch]" | xargs grep -l "$query"); do
    spatch -quiet -sp_file ../spatches/negative_unsigned $f;
  done
done > ../spatch.log
author
#22 lore raw
In reply to Roel Kluin
Quoted 2 lines · Roel Kluin
Quoted 1 line · Julia Lawall

On Wed, 23 Apr 2008, Roel Kluin wrote:

There was an error in my script so here's an updated version.

---
int="[0-9]"
hEx="[A-Fa-f0-9]"
an_="[A-Za-z0-9_]"
D="$int*\.\?$int\+x\?$hEx*[uUlL]\{0,3\}[fF]\?"
V="$an_\+$an_*"
w="\($V\|${V}\[$s$an_*${s}\]\|$V\.\|$V->\)\+"
s="[[:space:]]*";
S="[[:space:]]\+"
cendl="$s\(\/[\*\/].*\)\?$"
Q="[^[:alnum:]_]"

# define what to search for
left_operator="\([;,|^?:(]\|[\!+*/%&|~^-]=\|>>=\|<<=\|\[\|&&\|$an_$s&\)"
right_operator="\([;,&|^?:)]\|[\!+*/%&|~^<>-]=\|>>=\|<<=\|>[^>]\|<[^<]\|\]\)"
variable="$s\(\(++\|--\)$w\|$w\(++\|--\)\|$w\)$s"
comparison="\(\(>=\|<\)${s}0\|\([><\!=]=\|[<>]\)$s-$s$D\)$s"
query="$left_operator$variable$comparison$right_operator"

arr="\(\[[^\]]*\]$s\)*"
attr="__attribute__$s(([^;]*))"

# for each unsigned typedefs
for ut in "unsigned" "unsigned long" $(
git-grep "^${s}typedef${S}unsigned$S\($V$S\)*\($V$s$arr\|$attr$S$V$s$arr\|$V$s$arr$S$attr\)$s;$cendl" | 
sed -n "s/^[^.]*\.[hc]:${s}typedef${S}unsigned$S\($V$S\)*\(\($V\)$s$arr\|$attr$S\($V\)$s$arr\|\($V\)$s$arr$S$attr\)$s;$cendl/\3\5\7/p" |
sort | uniq); do
# create the spatch
  cat > ../spatches/negative_unsigned.cocci << EOF
@@
constant C;
$ut i;
@@
(
* i < 0
|
* i >= 0
|
* i = -C
|
* i < -C
|
* i >= -C
)
EOF
  # find
  for f in $(git-grep -l "\(^\|$Q\)$ut\($Q\|$\)" | grep "[^.]*\.[ch]" | xargs grep -l "$query"); do
    spatch -quiet -sp_file ../spatches/negative_unsigned $f;
  done
done > ../spatch.log
# to display the results nicely
sed -n "s/^\(.\)\(-- \([^[:space:]]*\)$s\|@ -\([0-9]*\),\|\).*$/\1 \3\4/p" ../spatch.log|
while read a b; do
  if [ "$a" = "-" ]; then
    if [ -f "$b" ]; then
      f="$b"
    elif [ -z "$b" ]; then
      echo "vi $f +$i";
      i=$(($i+1));
    fi
  elif [ "$a" = "@" ]; then
    i=$b;
  else
    i=$(($i+1));
  fi
done | sort
author
#23 lore raw
In reply to Roel Kluin
Quoted 26 lines · Julia Lawall
Quoted 8 lines

and besides your evaluated the tests:

* i < [any negative value]
* i >= [0 or any negative value]
* i = [any negative value]
* i != [any negative value]
* [0 or any negative value] <= i
* [0 or any negative value] > i

We do 0 > i via the isomoprhisms. But I have never seen such code.

As you mention, we could consider more kinds of comparison to 0 by writing more patterns, eg;

(
i < 0
|
i <= 0
|
i = -C
|
i < -C
|
i <= -C
)

Quoted 1 line

where C was previously declared to be any constant.

this should be different:

(
* i < 0
|
* i = -C
|
* i < -C
|
* i >= -C
)

author
#24 lore raw
In reply to Roel Kluin
Quoted 3 lines · Roel Kluin
Quoted 2 lines · Roel Kluin
Quoted 1 line · Julia Lawall

On Wed, 23 Apr 2008, Roel Kluin wrote:

Sorry, need coffee, use this one.

int="[0-9]"
hEx="[A-Fa-f0-9]"
an_="[A-Za-z0-9_]"
D="$int*\.\?$int\+x\?$hEx*[uUlL]\{0,3\}[fF]\?"
V="$an_\+$an_*"
w="\($V\|${V}\[$s$an_*${s}\]\|$V\.\|$V->\)\+"
s="[[:space:]]*";
S="[[:space:]]\+"
cendl="$s\(\/[\*\/].*\)\?$"
Q="[^[:alnum:]_]"

# define what to search for
left_operator="\([;,|^?:(]\|[\!+*/%&|~^-]=\|>>=\|<<=\|\[\|&&\|$an_$s&\)"
right_operator="\([;,&|^?:)]\|[\!+*/%&|~^<>-]=\|>>=\|<<=\|>[^>]\|<[^<]\|\]\)"
variable="$s\(\(++\|--\)$w\|$w\(++\|--\)\|$w\)$s"
comparison="\(\(>=\|<\)${s}0\|\([><\!=]=\|[<>]\)$s-$s$D\)$s"
query="$left_operator$variable$comparison$right_operator"

arr="\(\[[^\]]*\]$s\)*"
attr="__attribute__$s(([^;]*))"

# for each unsigned typedefs
for ut in "unsigned" "unsigned long" $(
git-grep "^${s}typedef${S}unsigned$S\($V$S\)*\($V$s$arr\|$attr$S$V$s$arr\|$V$s$arr$S$attr\)$s;$cendl" | 
sed -n "s/^[^.]*\.[hc]:${s}typedef${S}unsigned$S\($V$S\)*\(\($V\)$s$arr\|$attr$S\($V\)$s$arr\|\($V\)$s$arr$S$attr\)$s;$cendl/\3\5\7/p" |
sort | uniq); do
# create the spatch
  cat > ../spatches/negative_unsigned.cocci << EOF
@@
constant C;
$ut i;
@@
(
* i < 0
|
* i <= 0
|
* i = -C
|
* i != -C
|
* i < -C
|
* i > -C
|
* i <= -C
|
* i >= -C
)
EOF
  # find
  for f in $(git-grep -l "\(^\|$Q\)$ut\($Q\|$\)" | grep "[^.]*\.[ch]" | xargs grep -l "$query"); do
    spatch -quiet -sp_file ../spatches/negative_unsigned $f;
  done
done > ../spatch.log

#to display the results nicely:
sed -n "s/^\(.\)\(-- \([^[:space:]]*\)[[:space:]]\|@ -\([0-9]*\),\|\).*$/\1 \3\4/p" ../spatch.log| while read a b; do
if [ "$a" = "-" ]; then

    if [ -f "$b" ]; then
      f="$b"
    elif [ -z "$b" ]; then
      echo "vi $f +$i";
      i=$(($i+1));
    fi
  elif [ "$a" = "@" ]; then
    i=$b;
  else
    i=$(($i+1));

fi
done | sort

#25 lore raw
In reply to Roel Kluin
Quoted 32 lines · Roel Kluin
Quoted 26 lines · Julia Lawall
Quoted 8 lines

and besides your evaluated the tests:

* i < [any negative value]
* i >= [0 or any negative value]
* i = [any negative value]
* i != [any negative value]
* [0 or any negative value] <= i
* [0 or any negative value] > i

We do 0 > i via the isomoprhisms. But I have never seen such code.

As you mention, we could consider more kinds of comparison to 0 by writing more patterns, eg;

(
i < 0
|
i <= 0
|
i = -C
|
i < -C
|
i <= -C
)

Quoted 1 line

where C was previously declared to be any constant.

this should be different:

Quoted 9 lines

(
* i < 0
|
* i = -C
|
* i < -C
|
* i >= -C
)

Agreed. But maybe i <= -C should be there too? And i > -C.

julia

author
#26 lore raw
In reply to Roel Kluin

ok I tested it and these are in fact correct:

* i = -C
* i != -C

Also correct when someone fears that 'i' may become signed in the future:
* i <= 0
* i >= 0

But the latter, does not make sense when used as a test in a for or while loop. Also an else branch indicates a signed assumption.

So the spatch could contain for the basic matches:

(
* i < 0
|
* i < -C
|
* i > -C
|
* i <= -C
|
* i >= -C
)

author
#27 lore raw
In reply to Roel Kluin

Thanks for your feedback, julia, I finally used

(
* i < 0
|
* i < -C
|
* i > -C
|
* i <= -C
|
* i >= -C
)

I noted you had more results in the same files. Is there a difference in results when you remove the asterisks before the expression?

Here is my result (I posted 4 patches already):

---
*** sound/spi/at73c213.c 2008-03-27 12:25:54.000000000 +0100
@@ -174,7 +174,7 @@ static int snd_at73c213_set_bitrate(stru
dac_rate_new = 8 * (ssc_rate / ssc_div);

status = clk_round_rate(chip->board->dac_clk, dac_rate_new);
* if (status < 0)
return status;

/* Ignore difference smaller than 256 Hz. */
@@ -189,7 +189,7 @@ static int snd_at73c213_set_bitrate(stru

set_rate:
status = clk_set_rate(chip->board->dac_clk, status);
* if (status < 0)
return status;

/* Set divider in SSC device. */
*** arch/m32r/kernel/module.c 2008-03-27 12:25:15.000000000 +0100
@@ -172,7 +172,7 @@ int apply_relocate_add(Elf32_Shdr *sechd
break;
case R_M32R_18_PCREL_RELA:
relocation = (relocation - (Elf32_Addr) location);
* if (relocation < -0x20000 || 0x1fffc < relocation)
{
printk(KERN_ERR "module %s: relocation overflow: %u\n", me->name, relocation);
@@ -204,7 +204,7 @@ int apply_relocate_add(Elf32_Shdr *sechd
break;
case R_M32R_26_PCREL_RELA:
relocation = (relocation - (Elf32_Addr) location);
* if (relocation < -0x2000000 || 0x1fffffc < relocation)
{
printk(KERN_ERR "module %s: relocation overflow: %u\n", me->name, relocation);
*** arch/powerpc/sysdev/mpic_pasemi_msi.c 2008-03-27 12:25:20.000000000 +0100
@@ -109,7 +109,7 @@ static int pasemi_msi_setup_msi_irqs(str
* sources can be changed independently.
*/
hwirq = mpic_msi_alloc_hwirqs(msi_mpic, ALLOC_CHUNK);
* if (hwirq < 0) {
pr_debug("pasemi_msi: failed allocating hwirq\n"); return hwirq;
}
*** arch/powerpc/sysdev/mpic_u3msi.c 2008-03-27 12:25:20.000000000 +0100
@@ -122,7 +122,7 @@ static int u3msi_setup_msi_irqs(struct p

list_for_each_entry(entry, &pdev->msi_list, list) {
hwirq = mpic_msi_alloc_hwirqs(msi_mpic, 1);
* if (hwirq < 0) {
pr_debug("u3msi: failed allocating hwirq\n"); return hwirq;
}
*** fs/adfs/inode.c 2008-04-22 22:20:55.000000000 +0200
@@ -28,7 +28,7 @@ static int
adfs_get_block(struct inode *inode, sector_t block, struct buffer_head *bh,
int create)
{
* if (block < 0)
goto abort_negative;

if (!create) {
*** fs/befs/linuxvfs.c 2008-04-22 22:20:55.000000000 +0200
@@ -127,7 +127,7 @@ befs_get_block(struct inode *inode, sect
befs_debug(sb, "---> befs_get_block() for inode %lu, block %ld",
inode->i_ino, block);

* if (block < 0) {
befs_error(sb, "befs_get_block() was asked for a block "
"number less than zero: block %ld in inode %lu", block, inode->i_ino);
*** fs/udf/inode.c 2008-04-22 22:20:55.000000000 +0200
@@ -323,7 +323,7 @@ static int udf_get_block(struct inode *i

lock_kernel();

* if (block < 0)
goto abort_negative;

iinfo = UDF_I(inode);
@@ -2095,7 +2095,7 @@ int8_t inode_bmap(struct inode *inode, s
int8_t etype;
struct udf_inode_info *iinfo;

* if (block < 0) {
printk(KERN_ERR "udf: inode_bmap: block < 0\n"); return -1;
}
*** fs/ufs/inode.c 2008-04-22 22:20:55.000000000 +0200
@@ -56,7 +56,7 @@ static int ufs_block_to_path(struct inod

UFSD("ptrs=uspi->s_apb = %d,double_blocks=%ld \n",ptrs,double_blocks);
* if (i_block < 0) {
ufs_warning(inode->i_sb, "ufs_block_to_path", "block < 0");
} else if (i_block < direct_blocks) {
offsets[n++] = i_block;
@@ -440,7 +440,7 @@ int ufs_getfrag_block(struct inode *inod
lock_kernel();

UFSD("ENTER, ino %lu, fragment %llu\n", inode->i_ino, (unsigned long long)fragment);
* if (fragment < 0)
goto abort_negative;
if (fragment >
((UFS_NDADDR + uspi->s_apb + uspi->s_2apb + uspi->s_3apb)
*** drivers/atm/fore200e.c 2008-04-22 22:20:55.000000000 +0200
@@ -2920,7 +2920,7 @@ fore200e_proc_read(struct atm_dev *dev,
u32 media_index = FORE200E_MEDIA_INDEX(fore200e->bus->read(&fore200e->cp_queues->media_type));
u32 oc3_index;

* if ((media_index < 0) || (media_index > 4))
media_index = 5;

switch (fore200e->loop_mode) {
*** drivers/infiniband/core/user_mad.c 2008-04-22 22:20:55.000000000 +0200
@@ -712,7 +712,7 @@ static int ib_umad_unreg_agent(struct ib
mutex_lock(&file->port->file_mutex); mutex_lock(&file->mutex);

* if (id < 0 || id >= IB_UMAD_MAX_AGENTS || !__get_agent(file, id)) {
ret = -EINVAL;
goto out;
}
*** drivers/macintosh/therm_adt746x.c 2008-04-22 22:20:55.000000000 +0200
@@ -500,7 +500,7 @@ static ssize_t store_##name(struct devic
{ \
u32 val; \
val = simple_strtoul(buf, NULL, 10); \
* if (val < 0 || val > 255) \
return -EINVAL; \
printk(KERN_INFO "Setting specified fan speed to %d\n", val); \
data = val; \
*** drivers/media/video/cx88/cx88-blackbird.c 2008-03-27 12:25:32.000000000 +0100
@@ -547,7 +547,7 @@ static int blackbird_initialize_codec(st
return retval;

dev->mailbox = blackbird_find_mailbox(dev);
* if (dev->mailbox < 0)
return -1;

retval = blackbird_api_cmd(dev, CX2341X_ENC_PING_FW, 0, 0); /* ping */
*** drivers/net/ixp2000/ixpdev.c 2008-03-27 12:25:35.000000000 +0100
@@ -96,7 +96,7 @@ static int ixpdev_rx(struct net_device *
goto err;
}

* if (desc->channel < 0 || desc->channel >= nds_count) {
printk(KERN_ERR "ixp2000: rx err, channel %d\n",
desc->channel);
goto err;
*** drivers/net/wireless/iwlwifi/iwl-4965.c 2008-04-22 22:20:55.000000000 +0200
@@ -3121,7 +3121,7 @@ int iwl4965_hw_txq_attach_buf_to_tfd(str
u32 num_tbs = IWL_GET_BITS(*tfd, num_tbs);

/* Each TFD can point to a maximum 20 Tx buffers */
* if ((num_tbs >= MAX_NUM_OF_TBS) || (num_tbs < 0)) {
IWL_ERROR("Error can not send more than %d chunks\n",
MAX_NUM_OF_TBS);
return -EINVAL;
*** drivers/net/wireless/prism54/isl_ioctl.c 2008-04-22 22:11:58.000000000 +0200
@@ -1186,7 +1186,7 @@ prism54_get_encode(struct net_device *nd
rvalue |= mgt_get_request(priv, DOT11_OID_DEFKEYID, 0, NULL, &r); devindex = r.u;
/* Now get the key, return it */
* if ((index < 0) || (index > 3))
/* no index provided, use the current one */ index = devindex;
rvalue |= mgt_get_request(priv, DOT11_OID_DEFKEYX, index, NULL, &r);
*** drivers/net/wireless/rndis_wlan.c 2008-04-22 22:11:58.000000000 +0200
@@ -2425,7 +2425,7 @@ static int bcm4320_early_init(struct usb
else if (priv->param_roamdelta > 2)
priv->param_roamdelta = 2;

* if (priv->param_workaround_interval < 0)
priv->param_workaround_interval = 500;

rndis_set_config_parameter_str(dev, "Country", priv->param_country);
*** drivers/ps3/ps3av.c 2008-03-27 12:25:38.000000000 +0100
@@ -846,7 +846,7 @@ int ps3av_set_video_mode(u32 id)
u32 option;

size = ARRAY_SIZE(video_mode_table);
* if ((id & PS3AV_MODE_MASK) > size - 1 || id < 0) {
dev_dbg(&ps3av->dev->core, "%s: error id :%d\n", __func__, id); return -EINVAL;
}
@@ -895,7 +895,7 @@ int ps3av_video_mode2res(u32 id, u32 *xr

id = id & PS3AV_MODE_MASK;
size = ARRAY_SIZE(video_mode_table);
* if (id > size - 1 || id < 0) {
printk(KERN_ERR "%s: invalid mode %d\n", __func__, id); return -EINVAL;
}
*** drivers/scsi/dpt_i2o.c 2008-03-27 12:25:39.000000000 +0100
@@ -1096,7 +1096,7 @@ static struct adpt_device* adpt_find_dev
{
struct adpt_device* d;

* if(chan < 0 || chan >= MAX_CHANNEL)
return NULL;

if( pHba->channel[chan].device = NULL){
*** drivers/spi/spi_mpc83xx.c 2008-04-14 15:59:50.000000000 +0200
@@ -456,7 +456,7 @@ static int __init mpc83xx_spi_probe(stru

mpc83xx_spi->irq = platform_get_irq(dev, 0);

* if (mpc83xx_spi->irq < 0) {
ret = -ENXIO;
goto unmap_io;
}
*** drivers/spi/xilinx_spi.c 2008-04-12 14:33:04.000000000 +0200
@@ -354,7 +354,7 @@ static int __init xilinx_spi_probe(struc
}

xspi->irq = platform_get_irq(dev, 0);
* if (xspi->irq < 0) {
ret = -ENXIO;
goto unmap_io;
}
*** drivers/video/amifb.c 2008-04-14 17:31:23.000000000 +0200
@@ -2053,7 +2053,7 @@ static void amifb_copyarea(struct fb_inf
sy = area->sy + (dy - area->dy);

/* the source must be completely inside the virtual screen */
* if (sx < 0 || sy < 0 || (sx + width) > info->var.xres_virtual ||
(sy + height) > info->var.yres_virtual)
return;

*** drivers/video/atafb.c 2008-04-14 15:59:51.000000000 +0200
@@ -2598,7 +2598,7 @@ static void atafb_copyarea(struct fb_inf
sy = area->sy + (dy - area->dy);

/* the source must be completely inside the virtual screen */
* if (sx < 0 || sy < 0 || (sx + width) > info->var.xres_virtual ||
(sy + height) > info->var.yres_virtual)
return;

*** drivers/video/aty/aty128fb.c 2008-04-14 15:59:51.000000000 +0200
@@ -1350,7 +1350,7 @@ static int aty128_var_to_pll(u32 period_
}
}

* if (pll->post_divider < 0)
return -EINVAL;

/* calculate feedback divider */
*** drivers/video/vga16fb.c 2008-04-14 15:59:52.000000000 +0200
@@ -1092,7 +1092,7 @@ static void vga16fb_copyarea(struct fb_i
sy += (dy - old_dy);

/* the source must be completely inside the virtual screen */
* if (sx < 0 || sy < 0 || (sx + width) > vxres || (sy + height) > vyres)
return;

switch (info->fix.type) {
*** sound/pci/emu10k1/io.c 2008-03-27 12:25:54.000000000 +0100
@@ -254,7 +254,7 @@ int snd_emu1010_fpga_write(struct snd_em
if (reg > 0x3f)
return 1;
reg += 0x40; /* 0x40 upwards are registers. */
* if (value < 0 || value > 0x3f) /* 0 to 0x3f are values */
return 1;
spin_lock_irqsave(&emu->emu_lock, flags);
outl(reg, emu->port + A_IOCFG);
*** drivers/infiniband/hw/ehca/ehca_eq.c 2008-03-27 12:25:30.000000000 +0100
@@ -126,7 +126,7 @@ int ehca_create_eq(struct ehca_shca *shc
ret = ibmebus_request_irq(eq->ist, ehca_interrupt_eq,
IRQF_DISABLED, "ehca_eq", (void *)shca);
* if (ret < 0)
ehca_err(ib_dev, "Can't map interrupt handler.");

tasklet_init(&eq->interrupt_task, ehca_tasklet_eq, (long)shca);
@@ -134,7 +134,7 @@ int ehca_create_eq(struct ehca_shca *shc
ret = ibmebus_request_irq(eq->ist, ehca_interrupt_neq,
IRQF_DISABLED, "ehca_neq", (void *)shca);
* if (ret < 0)
ehca_err(ib_dev, "Can't map interrupt handler.");

tasklet_init(&eq->interrupt_task, ehca_tasklet_neq, (long)shca);
*** drivers/video/omap/omapfb_main.c 2008-04-22 22:20:55.000000000 +0200
@@ -275,7 +275,7 @@ static int _setcolreg(struct fb_info *in
if (r != 0)
break;

* if (regno < 0) {
r = -EINVAL;
break;
}
*** drivers/scsi/eata.c 2008-03-27 12:25:39.000000000 +0100
@@ -2347,11 +2347,11 @@ static irqreturn_t ihdlr(int irq, struct
printk
("%s: ihdlr, spp->eoc = 0, irq %d, reg 0x%x, count %d.\n",
ha->board_name, irq, reg, ha->iocount);
* if (spp->cpp_index < 0 || spp->cpp_index >= shost->can_queue)
printk
("%s: ihdlr, bad spp->cpp_index %d, irq %d, reg 0x%x, count %d.\n",
ha->board_name, spp->cpp_index, irq, reg, ha->iocount);
* if (spp->eoc = 0 || spp->cpp_index < 0
|| spp->cpp_index >= shost->can_queue)
goto handled;

*** drivers/char/rio/rioctrl.c 2008-04-22 22:11:58.000000000 +0200
@@ -405,7 +405,7 @@ int riocontrol(struct rio_info *p, dev_t
case RIO_RESUME:
rio_dprintk(RIO_DEBUG_CTRL, "RIO_RESUME\n");
port = arg;
* if ((port < 0) || (port > 511)) {
rio_dprintk(RIO_DEBUG_CTRL, "RIO_RESUME: Bad port number %d\n", port); p->RIOError.Error = PORT_NUMBER_OUT_OF_RANGE;
return -EINVAL;
@@ -497,7 +497,7 @@ int riocontrol(struct rio_info *p, dev_t
return -EFAULT;
}
rio_dprintk(RIO_DEBUG_CTRL, "Get module type for port %d\n", port);
* if (port < 0 || port > 511) {
rio_dprintk(RIO_DEBUG_CTRL, "RIO_GET_MODTYPE: Bad port number %d\n", port); p->RIOError.Error = PORT_NUMBER_OUT_OF_RANGE;
return -EINVAL;
@@ -1144,7 +1144,7 @@ int riocontrol(struct rio_info *p, dev_t
case RIO_MAP_B110_TO_115200:
rio_dprintk(RIO_DEBUG_CTRL, "Baud rate mapping\n");
port = arg;
* if (port < 0 || port > 511) {
rio_dprintk(RIO_DEBUG_CTRL, "Baud rate mapping: Bad port number %d\n", port); p->RIOError.Error = PORT_NUMBER_OUT_OF_RANGE;
return -EINVAL;

#28 lore raw
In reply to Roel Kluin
Quoted 14 lines · Roel Kluin

Thanks for your feedback, julia, I finally used

(
* i < 0
|
* i < -C
|
* i > -C
|
* i <= -C
|
* i >= -C
)

Quoted 2 lines

I noted you had more results in the same files. Is there a difference in results when you remove the asterisks before the expression?

I'm not sure to understand the question. * means "tell me about this item". So if you remove the *, it will do same the match, but it won't give you any output.

Sometimes I have posted to the kernel janitors mailing list semantic patches, in which - and + are used to remove and add things, rather than *, which just finds things. The semantics of the matching done with - and
+ is slightly different from the semantics with *, in that with - and +, all control-flow paths from the first node matched by the pattern have to use the metavariables (eg C) in a consistent way, whereas with * there just has to exist a single path that matches the pattern. But this is not relevant to our example, because we are just matching individual terms.

julia

#29 lore raw
In reply to Roel Kluin
Quoted 2 lines

I noted you had more results in the same files. Is there a difference in results when you remove the asterisks before the expression?

Actually, I'm a little puzzled by your results. None of your files seem to be in my output (based on a check of a few examples), but that is normal because you consider many other types. But none of my files are in your output either. Did you just remove them to avoid being redundant, or is your rule overlooking the simple unsigned int case?

I might have gotten a few more examples because of using the options -all_includes -I ./include. The it takes into account more include files, and thus has a better chance of finding structure fields that have an unsigned int type. But that doesn't seem to account for the difference.

julia

author
#30 lore raw
In reply to Roel Kluin
Quoted 8 lines · Julia Lawall
Quoted 2 lines

I noted you had more results in the same files. Is there a difference in results when you remove the asterisks before the expression?

Actually, I'm a little puzzled by your results. None of your files seem to be in my output (based on a check of a few examples), but that is normal because you consider many other types. But none of my files are in your output either. Did you just remove them to avoid being redundant, or is your rule overlooking the simple unsigned int case?

These are only the results with unsigned typedefs. I removed the previous. of the unsigned and unsigned long there were few that were not in your results.

Quoted 4 lines

I might have gotten a few more examples because of using the options -all_includes -I ./include. The it takes into account more include files, and thus has a better chance of finding structure fields that have an unsigned int type. But that doesn't seem to account for the difference.

Ok, thanks, I'll try that too.

Quoted 1 line

julia

To answer your other question: I'm already posting patches for the ones that should be fixed. Patches that fix things are always welcome.

Regards,

Roel Kluin