c++cnetwork-programmingcoverityhtonl

Coverity complains about htonl operands but why?


This code converts a local toggle into an outgoing network-order boolean (which is actually a 32bit uint) and is at least 10 years old but Coverity started complaining about it just recently. I don't understand what the problem is and where it's getting "operand |" from. Is the problem that htonl is only supposed to work on 32bit values and we have htons for 16 bit ones? Is this a false detection?

struct network_response_t {
    uint32_t exclusive;
}

bitmap16_t mode_t {
  TYPE_MIXED = 0x0,
  TYPE_EXCLUSIVE = 0x1,
  ...
}

mode_t local_mode;
network_response_t response;

response.exclusive = htonl((local_mode & TYPE_EXCLUSIVE) ? 1 : 0);

ERROR:

Operands don't affect result (CONSTANT_EXPRESSION_RESULT) result_independent_of_operands: (__uint16_t)((__uint32_t)((local_mode & TYPE_EXCLUSIVE) ? 1 : 0) & 65535) >> 8 is 0 regardless of the values of its operands. This occurs as the bitwise second operand of "|".


Solution

  • This is a false positive. On a little-endian platform, htonl does an endian swap, extracting the bytes of the argument and putting them back together in the opposite order using the bitwise OR operator. Coverity correctly realizes that one of those bytes will always be zero because the original argument in this case is always either 0 or 1. But it is wrong to conclude that fact is unintentional.

    I suggest reporting this back to Coverity's support team so they can get it fixed.