DeepCode offers an AI-based Static Program Analysis for Java, JavaScript and TypeScript, C/C++ and Python. As you might know, DeepCode uses thousands of open source repos to train our engine. We asked the engine team to provide some stats on the findings. On the top suggestions from our engine, we want to introduce and give some background in this series of blog articles.
Language: C
Defect: Integer Promotion on Bitwise Operations
Diagnose: Cast the result of shift left to unsigned short to avoid unexpected behavior because of integral type promotion. The shifted expression is promoted to unsigned int, which may introduce a number of unknown bits.
This example is sponsored by Linux in the Alpha architecture (see here ). Obviously, you can load them also in your own dashboard.
So, here is the code:
static __inline__ int get_dma_residue(unsigned int dmanr)
{
unsigned int io_port = (dmanr<=3)? ((dmanr&3)<<1) + 1 + IO_DMA1_BASE
: ((dmanr&3)<<2) + 2 + IO_DMA2_BASE;
/* using short to get 16-bit wrap around */
unsigned short count;
count = 1 + dma_inb(io_port);
count += dma_inb(io_port) << 8;
return (dmanr<=3)? count : (count<<1);
}
What we should observe is there count
variable which type is unsigned short
. The function returns the type int
and in the return statement, we have a conditional that either returns count
(which would need a typecast to int
) or a bitwise shift left of count
.
The type conversion rules for bitwise operations in C are actually not that straight forward. The long explanation - as pointed out by DeepCode with the link More Info - is here. Under the hood, C converts operants oftentimes to int
, applies the operation, and truncates the result to fit into the target variable. Bitwise operators are such an example.
Given the specific architecture, the implicit typecast between unsigned short
and int
might just work out perfectly. I would argue it is hard to follow the intent of the developer and he was aware (therefor the comment). Still, following the best practices, he should do explicit type conversions (see also the link above).
Top comments (0)