Source file src/runtime/alg.go

     1  // Copyright 2014 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 runtime
     6  
     7  import (
     8  	"internal/abi"
     9  	"internal/byteorder"
    10  	"internal/cpu"
    11  	"internal/goarch"
    12  	"internal/runtime/sys"
    13  	"unsafe"
    14  )
    15  
    16  const (
    17  	c0 = uintptr((8-goarch.PtrSize)/4*2860486313 + (goarch.PtrSize-4)/4*33054211828000289)
    18  	c1 = uintptr((8-goarch.PtrSize)/4*3267000013 + (goarch.PtrSize-4)/4*23344194077549503)
    19  )
    20  
    21  func memhash0(p unsafe.Pointer, h uintptr) uintptr {
    22  	return h
    23  }
    24  
    25  func memhash8(p unsafe.Pointer, h uintptr) uintptr {
    26  	return memhash(p, h, 1)
    27  }
    28  
    29  func memhash16(p unsafe.Pointer, h uintptr) uintptr {
    30  	return memhash(p, h, 2)
    31  }
    32  
    33  func memhash128(p unsafe.Pointer, h uintptr) uintptr {
    34  	return memhash(p, h, 16)
    35  }
    36  
    37  //go:nosplit
    38  func memhash_varlen(p unsafe.Pointer, h uintptr) uintptr {
    39  	ptr := sys.GetClosurePtr()
    40  	size := *(*uintptr)(unsafe.Pointer(ptr + unsafe.Sizeof(h)))
    41  	return memhash(p, h, size)
    42  }
    43  
    44  // runtime variable to check if the processor we're running on
    45  // actually supports the instructions used by the AES-based
    46  // hash implementation.
    47  var useAeshash bool
    48  
    49  // in asm_*.s
    50  
    51  // memhash should be an internal detail,
    52  // but widely used packages access it using linkname.
    53  // Notable members of the hall of shame include:
    54  //   - github.com/aacfactory/fns
    55  //   - github.com/dgraph-io/ristretto
    56  //   - github.com/minio/simdjson-go
    57  //   - github.com/nbd-wtf/go-nostr
    58  //   - github.com/outcaste-io/ristretto
    59  //   - github.com/puzpuzpuz/xsync/v2
    60  //   - github.com/puzpuzpuz/xsync/v3
    61  //   - github.com/authzed/spicedb
    62  //   - github.com/pingcap/badger
    63  //
    64  // Do not remove or change the type signature.
    65  // See go.dev/issue/67401.
    66  //
    67  //go:linkname memhash
    68  func memhash(p unsafe.Pointer, h, s uintptr) uintptr
    69  
    70  func memhash32(p unsafe.Pointer, h uintptr) uintptr
    71  
    72  func memhash64(p unsafe.Pointer, h uintptr) uintptr
    73  
    74  // strhash should be an internal detail,
    75  // but widely used packages access it using linkname.
    76  // Notable members of the hall of shame include:
    77  //   - github.com/aristanetworks/goarista
    78  //   - github.com/bytedance/sonic
    79  //   - github.com/bytedance/go-tagexpr/v2
    80  //   - github.com/cloudwego/dynamicgo
    81  //   - github.com/v2fly/v2ray-core/v5
    82  //
    83  // Do not remove or change the type signature.
    84  // See go.dev/issue/67401.
    85  //
    86  //go:linkname strhash
    87  func strhash(p unsafe.Pointer, h uintptr) uintptr
    88  
    89  func strhashFallback(a unsafe.Pointer, h uintptr) uintptr {
    90  	x := (*stringStruct)(a)
    91  	return memhashFallback(x.str, h, uintptr(x.len))
    92  }
    93  
    94  // NOTE: Because NaN != NaN, a map can contain any
    95  // number of (mostly useless) entries keyed with NaNs.
    96  // To avoid long hash chains, we assign a random number
    97  // as the hash value for a NaN.
    98  
    99  func f32hash(p unsafe.Pointer, h uintptr) uintptr {
   100  	f := *(*float32)(p)
   101  	switch {
   102  	case f == 0:
   103  		return c1 * (c0 ^ h) // +0, -0
   104  	case f != f:
   105  		return c1 * (c0 ^ h ^ uintptr(rand())) // any kind of NaN
   106  	default:
   107  		return memhash(p, h, 4)
   108  	}
   109  }
   110  
   111  func f64hash(p unsafe.Pointer, h uintptr) uintptr {
   112  	f := *(*float64)(p)
   113  	switch {
   114  	case f == 0:
   115  		return c1 * (c0 ^ h) // +0, -0
   116  	case f != f:
   117  		return c1 * (c0 ^ h ^ uintptr(rand())) // any kind of NaN
   118  	default:
   119  		return memhash(p, h, 8)
   120  	}
   121  }
   122  
   123  func c64hash(p unsafe.Pointer, h uintptr) uintptr {
   124  	x := (*[2]float32)(p)
   125  	return f32hash(unsafe.Pointer(&x[1]), f32hash(unsafe.Pointer(&x[0]), h))
   126  }
   127  
   128  func c128hash(p unsafe.Pointer, h uintptr) uintptr {
   129  	x := (*[2]float64)(p)
   130  	return f64hash(unsafe.Pointer(&x[1]), f64hash(unsafe.Pointer(&x[0]), h))
   131  }
   132  
   133  func interhash(p unsafe.Pointer, h uintptr) uintptr {
   134  	a := (*iface)(p)
   135  	tab := a.tab
   136  	if tab == nil {
   137  		return h
   138  	}
   139  	t := tab.Type
   140  	if t.Equal == nil {
   141  		// Check hashability here. We could do this check inside
   142  		// typehash, but we want to report the topmost type in
   143  		// the error text (e.g. in a struct with a field of slice type
   144  		// we want to report the struct, not the slice).
   145  		panic(errorString("hash of unhashable type " + toRType(t).string()))
   146  	}
   147  	if isDirectIface(t) {
   148  		return c1 * typehash(t, unsafe.Pointer(&a.data), h^c0)
   149  	} else {
   150  		return c1 * typehash(t, a.data, h^c0)
   151  	}
   152  }
   153  
   154  // nilinterhash should be an internal detail,
   155  // but widely used packages access it using linkname.
   156  // Notable members of the hall of shame include:
   157  //   - github.com/anacrolix/stm
   158  //   - github.com/aristanetworks/goarista
   159  //
   160  // Do not remove or change the type signature.
   161  // See go.dev/issue/67401.
   162  //
   163  //go:linkname nilinterhash
   164  func nilinterhash(p unsafe.Pointer, h uintptr) uintptr {
   165  	a := (*eface)(p)
   166  	t := a._type
   167  	if t == nil {
   168  		return h
   169  	}
   170  	if t.Equal == nil {
   171  		// See comment in interhash above.
   172  		panic(errorString("hash of unhashable type " + toRType(t).string()))
   173  	}
   174  	if isDirectIface(t) {
   175  		return c1 * typehash(t, unsafe.Pointer(&a.data), h^c0)
   176  	} else {
   177  		return c1 * typehash(t, a.data, h^c0)
   178  	}
   179  }
   180  
   181  // typehash computes the hash of the object of type t at address p.
   182  // h is the seed.
   183  // This function is seldom used. Most maps use for hashing either
   184  // fixed functions (e.g. f32hash) or compiler-generated functions
   185  // (e.g. for a type like struct { x, y string }). This implementation
   186  // is slower but more general and is used for hashing interface types
   187  // (called from interhash or nilinterhash, above) or for hashing in
   188  // maps generated by reflect.MapOf (reflect_typehash, below).
   189  // Note: this function must match the compiler generated
   190  // functions exactly. See issue 37716.
   191  //
   192  // typehash should be an internal detail,
   193  // but widely used packages access it using linkname.
   194  // Notable members of the hall of shame include:
   195  //   - github.com/puzpuzpuz/xsync/v2
   196  //   - github.com/puzpuzpuz/xsync/v3
   197  //
   198  // Do not remove or change the type signature.
   199  // See go.dev/issue/67401.
   200  //
   201  //go:linkname typehash
   202  func typehash(t *_type, p unsafe.Pointer, h uintptr) uintptr {
   203  	if t.TFlag&abi.TFlagRegularMemory != 0 {
   204  		// Handle ptr sizes specially, see issue 37086.
   205  		switch t.Size_ {
   206  		case 4:
   207  			return memhash32(p, h)
   208  		case 8:
   209  			return memhash64(p, h)
   210  		default:
   211  			return memhash(p, h, t.Size_)
   212  		}
   213  	}
   214  	switch t.Kind_ & abi.KindMask {
   215  	case abi.Float32:
   216  		return f32hash(p, h)
   217  	case abi.Float64:
   218  		return f64hash(p, h)
   219  	case abi.Complex64:
   220  		return c64hash(p, h)
   221  	case abi.Complex128:
   222  		return c128hash(p, h)
   223  	case abi.String:
   224  		return strhash(p, h)
   225  	case abi.Interface:
   226  		i := (*interfacetype)(unsafe.Pointer(t))
   227  		if len(i.Methods) == 0 {
   228  			return nilinterhash(p, h)
   229  		}
   230  		return interhash(p, h)
   231  	case abi.Array:
   232  		a := (*arraytype)(unsafe.Pointer(t))
   233  		for i := uintptr(0); i < a.Len; i++ {
   234  			h = typehash(a.Elem, add(p, i*a.Elem.Size_), h)
   235  		}
   236  		return h
   237  	case abi.Struct:
   238  		s := (*structtype)(unsafe.Pointer(t))
   239  		for _, f := range s.Fields {
   240  			if f.Name.IsBlank() {
   241  				continue
   242  			}
   243  			h = typehash(f.Typ, add(p, f.Offset), h)
   244  		}
   245  		return h
   246  	default:
   247  		// Should never happen, as typehash should only be called
   248  		// with comparable types.
   249  		panic(errorString("hash of unhashable type " + toRType(t).string()))
   250  	}
   251  }
   252  
   253  //go:linkname reflect_typehash reflect.typehash
   254  func reflect_typehash(t *_type, p unsafe.Pointer, h uintptr) uintptr {
   255  	return typehash(t, p, h)
   256  }
   257  
   258  func memequal0(p, q unsafe.Pointer) bool {
   259  	return true
   260  }
   261  func memequal8(p, q unsafe.Pointer) bool {
   262  	return *(*int8)(p) == *(*int8)(q)
   263  }
   264  func memequal16(p, q unsafe.Pointer) bool {
   265  	return *(*int16)(p) == *(*int16)(q)
   266  }
   267  func memequal32(p, q unsafe.Pointer) bool {
   268  	return *(*int32)(p) == *(*int32)(q)
   269  }
   270  func memequal64(p, q unsafe.Pointer) bool {
   271  	return *(*int64)(p) == *(*int64)(q)
   272  }
   273  func memequal128(p, q unsafe.Pointer) bool {
   274  	return *(*[2]int64)(p) == *(*[2]int64)(q)
   275  }
   276  func f32equal(p, q unsafe.Pointer) bool {
   277  	return *(*float32)(p) == *(*float32)(q)
   278  }
   279  func f64equal(p, q unsafe.Pointer) bool {
   280  	return *(*float64)(p) == *(*float64)(q)
   281  }
   282  func c64equal(p, q unsafe.Pointer) bool {
   283  	return *(*complex64)(p) == *(*complex64)(q)
   284  }
   285  func c128equal(p, q unsafe.Pointer) bool {
   286  	return *(*complex128)(p) == *(*complex128)(q)
   287  }
   288  func strequal(p, q unsafe.Pointer) bool {
   289  	return *(*string)(p) == *(*string)(q)
   290  }
   291  func interequal(p, q unsafe.Pointer) bool {
   292  	x := *(*iface)(p)
   293  	y := *(*iface)(q)
   294  	return x.tab == y.tab && ifaceeq(x.tab, x.data, y.data)
   295  }
   296  func nilinterequal(p, q unsafe.Pointer) bool {
   297  	x := *(*eface)(p)
   298  	y := *(*eface)(q)
   299  	return x._type == y._type && efaceeq(x._type, x.data, y.data)
   300  }
   301  func efaceeq(t *_type, x, y unsafe.Pointer) bool {
   302  	if t == nil {
   303  		return true
   304  	}
   305  	eq := t.Equal
   306  	if eq == nil {
   307  		panic(errorString("comparing uncomparable type " + toRType(t).string()))
   308  	}
   309  	if isDirectIface(t) {
   310  		// Direct interface types are ptr, chan, map, func, and single-element structs/arrays thereof.
   311  		// Maps and funcs are not comparable, so they can't reach here.
   312  		// Ptrs, chans, and single-element items can be compared directly using ==.
   313  		return x == y
   314  	}
   315  	return eq(x, y)
   316  }
   317  func ifaceeq(tab *itab, x, y unsafe.Pointer) bool {
   318  	if tab == nil {
   319  		return true
   320  	}
   321  	t := tab.Type
   322  	eq := t.Equal
   323  	if eq == nil {
   324  		panic(errorString("comparing uncomparable type " + toRType(t).string()))
   325  	}
   326  	if isDirectIface(t) {
   327  		// See comment in efaceeq.
   328  		return x == y
   329  	}
   330  	return eq(x, y)
   331  }
   332  
   333  // Testing adapters for hash quality tests (see hash_test.go)
   334  //
   335  // stringHash should be an internal detail,
   336  // but widely used packages access it using linkname.
   337  // Notable members of the hall of shame include:
   338  //   - github.com/k14s/starlark-go
   339  //
   340  // Do not remove or change the type signature.
   341  // See go.dev/issue/67401.
   342  //
   343  //go:linkname stringHash
   344  func stringHash(s string, seed uintptr) uintptr {
   345  	return strhash(noescape(unsafe.Pointer(&s)), seed)
   346  }
   347  
   348  func bytesHash(b []byte, seed uintptr) uintptr {
   349  	s := (*slice)(unsafe.Pointer(&b))
   350  	return memhash(s.array, seed, uintptr(s.len))
   351  }
   352  
   353  func int32Hash(i uint32, seed uintptr) uintptr {
   354  	return memhash32(noescape(unsafe.Pointer(&i)), seed)
   355  }
   356  
   357  func int64Hash(i uint64, seed uintptr) uintptr {
   358  	return memhash64(noescape(unsafe.Pointer(&i)), seed)
   359  }
   360  
   361  func efaceHash(i any, seed uintptr) uintptr {
   362  	return nilinterhash(noescape(unsafe.Pointer(&i)), seed)
   363  }
   364  
   365  func ifaceHash(i interface {
   366  	F()
   367  }, seed uintptr) uintptr {
   368  	return interhash(noescape(unsafe.Pointer(&i)), seed)
   369  }
   370  
   371  const hashRandomBytes = goarch.PtrSize / 4 * 64
   372  
   373  // used in asm_{386,amd64,arm64}.s to seed the hash function
   374  var aeskeysched [hashRandomBytes]byte
   375  
   376  // used in hash{32,64}.go to seed the hash function
   377  var hashkey [4]uintptr
   378  
   379  func alginit() {
   380  	// Install AES hash algorithms if the instructions needed are present.
   381  	if (GOARCH == "386" || GOARCH == "amd64") &&
   382  		cpu.X86.HasAES && // AESENC
   383  		cpu.X86.HasSSSE3 && // PSHUFB
   384  		cpu.X86.HasSSE41 { // PINSR{D,Q}
   385  		initAlgAES()
   386  		return
   387  	}
   388  	if GOARCH == "arm64" && cpu.ARM64.HasAES {
   389  		initAlgAES()
   390  		return
   391  	}
   392  	for i := range hashkey {
   393  		hashkey[i] = uintptr(bootstrapRand())
   394  	}
   395  }
   396  
   397  func initAlgAES() {
   398  	useAeshash = true
   399  	// Initialize with random data so hash collisions will be hard to engineer.
   400  	key := (*[hashRandomBytes / 8]uint64)(unsafe.Pointer(&aeskeysched))
   401  	for i := range key {
   402  		key[i] = bootstrapRand()
   403  	}
   404  }
   405  
   406  // Note: These routines perform the read with a native endianness.
   407  func readUnaligned32(p unsafe.Pointer) uint32 {
   408  	q := (*[4]byte)(p)
   409  	if goarch.BigEndian {
   410  		return byteorder.BEUint32(q[:])
   411  	}
   412  	return byteorder.LEUint32(q[:])
   413  }
   414  
   415  func readUnaligned64(p unsafe.Pointer) uint64 {
   416  	q := (*[8]byte)(p)
   417  	if goarch.BigEndian {
   418  		return byteorder.BEUint64(q[:])
   419  	}
   420  	return byteorder.LEUint64(q[:])
   421  }
   422  

View as plain text