Source file src/cmd/cover/cover.go

     1  // Copyright 2013 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"bytes"
     9  	"cmd/internal/cov/covcmd"
    10  	"cmp"
    11  	"encoding/json"
    12  	"flag"
    13  	"fmt"
    14  	"go/ast"
    15  	"go/parser"
    16  	"go/scanner"
    17  	"go/token"
    18  	"internal/coverage"
    19  	"internal/coverage/encodemeta"
    20  	"internal/coverage/slicewriter"
    21  	"io"
    22  	"log"
    23  	"os"
    24  	"path/filepath"
    25  	"slices"
    26  	"strconv"
    27  	"strings"
    28  
    29  	"cmd/internal/edit"
    30  	"cmd/internal/objabi"
    31  	"cmd/internal/telemetry/counter"
    32  )
    33  
    34  const usageMessage = "" +
    35  	`Usage of 'go tool cover':
    36  Given a coverage profile produced by 'go test':
    37  	go test -coverprofile=c.out
    38  
    39  Open a web browser displaying annotated source code:
    40  	go tool cover -html=c.out
    41  
    42  Write out an HTML file instead of launching a web browser:
    43  	go tool cover -html=c.out -o coverage.html
    44  
    45  Display coverage percentages to stdout for each function:
    46  	go tool cover -func=c.out
    47  
    48  Finally, to generate modified source code with coverage annotations
    49  for a package (what go test -cover does):
    50  	go tool cover -mode=set -var=CoverageVariableName \
    51  		-pkgcfg=<config> -outfilelist=<file> file1.go ... fileN.go
    52  
    53  where -pkgcfg points to a file containing the package path,
    54  package name, module path, and related info from "go build",
    55  and -outfilelist points to a file containing the filenames
    56  of the instrumented output files (one per input file).
    57  See https://pkg.go.dev/cmd/internal/cov/covcmd#CoverPkgConfig for
    58  more on the package config.
    59  `
    60  
    61  func usage() {
    62  	fmt.Fprint(os.Stderr, usageMessage)
    63  	fmt.Fprintln(os.Stderr, "\nFlags:")
    64  	flag.PrintDefaults()
    65  	fmt.Fprintln(os.Stderr, "\n  Only one of -html, -func, or -mode may be set.")
    66  	os.Exit(2)
    67  }
    68  
    69  var (
    70  	mode             = flag.String("mode", "", "coverage mode: set, count, atomic")
    71  	varVar           = flag.String("var", "GoCover", "name of coverage variable to generate")
    72  	output           = flag.String("o", "", "file for output")
    73  	outfilelist      = flag.String("outfilelist", "", "file containing list of output files (one per line) if -pkgcfg is in use")
    74  	htmlOut          = flag.String("html", "", "generate HTML representation of coverage profile")
    75  	funcOut          = flag.String("func", "", "output coverage profile information for each function")
    76  	pkgcfg           = flag.String("pkgcfg", "", "enable full-package instrumentation mode using params from specified config file")
    77  	pkgconfig        covcmd.CoverPkgConfig
    78  	outputfiles      []string // list of *.cover.go instrumented outputs to write, one per input (set when -pkgcfg is in use)
    79  	profile          string   // The profile to read; the value of -html or -func
    80  	counterStmt      func(*File, string) string
    81  	covervarsoutfile string // an additional Go source file into which we'll write definitions of coverage counter variables + meta data variables (set when -pkgcfg is in use).
    82  	cmode            coverage.CounterMode
    83  	cgran            coverage.CounterGranularity
    84  )
    85  
    86  const (
    87  	atomicPackagePath = "sync/atomic"
    88  	atomicPackageName = "_cover_atomic_"
    89  )
    90  
    91  func main() {
    92  	counter.Open()
    93  
    94  	objabi.AddVersionFlag()
    95  	flag.Usage = usage
    96  	objabi.Flagparse(usage)
    97  	counter.Inc("cover/invocations")
    98  	counter.CountFlags("cover/flag:", *flag.CommandLine)
    99  
   100  	// Usage information when no arguments.
   101  	if flag.NFlag() == 0 && flag.NArg() == 0 {
   102  		flag.Usage()
   103  	}
   104  
   105  	err := parseFlags()
   106  	if err != nil {
   107  		fmt.Fprintln(os.Stderr, err)
   108  		fmt.Fprintln(os.Stderr, `For usage information, run "go tool cover -help"`)
   109  		os.Exit(2)
   110  	}
   111  
   112  	// Generate coverage-annotated source.
   113  	if *mode != "" {
   114  		annotate(flag.Args())
   115  		return
   116  	}
   117  
   118  	// Output HTML or function coverage information.
   119  	if *htmlOut != "" {
   120  		err = htmlOutput(profile, *output)
   121  	} else {
   122  		err = funcOutput(profile, *output)
   123  	}
   124  
   125  	if err != nil {
   126  		fmt.Fprintf(os.Stderr, "cover: %v\n", err)
   127  		os.Exit(2)
   128  	}
   129  }
   130  
   131  // parseFlags sets the profile and counterStmt globals and performs validations.
   132  func parseFlags() error {
   133  	profile = *htmlOut
   134  	if *funcOut != "" {
   135  		if profile != "" {
   136  			return fmt.Errorf("too many options")
   137  		}
   138  		profile = *funcOut
   139  	}
   140  
   141  	// Must either display a profile or rewrite Go source.
   142  	if (profile == "") == (*mode == "") {
   143  		return fmt.Errorf("too many options")
   144  	}
   145  
   146  	if *varVar != "" && !token.IsIdentifier(*varVar) {
   147  		return fmt.Errorf("-var: %q is not a valid identifier", *varVar)
   148  	}
   149  
   150  	if *mode != "" {
   151  		switch *mode {
   152  		case "set":
   153  			counterStmt = setCounterStmt
   154  			cmode = coverage.CtrModeSet
   155  		case "count":
   156  			counterStmt = incCounterStmt
   157  			cmode = coverage.CtrModeCount
   158  		case "atomic":
   159  			counterStmt = atomicCounterStmt
   160  			cmode = coverage.CtrModeAtomic
   161  		case "regonly":
   162  			counterStmt = nil
   163  			cmode = coverage.CtrModeRegOnly
   164  		case "testmain":
   165  			counterStmt = nil
   166  			cmode = coverage.CtrModeTestMain
   167  		default:
   168  			return fmt.Errorf("unknown -mode %v", *mode)
   169  		}
   170  
   171  		if flag.NArg() == 0 {
   172  			return fmt.Errorf("missing source file(s)")
   173  		} else {
   174  			if *pkgcfg != "" {
   175  				if *output != "" {
   176  					return fmt.Errorf("please use '-outfilelist' flag instead of '-o'")
   177  				}
   178  				var err error
   179  				if outputfiles, err = readOutFileList(*outfilelist); err != nil {
   180  					return err
   181  				}
   182  				covervarsoutfile = outputfiles[0]
   183  				outputfiles = outputfiles[1:]
   184  				numInputs := len(flag.Args())
   185  				numOutputs := len(outputfiles)
   186  				if numOutputs != numInputs {
   187  					return fmt.Errorf("number of output files (%d) not equal to number of input files (%d)", numOutputs, numInputs)
   188  				}
   189  				if err := readPackageConfig(*pkgcfg); err != nil {
   190  					return err
   191  				}
   192  				return nil
   193  			} else {
   194  				if *outfilelist != "" {
   195  					return fmt.Errorf("'-outfilelist' flag applicable only when -pkgcfg used")
   196  				}
   197  			}
   198  			if flag.NArg() == 1 {
   199  				return nil
   200  			}
   201  		}
   202  	} else if flag.NArg() == 0 {
   203  		return nil
   204  	}
   205  	return fmt.Errorf("too many arguments")
   206  }
   207  
   208  func readOutFileList(path string) ([]string, error) {
   209  	data, err := os.ReadFile(path)
   210  	if err != nil {
   211  		return nil, fmt.Errorf("error reading -outfilelist file %q: %v", path, err)
   212  	}
   213  	return strings.Split(strings.TrimSpace(string(data)), "\n"), nil
   214  }
   215  
   216  func readPackageConfig(path string) error {
   217  	data, err := os.ReadFile(path)
   218  	if err != nil {
   219  		return fmt.Errorf("error reading pkgconfig file %q: %v", path, err)
   220  	}
   221  	if err := json.Unmarshal(data, &pkgconfig); err != nil {
   222  		return fmt.Errorf("error reading pkgconfig file %q: %v", path, err)
   223  	}
   224  	switch pkgconfig.Granularity {
   225  	case "perblock":
   226  		cgran = coverage.CtrGranularityPerBlock
   227  	case "perfunc":
   228  		cgran = coverage.CtrGranularityPerFunc
   229  	default:
   230  		return fmt.Errorf(`%s: pkgconfig requires perblock/perfunc value`, path)
   231  	}
   232  	return nil
   233  }
   234  
   235  // Block represents the information about a basic block to be recorded in the analysis.
   236  // Note: Our definition of basic block is based on control structures; we don't break
   237  // apart && and ||. We could but it doesn't seem important enough to bother.
   238  type Block struct {
   239  	startByte token.Pos
   240  	endByte   token.Pos
   241  	numStmt   int
   242  }
   243  
   244  // Package holds package-specific state.
   245  type Package struct {
   246  	mdb            *encodemeta.CoverageMetaDataBuilder
   247  	counterLengths []int
   248  }
   249  
   250  // Function holds func-specific state.
   251  type Func struct {
   252  	units      []coverage.CoverableUnit
   253  	counterVar string
   254  }
   255  
   256  // File is a wrapper for the state of a file used in the parser.
   257  // The basic parse tree walker is a method of this type.
   258  type File struct {
   259  	fset    *token.FileSet
   260  	name    string // Name of file.
   261  	astFile *ast.File
   262  	blocks  []Block
   263  	content []byte
   264  	edit    *edit.Buffer
   265  	mdb     *encodemeta.CoverageMetaDataBuilder
   266  	fn      Func
   267  	pkg     *Package
   268  }
   269  
   270  // Range represents a contiguous range of executable code within a basic block.
   271  type Range struct {
   272  	pos token.Pos
   273  	end token.Pos
   274  }
   275  
   276  // codeRanges analyzes a block range and returns the sub-ranges that contain
   277  // executable code, excluding comment-only and blank lines.
   278  // If no executable code is found, it returns a single zero-width range at
   279  // start, so that callers always get at least one range (required by pkgcfg
   280  // mode, which needs a counter unit for every function body).
   281  func (f *File) codeRanges(start, end token.Pos) []Range {
   282  	var (
   283  		startOffset = f.offset(start)
   284  		endOffset   = f.offset(end)
   285  		src         = f.content[startOffset:endOffset]
   286  		origFile    = f.fset.File(start)
   287  	)
   288  
   289  	// Create a temporary File for scanning this block.
   290  	// We use a separate file because we're scanning a slice of the
   291  	// original source, so positions in scanFile are relative to the
   292  	// block start, not the original file.
   293  	scanFile := token.NewFileSet().AddFile("", -1, len(src))
   294  
   295  	var s scanner.Scanner
   296  	s.Init(scanFile, src, nil, 0)
   297  
   298  	// Build ranges in a single pass through the token stream.
   299  	// We track the last line known to contain code (prevEndLine).
   300  	// When the next token appears on a line beyond prevEndLine+1,
   301  	// a gap (comment or blank lines) has been detected: close the
   302  	// current range and start a new one. Using the token's position
   303  	// directly (rather than the line start) ensures counter insertion
   304  	// lands after any closing "*/" on that line.
   305  	var ranges []Range
   306  	var codeStart token.Pos // start of current code range (in origFile)
   307  	prevEndLine := 0        // last line with code; 0 means no code yet
   308  
   309  	for {
   310  		pos, tok, lit := s.Scan()
   311  		if tok == token.EOF {
   312  			break
   313  		}
   314  
   315  		// Skip braces and automatic semicolons: braces are block
   316  		// delimiters, not executable code. The Go spec
   317  		// (https://go.dev/ref/spec#Semicolons) requires the scanner
   318  		// to insert semicolons (with lit == "\n") after }, ), ], etc.
   319  		// These are always on lines already marked by real tokens,
   320  		// except for lone "}" lines. Skipping both prevents a lone
   321  		// "}" from being treated as a separate code range, which
   322  		// would cause counter insertion after return statements.
   323  		if tok == token.LBRACE || tok == token.RBRACE {
   324  			continue
   325  		}
   326  		if tok == token.SEMICOLON && lit == "\n" {
   327  			continue
   328  		}
   329  
   330  		// Use PositionFor with adjusted=false to ignore //line directives.
   331  		startLine := scanFile.PositionFor(pos, false).Line
   332  		endLine := startLine
   333  		if tok == token.STRING {
   334  			// Only string literals can span multiple lines.
   335  			endLine = scanFile.PositionFor(s.End(), false).Line
   336  		}
   337  
   338  		if prevEndLine == 0 {
   339  			// First code token — start the first range.
   340  			codeStart = origFile.Pos(startOffset + scanFile.Offset(pos))
   341  		} else if startLine > prevEndLine+1 {
   342  			// Gap detected — close previous range, start new one.
   343  			codeEnd := origFile.Pos(startOffset + scanFile.Offset(scanFile.LineStart(prevEndLine+1)))
   344  			ranges = append(ranges, Range{pos: codeStart, end: codeEnd})
   345  			codeStart = origFile.Pos(startOffset + scanFile.Offset(pos))
   346  		}
   347  
   348  		if endLine > prevEndLine {
   349  			prevEndLine = endLine
   350  		}
   351  	}
   352  
   353  	// Close any open code range at the end.
   354  	if prevEndLine > 0 {
   355  		if prevEndLine < scanFile.LineCount() {
   356  			// There are non-code lines after the last code line
   357  			// (e.g., a lone "}"). Close at the next line's start.
   358  			codeEnd := origFile.Pos(startOffset + scanFile.Offset(scanFile.LineStart(prevEndLine+1)))
   359  			ranges = append(ranges, Range{pos: codeStart, end: codeEnd})
   360  		} else {
   361  			ranges = append(ranges, Range{pos: codeStart, end: end})
   362  		}
   363  	}
   364  
   365  	// If no code was found, return a zero-width range so that callers
   366  	// still get a counter (needed for pkgcfg function registration)
   367  	// but the range doesn't visually cover any source lines.
   368  	if len(ranges) == 0 {
   369  		return []Range{{pos: start, end: start}}
   370  	}
   371  
   372  	return ranges
   373  }
   374  
   375  // insideStatement reports whether pos falls strictly inside
   376  // (not at the start of) any statement in stmts.
   377  func insideStatement(pos token.Pos, stmts []ast.Stmt) bool {
   378  	// Binary search for the first statement starting at or after pos.
   379  	i, _ := slices.BinarySearchFunc(stmts, pos, func(s ast.Stmt, p token.Pos) int {
   380  		return cmp.Compare(s.Pos(), p)
   381  	})
   382  	// Check if pos falls inside the preceding statement.
   383  	return i > 0 && pos < stmts[i-1].End()
   384  }
   385  
   386  // mergeRangesWithinStatements merges consecutive ranges when a later range's
   387  // start position falls strictly inside a statement. This prevents counter
   388  // insertion inside multi-line statements such as const (...) blocks.
   389  type rangeWithStatements struct {
   390  	Range
   391  	numStmt int
   392  }
   393  
   394  func mergeRangesWithinStatements(ranges []Range, stmts []ast.Stmt) []rangeWithStatements {
   395  	merged := make([]rangeWithStatements, 0, len(ranges))
   396  	for _, r := range ranges {
   397  		// Statements are sorted by source position, so use binary search to
   398  		// find the statements whose positions fall within this range.
   399  		first, _ := slices.BinarySearchFunc(stmts, r.pos, func(s ast.Stmt, p token.Pos) int {
   400  			return cmp.Compare(s.Pos(), p)
   401  		})
   402  		last, _ := slices.BinarySearchFunc(stmts, r.end, func(s ast.Stmt, p token.Pos) int {
   403  			return cmp.Compare(s.Pos(), p)
   404  		})
   405  		numStmt := last - first
   406  
   407  		if len(merged) > 0 && insideStatement(r.pos, stmts) {
   408  			// Extend the previous range to cover this one.
   409  			last := &merged[len(merged)-1]
   410  			last.end = r.end
   411  			last.numStmt += numStmt
   412  		} else {
   413  			merged = append(merged, rangeWithStatements{Range: r, numStmt: numStmt})
   414  		}
   415  	}
   416  	return merged
   417  }
   418  
   419  // findText finds text in the original source, starting at pos.
   420  // It correctly skips over comments and assumes it need not
   421  // handle quoted strings.
   422  // It returns a byte offset within f.src.
   423  func (f *File) findText(pos token.Pos, text string) int {
   424  	b := []byte(text)
   425  	start := f.offset(pos)
   426  	i := start
   427  	s := f.content
   428  	for i < len(s) {
   429  		if bytes.HasPrefix(s[i:], b) {
   430  			return i
   431  		}
   432  		if i+2 <= len(s) && s[i] == '/' && s[i+1] == '/' {
   433  			for i < len(s) && s[i] != '\n' {
   434  				i++
   435  			}
   436  			continue
   437  		}
   438  		if i+2 <= len(s) && s[i] == '/' && s[i+1] == '*' {
   439  			for i += 2; ; i++ {
   440  				if i+2 > len(s) {
   441  					return 0
   442  				}
   443  				if s[i] == '*' && s[i+1] == '/' {
   444  					i += 2
   445  					break
   446  				}
   447  			}
   448  			continue
   449  		}
   450  		i++
   451  	}
   452  	return -1
   453  }
   454  
   455  // Visit implements the ast.Visitor interface.
   456  func (f *File) Visit(node ast.Node) ast.Visitor {
   457  	switch n := node.(type) {
   458  	case *ast.BlockStmt:
   459  		// If it's a switch or select, the body is a list of case clauses; don't tag the block itself.
   460  		if len(n.List) > 0 {
   461  			switch n.List[0].(type) {
   462  			case *ast.CaseClause: // switch
   463  				for _, n := range n.List {
   464  					clause := n.(*ast.CaseClause)
   465  					f.addCounters(clause.Colon+1, clause.Colon+1, clause.End(), clause.Body, false)
   466  				}
   467  				return f
   468  			case *ast.CommClause: // select
   469  				for _, n := range n.List {
   470  					clause := n.(*ast.CommClause)
   471  					f.addCounters(clause.Colon+1, clause.Colon+1, clause.End(), clause.Body, false)
   472  				}
   473  				return f
   474  			}
   475  		}
   476  		f.addCounters(n.Lbrace, n.Lbrace+1, n.Rbrace+1, n.List, true) // +1 to step past closing brace.
   477  	case *ast.IfStmt:
   478  		if n.Init != nil {
   479  			ast.Walk(f, n.Init)
   480  		}
   481  		ast.Walk(f, n.Cond)
   482  		ast.Walk(f, n.Body)
   483  		if n.Else == nil {
   484  			return nil
   485  		}
   486  		// The elses are special, because if we have
   487  		//	if x {
   488  		//	} else if y {
   489  		//	}
   490  		// we want to cover the "if y". To do this, we need a place to drop the counter,
   491  		// so we add a hidden block:
   492  		//	if x {
   493  		//	} else {
   494  		//		if y {
   495  		//		}
   496  		//	}
   497  		elseOffset := f.findText(n.Body.End(), "else")
   498  		if elseOffset < 0 {
   499  			panic("lost else")
   500  		}
   501  		f.edit.Insert(elseOffset+4, "{")
   502  		f.edit.Insert(f.offset(n.Else.End()), "}")
   503  
   504  		// We just created a block, now walk it.
   505  		// Adjust the position of the new block to start after
   506  		// the "else". That will cause it to follow the "{"
   507  		// we inserted above.
   508  		pos := f.fset.File(n.Body.End()).Pos(elseOffset + 4)
   509  		switch stmt := n.Else.(type) {
   510  		case *ast.IfStmt:
   511  			block := &ast.BlockStmt{
   512  				Lbrace: pos,
   513  				List:   []ast.Stmt{stmt},
   514  				Rbrace: stmt.End(),
   515  			}
   516  			n.Else = block
   517  		case *ast.BlockStmt:
   518  			stmt.Lbrace = pos
   519  		default:
   520  			panic("unexpected node type in if")
   521  		}
   522  		ast.Walk(f, n.Else)
   523  		return nil
   524  	case *ast.SelectStmt:
   525  		// Don't annotate an empty select - creates a syntax error.
   526  		if n.Body == nil || len(n.Body.List) == 0 {
   527  			return nil
   528  		}
   529  	case *ast.SwitchStmt:
   530  		// Don't annotate an empty switch - creates a syntax error.
   531  		if n.Body == nil || len(n.Body.List) == 0 {
   532  			if n.Init != nil {
   533  				ast.Walk(f, n.Init)
   534  			}
   535  			if n.Tag != nil {
   536  				ast.Walk(f, n.Tag)
   537  			}
   538  			return nil
   539  		}
   540  	case *ast.TypeSwitchStmt:
   541  		// Don't annotate an empty type switch - creates a syntax error.
   542  		if n.Body == nil || len(n.Body.List) == 0 {
   543  			if n.Init != nil {
   544  				ast.Walk(f, n.Init)
   545  			}
   546  			ast.Walk(f, n.Assign)
   547  			return nil
   548  		}
   549  	case *ast.FuncDecl:
   550  		// Don't annotate functions with blank names - they cannot be executed.
   551  		// Similarly for bodyless funcs.
   552  		if n.Name.Name == "_" || n.Body == nil {
   553  			return nil
   554  		}
   555  		fname := n.Name.Name
   556  		// Skip AddUint32 and StoreUint32 if we're instrumenting
   557  		// sync/atomic itself in atomic mode (out of an abundance of
   558  		// caution), since as part of the instrumentation process we
   559  		// add calls to AddUint32/StoreUint32, and we don't want to
   560  		// somehow create an infinite loop.
   561  		//
   562  		// Note that in the current implementation (Go 1.20) both
   563  		// routines are assembly stubs that forward calls to the
   564  		// internal/runtime/atomic equivalents, hence the infinite
   565  		// loop scenario is purely theoretical (maybe if in some
   566  		// future implementation one of these functions might be
   567  		// written in Go). See #57445 for more details.
   568  		if atomicOnAtomic() && (fname == "AddUint32" || fname == "StoreUint32") {
   569  			return nil
   570  		}
   571  		// Determine proper function or method name.
   572  		if r := n.Recv; r != nil && len(r.List) == 1 {
   573  			t := r.List[0].Type
   574  			star := ""
   575  			if p, _ := t.(*ast.StarExpr); p != nil {
   576  				t = p.X
   577  				star = "*"
   578  			}
   579  			if p, _ := t.(*ast.Ident); p != nil {
   580  				fname = star + p.Name + "." + fname
   581  			}
   582  		}
   583  		walkBody := true
   584  		if *pkgcfg != "" {
   585  			f.preFunc(n, fname)
   586  			if pkgconfig.Granularity == "perfunc" {
   587  				walkBody = false
   588  			}
   589  		}
   590  		if walkBody {
   591  			ast.Walk(f, n.Body)
   592  		}
   593  		if *pkgcfg != "" {
   594  			flit := false
   595  			f.postFunc(n, fname, flit, n.Body)
   596  		}
   597  		return nil
   598  	case *ast.FuncLit:
   599  		// For function literals enclosed in functions, just glom the
   600  		// code for the literal in with the enclosing function (for now).
   601  		if f.fn.counterVar != "" {
   602  			return f
   603  		}
   604  
   605  		// Hack: function literals aren't named in the go/ast representation,
   606  		// and we don't know what name the compiler will choose. For now,
   607  		// just make up a descriptive name.
   608  		pos := n.Pos()
   609  		p := f.fset.File(pos).Position(pos)
   610  		fname := fmt.Sprintf("func.L%d.C%d", p.Line, p.Column)
   611  		if *pkgcfg != "" {
   612  			f.preFunc(n, fname)
   613  		}
   614  		if pkgconfig.Granularity != "perfunc" {
   615  			ast.Walk(f, n.Body)
   616  		}
   617  		if *pkgcfg != "" {
   618  			flit := true
   619  			f.postFunc(n, fname, flit, n.Body)
   620  		}
   621  		return nil
   622  	}
   623  	return f
   624  }
   625  
   626  func mkCounterVarName(idx int) string {
   627  	return fmt.Sprintf("%s_%d", *varVar, idx)
   628  }
   629  
   630  func mkPackageIdVar() string {
   631  	return *varVar + "P"
   632  }
   633  
   634  func mkMetaVar() string {
   635  	return *varVar + "M"
   636  }
   637  
   638  func mkPackageIdExpression() string {
   639  	ppath := pkgconfig.PkgPath
   640  	if hcid := coverage.HardCodedPkgID(ppath); hcid != -1 {
   641  		return fmt.Sprintf("uint32(%d)", uint32(hcid))
   642  	}
   643  	return mkPackageIdVar()
   644  }
   645  
   646  func (f *File) preFunc(fn ast.Node, fname string) {
   647  	f.fn.units = f.fn.units[:0]
   648  
   649  	// create a new counter variable for this function.
   650  	cv := mkCounterVarName(len(f.pkg.counterLengths))
   651  	f.fn.counterVar = cv
   652  }
   653  
   654  func (f *File) postFunc(fn ast.Node, funcname string, flit bool, body *ast.BlockStmt) {
   655  
   656  	// Tack on single counter write if we are in "perfunc" mode.
   657  	singleCtr := ""
   658  	if pkgconfig.Granularity == "perfunc" {
   659  		singleCtr = "; " + f.newCounter(fn.Pos(), fn.Pos(), 1)
   660  	}
   661  
   662  	// record the length of the counter var required.
   663  	nc := len(f.fn.units) + coverage.FirstCtrOffset
   664  	f.pkg.counterLengths = append(f.pkg.counterLengths, nc)
   665  
   666  	// FIXME: for windows, do we want "\" and not "/"? Need to test here.
   667  	// Currently filename is formed as packagepath + "/" + basename.
   668  	fnpos := f.fset.Position(fn.Pos())
   669  	ppath := pkgconfig.PkgPath
   670  	filename := ppath + "/" + filepath.Base(fnpos.Filename)
   671  
   672  	// The convention for cmd/cover is that if the go command that
   673  	// kicks off coverage specifies a local import path (e.g. "go test
   674  	// -cover ./thispackage"), the tool will capture full pathnames
   675  	// for source files instead of relative paths, which tend to work
   676  	// more smoothly for "go tool cover -html". See also issue #56433
   677  	// for more details.
   678  	if pkgconfig.Local {
   679  		filename = f.name
   680  	}
   681  
   682  	// Hand off function to meta-data builder.
   683  	fd := coverage.FuncDesc{
   684  		Funcname: funcname,
   685  		Srcfile:  filename,
   686  		Units:    f.fn.units,
   687  		Lit:      flit,
   688  	}
   689  	funcId := f.mdb.AddFunc(fd)
   690  
   691  	hookWrite := func(cv string, which int, val string) string {
   692  		return fmt.Sprintf("%s[%d] = %s", cv, which, val)
   693  	}
   694  	if *mode == "atomic" {
   695  		hookWrite = func(cv string, which int, val string) string {
   696  			return fmt.Sprintf("%sStoreUint32(&%s[%d], %s)",
   697  				atomicPackagePrefix(), cv, which, val)
   698  		}
   699  	}
   700  
   701  	// Generate the registration hook sequence for the function. This
   702  	// sequence looks like
   703  	//
   704  	//   counterVar[0] = <num_units>
   705  	//   counterVar[1] = pkgId
   706  	//   counterVar[2] = fnId
   707  	//
   708  	cv := f.fn.counterVar
   709  	regHook := hookWrite(cv, 0, strconv.Itoa(len(f.fn.units))) + " ; " +
   710  		hookWrite(cv, 1, mkPackageIdExpression()) + " ; " +
   711  		hookWrite(cv, 2, strconv.Itoa(int(funcId))) + singleCtr
   712  
   713  	// Insert the registration sequence into the function. We want this sequence to
   714  	// appear before any counter updates, so use a hack to ensure that this edit
   715  	// applies before the edit corresponding to the prolog counter update.
   716  
   717  	boff := f.offset(body.Pos())
   718  	ipos := f.fset.File(body.Pos()).Pos(boff)
   719  	ip := f.offset(ipos)
   720  	f.edit.Replace(ip, ip+1, string(f.content[ipos-1])+regHook+" ; ")
   721  
   722  	f.fn.counterVar = ""
   723  }
   724  
   725  func annotate(names []string) {
   726  	var p *Package
   727  	if *pkgcfg != "" {
   728  		pp := pkgconfig.PkgPath
   729  		pn := pkgconfig.PkgName
   730  		mp := pkgconfig.ModulePath
   731  		mdb, err := encodemeta.NewCoverageMetaDataBuilder(pp, pn, mp)
   732  		if err != nil {
   733  			log.Fatalf("creating coverage meta-data builder: %v\n", err)
   734  		}
   735  		p = &Package{
   736  			mdb: mdb,
   737  		}
   738  	}
   739  	// TODO: process files in parallel here if it matters.
   740  	for k, name := range names {
   741  		if strings.ContainsAny(name, "\r\n") {
   742  			// annotateFile uses '//line' directives, which don't permit newlines.
   743  			log.Fatalf("cover: input path contains newline character: %q", name)
   744  		}
   745  
   746  		fd := os.Stdout
   747  		isStdout := true
   748  		if *pkgcfg != "" {
   749  			var err error
   750  			fd, err = os.Create(outputfiles[k])
   751  			if err != nil {
   752  				log.Fatalf("cover: %s", err)
   753  			}
   754  			isStdout = false
   755  		} else if *output != "" {
   756  			var err error
   757  			fd, err = os.Create(*output)
   758  			if err != nil {
   759  				log.Fatalf("cover: %s", err)
   760  			}
   761  			isStdout = false
   762  		}
   763  		p.annotateFile(name, fd)
   764  		if !isStdout {
   765  			if err := fd.Close(); err != nil {
   766  				log.Fatalf("cover: %s", err)
   767  			}
   768  		}
   769  	}
   770  
   771  	if *pkgcfg != "" {
   772  		fd, err := os.Create(covervarsoutfile)
   773  		if err != nil {
   774  			log.Fatalf("cover: %s", err)
   775  		}
   776  		p.emitMetaData(fd)
   777  		if err := fd.Close(); err != nil {
   778  			log.Fatalf("cover: %s", err)
   779  		}
   780  	}
   781  }
   782  
   783  func (p *Package) annotateFile(name string, fd io.Writer) {
   784  	fset := token.NewFileSet()
   785  	content, err := os.ReadFile(name)
   786  	if err != nil {
   787  		log.Fatalf("cover: %s: %s", name, err)
   788  	}
   789  	parsedFile, err := parser.ParseFile(fset, name, content, parser.ParseComments|parser.SkipObjectResolution)
   790  	if err != nil {
   791  		log.Fatalf("cover: %s: %s", name, err)
   792  	}
   793  
   794  	file := &File{
   795  		fset:    fset,
   796  		name:    name,
   797  		content: content,
   798  		edit:    edit.NewBuffer(content),
   799  		astFile: parsedFile,
   800  	}
   801  	if p != nil {
   802  		file.mdb = p.mdb
   803  		file.pkg = p
   804  	}
   805  
   806  	if *mode == "atomic" {
   807  		// Add import of sync/atomic immediately after package clause.
   808  		// We do this even if there is an existing import, because the
   809  		// existing import may be shadowed at any given place we want
   810  		// to refer to it, and our name (_cover_atomic_) is less likely to
   811  		// be shadowed. The one exception is if we're visiting the
   812  		// sync/atomic package itself, in which case we can refer to
   813  		// functions directly without an import prefix. See also #57445.
   814  		if pkgconfig.PkgPath != "sync/atomic" {
   815  			file.edit.Insert(file.offset(file.astFile.Name.End()),
   816  				fmt.Sprintf("; import %s %q", atomicPackageName, atomicPackagePath))
   817  		}
   818  	}
   819  	if pkgconfig.PkgName == "main" {
   820  		file.edit.Insert(file.offset(file.astFile.Name.End()),
   821  			"; import _ \"runtime/coverage\"")
   822  	}
   823  
   824  	if counterStmt != nil {
   825  		ast.Walk(file, file.astFile)
   826  	}
   827  	newContent := file.edit.Bytes()
   828  
   829  	if strings.ContainsAny(name, "\r\n") {
   830  		// This should have been checked by the caller already, but we double check
   831  		// here just to be sure we haven't missed a caller somewhere.
   832  		panic(fmt.Sprintf("annotateFile: name contains unexpected newline character: %q", name))
   833  	}
   834  	fmt.Fprintf(fd, "//line %s:1:1\n", name)
   835  	fd.Write(newContent)
   836  
   837  	// After printing the source tree, add some declarations for the
   838  	// counters etc. We could do this by adding to the tree, but it's
   839  	// easier just to print the text.
   840  	file.addVariables(fd)
   841  
   842  	// Emit a reference to the atomic package to avoid
   843  	// import and not used error when there's no code in a file.
   844  	if *mode == "atomic" {
   845  		fmt.Fprintf(fd, "\nvar _ = %sLoadUint32\n", atomicPackagePrefix())
   846  	}
   847  }
   848  
   849  // setCounterStmt returns the expression: __count[23] = 1.
   850  func setCounterStmt(f *File, counter string) string {
   851  	return fmt.Sprintf("%s = 1", counter)
   852  }
   853  
   854  // incCounterStmt returns the expression: __count[23]++.
   855  func incCounterStmt(f *File, counter string) string {
   856  	return fmt.Sprintf("%s++", counter)
   857  }
   858  
   859  // atomicCounterStmt returns the expression: atomic.AddUint32(&__count[23], 1)
   860  func atomicCounterStmt(f *File, counter string) string {
   861  	return fmt.Sprintf("%sAddUint32(&%s, 1)", atomicPackagePrefix(), counter)
   862  }
   863  
   864  // newCounter creates a new counter expression of the appropriate form.
   865  func (f *File) newCounter(start, end token.Pos, numStmt int) string {
   866  	var stmt string
   867  	if *pkgcfg != "" {
   868  		slot := len(f.fn.units) + coverage.FirstCtrOffset
   869  		if f.fn.counterVar == "" {
   870  			panic("internal error: counter var unset")
   871  		}
   872  		stmt = counterStmt(f, fmt.Sprintf("%s[%d]", f.fn.counterVar, slot))
   873  		// Physical positions, ignoring //line directives.
   874  		stpos := f.position(start)
   875  		enpos := f.position(end)
   876  		stpos, enpos = dedup(stpos, enpos)
   877  		unit := coverage.CoverableUnit{
   878  			StLine:  uint32(stpos.Line),
   879  			StCol:   uint32(stpos.Column),
   880  			EnLine:  uint32(enpos.Line),
   881  			EnCol:   uint32(enpos.Column),
   882  			NxStmts: uint32(numStmt),
   883  		}
   884  		f.fn.units = append(f.fn.units, unit)
   885  	} else {
   886  		stmt = counterStmt(f, fmt.Sprintf("%s.Count[%d]", *varVar,
   887  			len(f.blocks)))
   888  		f.blocks = append(f.blocks, Block{start, end, numStmt})
   889  	}
   890  	return stmt
   891  }
   892  
   893  // addCounters takes a list of statements and adds counters to the beginning of
   894  // each basic block at the top level of that list. For instance, given
   895  //
   896  //	S1
   897  //	if cond {
   898  //		S2
   899  //	}
   900  //	S3
   901  //
   902  // counters will be added before S1 and before S3. The block containing S2
   903  // will be visited in a separate call.
   904  // TODO: Nested simple blocks get unnecessary (but correct) counters
   905  func (f *File) addCounters(pos, insertPos, blockEnd token.Pos, list []ast.Stmt, extendToClosingBrace bool) {
   906  	// Special case: make sure we add a counter to an empty block. Can't do this below
   907  	// or we will add a counter to an empty statement list after, say, a return statement.
   908  	if len(list) == 0 {
   909  		r := f.codeRanges(insertPos, blockEnd)[0]
   910  		f.edit.Insert(f.offset(r.pos), f.newCounter(r.pos, r.end, 0)+";")
   911  		return
   912  	}
   913  	// Make a copy of the list, as we may mutate it and should leave the
   914  	// existing list intact.
   915  	list = append([]ast.Stmt(nil), list...)
   916  	// We have a block (statement list), but it may have several basic blocks due to the
   917  	// appearance of statements that affect the flow of control.
   918  	for {
   919  		// Find first statement that affects flow of control (break, continue, if, etc.).
   920  		// It will be the last statement of this basic block.
   921  		var last int
   922  		end := blockEnd
   923  		for last = 0; last < len(list); last++ {
   924  			stmt := list[last]
   925  			end = f.statementBoundary(stmt)
   926  			if f.endsBasicSourceBlock(stmt) {
   927  				// If it is a labeled statement, we need to place a counter between
   928  				// the label and its statement because it may be the target of a goto
   929  				// and thus start a basic block. That is, given
   930  				//	foo: stmt
   931  				// we need to create
   932  				//	foo: ; stmt
   933  				// and mark the label as a block-terminating statement.
   934  				// The result will then be
   935  				//	foo: COUNTER[n]++; stmt
   936  				// However, we can't do this if the labeled statement is already
   937  				// a control statement, such as a labeled for.
   938  				if label, isLabel := stmt.(*ast.LabeledStmt); isLabel && !f.isControl(label.Stmt) {
   939  					newLabel := *label
   940  					newLabel.Stmt = &ast.EmptyStmt{
   941  						Semicolon: label.Stmt.Pos(),
   942  						Implicit:  true,
   943  					}
   944  					end = label.Pos() // Previous block ends before the label.
   945  					list[last] = &newLabel
   946  					// Open a gap and drop in the old statement, now without a label.
   947  					list = append(list, nil)
   948  					copy(list[last+1:], list[last:])
   949  					list[last+1] = label.Stmt
   950  				}
   951  				last++
   952  				extendToClosingBrace = false // Block is broken up now.
   953  				break
   954  			}
   955  		}
   956  		if extendToClosingBrace {
   957  			end = blockEnd
   958  		}
   959  		if pos != end { // Can have no source to cover if e.g. blocks abut.
   960  			// Create counters only for executable code ranges.
   961  			// Merge back ranges that fall inside a statement to avoid
   962  			// inserting counters inside multi-line constructs (e.g. const blocks).
   963  			for i, r := range mergeRangesWithinStatements(f.codeRanges(pos, end), list[:last]) {
   964  				insertOffset := f.offset(r.pos)
   965  				if i == 0 {
   966  					insertOffset = f.offset(insertPos)
   967  				}
   968  				f.edit.Insert(insertOffset, f.newCounter(r.pos, r.end, r.numStmt)+";")
   969  			}
   970  		}
   971  		list = list[last:]
   972  		if len(list) == 0 {
   973  			break
   974  		}
   975  		pos = list[0].Pos()
   976  		insertPos = pos
   977  	}
   978  }
   979  
   980  // hasFuncLiteral reports the existence and position of the first func literal
   981  // in the node, if any. If a func literal appears, it usually marks the termination
   982  // of a basic block because the function body is itself a block.
   983  // Therefore we draw a line at the start of the body of the first function literal we find.
   984  // TODO: what if there's more than one? Probably doesn't matter much.
   985  func hasFuncLiteral(n ast.Node) (bool, token.Pos) {
   986  	if n == nil {
   987  		return false, 0
   988  	}
   989  	var literal funcLitFinder
   990  	ast.Walk(&literal, n)
   991  	return literal.found(), token.Pos(literal)
   992  }
   993  
   994  // statementBoundary finds the location in s that terminates the current basic
   995  // block in the source.
   996  func (f *File) statementBoundary(s ast.Stmt) token.Pos {
   997  	// Control flow statements are easy.
   998  	switch s := s.(type) {
   999  	case *ast.BlockStmt:
  1000  		// Treat blocks like basic blocks to avoid overlapping counters.
  1001  		return s.Lbrace
  1002  	case *ast.IfStmt:
  1003  		found, pos := hasFuncLiteral(s.Init)
  1004  		if found {
  1005  			return pos
  1006  		}
  1007  		found, pos = hasFuncLiteral(s.Cond)
  1008  		if found {
  1009  			return pos
  1010  		}
  1011  		return s.Body.Lbrace
  1012  	case *ast.ForStmt:
  1013  		found, pos := hasFuncLiteral(s.Init)
  1014  		if found {
  1015  			return pos
  1016  		}
  1017  		found, pos = hasFuncLiteral(s.Cond)
  1018  		if found {
  1019  			return pos
  1020  		}
  1021  		found, pos = hasFuncLiteral(s.Post)
  1022  		if found {
  1023  			return pos
  1024  		}
  1025  		return s.Body.Lbrace
  1026  	case *ast.LabeledStmt:
  1027  		return f.statementBoundary(s.Stmt)
  1028  	case *ast.RangeStmt:
  1029  		found, pos := hasFuncLiteral(s.X)
  1030  		if found {
  1031  			return pos
  1032  		}
  1033  		return s.Body.Lbrace
  1034  	case *ast.SwitchStmt:
  1035  		found, pos := hasFuncLiteral(s.Init)
  1036  		if found {
  1037  			return pos
  1038  		}
  1039  		found, pos = hasFuncLiteral(s.Tag)
  1040  		if found {
  1041  			return pos
  1042  		}
  1043  		return s.Body.Lbrace
  1044  	case *ast.SelectStmt:
  1045  		return s.Body.Lbrace
  1046  	case *ast.TypeSwitchStmt:
  1047  		found, pos := hasFuncLiteral(s.Init)
  1048  		if found {
  1049  			return pos
  1050  		}
  1051  		return s.Body.Lbrace
  1052  	}
  1053  	// If not a control flow statement, it is a declaration, expression, call, etc. and it may have a function literal.
  1054  	// If it does, that's tricky because we want to exclude the body of the function from this block.
  1055  	// Draw a line at the start of the body of the first function literal we find.
  1056  	// TODO: what if there's more than one? Probably doesn't matter much.
  1057  	found, pos := hasFuncLiteral(s)
  1058  	if found {
  1059  		return pos
  1060  	}
  1061  	return s.End()
  1062  }
  1063  
  1064  // endsBasicSourceBlock reports whether s changes the flow of control: break, if, etc.,
  1065  // or if it's just problematic, for instance contains a function literal, which will complicate
  1066  // accounting due to the block-within-an expression.
  1067  func (f *File) endsBasicSourceBlock(s ast.Stmt) bool {
  1068  	switch s := s.(type) {
  1069  	case *ast.BlockStmt:
  1070  		// Treat blocks like basic blocks to avoid overlapping counters.
  1071  		return true
  1072  	case *ast.BranchStmt:
  1073  		return true
  1074  	case *ast.ForStmt:
  1075  		return true
  1076  	case *ast.IfStmt:
  1077  		return true
  1078  	case *ast.LabeledStmt:
  1079  		return true // A goto may branch here, starting a new basic block.
  1080  	case *ast.RangeStmt:
  1081  		return true
  1082  	case *ast.SwitchStmt:
  1083  		return true
  1084  	case *ast.SelectStmt:
  1085  		return true
  1086  	case *ast.TypeSwitchStmt:
  1087  		return true
  1088  	case *ast.ExprStmt:
  1089  		// Calls to panic change the flow.
  1090  		// We really should verify that "panic" is the predefined function,
  1091  		// but without type checking we can't and the likelihood of it being
  1092  		// an actual problem is vanishingly small.
  1093  		if call, ok := s.X.(*ast.CallExpr); ok {
  1094  			if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "panic" && len(call.Args) == 1 {
  1095  				return true
  1096  			}
  1097  		}
  1098  	}
  1099  	found, _ := hasFuncLiteral(s)
  1100  	return found
  1101  }
  1102  
  1103  // isControl reports whether s is a control statement that, if labeled, cannot be
  1104  // separated from its label.
  1105  func (f *File) isControl(s ast.Stmt) bool {
  1106  	switch s.(type) {
  1107  	case *ast.ForStmt, *ast.RangeStmt, *ast.SwitchStmt, *ast.SelectStmt, *ast.TypeSwitchStmt:
  1108  		return true
  1109  	}
  1110  	return false
  1111  }
  1112  
  1113  // funcLitFinder implements the ast.Visitor pattern to find the location of any
  1114  // function literal in a subtree.
  1115  type funcLitFinder token.Pos
  1116  
  1117  func (f *funcLitFinder) Visit(node ast.Node) (w ast.Visitor) {
  1118  	if f.found() {
  1119  		return nil // Prune search.
  1120  	}
  1121  	switch n := node.(type) {
  1122  	case *ast.FuncLit:
  1123  		*f = funcLitFinder(n.Body.Lbrace)
  1124  		return nil // Prune search.
  1125  	}
  1126  	return f
  1127  }
  1128  
  1129  func (f *funcLitFinder) found() bool {
  1130  	return token.Pos(*f) != token.NoPos
  1131  }
  1132  
  1133  // Sort interface for []block1; used for self-check in addVariables.
  1134  
  1135  type block1 struct {
  1136  	Block
  1137  	index int
  1138  }
  1139  
  1140  // position returns the Position for pos, ignoring //line directives.
  1141  func (f *File) position(pos token.Pos) token.Position {
  1142  	return f.fset.PositionFor(pos, false)
  1143  }
  1144  
  1145  // offset translates a token position into a 0-indexed byte offset.
  1146  func (f *File) offset(pos token.Pos) int {
  1147  	return f.position(pos).Offset
  1148  }
  1149  
  1150  // addVariables adds to the end of the file the declarations to set up the counter and position variables.
  1151  func (f *File) addVariables(w io.Writer) {
  1152  	if *pkgcfg != "" {
  1153  		return
  1154  	}
  1155  	// Self-check: Verify that the instrumented basic blocks are disjoint.
  1156  	t := make([]block1, len(f.blocks))
  1157  	for i := range f.blocks {
  1158  		t[i].Block = f.blocks[i]
  1159  		t[i].index = i
  1160  	}
  1161  	slices.SortFunc(t, func(a, b block1) int {
  1162  		return cmp.Compare(a.startByte, b.startByte)
  1163  	})
  1164  	for i := 1; i < len(t); i++ {
  1165  		if t[i-1].endByte > t[i].startByte {
  1166  			fmt.Fprintf(os.Stderr, "cover: internal error: block %d overlaps block %d\n", t[i-1].index, t[i].index)
  1167  			// Note: error message is in byte positions, not token positions.
  1168  			fmt.Fprintf(os.Stderr, "\t%s:#%d,#%d %s:#%d,#%d\n",
  1169  				f.name, f.offset(t[i-1].startByte), f.offset(t[i-1].endByte),
  1170  				f.name, f.offset(t[i].startByte), f.offset(t[i].endByte))
  1171  		}
  1172  	}
  1173  
  1174  	// Declare the coverage struct as a package-level variable.
  1175  	fmt.Fprintf(w, "\nvar %s = struct {\n", *varVar)
  1176  	fmt.Fprintf(w, "\tCount     [%d]uint32\n", len(f.blocks))
  1177  	fmt.Fprintf(w, "\tPos       [3 * %d]uint32\n", len(f.blocks))
  1178  	fmt.Fprintf(w, "\tNumStmt   [%d]uint16\n", len(f.blocks))
  1179  	fmt.Fprintf(w, "} {\n")
  1180  
  1181  	// Initialize the position array field.
  1182  	fmt.Fprintf(w, "\tPos: [3 * %d]uint32{\n", len(f.blocks))
  1183  
  1184  	// A nice long list of positions. Each position is encoded as follows to reduce size:
  1185  	// - 32-bit starting line number
  1186  	// - 32-bit ending line number
  1187  	// - (16 bit ending column number << 16) | (16-bit starting column number).
  1188  	for i, block := range f.blocks {
  1189  		// Physical positions, ignoring //line directives.
  1190  		start := f.position(block.startByte)
  1191  		end := f.position(block.endByte)
  1192  
  1193  		start, end = dedup(start, end)
  1194  
  1195  		fmt.Fprintf(w, "\t\t%d, %d, %#x, // [%d]\n", start.Line, end.Line, (end.Column&0xFFFF)<<16|(start.Column&0xFFFF), i)
  1196  	}
  1197  
  1198  	// Close the position array.
  1199  	fmt.Fprintf(w, "\t},\n")
  1200  
  1201  	// Initialize the position array field.
  1202  	fmt.Fprintf(w, "\tNumStmt: [%d]uint16{\n", len(f.blocks))
  1203  
  1204  	// A nice long list of statements-per-block, so we can give a conventional
  1205  	// valuation of "percent covered". To save space, it's a 16-bit number, so we
  1206  	// clamp it if it overflows - won't matter in practice.
  1207  	for i, block := range f.blocks {
  1208  		n := block.numStmt
  1209  		if n > 1<<16-1 {
  1210  			n = 1<<16 - 1
  1211  		}
  1212  		fmt.Fprintf(w, "\t\t%d, // %d\n", n, i)
  1213  	}
  1214  
  1215  	// Close the statements-per-block array.
  1216  	fmt.Fprintf(w, "\t},\n")
  1217  
  1218  	// Close the struct initialization.
  1219  	fmt.Fprintf(w, "}\n")
  1220  }
  1221  
  1222  // It is possible for positions to repeat when there is a line
  1223  // directive that does not specify column information and the input
  1224  // has not been passed through gofmt.
  1225  // See issues #27530 and #30746.
  1226  // Tests are TestHtmlUnformatted and TestLineDup.
  1227  // We use a map to avoid duplicates.
  1228  
  1229  // pos2 is a pair of token.Position values, used as a map key type.
  1230  type pos2 struct {
  1231  	p1, p2 token.Position
  1232  }
  1233  
  1234  // seenPos2 tracks whether we have seen a token.Position pair.
  1235  var seenPos2 = make(map[pos2]bool)
  1236  
  1237  // dedup takes a token.Position pair and returns a pair that does not
  1238  // duplicate any existing pair. The returned pair will have the Offset
  1239  // fields cleared.
  1240  func dedup(p1, p2 token.Position) (r1, r2 token.Position) {
  1241  	key := pos2{
  1242  		p1: p1,
  1243  		p2: p2,
  1244  	}
  1245  
  1246  	// We want to ignore the Offset fields in the map,
  1247  	// since cover uses only file/line/column.
  1248  	key.p1.Offset = 0
  1249  	key.p2.Offset = 0
  1250  
  1251  	for seenPos2[key] {
  1252  		key.p2.Column++
  1253  	}
  1254  	seenPos2[key] = true
  1255  
  1256  	return key.p1, key.p2
  1257  }
  1258  
  1259  func (p *Package) emitMetaData(w io.Writer) {
  1260  	if *pkgcfg == "" {
  1261  		return
  1262  	}
  1263  
  1264  	// If the "EmitMetaFile" path has been set, invoke a helper
  1265  	// that will write out a pre-cooked meta-data file for this package
  1266  	// to the specified location, in effect simulating the execution
  1267  	// of a test binary that doesn't do any testing to speak of.
  1268  	if pkgconfig.EmitMetaFile != "" {
  1269  		p.emitMetaFile(pkgconfig.EmitMetaFile)
  1270  	}
  1271  
  1272  	// Something went wrong if regonly/testmain mode is in effect and
  1273  	// we have instrumented functions.
  1274  	if counterStmt == nil && len(p.counterLengths) != 0 {
  1275  		panic("internal error: seen functions with regonly/testmain")
  1276  	}
  1277  
  1278  	// Emit package name.
  1279  	fmt.Fprintf(w, "\npackage %s\n\n", pkgconfig.PkgName)
  1280  
  1281  	// Emit package ID var.
  1282  	fmt.Fprintf(w, "\nvar %sP uint32\n", *varVar)
  1283  
  1284  	// Emit all of the counter variables.
  1285  	for k := range p.counterLengths {
  1286  		cvn := mkCounterVarName(k)
  1287  		fmt.Fprintf(w, "var %s [%d]uint32\n", cvn, p.counterLengths[k])
  1288  	}
  1289  
  1290  	// Emit encoded meta-data.
  1291  	var sws slicewriter.WriteSeeker
  1292  	digest, err := p.mdb.Emit(&sws)
  1293  	if err != nil {
  1294  		log.Fatalf("encoding meta-data: %v", err)
  1295  	}
  1296  	p.mdb = nil
  1297  	fmt.Fprintf(w, "var %s = [...]byte{\n", mkMetaVar())
  1298  	payload := sws.BytesWritten()
  1299  	for k, b := range payload {
  1300  		fmt.Fprintf(w, " 0x%x,", b)
  1301  		if k != 0 && k%8 == 0 {
  1302  			fmt.Fprintf(w, "\n")
  1303  		}
  1304  	}
  1305  	fmt.Fprintf(w, "}\n")
  1306  
  1307  	fixcfg := covcmd.CoverFixupConfig{
  1308  		Strategy:           "normal",
  1309  		MetaVar:            mkMetaVar(),
  1310  		MetaLen:            len(payload),
  1311  		MetaHash:           fmt.Sprintf("%x", digest),
  1312  		PkgIdVar:           mkPackageIdVar(),
  1313  		CounterPrefix:      *varVar,
  1314  		CounterGranularity: pkgconfig.Granularity,
  1315  		CounterMode:        *mode,
  1316  	}
  1317  	fixdata, err := json.Marshal(fixcfg)
  1318  	if err != nil {
  1319  		log.Fatalf("marshal fixupcfg: %v", err)
  1320  	}
  1321  	if err := os.WriteFile(pkgconfig.OutConfig, fixdata, 0666); err != nil {
  1322  		log.Fatalf("error writing %s: %v", pkgconfig.OutConfig, err)
  1323  	}
  1324  }
  1325  
  1326  // atomicOnAtomic returns true if we're instrumenting
  1327  // the sync/atomic package AND using atomic mode.
  1328  func atomicOnAtomic() bool {
  1329  	return *mode == "atomic" && pkgconfig.PkgPath == "sync/atomic"
  1330  }
  1331  
  1332  // atomicPackagePrefix returns the import path prefix used to refer to
  1333  // our special import of sync/atomic; this is either set to the
  1334  // constant atomicPackageName plus a dot or the empty string if we're
  1335  // instrumenting the sync/atomic package itself.
  1336  func atomicPackagePrefix() string {
  1337  	if atomicOnAtomic() {
  1338  		return ""
  1339  	}
  1340  	return atomicPackageName + "."
  1341  }
  1342  
  1343  func (p *Package) emitMetaFile(outpath string) {
  1344  	// Open output file.
  1345  	of, err := os.OpenFile(outpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
  1346  	if err != nil {
  1347  		log.Fatalf("opening covmeta %s: %v", outpath, err)
  1348  	}
  1349  
  1350  	if len(p.counterLengths) == 0 {
  1351  		// This corresponds to the case where we have no functions
  1352  		// in the package to instrument. Leave the file empty file if
  1353  		// this happens.
  1354  		if err = of.Close(); err != nil {
  1355  			log.Fatalf("closing meta-data file: %v", err)
  1356  		}
  1357  		return
  1358  	}
  1359  
  1360  	// Encode meta-data.
  1361  	var sws slicewriter.WriteSeeker
  1362  	digest, err := p.mdb.Emit(&sws)
  1363  	if err != nil {
  1364  		log.Fatalf("encoding meta-data: %v", err)
  1365  	}
  1366  	payload := sws.BytesWritten()
  1367  	blobs := [][]byte{payload}
  1368  
  1369  	// Write meta-data file directly.
  1370  	mfw := encodemeta.NewCoverageMetaFileWriter(outpath, of)
  1371  	err = mfw.Write(digest, blobs, cmode, cgran)
  1372  	if err != nil {
  1373  		log.Fatalf("writing meta-data file: %v", err)
  1374  	}
  1375  	if err = of.Close(); err != nil {
  1376  		log.Fatalf("closing meta-data file: %v", err)
  1377  	}
  1378  }
  1379  

View as plain text