Repository: mdempsky/maligned Branch: master Commit: d7cd9a96ae47 Files: 10 Total size: 12.0 KB Directory structure: gitextract_1l89j5ld/ ├── LICENSE ├── README.md ├── go.mod ├── go.sum ├── maligned.go └── passes/ └── maligned/ ├── analyzer.go ├── analyzer_test.go └── testdata/ └── src/ └── a/ ├── a.go ├── ptr.go └── zero.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ Copyright (c) 2012 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: README.md ================================================ **Deprecated:** Use https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/fieldalignment instead. Install: go get github.com/mdempsky/maligned Usage: maligned cmd/compile/internal/gc cmd/link/internal/ld ================================================ FILE: go.mod ================================================ module github.com/mdempsky/maligned go 1.15 require ( golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27 // indirect golang.org/x/tools v0.1.9 ) ================================================ FILE: go.sum ================================================ github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/mod v0.5.1 h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27 h1:XDXtA5hveEEV8JB2l7nhMTp3t3cHp9ZpwcdjqyEWLlo= golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.9 h1:j9KsMiaP1c3B0OTQGth0/k+miLGTgLsAFUCrF2vLcF8= golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= ================================================ FILE: maligned.go ================================================ // Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "flag" "github.com/mdempsky/maligned/passes/maligned" "golang.org/x/tools/go/analysis/singlechecker" ) func main() { flag.Parse() singlechecker.Main(maligned.Analyzer) } ================================================ FILE: passes/maligned/analyzer.go ================================================ package maligned import ( "go/ast" "go/token" "go/types" "sort" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" ) const Doc = "TODO" var Analyzer = &analysis.Analyzer{ Name: "maligned", Doc: Doc, Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: run, } func run(pass *analysis.Pass) (interface{}, error) { inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) nodeFilter := []ast.Node{ (*ast.StructType)(nil), } inspect.Preorder(nodeFilter, func(node ast.Node) { if s, ok := node.(*ast.StructType); ok { malign(pass, node.Pos(), pass.TypesInfo.Types[s].Type.(*types.Struct)) } }) return nil, nil } var unsafePointerTyp = types.Unsafe.Scope().Lookup("Pointer").(*types.TypeName).Type() func malign(pass *analysis.Pass, pos token.Pos, str *types.Struct) { wordSize := pass.TypesSizes.Sizeof(unsafePointerTyp) maxAlign := pass.TypesSizes.Alignof(unsafePointerTyp) s := gcSizes{wordSize, maxAlign} optsz, optptrs := optimalOrder(str, &s) if sz := s.Sizeof(str); sz != optsz { pass.Reportf(pos, "struct of size %d could be %d", sz, optsz) } if ptrs := s.ptrdata(str); ptrs != optptrs { pass.Reportf(pos, "struct with %d pointer bytes could be %d", ptrs, optptrs) } } func optimalOrder(str *types.Struct, sizes *gcSizes) (int64, int64) { nf := str.NumFields() type elem struct { field *types.Var alignof int64 sizeof int64 ptrdata int64 } elems := make([]elem, nf) for i := 0; i < nf; i++ { field := str.Field(i) ft := field.Type() elems[i] = elem{ field, sizes.Alignof(ft), sizes.Sizeof(ft), sizes.ptrdata(ft), } } sort.Slice(elems, func(i, j int) bool { ei := &elems[i] ej := &elems[j] // Place zero sized objects before non-zero sized objects. zeroi := ei.sizeof == 0 zeroj := ej.sizeof == 0 if zeroi != zeroj { return zeroi } // Next, place more tightly aligned objects before less tightly aligned objects. if ei.alignof != ej.alignof { return ei.alignof > ej.alignof } // Place pointerful objects before pointer-free objects. noptrsi := ei.ptrdata == 0 noptrsj := ej.ptrdata == 0 if noptrsi != noptrsj { return noptrsj } if !noptrsi { // If both have pointers... // ... then place objects with less trailing // non-pointer bytes earlier. That is, place // the field with the most trailing // non-pointer bytes at the end of the // pointerful section. traili := ei.sizeof - ei.ptrdata trailj := ej.sizeof - ej.ptrdata if traili != trailj { return traili < trailj } } // Lastly, order by size. if ei.sizeof != ej.sizeof { return ei.sizeof > ej.sizeof } return false }) var fields []*types.Var for _, e := range elems { fields = append(fields, e.field) } optimal := types.NewStruct(fields, nil) return sizes.Sizeof(optimal), sizes.ptrdata(optimal) } // Code below based on go/types.StdSizes. type gcSizes struct { WordSize int64 MaxAlign int64 } func (s *gcSizes) Alignof(T types.Type) int64 { // NOTE: On amd64, complex64 is 8 byte aligned, // even though float32 is only 4 byte aligned. // For arrays and structs, alignment is defined in terms // of alignment of the elements and fields, respectively. switch t := T.Underlying().(type) { case *types.Array: // spec: "For a variable x of array type: unsafe.Alignof(x) // is the same as unsafe.Alignof(x[0]), but at least 1." return s.Alignof(t.Elem()) case *types.Struct: // spec: "For a variable x of struct type: unsafe.Alignof(x) // is the largest of the values unsafe.Alignof(x.f) for each // field f of x, but at least 1." max := int64(1) for i, nf := 0, t.NumFields(); i < nf; i++ { if a := s.Alignof(t.Field(i).Type()); a > max { max = a } } return max } a := s.Sizeof(T) // may be 0 // spec: "For a variable x of any type: unsafe.Alignof(x) is at least 1." if a < 1 { return 1 } if a > s.MaxAlign { return s.MaxAlign } return a } var basicSizes = [...]byte{ types.Bool: 1, types.Int8: 1, types.Int16: 2, types.Int32: 4, types.Int64: 8, types.Uint8: 1, types.Uint16: 2, types.Uint32: 4, types.Uint64: 8, types.Float32: 4, types.Float64: 8, types.Complex64: 8, types.Complex128: 16, } func (s *gcSizes) Sizeof(T types.Type) int64 { switch t := T.Underlying().(type) { case *types.Basic: k := t.Kind() if int(k) < len(basicSizes) { if s := basicSizes[k]; s > 0 { return int64(s) } } if k == types.String { return s.WordSize * 2 } case *types.Array: return t.Len() * s.Sizeof(t.Elem()) case *types.Slice: return s.WordSize * 3 case *types.Struct: nf := t.NumFields() if nf == 0 { return 0 } var o int64 max := int64(1) for i := 0; i < nf; i++ { ft := t.Field(i).Type() a, sz := s.Alignof(ft), s.Sizeof(ft) if a > max { max = a } if i == nf-1 && sz == 0 && o != 0 { sz = 1 } o = align(o, a) + sz } return align(o, max) case *types.Interface: return s.WordSize * 2 } return s.WordSize // catch-all } // align returns the smallest y >= x such that y % a == 0. func align(x, a int64) int64 { y := x + a - 1 return y - y%a } func (s *gcSizes) ptrdata(T types.Type) int64 { switch t := T.Underlying().(type) { case *types.Basic: switch t.Kind() { case types.String, types.UnsafePointer: return s.WordSize } return 0 case *types.Chan, *types.Map, *types.Pointer, *types.Signature, *types.Slice: return s.WordSize case *types.Interface: return 2 * s.WordSize case *types.Array: n := t.Len() if n == 0 { return 0 } a := s.ptrdata(t.Elem()) if a == 0 { return 0 } z := s.Sizeof(t.Elem()) return (n-1)*z + a case *types.Struct: nf := t.NumFields() if nf == 0 { return 0 } var o, p int64 max := int64(1) for i := 0; i < nf; i++ { ft := t.Field(i).Type() a, sz := s.Alignof(ft), s.Sizeof(ft) fp := s.ptrdata(ft) if a > max { max = a } if i == nf-1 && sz == 0 && o != 0 { sz = 1 } o = align(o, a) if fp != 0 { p = o + fp } o += sz } return p } panic("impossible") return 0 } ================================================ FILE: passes/maligned/analyzer_test.go ================================================ package maligned_test import ( "testing" "github.com/mdempsky/maligned/passes/maligned" "golang.org/x/tools/go/analysis/analysistest" ) func TestTest(t *testing.T) { testdata := analysistest.TestData() analysistest.Run(t, testdata, maligned.Analyzer, "a") } ================================================ FILE: passes/maligned/testdata/src/a/a.go ================================================ package a type Good struct { y int32 x byte z byte } type Bad struct { // want "struct of size 12 could be 8" x byte y int32 z byte } ================================================ FILE: passes/maligned/testdata/src/a/ptr.go ================================================ package a type PointerGood struct { P *int buf [1000]uintptr } type PointerBad struct { // want "struct with 8008 pointer bytes could be 8" buf [1000]uintptr P *int } type PointerSorta struct { a struct { p *int q uintptr } b struct { p *int q [2]uintptr } } type PointerSortaBad struct { // want "struct with 32 pointer bytes could be 24" a struct { p *int q [2]uintptr } b struct { p *int q uintptr } } ================================================ FILE: passes/maligned/testdata/src/a/zero.go ================================================ package a type ZeroGood struct { a [0]byte b uint32 } type ZeroBad struct { // want "struct of size 8 could be 4" a uint32 b [0]byte }