0

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 "|".

Glebbb
  • 356
  • 1
  • 8
  • Would `uint32_t mode_exclusive = (local_mode & TYPE_EXCLUSIVE) ? 1 : 0; response.exclusive = htonl(mode_exclusive);` be a workaround? `mode_t` seems to be `uint16_t` (because it's defined with `bitmap16_t`) and that might be the issue. The extra cast to `__uint16_t` in the error message may be confirming that as, otherwise, I see no reason for it. – Craig Estey Feb 05 '21 at 03:14

1 Answers1

4

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.

Scott McPeak
  • 8,803
  • 2
  • 40
  • 79
  • Thanks for the explanation, that makes a lot of sense now and kind of a weird assumption on Coverity's part. – Glebbb Feb 05 '21 at 03:54
  • The basic idea of the check is sound: if a complete expression always evaluates to a constant despite having variable inputs, then something is probably amiss (this happens somewhat often due to operator precedence mistakes). But here, it's only a subexpression that is constant, which alone is not (IMO) strong enough evidence to warrant a finding. – Scott McPeak Feb 05 '21 at 04:30