github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/tools/checkunsafe/check_unsafe.go (about)

     1  // Copyright 2019 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package checkunsafe allows unsafe imports only in files named appropriately.
    16  package checkunsafe
    17  
    18  import (
    19  	"fmt"
    20  	"path"
    21  	"strconv"
    22  	"strings"
    23  
    24  	"golang.org/x/tools/go/analysis"
    25  )
    26  
    27  // Analyzer defines the entrypoint.
    28  var Analyzer = &analysis.Analyzer{
    29  	Name: "checkunsafe",
    30  	Doc:  "allows unsafe use only in specified files",
    31  	Run:  run,
    32  }
    33  
    34  func run(pass *analysis.Pass) (interface{}, error) {
    35  	for _, f := range pass.Files {
    36  		for _, imp := range f.Imports {
    37  			// Is this an unsafe import?
    38  			pkg, err := strconv.Unquote(imp.Path.Value)
    39  			if err != nil || pkg != "unsafe" {
    40  				continue
    41  			}
    42  
    43  			// Extract the filename.
    44  			filename := pass.Fset.File(imp.Pos()).Name()
    45  
    46  			// Allow files named _unsafe.go or _test.go to opt out.
    47  			if strings.HasSuffix(filename, "_unsafe.go") || strings.HasSuffix(filename, "_test.go") {
    48  				continue
    49  			}
    50  
    51  			// Throw the error.
    52  			pass.Reportf(imp.Pos(), fmt.Sprintf("package unsafe imported by %s; must end with _unsafe.go", path.Base(filename)))
    53  		}
    54  	}
    55  	return nil, nil
    56  }