Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 6 Aug 2012 05:41:47 GMT
From:      William Ahern <william@25thandclement.com>
To:        freebsd-gnats-submit@FreeBSD.org
Subject:   standards/170403: wrong ntohs expression type tickling clang
Message-ID:  <201208060541.q765flwf012685@red.freebsd.org>
Resent-Message-ID: <201208060550.q765o1jh058128@freefall.freebsd.org>

next in thread | raw e-mail | index | archive | help

>Number:         170403
>Category:       standards
>Synopsis:       wrong ntohs expression type tickling clang
>Confidential:   no
>Severity:       non-critical
>Priority:       low
>Responsible:    freebsd-standards
>State:          open
>Quarter:        
>Keywords:       
>Date-Required:
>Class:          sw-bug
>Submitter-Id:   current-users
>Arrival-Date:   Mon Aug 06 05:50:01 UTC 2012
>Closed-Date:
>Last-Modified:
>Originator:     William Ahern
>Release:        9.0-RELEASE
>Organization:
>Environment:
FreeBSD fbsd 9.0-RELEASE FreeBSD 9.0-RELEASE #0: Tue Jan  3 07:46:30 UTC 2012     root@farrell.cse.buffalo.edu:/usr/obj/usr/src/sys/GENERIC  amd64
>Description:
I reported this bug to Apple a couple of years ago. Maybe it was inherited from FreeBSD.

The source of the problem is ntohs/htons optimization. ntohs expands to

(__builtin_constant_p(_x) ?  __bswap16_const((__uint16_t)(_x)) : __bswap16_var(_x))

in /usr/include/machine/endian.h.

The problem is that the promoted type of that ternary expression is int. But ntohs and htons are defined to have a return type of uint16_t.

Normally, this is a case of no harm no foul because basically every value gets promoted to int eventually, when used as an operand or argument. Nonetheless, the clang printf analyzer complains when using the %hu format specifier. GCC keeps silent, which is probably why this issue never came to anybody's attention.

$ make CC=clang foo
clang -O2 -pipe   foo.c  -o foo
foo.c:8:12: warning: conversion specifies type 'unsigned short' but the argument
      has type 'int' [-Wformat]
        printf("%hu\n", ntohs(i));
                ~~^     ~~~~~~~~
                %d
1 warning generated.

>How-To-Repeat:
// make CC=clang foo
#include <stdio.h>
#include <arpa/inet.h>

int main(void) {
	uint16_t i = 1234;

	printf("%hu\n", ntohs(i));

	return 0;
}

>Fix:
Cast the result of the __bswap16  expression to __uint16_t, either in the __ntohs/__htons macros, or in the __bswap16 macro directly like with __bswap16_const.


>Release-Note:
>Audit-Trail:
>Unformatted:



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?201208060541.q765flwf012685>