Takahiro Suzuki | 241c10e | 2020-12-17 20:17:57 +0900 | [diff] [blame^] | 1 | // Copyright 2018 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 detrand provides deterministically random functionality. |
| 6 | // |
| 7 | // The pseudo-randomness of these functions is seeded by the program binary |
| 8 | // itself and guarantees that the output does not change within a program, |
| 9 | // while ensuring that the output is unstable across different builds. |
| 10 | package detrand |
| 11 | |
| 12 | import ( |
| 13 | "encoding/binary" |
| 14 | "hash/fnv" |
| 15 | "os" |
| 16 | ) |
| 17 | |
| 18 | // Disable disables detrand such that all functions returns the zero value. |
| 19 | // This function is not concurrent-safe and must be called during program init. |
| 20 | func Disable() { |
| 21 | randSeed = 0 |
| 22 | } |
| 23 | |
| 24 | // Bool returns a deterministically random boolean. |
| 25 | func Bool() bool { |
| 26 | return randSeed%2 == 1 |
| 27 | } |
| 28 | |
| 29 | // randSeed is a best-effort at an approximate hash of the Go binary. |
| 30 | var randSeed = binaryHash() |
| 31 | |
| 32 | func binaryHash() uint64 { |
| 33 | // Open the Go binary. |
| 34 | s, err := os.Executable() |
| 35 | if err != nil { |
| 36 | return 0 |
| 37 | } |
| 38 | f, err := os.Open(s) |
| 39 | if err != nil { |
| 40 | return 0 |
| 41 | } |
| 42 | defer f.Close() |
| 43 | |
| 44 | // Hash the size and several samples of the Go binary. |
| 45 | const numSamples = 8 |
| 46 | var buf [64]byte |
| 47 | h := fnv.New64() |
| 48 | fi, err := f.Stat() |
| 49 | if err != nil { |
| 50 | return 0 |
| 51 | } |
| 52 | binary.LittleEndian.PutUint64(buf[:8], uint64(fi.Size())) |
| 53 | h.Write(buf[:8]) |
| 54 | for i := int64(0); i < numSamples; i++ { |
| 55 | if _, err := f.ReadAt(buf[:], i*fi.Size()/numSamples); err != nil { |
| 56 | return 0 |
| 57 | } |
| 58 | h.Write(buf[:]) |
| 59 | } |
| 60 | return h.Sum64() |
| 61 | } |