Source file src/cmd/compile/internal/test/typedesc_test.go

     1  // Copyright 2026 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 test
     6  
     7  import (
     8  	"fmt"
     9  	"internal/abi"
    10  	"internal/testenv"
    11  	"os"
    12  	"path/filepath"
    13  	"strings"
    14  	"testing"
    15  
    16  	"cmd/internal/archive"
    17  	"cmd/internal/goobj"
    18  	"cmd/internal/objabi"
    19  )
    20  
    21  // TestNoalgDescriptorUpgrade checks that a type descriptor does not depend
    22  // on whether the package first needed the type in a noalg context.
    23  //
    24  // A package that needs a type only as part of something marked noalg, such
    25  // as the group type of a map, writes a descriptor without the type's hash
    26  // and equality algorithms. If the package then needs the type for its own
    27  // sake, writeType upgrades that descriptor in place instead of writing a
    28  // new one. The upgraded descriptor has to come out the same as the one a
    29  // package that never needed the noalg form writes, because the linker may
    30  // keep either. See issue #82462.
    31  func TestNoalgDescriptorUpgrade(t *testing.T) {
    32  	testenv.MustHaveGoBuild(t)
    33  	t.Parallel()
    34  
    35  	// A map[int]int holds its keys and its elements in
    36  	// [abi.MapGroupSlots]int arrays within the group type, which is the
    37  	// type the packages below reach by two different routes.
    38  	const n = abi.MapGroupSlots
    39  	sym := fmt.Sprintf("type:[%d]int", n)
    40  
    41  	// noalgFirst reaches the array type through the group type of M, which
    42  	// is marked noalg, before reaching it on its own.
    43  	noalgFirst := fmt.Sprintf(`package p
    44  
    45  type M map[int]int
    46  
    47  var sinkM M
    48  var sinkA [%[1]d]int
    49  
    50  func useMap()   { sinkM = M{1: 2} }
    51  func useArray() { sinkA = [%[1]d]int{} }
    52  `, n)
    53  	// noalgOnly reaches it only through the group type of M, so its
    54  	// descriptor stays noalg.
    55  	const noalgOnly = `package p
    56  
    57  type M map[int]int
    58  
    59  var sinkM M
    60  
    61  func useMap() { sinkM = M{1: 2} }
    62  `
    63  	// algOnly reaches it on its own, and never in a noalg context.
    64  	algOnly := fmt.Sprintf(`package p
    65  
    66  var sinkA [%[1]d]int
    67  
    68  func useArray() { sinkA = [%[1]d]int{} }
    69  `, n)
    70  
    71  	dir := t.TempDir()
    72  	upgraded := compileSym(t, dir, "upgraded", noalgFirst, sym)
    73  	noalg := compileSym(t, dir, "noalg", noalgOnly, sym)
    74  	full := compileSym(t, dir, "full", algOnly, sym)
    75  
    76  	// Guard against the test going vacuous: noalgOnly must really produce
    77  	// a noalg descriptor, so that noalgFirst really exercises the upgrade.
    78  	if !strings.Contains(noalg, "weakdef=true") {
    79  		t.Fatalf("%s is not noalg when reached only through a map group type:\n%s", sym, noalg)
    80  	}
    81  
    82  	if upgraded != full {
    83  		t.Errorf("%s differs depending on whether a noalg descriptor was written first\nupgraded:\n%s\nwritten in full:\n%s", sym, upgraded, full)
    84  	}
    85  }
    86  
    87  // compileSym compiles src as package p in its own directory under dir, and
    88  // returns a description of the symbol named sym: everything the object file
    89  // records about it, except for the name.
    90  func compileSym(t *testing.T, dir, name, src, sym string) string {
    91  	t.Helper()
    92  
    93  	pdir := filepath.Join(dir, name)
    94  	if err := os.Mkdir(pdir, 0o777); err != nil {
    95  		t.Fatal(err)
    96  	}
    97  	gofile := filepath.Join(pdir, "p.go")
    98  	if err := os.WriteFile(gofile, []byte(src), 0o666); err != nil {
    99  		t.Fatal(err)
   100  	}
   101  	ofile := filepath.Join(pdir, "p.o")
   102  	out, err := testenv.Command(t, testenv.GoToolPath(t), "tool", "compile", "-p=p", "-o", ofile, gofile).CombinedOutput()
   103  	if err != nil {
   104  		t.Fatalf("compiling %s failed: %v\n%s", name, err, out)
   105  	}
   106  
   107  	f, err := os.Open(ofile)
   108  	if err != nil {
   109  		t.Fatal(err)
   110  	}
   111  	defer f.Close()
   112  	a, err := archive.Parse(f, false)
   113  	if err != nil {
   114  		t.Fatal(err)
   115  	}
   116  	for _, e := range a.Entries {
   117  		if e.Type != archive.EntryGoObj {
   118  			continue
   119  		}
   120  		b := make([]byte, e.Obj.Size)
   121  		if _, err := f.ReadAt(b, e.Obj.Offset); err != nil {
   122  			t.Fatal(err)
   123  		}
   124  		if s := describeSym(goobj.NewReaderFromBytes(b, false), sym); s != "" {
   125  			return s
   126  		}
   127  	}
   128  	t.Fatalf("%s: no %s symbol in %s", name, sym, ofile)
   129  	return ""
   130  }
   131  
   132  // describeSym returns a description of the symbol named sym defined in r, or
   133  // the empty string if r does not define one.
   134  func describeSym(r *goobj.Reader, sym string) string {
   135  	resolve := func(s goobj.SymRef) string {
   136  		// Referenced symbols from other packages are named in the refName
   137  		// table; the rest are indexed, in the order the reader lays them out.
   138  		var i uint32
   139  		switch s.PkgIdx {
   140  		case goobj.PkgIdxInvalid:
   141  			return ""
   142  		case goobj.PkgIdxHashed64:
   143  			i = s.SymIdx + uint32(r.NSym())
   144  		case goobj.PkgIdxHashed:
   145  			i = s.SymIdx + uint32(r.NSym()+r.NHashed64def())
   146  		case goobj.PkgIdxNone:
   147  			i = s.SymIdx + uint32(r.NSym()+r.NHashed64def()+r.NHasheddef())
   148  		case goobj.PkgIdxBuiltin:
   149  			name, _ := goobj.BuiltinName(int(s.SymIdx))
   150  			return name
   151  		case goobj.PkgIdxSelf:
   152  			i = s.SymIdx
   153  		default:
   154  			for j := 0; j < r.NRefName(); j++ {
   155  				if rn := r.RefName(j); rn.Sym() == s {
   156  					return rn.Name(r)
   157  				}
   158  			}
   159  			return "?"
   160  		}
   161  		return r.Sym(i).Name(r)
   162  	}
   163  
   164  	ndef := uint32(r.NSym() + r.NHashed64def() + r.NHasheddef() + r.NNonpkgdef())
   165  	for i := uint32(0); i < ndef; i++ {
   166  		s := r.Sym(i)
   167  		if s.Name(r) != sym {
   168  			continue
   169  		}
   170  		var b strings.Builder
   171  		fmt.Fprintf(&b, "%v size=%d align=%d dupok=%v weakdef=%v typelink=%v\n",
   172  			objabi.SymKind(s.Type()), s.Siz(), s.Align(), s.Dupok(), s.WeakDef(), s.Typelink())
   173  		fmt.Fprintf(&b, "\tdata % x\n", r.Data(i))
   174  		for _, rel := range r.Relocs(i) {
   175  			fmt.Fprintf(&b, "\trel %d+%d t=%v %s+%d\n", rel.Off(), rel.Siz(), objabi.RelocType(rel.Type()), resolve(rel.Sym()), rel.Add())
   176  		}
   177  		return b.String()
   178  	}
   179  	return ""
   180  }
   181  

View as plain text