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

View as plain text