github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/runtime/coverage/apis.go (about)

     1  // Copyright 2022 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 coverage
     6  
     7  import (
     8  	"fmt"
     9  	"internal/coverage"
    10  	"io"
    11  	"reflect"
    12  	"sync/atomic"
    13  	"unsafe"
    14  )
    15  
    16  // WriteMetaDir writes a coverage meta-data file for the currently
    17  // running program to the directory specified in 'dir'. An error will
    18  // be returned if the operation can't be completed successfully (for
    19  // example, if the currently running program was not built with
    20  // "-cover", or if the directory does not exist).
    21  func WriteMetaDir(dir string) error {
    22  	if !finalHashComputed {
    23  		return fmt.Errorf("error: no meta-data available (binary not built with -cover?)")
    24  	}
    25  	return emitMetaDataToDirectory(dir, getCovMetaList())
    26  }
    27  
    28  // WriteMeta writes the meta-data content (the payload that would
    29  // normally be emitted to a meta-data file) for the currently running
    30  // program to the the writer 'w'. An error will be returned if the
    31  // operation can't be completed successfully (for example, if the
    32  // currently running program was not built with "-cover", or if a
    33  // write fails).
    34  func WriteMeta(w io.Writer) error {
    35  	if w == nil {
    36  		return fmt.Errorf("error: nil writer in WriteMeta")
    37  	}
    38  	if !finalHashComputed {
    39  		return fmt.Errorf("error: no meta-data available (binary not built with -cover?)")
    40  	}
    41  	ml := getCovMetaList()
    42  	return writeMetaData(w, ml, cmode, cgran, finalHash)
    43  }
    44  
    45  // WriteCountersDir writes a coverage counter-data file for the
    46  // currently running program to the directory specified in 'dir'. An
    47  // error will be returned if the operation can't be completed
    48  // successfully (for example, if the currently running program was not
    49  // built with "-cover", or if the directory does not exist). The
    50  // counter data written will be a snapshot taken at the point of the
    51  // call.
    52  func WriteCountersDir(dir string) error {
    53  	return emitCounterDataToDirectory(dir)
    54  }
    55  
    56  // WriteCounters writes coverage counter-data content for
    57  // the currently running program to the writer 'w'. An error will be
    58  // returned if the operation can't be completed successfully (for
    59  // example, if the currently running program was not built with
    60  // "-cover", or if a write fails). The counter data written will be a
    61  // snapshot taken at the point of the invocation.
    62  func WriteCounters(w io.Writer) error {
    63  	if w == nil {
    64  		return fmt.Errorf("error: nil writer in WriteCounters")
    65  	}
    66  	// Ask the runtime for the list of coverage counter symbols.
    67  	cl := getCovCounterList()
    68  	if len(cl) == 0 {
    69  		return fmt.Errorf("program not built with -cover")
    70  	}
    71  	if !finalHashComputed {
    72  		return fmt.Errorf("meta-data not written yet, unable to write counter data")
    73  	}
    74  
    75  	pm := getCovPkgMap()
    76  	s := &emitState{
    77  		counterlist: cl,
    78  		pkgmap:      pm,
    79  	}
    80  	return s.emitCounterDataToWriter(w)
    81  }
    82  
    83  // ClearCounters clears/resets all coverage counter variables in the
    84  // currently running program. It returns an error if the program in
    85  // question was not built with the "-cover" flag. Clearing of coverage
    86  // counters is also not supported for programs not using atomic
    87  // counter mode (see more detailed comments below for the rationale
    88  // here).
    89  func ClearCounters() error {
    90  	cl := getCovCounterList()
    91  	if len(cl) == 0 {
    92  		return fmt.Errorf("program not built with -cover")
    93  	}
    94  	if cmode != coverage.CtrModeAtomic {
    95  		return fmt.Errorf("ClearCounters invoked for program build with -covermode=%s (please use -covermode=atomic)", cmode.String())
    96  	}
    97  
    98  	// Implementation note: this function would be faster and simpler
    99  	// if we could just zero out the entire counter array, but for the
   100  	// moment we go through and zero out just the slots in the array
   101  	// corresponding to the counter values. We do this to avoid the
   102  	// following bad scenario: suppose that a user builds their Go
   103  	// program with "-cover", and that program has a function (call it
   104  	// main.XYZ) that invokes ClearCounters:
   105  	//
   106  	//     func XYZ() {
   107  	//       ... do some stuff ...
   108  	//       coverage.ClearCounters()
   109  	//       if someCondition {   <<--- HERE
   110  	//         ...
   111  	//       }
   112  	//     }
   113  	//
   114  	// At the point where ClearCounters executes, main.XYZ has not yet
   115  	// finished running, thus as soon as the call returns the line
   116  	// marked "HERE" above will trigger the writing of a non-zero
   117  	// value into main.XYZ's counter slab. However since we've just
   118  	// finished clearing the entire counter segment, we will have lost
   119  	// the values in the prolog portion of main.XYZ's counter slab
   120  	// (nctrs, pkgid, funcid). This means that later on at the end of
   121  	// program execution as we walk through the entire counter array
   122  	// for the program looking for executed functions, we'll zoom past
   123  	// main.XYZ's prolog (which was zero'd) and hit the non-zero
   124  	// counter value corresponding to the "HERE" block, which will
   125  	// then be interpreted as the start of another live function.
   126  	// Things will go downhill from there.
   127  	//
   128  	// This same scenario is also a potential risk if the program is
   129  	// running on an architecture that permits reordering of
   130  	// writes/stores, since the inconsistency described above could
   131  	// arise here. Example scenario:
   132  	//
   133  	//     func ABC() {
   134  	//       ...                    // prolog
   135  	//       if alwaysTrue() {
   136  	//         XYZ()                // counter update here
   137  	//       }
   138  	//     }
   139  	//
   140  	// In the instrumented version of ABC, the prolog of the function
   141  	// will contain a series of stores to the initial portion of the
   142  	// counter array to write number-of-counters, pkgid, funcid. Later
   143  	// in the function there is also a store to increment a counter
   144  	// for the block containing the call to XYZ(). If the CPU is
   145  	// allowed to reorder stores and decides to issue the XYZ store
   146  	// before the prolog stores, this could be observable as an
   147  	// inconsistency similar to the one above. Hence the requirement
   148  	// for atomic counter mode: according to package atomic docs,
   149  	// "...operations that happen in a specific order on one thread,
   150  	// will always be observed to happen in exactly that order by
   151  	// another thread". Thus we can be sure that there will be no
   152  	// inconsistency when reading the counter array from the thread
   153  	// running ClearCounters.
   154  
   155  	var sd []atomic.Uint32
   156  
   157  	bufHdr := (*reflect.SliceHeader)(unsafe.Pointer(&sd))
   158  	for _, c := range cl {
   159  		bufHdr.Data = uintptr(unsafe.Pointer(c.Counters))
   160  		bufHdr.Len = int(c.Len)
   161  		bufHdr.Cap = int(c.Len)
   162  		for i := 0; i < len(sd); i++ {
   163  			// Skip ahead until the next non-zero value.
   164  			sdi := sd[i].Load()
   165  			if sdi == 0 {
   166  				continue
   167  			}
   168  			// We found a function that was executed; clear its counters.
   169  			nCtrs := sdi
   170  			for j := 0; j < int(nCtrs); j++ {
   171  				sd[i+coverage.FirstCtrOffset+j].Store(0)
   172  			}
   173  			// Move to next function.
   174  			i += coverage.FirstCtrOffset + int(nCtrs) - 1
   175  		}
   176  	}
   177  	return nil
   178  }