|
| 1 | +# CastAddressToIntegerAtReturn and CastIntegerToAddressAtReturn |
| 2 | + |
| 3 | +**Message**: Returning an address value in a function with integer return type is not portable.<br/> |
| 4 | +**Category**: Portability<br/> |
| 5 | +**Severity**: Portability<br/> |
| 6 | +**Language**: C/C++ |
| 7 | + |
| 8 | +## Description |
| 9 | + |
| 10 | +A function silently narrows a pointer (address) down to a plain integer return type, or the other way |
| 11 | +around. On platforms where `sizeof(void*) != sizeof(int)` (most notably 64-bit platforms, where a |
| 12 | +pointer is 8 bytes and `int` is usually still 4 bytes) this loses information: part of the address is |
| 13 | +silently discarded. |
| 14 | + |
| 15 | +- `CastAddressToIntegerAtReturn`: a function with an integer return type returns a pointer value, for |
| 16 | + example `int foo(char *p) { return p; }`. |
| 17 | +- `CastIntegerToAddressAtReturn`: a function with a pointer return type returns a plain integer value, |
| 18 | + for example `void* foo(int i) { return i; }`. |
| 19 | + |
| 20 | +This checks `char`/`short`/`int` (not `long`/`long long`, and not `bool`, which is a common, |
| 21 | +intentional idiom rather than a truncation bug), and only when analyzing for a 64-bit target - on a |
| 22 | +32-bit target a pointer and an `int` are the same width, so returning one as the other isn't a |
| 23 | +portability problem there. This checker only runs when the `portability` severity is enabled. |
| 24 | + |
| 25 | +## Motivation |
| 26 | + |
| 27 | +Storing an address in a type that is narrower than a pointer is not portable: it works by accident on |
| 28 | +platforms where the two types happen to be the same width, and silently truncates the address (or |
| 29 | +sign-extends a small integer into a bogus address) on platforms where they are not, most notably when |
| 30 | +porting 32-bit code to 64-bit. |
| 31 | + |
| 32 | +## How to fix |
| 33 | + |
| 34 | +Use a pointer type, or an integer type explicitly meant to hold a pointer (`intptr_t`/`uintptr_t` from |
| 35 | +`<cstdint>`), instead of a plain `int`/`char`/etc. |
| 36 | + |
| 37 | +Before: |
| 38 | +```cpp |
| 39 | +void* foo(int i) { |
| 40 | + return i; // <- CastIntegerToAddressAtReturn |
| 41 | +} |
| 42 | +``` |
| 43 | +
|
| 44 | +After: |
| 45 | +```cpp |
| 46 | +#include <cstdint> |
| 47 | +void* foo(intptr_t i) { |
| 48 | + return reinterpret_cast<void*>(i); |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +## Related checkers |
| 53 | + |
| 54 | +- [AssignmentAddressToInteger.md](AssignmentAddressToInteger.md) - the same idea, but for a plain |
| 55 | + assignment rather than a function `return`. |
0 commit comments