Shift out of range¶
ID: go/shift-out-of-rangeKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - reliability - correctness - external/cwe/cwe-197Query suites: - go-security-and-quality.qls
Click to see the query in the CodeQL repository
Shifting an integer value by more than the number of bits in its type always results in -1 for right-shifts of negative values and 0 for other shifts. Hence, such a shift expression is either redundant or indicates a logic mistake.
Recommendation¶
Examine the length check to see whether it is redundant and can be removed, or a mistake that should be fixed.
Example¶
The following code snippet attempts to compute the value 240 (1099511627776). However, since the left operandbase is of typeint32 (32 bits), the shift operation overflows, yielding zero.
packagemainfuncshift(baseint32)int32{returnbase<<40}varx1=shift(1)
To prevent this, the type ofbase should be changed toint64:
packagemainfuncshiftGood(baseint64)int64{returnbase<<40}varx2=shiftGood(1)
References¶
The Go Programming Language Specification:Arithmetic operators.
Common Weakness Enumeration:CWE-197.