| 1 | // Copyright 2010-2025 Chris Spiegel. |
| 2 | // |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | |
| 5 | #include <cerrno> |
| 6 | #include <chrono> |
| 7 | #include <climits> |
| 8 | #include <cstring> |
| 9 | #include <fstream> |
| 10 | #include <memory> |
| 11 | |
| 12 | #include "random.h" |
| 13 | #include "iff.h" |
| 14 | #include "io.h" |
| 15 | #include "options.h" |
| 16 | #include "process.h" |
| 17 | #include "stash.h" |
| 18 | #include "types.h" |
| 19 | #include "util.h" |
| 20 | #include "zterp.h" |
| 21 | |
| 22 | // The random number generator can be in either a random or predictable |
| 23 | // state. The predictable state always uses a PRNG with a seed provided |
| 24 | // by the game. The random state uses either a PRNG or a random device |
| 25 | // file. If no device file is used, a seed comes either from the user or |
| 26 | // from the current time. |
| 27 | // |
| 28 | // In predictable mode, autosaves include the current state of the PRNG |
| 29 | // so autorestores can pick up right where they left off. In random |
| 30 | // mode, the state is not stored. |
| 31 | // |
| 32 | // In other saves (normal and meta), the state of the PRNG is never |
| 33 | // stored. Doing so portably would be impossible since different |
| 34 | // interpreters use different PRNGs, and interpreters may even be using |
| 35 | // non-deterministic RNGs, e.g. /dev/urandom on Linux. Even if a private |
| 36 | // chunk were used (such as that used for autosaves), Infocom never |
| 37 | // intended for seeds to be stored anyway: per the EZIP documentation: |
| 38 | // “The seed for RANDOM should not be saved or restored”. |
| 39 | // |
| 40 | // This implementation is actually at odds with Infocom’s EZIP |
| 41 | // documentation, which is at odds with the standard’s recommendation |
| 42 | // (or rather the other way around: the standard is at odds with |
| 43 | // Infocom). Infocom mandates that predictable mode generate a sequence |
| 44 | // of numbers from 1 to S, where S is the provided seed value. The |
| 45 | // standard recommends this but only for values of S less than 1000. |
| 46 | // Here a PRNG is always used, which is what ZVM also does on the |
| 47 | // recommendation of Andrew Plotkin: |
| 48 | // https://intfiction.org/t/z-machine-rng/7298 |
| 49 | static enum class Mode { |
| 50 | Random, |
| 51 | Predictable, |
| 52 | } mode = Mode::Random; |
| 53 | |
| 54 | class Xorshift32 { |
| 55 | public: |
| 56 | void srand(uint32_t s) { |
| 57 | if (s == 0) { |
| 58 | s = 1; |
| 59 | } |
| 60 | |
| 61 | m_state = s; |
| 62 | } |
| 63 | |
| 64 | uint32_t rand() { |
| 65 | m_state ^= m_state << 13; |
| 66 | m_state ^= m_state >> 17; |
| 67 | m_state ^= m_state << 5; |
| 68 | |
| 69 | return m_state; |
| 70 | } |
| 71 | |
| 72 | uint32_t state() const { |
| 73 | return m_state; |
| 74 | } |
| 75 | |
| 76 | void set_state(uint32_t state) { |
| 77 | if (state != 0) { |
| 78 | m_state = state; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | private: |
| 83 | uint32_t m_state = 1; |
| 84 | }; |
| 85 | |
| 86 | static Xorshift32 xorshift32; |
| 87 | |
| 88 | static std::ifstream random_file; |
| 89 | |
| 90 | static uint32_t zterp_rand() |
| 91 | { |
| 92 | if (mode == Mode::Random && random_file.is_open()) { |
| 93 | uint32_t value; |
| 94 | |
| 95 | if (random_file.read(reinterpret_cast<char *>(&value), sizeof value)) { |
| 96 | return value; |
| 97 | } else { |
| 98 | warning("error reading from %s: switching to PRNG", options.random_device->c_str()); |
| 99 | random_file.close(); |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | return xorshift32.rand(); |
| 104 | } |
| 105 | |
| 106 | // Called with 0, set the PRNG to random mode. Then seed it with either |
| 107 | // a) a user-provided seed (via -z) if available, or |
| 108 | // b) a seed derived from a hash of the constituent bytes of the value |
| 109 | // returned by time(nullptr) |
| 110 | // |
| 111 | // Otherwise, set the PRNG to predictable mode and seed with the |
| 112 | // provided value. |
| 113 | static void seed_random(uint32_t seed) |
| 114 | { |
| 115 | if (seed == 0) { |
| 116 | mode = Mode::Random; |
| 117 | |
| 118 | if (options.random_seed == nullptr) { |
| 119 | auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); |
| 120 | const unsigned char *p = reinterpret_cast<const unsigned char *>(&t); |
| 121 | uint32_t s = 0; |
| 122 | |
| 123 | // time_t hashing based on code by Lawrence Kirby. |
| 124 | for (size_t i = 0; i < sizeof t; i++) { |
| 125 | s = s * (UCHAR_MAX + 2U) + p[i]; |
| 126 | } |
| 127 | |
| 128 | xorshift32.srand(s); |
| 129 | } else { |
| 130 | xorshift32.srand(*options.random_seed); |
| 131 | } |
| 132 | } else { |
| 133 | mode = Mode::Predictable; |
| 134 | |
| 135 | xorshift32.srand(seed); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | enum class RNGType { |
| 140 | Xorshift32 = 0, |
| 141 | }; |
| 142 | |
| 143 | IFF::TypeID random_write_rand(IO &io) |
| 144 | { |
| 145 | if (mode == Mode::Random) { |
| 146 | return IFF::TypeID(); |
| 147 | } |
| 148 | |
| 149 | io.write16(static_cast<uint16_t>(RNGType::Xorshift32)); |
| 150 | io.write32(xorshift32.state()); |
| 151 | |
| 152 | return IFF::TypeID("Rand"); |
| 153 | } |
| 154 | |
| 155 | void random_read_rand(IO &io) |
| 156 | { |
| 157 | uint16_t rng_type; |
| 158 | uint32_t state; |
| 159 | |
| 160 | try { |
| 161 | rng_type = io.read16(); |
| 162 | state = io.read32(); |
| 163 | } catch (const IO::IOError &) { |
| 164 | return; |
| 165 | } |
| 166 | |
| 167 | if (rng_type == static_cast<uint16_t>(RNGType::Xorshift32) && state != 0) { |
| 168 | xorshift32.set_state(state); |
| 169 | mode = Mode::Predictable; |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | class RandomStasher : public Stasher { |
| 174 | public: |
| 175 | void backup() override { |
| 176 | m_mode = mode; |
| 177 | m_xorshift32 = xorshift32; |
| 178 | } |
| 179 | |
| 180 | bool restore() override { |
| 181 | mode = m_mode; |
| 182 | xorshift32 = m_xorshift32; |
| 183 | |
| 184 | return true; |
| 185 | } |
| 186 | |
| 187 | void free() override { |
| 188 | } |
| 189 | |
| 190 | private: |
| 191 | Mode m_mode = Mode::Random; |
| 192 | Xorshift32 m_xorshift32; |
| 193 | }; |
| 194 | |
| 195 | void init_random(bool first_run) |
| 196 | { |
| 197 | seed_random(0); |
| 198 | |
| 199 | if (first_run) { |
| 200 | if (options.random_device != nullptr && !random_file.is_open()) { |
| 201 | random_file.open(options.random_device->c_str(), std::ifstream::binary); |
| 202 | if (!random_file.is_open()) { |
| 203 | warning("unable to open random device %s: %s\n", options.random_device->c_str(), std::strerror(errno)); |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | stash_register(std::make_unique<RandomStasher>()); |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | void zrandom() |
| 212 | { |
| 213 | int16_t v = as_signed(zargs[0]); |
| 214 | |
| 215 | if (v <= 0) { |
| 216 | // Cast to long for the pathological case of -32768 and 16-bit |
| 217 | // int: 32768 isn’t representable in an int, so -v is undefined. |
| 218 | seed_random(-static_cast<long>(v)); |
| 219 | store(0); |
| 220 | } else { |
| 221 | store(zterp_rand() % zargs[0] + 1); |
| 222 | } |
| 223 | } |