Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/66056978/coverity-complains-about-htonl-operands-but-why

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...