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  func mapKeyError(t *maptype, p unsafe.Pointer) error {
   254  	if !t.HashMightPanic() {
   255  		return nil
   256  	}
   257  	return mapKeyError2(t.Key, p)
   258  }
   259  
   260  func mapKeyError2(t *_type, p unsafe.Pointer) error {
   261  	if t.TFlag&abi.TFlagRegularMemory != 0 {
   262  		return nil
   263  	}
   264  	switch t.Kind_ & abi.KindMask {
   265  	case abi.Float32, abi.Float64, abi.Complex64, abi.Complex128, abi.String:
   266  		return nil
   267  	case abi.Interface:
   268  		i := (*interfacetype)(unsafe.Pointer(t))
   269  		var t *_type
   270  		var pdata *unsafe.Pointer
   271  		if len(i.Methods) == 0 {
   272  			a := (*eface)(p)
   273  			t = a._type
   274  			if t == nil {
   275  				return nil
   276  			}
   277  			pdata = &a.data
   278  		} else {
   279  			a := (*iface)(p)
   280  			if a.tab == nil {
   281  				return nil
   282  			}
   283  			t = a.tab.Type
   284  			pdata = &a.data
   285  		}
   286  
   287  		if t.Equal == nil {
   288  			return errorString("hash of unhashable type " + toRType(t).string())
   289  		}
   290  
   291  		if isDirectIface(t) {
   292  			return mapKeyError2(t, unsafe.Pointer(pdata))
   293  		} else {
   294  			return mapKeyError2(t, *pdata)
   295  		}
   296  	case abi.Array:
   297  		a := (*arraytype)(unsafe.Pointer(t))
   298  		for i := uintptr(0); i < a.Len; i++ {
   299  			if err := mapKeyError2(a.Elem, add(p, i*a.Elem.Size_)); err != nil {
   300  				return err
   301  			}
   302  		}
   303  		return nil
   304  	case abi.Struct:
   305  		s := (*structtype)(unsafe.Pointer(t))
   306  		for _, f := range s.Fields {
   307  			if f.Name.IsBlank() {
   308  				continue
   309  			}
   310  			if err := mapKeyError2(f.Typ, add(p, f.Offset)); err != nil {
   311  				return err
   312  			}
   313  		}
   314  		return nil
   315  	default:
   316  		// Should never happen, keep this case for robustness.
   317  		return errorString("hash of unhashable type " + toRType(t).string())
   318  	}
   319  }
   320  
   321  //go:linkname reflect_typehash reflect.typehash
   322  func reflect_typehash(t *_type, p unsafe.Pointer, h uintptr) uintptr {
   323  	return typehash(t, p, h)
   324  }
   325  
   326  func memequal0(p, q unsafe.Pointer) bool {
   327  	return true
   328  }
   329  func memequal8(p, q unsafe.Pointer) bool {
   330  	return *(*int8)(p) == *(*int8)(q)
   331  }
   332  func memequal16(p, q unsafe.Pointer) bool {
   333  	return *(*int16)(p) == *(*int16)(q)
   334  }
   335  func memequal32(p, q unsafe.Pointer) bool {
   336  	return *(*int32)(p) == *(*int32)(q)
   337  }
   338  func memequal64(p, q unsafe.Pointer) bool {
   339  	return *(*int64)(p) == *(*int64)(q)
   340  }
   341  func memequal128(p, q unsafe.Pointer) bool {
   342  	return *(*[2]int64)(p) == *(*[2]int64)(q)
   343  }
   344  func f32equal(p, q unsafe.Pointer) bool {
   345  	return *(*float32)(p) == *(*float32)(q)
   346  }
   347  func f64equal(p, q unsafe.Pointer) bool {
   348  	return *(*float64)(p) == *(*float64)(q)
   349  }
   350  func c64equal(p, q unsafe.Pointer) bool {
   351  	return *(*complex64)(p) == *(*complex64)(q)
   352  }
   353  func c128equal(p, q unsafe.Pointer) bool {
   354  	return *(*complex128)(p) == *(*complex128)(q)
   355  }
   356  func strequal(p, q unsafe.Pointer) bool {
   357  	return *(*string)(p) == *(*string)(q)
   358  }
   359  func interequal(p, q unsafe.Pointer) bool {
   360  	x := *(*iface)(p)
   361  	y := *(*iface)(q)
   362  	return x.tab == y.tab && ifaceeq(x.tab, x.data, y.data)
   363  }
   364  func nilinterequal(p, q unsafe.Pointer) bool {
   365  	x := *(*eface)(p)
   366  	y := *(*eface)(q)
   367  	return x._type == y._type && efaceeq(x._type, x.data, y.data)
   368  }
   369  func efaceeq(t *_type, x, y unsafe.Pointer) bool {
   370  	if t == nil {
   371  		return true
   372  	}
   373  	eq := t.Equal
   374  	if eq == nil {
   375  		panic(errorString("comparing uncomparable type " + toRType(t).string()))
   376  	}
   377  	if isDirectIface(t) {
   378  		// Direct interface types are ptr, chan, map, func, and single-element structs/arrays thereof.
   379  		// Maps and funcs are not comparable, so they can't reach here.
   380  		// Ptrs, chans, and single-element items can be compared directly using ==.
   381  		return x == y
   382  	}
   383  	return eq(x, y)
   384  }
   385  func ifaceeq(tab *itab, x, y unsafe.Pointer) bool {
   386  	if tab == nil {
   387  		return true
   388  	}
   389  	t := tab.Type
   390  	eq := t.Equal
   391  	if eq == nil {
   392  		panic(errorString("comparing uncomparable type " + toRType(t).string()))
   393  	}
   394  	if isDirectIface(t) {
   395  		// See comment in efaceeq.
   396  		return x == y
   397  	}
   398  	return eq(x, y)
   399  }
   400  
   401  // Testing adapters for hash quality tests (see hash_test.go)
   402  //
   403  // stringHash should be an internal detail,
   404  // but widely used packages access it using linkname.
   405  // Notable members of the hall of shame include:
   406  //   - github.com/k14s/starlark-go
   407  //
   408  // Do not remove or change the type signature.
   409  // See go.dev/issue/67401.
   410  //
   411  //go:linkname stringHash
   412  func stringHash(s string, seed uintptr) uintptr {
   413  	return strhash(noescape(unsafe.Pointer(&s)), seed)
   414  }
   415  
   416  func bytesHash(b []byte, seed uintptr) uintptr {
   417  	s := (*slice)(unsafe.Pointer(&b))
   418  	return memhash(s.array, seed, uintptr(s.len))
   419  }
   420  
   421  func int32Hash(i uint32, seed uintptr) uintptr {
   422  	return memhash32(noescape(unsafe.Pointer(&i)), seed)
   423  }
   424  
   425  func int64Hash(i uint64, seed uintptr) uintptr {
   426  	return memhash64(noescape(unsafe.Pointer(&i)), seed)
   427  }
   428  
   429  func efaceHash(i any, seed uintptr) uintptr {
   430  	return nilinterhash(noescape(unsafe.Pointer(&i)), seed)
   431  }
   432  
   433  func ifaceHash(i interface {
   434  	F()
   435  }, seed uintptr) uintptr {
   436  	return interhash(noescape(unsafe.Pointer(&i)), seed)
   437  }
   438  
   439  const hashRandomBytes = goarch.PtrSize / 4 * 64
   440  
   441  // used in asm_{386,amd64,arm64}.s to seed the hash function
   442  var aeskeysched [hashRandomBytes]byte
   443  
   444  // used in hash{32,64}.go to seed the hash function
   445  var hashkey [4]uintptr
   446  
   447  func alginit() {
   448  	// Install AES hash algorithms if the instructions needed are present.
   449  	if (GOARCH == "386" || GOARCH == "amd64") &&
   450  		cpu.X86.HasAES && // AESENC
   451  		cpu.X86.HasSSSE3 && // PSHUFB
   452  		cpu.X86.HasSSE41 { // PINSR{D,Q}
   453  		initAlgAES()
   454  		return
   455  	}
   456  	if GOARCH == "arm64" && cpu.ARM64.HasAES {
   457  		initAlgAES()
   458  		return
   459  	}
   460  	for i := range hashkey {
   461  		hashkey[i] = uintptr(bootstrapRand())
   462  	}
   463  }
   464  
   465  func initAlgAES() {
   466  	useAeshash = true
   467  	// Initialize with random data so hash collisions will be hard to engineer.
   468  	key := (*[hashRandomBytes / 8]uint64)(unsafe.Pointer(&aeskeysched))
   469  	for i := range key {
   470  		key[i] = bootstrapRand()
   471  	}
   472  }
   473  
   474  // Note: These routines perform the read with a native endianness.
   475  func readUnaligned32(p unsafe.Pointer) uint32 {
   476  	q := (*[4]byte)(p)
   477  	if goarch.BigEndian {
   478  		return byteorder.BEUint32(q[:])
   479  	}
   480  	return byteorder.LEUint32(q[:])
   481  }
   482  
   483  func readUnaligned64(p unsafe.Pointer) uint64 {
   484  	q := (*[8]byte)(p)
   485  	if goarch.BigEndian {
   486  		return byteorder.BEUint64(q[:])
   487  	}
   488  	return byteorder.LEUint64(q[:])
   489  }
   490  

View as plain text