Debian Codegraph @

staticcheck/sa9006/sa9006.go

raw
1 package sa9006
2
3 import (
4 "fmt"
5 "go/ast"
6 "go/types"
7
8 "honnef.co/go/tools/analysis/code"
9 "honnef.co/go/tools/analysis/lint"
10 "honnef.co/go/tools/analysis/report"
11 "honnef.co/go/tools/pattern"
12
13 "golang.org/x/tools/go/analysis"
14 )
15
16 var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
17 Analyzer: &analysis.Analyzer{
18 Name: "SA9006",
19 Run: run,
20 Requires: code.RequiredAnalyzers,
21 },
22 Doc: &lint.RawDocumentation{
23 Title: `Dubious bit shifting of a fixed size integer value`,
24 Text: `Bit shifting a value past its size will always clear the value.
25
26 For instance:
27
28 v := int8(42)
29 v >>= 8
30
31 will always result in 0.
32
33 This check flags bit shifting operations on fixed size integer values only.
34 That is, int, uint and uintptr are never flagged to avoid potential false
35 positives in somewhat exotic but valid bit twiddling tricks:
36
37 // Clear any value above 32 bits if integers are more than 32 bits.
38 func f(i int) int {
39 v := i >> 32
40 v = v << 32
41 return i-v
42 }`,
43 Since: "2020.2",
44 Severity: lint.SeverityWarning,
45 // Technically this should be MergeIfAll, because the type of
46 // v might be different for different build tags. Practically,
47 // don't write code that depends on that.
48 MergeIf: lint.MergeIfAny,
49 },
50 })
51
52 var Analyzer = SCAnalyzer.Analyzer
53 var (
54 checkFixedLengthTypeShiftQ = pattern.MustParse(`
55 (Or
56 (AssignStmt _ (Or ">>=" "<<=") _)
57 (BinaryExpr _ (Or ">>" "<<") _))
58 `)
59 )
60
61 func run(pass *analysis.Pass) (any, error) {
62 isDubiousShift := func(x, y ast.Expr) (int64, int64, bool) {
63 typ, ok := pass.TypesInfo.TypeOf(x).Underlying().(*types.Basic)
64 if !ok {
65 return 0, 0, false
66 }
67 switch typ.Kind() {
68 case types.Int8, types.Int16, types.Int32, types.Int64,
69 types.Uint8, types.Uint16, types.Uint32, types.Uint64:
70 // We're only interested in fixed–size types.
71 default:
72 return 0, 0, false
73 }
74
75 const bitsInByte = 8
76 typeBits := pass.TypesSizes.Sizeof(typ) * bitsInByte
77
78 shiftLength, ok := code.ExprToInt(pass, y)
79 if !ok {
80 return 0, 0, false
81 }
82
83 return typeBits, shiftLength, shiftLength >= typeBits
84 }
85
86 for node := range code.Matches(pass, checkFixedLengthTypeShiftQ) {
87 switch e := node.(type) {
88 case *ast.AssignStmt:
89 if size, shift, yes := isDubiousShift(e.Lhs[0], e.Rhs[0]); yes {
90 report.Report(pass, e, fmt.Sprintf("shifting %d-bit value by %d bits will always clear it", size, shift))
91 }
92 case *ast.BinaryExpr:
93 if size, shift, yes := isDubiousShift(e.X, e.Y); yes {
94 report.Report(pass, e, fmt.Sprintf("shifting %d-bit value by %d bits will always clear it", size, shift))
95 }
96 }
97 }
98
99 return nil, nil
100 }