| 1 | // Copyright 2010-2024 Chris Spiegel. |
| 2 | // |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | |
| 5 | #include <algorithm> |
| 6 | #include <array> |
| 7 | #include <chrono> |
| 8 | #include <cstdio> |
| 9 | #include <cstring> |
| 10 | #include <ctime> |
| 11 | #include <deque> |
| 12 | #include <iomanip> |
| 13 | #include <locale> |
| 14 | #include <memory> |
| 15 | #include <new> |
| 16 | #include <sstream> |
| 17 | #include <string> |
| 18 | #include <unordered_map> |
| 19 | #include <utility> |
| 20 | #include <vector> |
| 21 | |
| 22 | #include "stack.h" |
| 23 | #include "branch.h" |
| 24 | #include "iff.h" |
| 25 | #include "io.h" |
| 26 | #include "memory.h" |
| 27 | #include "meta.h" |
| 28 | #include "options.h" |
| 29 | #include "osdep.h" |
| 30 | #include "process.h" |
| 31 | #include "random.h" |
| 32 | #include "screen.h" |
| 33 | #include "stash.h" |
| 34 | #include "types.h" |
| 35 | #include "util.h" |
| 36 | #include "zterp.h" |
| 37 | |
| 38 | #ifdef ZTERP_GLK |
| 39 | #include "glkautosave.h" |
| 40 | #endif |
| 41 | |
| 42 | using namespace std::literals; |
| 43 | |
| 44 | enum class StoreWhere { |
| 45 | Variable, |
| 46 | None, |
| 47 | Push, |
| 48 | }; |
| 49 | |
| 50 | struct CallFrame { |
| 51 | uint32_t pc; |
| 52 | uint16_t *sp; |
| 53 | uint8_t nlocals; |
| 54 | uint8_t nargs; |
| 55 | uint16_t where; |
| 56 | std::array<uint16_t, 15> locals; |
| 57 | }; |
| 58 | |
| 59 | static CallFrame *frames; |
| 60 | static CallFrame *fp; |
| 61 | |
| 62 | #define BASE_OF_FRAMES frames |
| 63 | static CallFrame *TOP_OF_FRAMES; |
| 64 | #define CURRENT_FRAME (fp - 1) |
| 65 | #define NFRAMES (static_cast<long>(fp - frames)) |
| 66 | |
| 67 | static uint16_t *stack; |
| 68 | static uint16_t *sp; |
| 69 | |
| 70 | #define BASE_OF_STACK stack |
| 71 | static uint16_t *TOP_OF_STACK; |
| 72 | |
| 73 | static void push_stack(uint16_t n) |
| 74 | { |
| 75 | ZASSERT(sp != TOP_OF_STACK, "stack overflow"); |
| 76 | *sp++ = n; |
| 77 | } |
| 78 | |
| 79 | static uint16_t pop_stack() |
| 80 | { |
| 81 | ZASSERT(sp > CURRENT_FRAME->sp, "stack underflow"); |
| 82 | return *--sp; |
| 83 | } |
| 84 | |
| 85 | struct SaveState { |
| 86 | public: |
| 87 | SaveType savetype; |
| 88 | std::vector<uint8_t> quetzal; |
| 89 | std::string desc; |
| 90 | |
| 91 | SaveState(SaveType savetype_, const char *desc_, std::vector<uint8_t> quetzal_) : |
| 92 | savetype(savetype_), |
| 93 | quetzal(std::move(quetzal_)), |
| 94 | desc(desc_ == nullptr ? format_time() : desc_) |
| 95 | { |
| 96 | } |
| 97 | |
| 98 | private: |
| 99 | static std::string format_time() { |
| 100 | auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); |
| 101 | auto *lt = std::localtime(&now); |
| 102 | |
| 103 | if (lt == nullptr) { |
| 104 | return "<no time information>"; |
| 105 | } else { |
| 106 | std::ostringstream formatted_time; |
| 107 | |
| 108 | try { |
| 109 | formatted_time.imbue(std::locale("")); |
| 110 | } catch (...) { |
| 111 | // If the locale is invalid, don’t worry about it. |
| 112 | } |
| 113 | |
| 114 | formatted_time << std::put_time(lt, "%c"); |
| 115 | |
| 116 | return formatted_time.str(); |
| 117 | } |
| 118 | } |
| 119 | }; |
| 120 | |
| 121 | struct SaveStack { |
| 122 | std::deque<SaveState> states; |
| 123 | unsigned long max = 0; |
| 124 | |
| 125 | void push(SaveState state) { |
| 126 | // If the maximum number has been reached, drop the last element. |
| 127 | // |
| 128 | // Small note: calling @restore_undo twice should succeed both times |
| 129 | // if @save_undo was called twice (or three, four, etc. times). If |
| 130 | // there aren’t enough slots, however, @restore_undo calls that should |
| 131 | // work will fail because the earlier save states will have been |
| 132 | // dropped. This can easily be seen by running TerpEtude’s undo test |
| 133 | // with the slot count set to 1. By default, the number of save slots |
| 134 | // is 100, so this will not be an issue unless a game goes out of its |
| 135 | // way to cause problems. |
| 136 | if (max > 0 && states.size() == max) { |
| 137 | states.pop_back(); |
| 138 | } |
| 139 | |
| 140 | states.push_front(std::move(state)); |
| 141 | } |
| 142 | |
| 143 | // Remove the first “n” saves from the specified stack. If there are |
| 144 | // not enough saves available, remove all saves. |
| 145 | void trim_saves(size_t n) { |
| 146 | states.erase(states.begin(), n > states.size() ? states.end() : states.begin() + n); |
| 147 | states.shrink_to_fit(); |
| 148 | } |
| 149 | |
| 150 | void clear() { |
| 151 | states.clear(); |
| 152 | states.shrink_to_fit(); |
| 153 | } |
| 154 | }; |
| 155 | static std::unordered_map<SaveStackType, SaveStack, EnumClassHash> save_stacks; |
| 156 | |
| 157 | bool seen_save_undo = false; |
| 158 | |
| 159 | static void add_frame(uint32_t pc_, uint16_t *sp_, uint8_t nlocals, uint8_t nargs, uint16_t where) |
| 160 | { |
| 161 | ZASSERT(fp != TOP_OF_FRAMES, "call stack too deep: %ld", NFRAMES + 1); |
| 162 | |
| 163 | fp->pc = pc_; |
| 164 | fp->sp = sp_; |
| 165 | fp->nlocals = nlocals; |
| 166 | fp->nargs = nargs; |
| 167 | fp->where = where; |
| 168 | |
| 169 | fp++; |
| 170 | } |
| 171 | |
| 172 | uint16_t variable(uint16_t var) |
| 173 | { |
| 174 | ZASSERT(var < 0x100, "unable to decode variable %u", static_cast<unsigned int>(var)); |
| 175 | |
| 176 | if (var == 0) { // Stack |
| 177 | return pop_stack(); |
| 178 | } else if (var <= 0x0f) { // Locals |
| 179 | ZASSERT(var <= CURRENT_FRAME->nlocals, "attempting to read from nonexistent local variable %d: routine has %d", static_cast<int>(var), CURRENT_FRAME->nlocals); |
| 180 | return CURRENT_FRAME->locals[var - 1]; |
| 181 | } else if (var <= 0xff) { // Globals |
| 182 | var -= 0x10; |
| 183 | return word(header.globals + (var * 2)); |
| 184 | } |
| 185 | |
| 186 | // This is an “impossible” situation (ie, the game did something wrong). |
| 187 | // It will be caught above if safety checks are turned on, but if they |
| 188 | // are not, do what we can: lie. |
| 189 | return -1; |
| 190 | } |
| 191 | |
| 192 | void store_variable(uint16_t var, uint16_t n) |
| 193 | { |
| 194 | ZASSERT(var < 0x100, "unable to decode variable %u", static_cast<unsigned int>(var)); |
| 195 | |
| 196 | if (var == 0) { // Stack |
| 197 | push_stack(n); |
| 198 | } else if (var <= 0x0f) { // Locals |
| 199 | ZASSERT(var <= CURRENT_FRAME->nlocals, "attempting to store to nonexistent local variable %d: routine has %d", static_cast<int>(var), CURRENT_FRAME->nlocals); |
| 200 | CURRENT_FRAME->locals[var - 1] = n; |
| 201 | } else if (var <= 0xff) { // Globals |
| 202 | var -= 0x10; |
| 203 | store_word(header.globals + (var * 2), n); |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | static uint16_t &stack_top_element() |
| 208 | { |
| 209 | ZASSERT(sp > CURRENT_FRAME->sp, "stack underflow"); |
| 210 | |
| 211 | return sp[-1]; |
| 212 | } |
| 213 | |
| 214 | void zpush() |
| 215 | { |
| 216 | push_stack(zargs[0]); |
| 217 | } |
| 218 | |
| 219 | void zpull() |
| 220 | { |
| 221 | uint16_t v; |
| 222 | |
| 223 | if (zversion != 6) { |
| 224 | v = pop_stack(); |
| 225 | |
| 226 | // The z-spec 1.1 requires indirect variable references to the stack not to push/pop |
| 227 | if (zargs[0] == 0) { |
| 228 | stack_top_element() = v; |
| 229 | } else { |
| 230 | store_variable(zargs[0], v); |
| 231 | } |
| 232 | } else { |
| 233 | if (znargs == 0) { |
| 234 | v = pop_stack(); |
| 235 | } else { |
| 236 | uint16_t slots = user_word(zargs[0]) + 1; |
| 237 | |
| 238 | ZASSERT(slots != 0, "user stack counter overflow"); |
| 239 | ZASSERT(zargs[0] + (2UL * slots) <= header.static_end - 2, "user stack access out of bounds"); |
| 240 | |
| 241 | v = user_word(zargs[0] + (2 * slots)); |
| 242 | |
| 243 | user_store_word(zargs[0], slots); |
| 244 | } |
| 245 | |
| 246 | store(v); |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | void zload() |
| 251 | { |
| 252 | // The z-spec 1.1 requires indirect variable references to the stack not to push/pop |
| 253 | if (zargs[0] == 0) { |
| 254 | store(stack_top_element()); |
| 255 | } else { |
| 256 | store(variable(zargs[0])); |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | void zstore() |
| 261 | { |
| 262 | // The z-spec 1.1 requires indirect variable references to the stack not to push/pop |
| 263 | if (zargs[0] == 0) { |
| 264 | stack_top_element() = zargs[1]; |
| 265 | } else { |
| 266 | store_variable(zargs[0], zargs[1]); |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | static void call(StoreWhere store_where) |
| 271 | { |
| 272 | uint16_t where; |
| 273 | |
| 274 | if (zargs[0] == 0) { |
| 275 | // call(StoreWhere::Push) should never happen if zargs[0] is 0. |
| 276 | if (store_where == StoreWhere::Variable) { |
| 277 | store(0); |
| 278 | } |
| 279 | return; |
| 280 | } |
| 281 | |
| 282 | uint32_t jmp_to = unpack_routine(zargs[0]); |
| 283 | ZASSERT(jmp_to < memory_size - 1, "call to invalid address 0x%lx", static_cast<unsigned long>(jmp_to)); |
| 284 | |
| 285 | uint8_t nlocals = byte(jmp_to++); |
| 286 | ZASSERT(nlocals <= 15, "too many (%d) locals at 0x%lx", nlocals, static_cast<unsigned long>(jmp_to) - 1); |
| 287 | |
| 288 | if (zversion <= 4) { |
| 289 | ZASSERT(jmp_to + (nlocals * 2) < memory_size, "call to invalid address 0x%lx", static_cast<unsigned long>(jmp_to)); |
| 290 | } |
| 291 | |
| 292 | switch (store_where) { |
| 293 | case StoreWhere::Variable: where = byte(pc++); break; // Where to store return value |
| 294 | case StoreWhere::None: where = 0xff + 1; break; // Or a tag meaning no return value |
| 295 | case StoreWhere::Push: where = 0xff + 2; break; // Or a tag meaning push the return value |
| 296 | default: die("internal error: invalid store_where value (%d)", static_cast<int>(store_where)); |
| 297 | } |
| 298 | |
| 299 | add_frame(pc, sp, nlocals, znargs - 1, where); |
| 300 | |
| 301 | for (int i = 0; i < nlocals; i++) { |
| 302 | if (i < znargs - 1) { |
| 303 | CURRENT_FRAME->locals[i] = zargs[i + 1]; |
| 304 | } else { |
| 305 | if (zversion <= 4) { |
| 306 | CURRENT_FRAME->locals[i] = word(jmp_to + (2 * i)); |
| 307 | } else { |
| 308 | CURRENT_FRAME->locals[i] = 0; |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | // Take care of locals! |
| 314 | if (zversion <= 4) { |
| 315 | jmp_to += nlocals * 2; |
| 316 | } |
| 317 | |
| 318 | pc = jmp_to; |
| 319 | } |
| 320 | |
| 321 | void start_v6() |
| 322 | { |
| 323 | call(StoreWhere::None); |
| 324 | } |
| 325 | |
| 326 | uint16_t internal_call(uint16_t routine, std::vector<uint16_t> args) |
| 327 | { |
| 328 | auto saved_zargs = zargs; |
| 329 | auto saved_znargs = znargs; |
| 330 | |
| 331 | ZASSERT(args.size() < 8, "internal error: too many arguments"); |
| 332 | |
| 333 | znargs = 1 + args.size(); |
| 334 | zargs[0] = routine; |
| 335 | std::copy(args.begin(), args.end(), &zargs[1]); |
| 336 | call(StoreWhere::Push); |
| 337 | |
| 338 | process_instructions(); |
| 339 | |
| 340 | zargs = saved_zargs; |
| 341 | znargs = saved_znargs; |
| 342 | |
| 343 | return pop_stack(); |
| 344 | } |
| 345 | |
| 346 | void zcall_store() |
| 347 | { |
| 348 | call(StoreWhere::Variable); |
| 349 | } |
| 350 | void zcall_nostore() |
| 351 | { |
| 352 | call(StoreWhere::None); |
| 353 | } |
| 354 | |
| 355 | void do_return(uint16_t retval) |
| 356 | { |
| 357 | ZASSERT(NFRAMES > 1, "return attempted outside of a function"); |
| 358 | |
| 359 | pc = CURRENT_FRAME->pc; |
| 360 | sp = CURRENT_FRAME->sp; |
| 361 | uint16_t where = CURRENT_FRAME->where; |
| 362 | fp--; |
| 363 | |
| 364 | if (where <= 0xff) { |
| 365 | store_variable(where, retval); |
| 366 | } else if (where == 0xff + 2) { |
| 367 | push_stack(retval); |
| 368 | throw Operation::Return(); |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | void zret_popped() |
| 373 | { |
| 374 | do_return(pop_stack()); |
| 375 | } |
| 376 | |
| 377 | void zpop() |
| 378 | { |
| 379 | pop_stack(); |
| 380 | } |
| 381 | |
| 382 | void zcatch() |
| 383 | { |
| 384 | ZASSERT(zversion == 6 || NFRAMES > 1, "@catch called outside of a function"); |
| 385 | |
| 386 | // Must account for the dummy frame in non-V6 stories. |
| 387 | store(zversion == 6 ? NFRAMES : NFRAMES - 1); |
| 388 | } |
| 389 | |
| 390 | void zthrow() |
| 391 | { |
| 392 | // As with @catch, account for the dummy frame. |
| 393 | if (zversion != 6) { |
| 394 | ZASSERT(zargs[1] != 0xffff, "unwinding too far"); |
| 395 | zargs[1]++; |
| 396 | } |
| 397 | |
| 398 | ZASSERT(zversion == 6 || NFRAMES > 1, "@throw called outside of a function"); |
| 399 | ZASSERT(zargs[1] <= NFRAMES, "unwinding too far"); |
| 400 | |
| 401 | fp = BASE_OF_FRAMES + zargs[1]; |
| 402 | |
| 403 | do_return(zargs[0]); |
| 404 | } |
| 405 | |
| 406 | void zret() |
| 407 | { |
| 408 | do_return(zargs[0]); |
| 409 | } |
| 410 | |
| 411 | void zrtrue() |
| 412 | { |
| 413 | do_return(1); |
| 414 | } |
| 415 | |
| 416 | void zrfalse() |
| 417 | { |
| 418 | do_return(0); |
| 419 | } |
| 420 | |
| 421 | void zcheck_arg_count() |
| 422 | { |
| 423 | branch_if(zargs[0] <= CURRENT_FRAME->nargs); |
| 424 | } |
| 425 | |
| 426 | #ifndef ZTERP_NO_V6 |
| 427 | void zpop_stack() |
| 428 | { |
| 429 | if (znargs == 1) { |
| 430 | for (uint16_t i = 0; i < zargs[0]; i++) { |
| 431 | pop_stack(); |
| 432 | } |
| 433 | } else { |
| 434 | user_store_word(zargs[1], user_word(zargs[1]) + zargs[0]); |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | void zpush_stack() |
| 439 | { |
| 440 | uint16_t slots = user_word(zargs[1]); |
| 441 | |
| 442 | if (slots == 0) { |
| 443 | branch_if(false); |
| 444 | return; |
| 445 | } |
| 446 | |
| 447 | user_store_word(zargs[1] + (2 * slots), zargs[0]); |
| 448 | user_store_word(zargs[1], slots - 1); |
| 449 | |
| 450 | branch_if(true); |
| 451 | } |
| 452 | #endif |
| 453 | |
| 454 | // Compress dynamic memory according to Quetzal. On failure, |
| 455 | // std::bad_alloc is thrown. |
| 456 | static std::vector<uint8_t> compress_memory() |
| 457 | { |
| 458 | long i = 0; |
| 459 | std::vector<uint8_t> compressed; |
| 460 | |
| 461 | compressed.reserve(header.static_start); |
| 462 | |
| 463 | while (true) { |
| 464 | long run = i; |
| 465 | |
| 466 | // Count zeroes. Stop counting when: |
| 467 | // • The end of dynamic memory is reached, or |
| 468 | // • A non-zero value is found |
| 469 | while (i < header.static_start && (byte(i) ^ dynamic_memory[i]) == 0) { |
| 470 | i++; |
| 471 | } |
| 472 | |
| 473 | run = i - run; |
| 474 | |
| 475 | // A run of zeroes at the end need not be written. |
| 476 | if (i == header.static_start) { |
| 477 | break; |
| 478 | } |
| 479 | |
| 480 | // If there has been a run of zeroes, write them out |
| 481 | // 256 at a time. |
| 482 | while (run > 0) { |
| 483 | compressed.push_back(0); |
| 484 | compressed.push_back(run > 256 ? 255 : run - 1); |
| 485 | run -= 256; |
| 486 | } |
| 487 | |
| 488 | // The current byte differs from the story, so write it. |
| 489 | compressed.push_back(byte(i) ^ dynamic_memory[i]); |
| 490 | |
| 491 | i++; |
| 492 | } |
| 493 | |
| 494 | return compressed; |
| 495 | } |
| 496 | |
| 497 | // Reverse of the above function. |
| 498 | static bool uncompress_memory(const uint8_t *compressed, uint32_t size) |
| 499 | { |
| 500 | uint32_t memory_index = 0; |
| 501 | |
| 502 | std::copy(dynamic_memory.begin(), dynamic_memory.begin() + header.static_start, memory.begin()); |
| 503 | |
| 504 | for (uint32_t i = 0; i < size; i++) { |
| 505 | if (compressed[i] != 0) { |
| 506 | if (memory_index == header.static_start) { |
| 507 | return false; |
| 508 | } |
| 509 | store_byte(memory_index, byte(memory_index) ^ compressed[i]); |
| 510 | memory_index++; |
| 511 | } else { |
| 512 | if (++i == size) { |
| 513 | return false; |
| 514 | } |
| 515 | |
| 516 | if (memory_index + (compressed[i] + 1) > header.static_start) { |
| 517 | return false; |
| 518 | } |
| 519 | memory_index += (compressed[i] + 1); |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | return true; |
| 524 | } |
| 525 | |
| 526 | static IFF::TypeID write_ifhd(IO &savefile) |
| 527 | { |
| 528 | savefile.write16(header.release); |
| 529 | savefile.write_exact(header.serial, sizeof header.serial); |
| 530 | savefile.write16(header.checksum); |
| 531 | savefile.write8((pc >> 16) & 0xff); |
| 532 | savefile.write8((pc >> 8) & 0xff); |
| 533 | savefile.write8((pc >> 0) & 0xff); |
| 534 | |
| 535 | return IFF::TypeID("IFhd"); |
| 536 | } |
| 537 | |
| 538 | // Store the filename in an IntD chunk. |
| 539 | static IFF::TypeID write_intd(IO &savefile) |
| 540 | { |
| 541 | savefile.write_exact("UNIX", 4); |
| 542 | savefile.write8(0x02); |
| 543 | savefile.write8(0); |
| 544 | savefile.write16(0); |
| 545 | savefile.write_exact(" ", 4); |
| 546 | savefile.write_exact(game_file.c_str(), game_file.size()); |
| 547 | |
| 548 | return IFF::TypeID("IntD"); |
| 549 | } |
| 550 | |
| 551 | static IFF::TypeID write_mem(IO &savefile) |
| 552 | { |
| 553 | std::vector<uint8_t> compressed; |
| 554 | uint32_t memsize = header.static_start; |
| 555 | const uint8_t *mem = memory.data(); |
| 556 | IFF::TypeID type = IFF::TypeID("UMem"); |
| 557 | |
| 558 | try { |
| 559 | compressed = compress_memory(); |
| 560 | // It is possible for the compressed memory size to be larger than |
| 561 | // uncompressed; in this case, don’t use compressed memory. |
| 562 | if (compressed.size() < header.static_start) { |
| 563 | mem = compressed.data(); |
| 564 | memsize = compressed.size(); |
| 565 | type = IFF::TypeID("CMem"); |
| 566 | } |
| 567 | } catch (const std::bad_alloc &) { |
| 568 | } |
| 569 | |
| 570 | savefile.write_exact(mem, memsize); |
| 571 | |
| 572 | return type; |
| 573 | } |
| 574 | |
| 575 | // Quetzal save/restore functions. |
| 576 | static IFF::TypeID write_stks(IO &savefile) |
| 577 | { |
| 578 | // Add one more “fake” call frame with just enough information to |
| 579 | // calculate the evaluation stack used by the current routine. |
| 580 | fp->sp = sp; |
| 581 | for (CallFrame *p = BASE_OF_FRAMES; p != fp; p++) { |
| 582 | savefile.write8((p->pc >> 16) & 0xff); |
| 583 | savefile.write8((p->pc >> 8) & 0xff); |
| 584 | savefile.write8((p->pc >> 0) & 0xff); |
| 585 | |
| 586 | uint8_t flags = p->nlocals; |
| 587 | if (p->where > 0xff) { |
| 588 | flags |= 0x10; |
| 589 | } |
| 590 | savefile.write8(flags); |
| 591 | |
| 592 | if (p->where > 0xff) { |
| 593 | savefile.write8(0); |
| 594 | } else { |
| 595 | savefile.write8(p->where); |
| 596 | } |
| 597 | |
| 598 | savefile.write8((1U << p->nargs) - 1); |
| 599 | |
| 600 | // number of words of evaluation stack used |
| 601 | savefile.write16((p + 1)->sp - p->sp); |
| 602 | |
| 603 | // local variables |
| 604 | for (int i = 0; i < p->nlocals; i++) { |
| 605 | savefile.write16(p->locals[i]); |
| 606 | } |
| 607 | |
| 608 | // evaluation stack |
| 609 | for (std::ptrdiff_t i = 0; i < (p + 1)->sp - p->sp; i++) { |
| 610 | savefile.write16(p->sp[i]); |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | return IFF::TypeID("Stks"); |
| 615 | } |
| 616 | |
| 617 | static IFF::TypeID write_anno(IO &savefile) |
| 618 | { |
| 619 | std::string anno = "Interpreter: Bocfel "s + ZTERP_VERSION; |
| 620 | savefile.write_exact(anno.c_str(), anno.size()); |
| 621 | |
| 622 | return IFF::TypeID("ANNO"); |
| 623 | } |
| 624 | |
| 625 | static IFF::TypeID write_args(IO &savefile, SaveOpcode saveopcode) |
| 626 | { |
| 627 | savefile.write8(static_cast<uint8_t>(saveopcode)); |
| 628 | |
| 629 | for (int i = 0; i < znargs; i++) { |
| 630 | savefile.write16(zargs[i]); |
| 631 | } |
| 632 | |
| 633 | return IFF::TypeID("Args"); |
| 634 | } |
| 635 | |
| 636 | static void write_undo_msav(IO &savefile, SaveStackType type) |
| 637 | { |
| 638 | SaveStack &s = save_stacks[type]; |
| 639 | |
| 640 | savefile.write32(0); // Version |
| 641 | savefile.write32(s.states.size()); |
| 642 | |
| 643 | for (auto state = s.states.crbegin(); state != s.states.crend(); ++state) { |
| 644 | if (type == SaveStackType::Game) { |
| 645 | savefile.write8(static_cast<uint8_t>(state->savetype)); |
| 646 | } else if (type == SaveStackType::User) { |
| 647 | if (state->desc.empty()) { |
| 648 | savefile.write32(0); |
| 649 | } else { |
| 650 | savefile.write32(state->desc.size()); |
| 651 | savefile.write_exact(state->desc.c_str(), state->desc.size()); |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | savefile.write32(state->quetzal.size()); |
| 656 | savefile.write_exact(state->quetzal.data(), state->quetzal.size()); |
| 657 | } |
| 658 | } |
| 659 | |
| 660 | static IFF::TypeID write_undo(IO &savefile) |
| 661 | { |
| 662 | write_undo_msav(savefile, SaveStackType::Game); |
| 663 | |
| 664 | return IFF::TypeID("Undo"); |
| 665 | } |
| 666 | |
| 667 | static IFF::TypeID write_msav(IO &savefile) |
| 668 | { |
| 669 | write_undo_msav(savefile, SaveStackType::User); |
| 670 | |
| 671 | return IFF::TypeID("MSav"); |
| 672 | } |
| 673 | |
| 674 | template<typename... Types> |
| 675 | static void write_chunk(IO &io, IFF::TypeID (*writefunc)(IO &savefile, Types... args), Types... args) |
| 676 | { |
| 677 | long chunk_pos = io.tell(); |
| 678 | // Type and size, to be filled in below. |
| 679 | io.write32(0); |
| 680 | io.write32(0); |
| 681 | auto type = writefunc(io, args...); |
| 682 | if (type.empty()) { |
| 683 | io.seek(chunk_pos, IO::SeekFrom::Start); |
| 684 | return; |
| 685 | } |
| 686 | long end_pos = io.tell(); |
| 687 | long size = end_pos - chunk_pos - 8; |
| 688 | io.seek(chunk_pos, IO::SeekFrom::Start); |
| 689 | io.write32(type.val()); |
| 690 | io.write32(size); |
| 691 | io.seek(end_pos, IO::SeekFrom::Start); |
| 692 | if ((size & 1) == 1) { |
| 693 | io.write8(0); // padding |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | // Meta saves (generated by the interpreter) are based on Quetzal. The |
| 698 | // format of the save state is the same (that is, the IFhd, IntD, and |
| 699 | // CMem/UMem chunks are identical). The type of the save file itself is |
| 700 | // BFZS instead of IFZS to prevent the files from being used by a normal |
| 701 | // @restore (as they are not compatible). See Quetzal.md for a |
| 702 | // description of how BFZS differs from IFZS. |
| 703 | static bool save_quetzal(IO &savefile, SaveType savetype, SaveOpcode saveopcode, bool on_save_stack) |
| 704 | { |
| 705 | try { |
| 706 | bool is_bfzs = savetype == SaveType::Meta || savetype == SaveType::Autosave || savetype == SaveType::AutosaveLib; |
| 707 | |
| 708 | savefile.write_exact("FORM", 4); |
| 709 | savefile.write32(0); // to be filled in |
| 710 | savefile.write_exact(is_bfzs ? "BFZS" : "IFZS", 4); |
| 711 | |
| 712 | write_chunk(savefile, write_ifhd); |
| 713 | write_chunk(savefile, write_intd); |
| 714 | write_chunk(savefile, write_mem); |
| 715 | write_chunk(savefile, write_stks); |
| 716 | write_chunk(savefile, write_anno); |
| 717 | |
| 718 | // When saving to a stack (either for undo or for in-memory saves), |
| 719 | // don’t store history, persistent transcripts, or notes. History is |
| 720 | // pointless, since the user can see this history already. Persistent |
| 721 | // transcripts want to track what actually happened. If the user types |
| 722 | // UNDO, for example, that should be reflected in the transcript. And |
| 723 | // notes shouldn’t be cleared just because the user undid a turn; if a |
| 724 | // user doesn’t want the notes, he can delete them, but he can’t bring |
| 725 | // back notes that he never wanted deleted. |
| 726 | if (!on_save_stack) { |
| 727 | write_chunk(savefile, screen_write_bfhs); |
| 728 | write_chunk(savefile, screen_write_bfts); |
| 729 | write_chunk(savefile, meta_write_bfnt); |
| 730 | } |
| 731 | |
| 732 | // When restoring a meta save, @read will be called to bring the user |
| 733 | // back to the same place as the save occurred. While memory and the |
| 734 | // stack will be restored properly, the arguments to @read will not |
| 735 | // (as the normal Z-machine save/restore mechanism doesn’t need them: |
| 736 | // all restoring does is store or branch, using the location of the |
| 737 | // program counter after restore). If this is a meta save, store zargs |
| 738 | // so it can be restored before re-entering @read. |
| 739 | if (is_bfzs) { |
| 740 | write_chunk(savefile, write_args, saveopcode); |
| 741 | write_chunk(savefile, screen_write_scrn); |
| 742 | } |
| 743 | |
| 744 | if (savetype == SaveType::Autosave || savetype == SaveType::AutosaveLib) { |
| 745 | write_chunk(savefile, write_undo); |
| 746 | write_chunk(savefile, write_msav); |
| 747 | write_chunk(savefile, random_write_rand); |
| 748 | } |
| 749 | |
| 750 | long file_size = savefile.tell(); |
| 751 | savefile.seek(4, IO::SeekFrom::Start); |
| 752 | savefile.write32(file_size - 8); // entire file size minus 8 (FORM + size) |
| 753 | |
| 754 | return true; |
| 755 | } catch (const IO::IOError &) { |
| 756 | return false; |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | static void read_mem(IFF &iff) |
| 761 | { |
| 762 | uint32_t size; |
| 763 | |
| 764 | if (iff.find(IFF::TypeID("CMem"), size)) { |
| 765 | std::vector<uint8_t> buf; |
| 766 | |
| 767 | // Dynamic memory is 64KB, and a worst-case save should take up |
| 768 | // 1.5× that value, or 96KB. Simply double the 64KB to avoid |
| 769 | // potential edge-case problems. |
| 770 | if (size > 131072) { |
| 771 | throw RestoreError(fstring("reported CMem size too large (%lu bytes)", static_cast<unsigned long>(size))); |
| 772 | } |
| 773 | |
| 774 | if (size > 0) { |
| 775 | try { |
| 776 | buf.resize(size); |
| 777 | iff.io()->read_exact(buf.data(), size); |
| 778 | } catch (const std::bad_alloc &) { |
| 779 | throw RestoreError("unable to allocate memory for CMem"); |
| 780 | } catch (const IO::IOError &) { |
| 781 | throw RestoreError("unexpected eof reading compressed memory"); |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | if (!uncompress_memory(buf.data(), size)) { |
| 786 | throw RestoreError("memory cannot be uncompressed"); |
| 787 | } |
| 788 | } else if (iff.find(IFF::TypeID("UMem"), size)) { |
| 789 | if (size != header.static_start) { |
| 790 | throw RestoreError("memory size mismatch"); |
| 791 | } |
| 792 | try { |
| 793 | iff.io()->read_exact(memory.data(), header.static_start); |
| 794 | } catch (const IO::OpenError &) { |
| 795 | throw RestoreError("unexpected eof reading memory"); |
| 796 | } |
| 797 | } else { |
| 798 | throw RestoreError("no memory chunk found"); |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | static void read_stks(IFF &iff) |
| 803 | { |
| 804 | uint32_t size, n = 0, frameno = 0; |
| 805 | |
| 806 | if (!iff.find(IFF::TypeID("Stks"), size)) { |
| 807 | throw RestoreError("no stacks chunk found"); |
| 808 | } |
| 809 | if (size == 0) { |
| 810 | throw RestoreError("empty stacks chunk"); |
| 811 | } |
| 812 | |
| 813 | sp = BASE_OF_STACK; |
| 814 | fp = BASE_OF_FRAMES; |
| 815 | |
| 816 | while (n < size) { |
| 817 | uint8_t frame[8]; |
| 818 | uint8_t nargs = 0; |
| 819 | |
| 820 | try { |
| 821 | iff.io()->read_exact(frame, sizeof frame); |
| 822 | } catch (const IO::IOError &) { |
| 823 | throw RestoreError("unexpected eof reading stack frame"); |
| 824 | } |
| 825 | n += sizeof frame; |
| 826 | |
| 827 | uint8_t nlocals = frame[3] & 0xf; |
| 828 | uint16_t nstack = (frame[6] << 8) | frame[7]; |
| 829 | frame[5]++; |
| 830 | while ((frame[5] >>= 1) != 0) { |
| 831 | nargs++; |
| 832 | } |
| 833 | |
| 834 | uint32_t frame_pc = (static_cast<uint32_t>(frame[0]) << 16) | (static_cast<uint32_t>(frame[1]) << 8) | static_cast<uint32_t>(frame[2]); |
| 835 | if (frame_pc >= memory_size) { |
| 836 | throw RestoreError(fstring("frame #%lu pc out of range (0x%lx)", static_cast<unsigned long>(frameno), static_cast<unsigned long>(frame_pc))); |
| 837 | } |
| 838 | |
| 839 | add_frame(frame_pc, sp, nlocals, nargs, ((frame[3] & 0x10) == 0x10) ? 0xff + 1 : frame[4]); |
| 840 | |
| 841 | for (int i = 0; i < nlocals; i++) { |
| 842 | uint16_t l; |
| 843 | |
| 844 | try { |
| 845 | l = iff.io()->read16(); |
| 846 | } catch (const IO::IOError &) { |
| 847 | throw RestoreError("unexpected eof reading local variable"); |
| 848 | } |
| 849 | CURRENT_FRAME->locals[i] = l; |
| 850 | |
| 851 | n += sizeof l; |
| 852 | } |
| 853 | |
| 854 | for (uint16_t i = 0; i < nstack; i++) { |
| 855 | uint16_t s; |
| 856 | |
| 857 | try { |
| 858 | s = iff.io()->read16(); |
| 859 | } catch (const IO::IOError &) { |
| 860 | throw RestoreError("unexpected eof reading stack entry"); |
| 861 | } |
| 862 | push_stack(s); |
| 863 | |
| 864 | n += sizeof s; |
| 865 | } |
| 866 | |
| 867 | frameno++; |
| 868 | } |
| 869 | |
| 870 | if (n != size) { |
| 871 | throw RestoreError("stack size mismatch"); |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | static void read_args(IFF &iff, SaveOpcode &saveopcode) |
| 876 | { |
| 877 | uint32_t size; |
| 878 | uint8_t saveopcode_temp; |
| 879 | |
| 880 | if (!iff.find(IFF::TypeID("Args"), size)) { |
| 881 | throw RestoreError("no meta save Args chunk found"); |
| 882 | } |
| 883 | |
| 884 | try { |
| 885 | saveopcode_temp = iff.io()->read8(); |
| 886 | } catch (const IO::IOError &) { |
| 887 | throw RestoreError("short read in Args"); |
| 888 | } |
| 889 | |
| 890 | saveopcode = static_cast<SaveOpcode>(saveopcode_temp); |
| 891 | |
| 892 | size--; |
| 893 | |
| 894 | // @read takes between 1 and 4 operands, @read_char takes |
| 895 | // between 1 and 3. |
| 896 | // @save and @restore take none. (Args are possible in z5, |
| 897 | // but I haven’t implemented that yet.) |
| 898 | switch (saveopcode) { |
| 899 | case SaveOpcode::Read: |
| 900 | if (size != 2 && size != 4 && size != 6 && size != 8) { |
| 901 | throw RestoreError(fstring("invalid Args size for %d: %lu", static_cast<int>(saveopcode), static_cast<unsigned long>(size))); |
| 902 | } |
| 903 | break; |
| 904 | case SaveOpcode::ReadChar: |
| 905 | if (size != 2 && size != 4 && size != 6) { |
| 906 | throw RestoreError(fstring("invalid Args size for %d: %lu", static_cast<int>(saveopcode), static_cast<unsigned long>(size))); |
| 907 | } |
| 908 | break; |
| 909 | case SaveOpcode::Save: |
| 910 | case SaveOpcode::Restore: |
| 911 | if (size != 0) { |
| 912 | throw RestoreError(fstring("invalid Args size for %d: %lu", static_cast<int>(saveopcode), static_cast<unsigned long>(size))); |
| 913 | } |
| 914 | break; |
| 915 | default: |
| 916 | throw RestoreError(fstring("invalid save opcode: %d\n", static_cast<int>(saveopcode))); |
| 917 | } |
| 918 | |
| 919 | znargs = size / 2; |
| 920 | |
| 921 | for (int i = 0; i < znargs; i++) { |
| 922 | try { |
| 923 | zargs[i] = iff.io()->read16(); |
| 924 | } catch (const IO::IOError &) { |
| 925 | throw RestoreError("short read in Args"); |
| 926 | } |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | static void read_bfzs_specific(IFF &iff, SaveType savetype, SaveOpcode &saveopcode) |
| 931 | { |
| 932 | uint32_t size; |
| 933 | |
| 934 | read_args(iff, saveopcode); |
| 935 | |
| 936 | if ((savetype == SaveType::Autosave || savetype == SaveType::AutosaveLib) && |
| 937 | iff.find(IFF::TypeID("Rand"), size)) |
| 938 | { |
| 939 | random_read_rand(*iff.io()); |
| 940 | } |
| 941 | |
| 942 | if (iff.find(IFF::TypeID("Scrn"), size)) { |
| 943 | // Restoring cannot fail after this, because this function |
| 944 | // actively touches the screen (changing window |
| 945 | // configuration, etc). It would be possible to stash the |
| 946 | // screen state, but it would (potentially) be lossy: if the |
| 947 | // upper window is reduced, for example, there will be |
| 948 | // missing text once it is enlarged again. |
| 949 | try { |
| 950 | screen_read_scrn(*iff.io(), size); |
| 951 | } catch (const RestoreError &e) { |
| 952 | throw RestoreError(fstring("unable to parse screen state: %s", e.what())); |
| 953 | } |
| 954 | } else { |
| 955 | warning("no Scrn chunk in meta save"); |
| 956 | } |
| 957 | } |
| 958 | |
| 959 | // Any errors reading the Undo and MSav chunks are ignored. It’s better |
| 960 | // to have a valid autorestore with no undo/user saves than no |
| 961 | // autorestore at all. |
| 962 | static void read_undo_msav(IO &savefile, uint32_t size, SaveStackType type) |
| 963 | { |
| 964 | bool updated_seen_save_undo = seen_save_undo; |
| 965 | |
| 966 | try { |
| 967 | uint32_t version = savefile.read32(); |
| 968 | SaveStack &save_stack = save_stacks[type]; |
| 969 | size_t actual_size = 0; |
| 970 | if (version != 0) { |
| 971 | return; |
| 972 | } |
| 973 | uint32_t count = savefile.read32(); |
| 974 | |
| 975 | actual_size += 4 + 4; |
| 976 | |
| 977 | SaveStack temp = SaveStack(); |
| 978 | temp.max = save_stack.max; |
| 979 | save_stack.clear(); |
| 980 | |
| 981 | for (uint32_t i = 0; i < count; i++) { |
| 982 | uint8_t savetype = static_cast<uint8_t>(SaveType::Meta); |
| 983 | std::string desc; |
| 984 | std::vector<uint8_t> quetzal; |
| 985 | |
| 986 | if (type == SaveStackType::Game) { |
| 987 | savetype = savefile.read8(); |
| 988 | if (static_cast<SaveType>(savetype) != SaveType::Normal && static_cast<SaveType>(savetype) != SaveType::Meta) { |
| 989 | return; |
| 990 | } |
| 991 | |
| 992 | if (static_cast<SaveType>(savetype) == SaveType::Normal) { |
| 993 | updated_seen_save_undo = true; |
| 994 | } |
| 995 | |
| 996 | actual_size += 1; |
| 997 | } else if (type == SaveStackType::User) { |
| 998 | desc.resize(savefile.read32()); |
| 999 | savefile.read_exact(&desc[0], desc.size()); |
| 1000 | |
| 1001 | actual_size += 4 + desc.size(); |
| 1002 | } |
| 1003 | |
| 1004 | uint32_t quetzal_size = savefile.read32(); |
| 1005 | quetzal.resize(quetzal_size); |
| 1006 | savefile.read_exact(quetzal.data(), quetzal_size); |
| 1007 | |
| 1008 | if (count - i <= save_stack.max) { |
| 1009 | SaveState newstate(static_cast<SaveType>(savetype), desc.c_str(), quetzal); |
| 1010 | temp.push(std::move(newstate)); |
| 1011 | } |
| 1012 | |
| 1013 | actual_size += 4 + quetzal_size; |
| 1014 | } |
| 1015 | |
| 1016 | if (actual_size != size) { |
| 1017 | return; |
| 1018 | } |
| 1019 | |
| 1020 | save_stack = std::move(temp); |
| 1021 | } catch (const IO::IOError &) { |
| 1022 | return; |
| 1023 | } catch (const std::bad_alloc &) { |
| 1024 | return; |
| 1025 | } |
| 1026 | |
| 1027 | seen_save_undo = updated_seen_save_undo; |
| 1028 | } |
| 1029 | |
| 1030 | static void read_undo(IO &savefile, uint32_t size) |
| 1031 | { |
| 1032 | read_undo_msav(savefile, size, SaveStackType::Game); |
| 1033 | } |
| 1034 | |
| 1035 | static void read_msav(IO &savefile, uint32_t size) |
| 1036 | { |
| 1037 | read_undo_msav(savefile, size, SaveStackType::User); |
| 1038 | } |
| 1039 | |
| 1040 | // Earlier versions of Bocfel’s meta-saves neglected to take into |
| 1041 | // account the fact that the call to @read may have included arguments |
| 1042 | // pulled from the stack. Any such arguments are lost in an old-style |
| 1043 | // save, meaning the save file is not usable. However, most calls to |
| 1044 | // @read do not use the stack, so most old-style saves should work just |
| 1045 | // fine. This function is used to determine whether the @read |
| 1046 | // instruction used for the meta-save pulled from the stack. If so, the |
| 1047 | // restore will fail, but otherwise, it will proceed. |
| 1048 | static bool instruction_has_stack_argument(uint32_t addr) |
| 1049 | { |
| 1050 | uint32_t types = user_byte(addr++); |
| 1051 | |
| 1052 | for (int i = 6; i >= 0; i -= 2) { |
| 1053 | switch ((types >> i) & 0x03) { |
| 1054 | case 0: |
| 1055 | addr += 2; |
| 1056 | break; |
| 1057 | case 1: |
| 1058 | addr++; |
| 1059 | break; |
| 1060 | case 2: |
| 1061 | if (user_byte(addr++) == 0) { |
| 1062 | return true; |
| 1063 | } |
| 1064 | break; |
| 1065 | default: |
| 1066 | return false; |
| 1067 | } |
| 1068 | } |
| 1069 | |
| 1070 | return false; |
| 1071 | } |
| 1072 | |
| 1073 | static bool restore_quetzal(const std::shared_ptr<IO> &savefile, SaveType savetype, SaveOpcode &saveopcode, bool close_window) |
| 1074 | { |
| 1075 | std::unique_ptr<IFF> iff; |
| 1076 | uint32_t size; |
| 1077 | uint8_t ifhd[13]; |
| 1078 | uint32_t newpc; |
| 1079 | bool is_bfzs = savetype == SaveType::Meta || savetype == SaveType::Autosave || savetype == SaveType::AutosaveLib; |
| 1080 | bool is_bfms = false; |
| 1081 | Stash stash; |
| 1082 | uint16_t flags2 = word(0x10); |
| 1083 | |
| 1084 | saveopcode = SaveOpcode::None; |
| 1085 | |
| 1086 | if (is_bfzs) { |
| 1087 | try { |
| 1088 | iff = std::make_unique<IFF>(savefile, IFF::TypeID("BFZS")); |
| 1089 | } catch (const IFF::InvalidFile &) { |
| 1090 | try { |
| 1091 | iff = std::make_unique<IFF>(savefile, IFF::TypeID("BFMS")); |
| 1092 | is_bfms = true; |
| 1093 | } catch (const IFF::InvalidFile &) { |
| 1094 | } |
| 1095 | } |
| 1096 | } else { |
| 1097 | try { |
| 1098 | iff = std::make_unique<IFF>(savefile, IFF::TypeID("IFZS")); |
| 1099 | } catch (const IFF::InvalidFile &) { |
| 1100 | } |
| 1101 | } |
| 1102 | |
| 1103 | try { |
| 1104 | if (iff == nullptr || |
| 1105 | !iff->find(IFF::TypeID("IFhd"), size) || |
| 1106 | size != 13) { |
| 1107 | |
| 1108 | throw RestoreError("corrupted save file or not a save file at all"); |
| 1109 | } |
| 1110 | |
| 1111 | try { |
| 1112 | iff->io()->read_exact(ifhd, sizeof ifhd); |
| 1113 | } catch (const IO::IOError &) { |
| 1114 | throw RestoreError("corrupted save file or not a save file at all"); |
| 1115 | } |
| 1116 | |
| 1117 | if (((ifhd[0] << 8) | ifhd[1]) != header.release || |
| 1118 | std::memcmp(&ifhd[2], header.serial, sizeof header.serial) != 0 || |
| 1119 | ((ifhd[8] << 8) | ifhd[9]) != header.checksum) { |
| 1120 | |
| 1121 | throw RestoreError("wrong game or version"); |
| 1122 | } |
| 1123 | |
| 1124 | newpc = (static_cast<uint32_t>(ifhd[10]) << 16) | (static_cast<uint32_t>(ifhd[11]) << 8) | static_cast<uint32_t>(ifhd[12]); |
| 1125 | if (newpc >= memory_size) { |
| 1126 | throw RestoreError(fstring("pc out of range (0x%lx)", static_cast<unsigned long>(newpc))); |
| 1127 | } |
| 1128 | |
| 1129 | if (is_bfms && instruction_has_stack_argument(newpc + 1)) { |
| 1130 | throw RestoreError("detected incompatible meta save: please file a bug report at https://bocfel.org/issues"); |
| 1131 | } |
| 1132 | |
| 1133 | if (is_bfzs && (savetype == SaveType::Autosave || savetype == SaveType::AutosaveLib)) { |
| 1134 | if (iff->find(IFF::TypeID("Undo"), size)) { |
| 1135 | read_undo(*iff->io(), size); |
| 1136 | } |
| 1137 | |
| 1138 | if (iff->find(IFF::TypeID("MSav"), size)) { |
| 1139 | read_msav(*iff->io(), size); |
| 1140 | } |
| 1141 | } |
| 1142 | |
| 1143 | stash.backup(); |
| 1144 | |
| 1145 | read_mem(*iff); |
| 1146 | read_stks(*iff); |
| 1147 | |
| 1148 | if (iff->find(IFF::TypeID("Bfnt"), size)) { |
| 1149 | meta_read_bfnt(*iff->io(), size); |
| 1150 | } |
| 1151 | |
| 1152 | if (iff->find(IFF::TypeID("Bfhs"), size)) { |
| 1153 | // In the regular restore case, we display the history (from |
| 1154 | // the save file) unless this is disabled by the -H option. |
| 1155 | // We always redisplay after an autosave, unless we’re doing |
| 1156 | // a library-state autosave, in which case we don’t need to. |
| 1157 | if (savetype == SaveType::Autosave || !options.disable_history_playback) { |
| 1158 | try { |
| 1159 | long start = iff->io()->tell(); |
| 1160 | |
| 1161 | screen_read_bfhs(*iff->io(), savetype == SaveType::Autosave); |
| 1162 | |
| 1163 | if (iff->io()->tell() - start != size) { |
| 1164 | throw RestoreError("history size mismatch"); |
| 1165 | } |
| 1166 | } catch (const IO::IOError &) { |
| 1167 | throw RestoreError("can't find location in file"); |
| 1168 | } |
| 1169 | } |
| 1170 | } else if (savetype == SaveType::Autosave) { |
| 1171 | warning("unable to find history record"); |
| 1172 | screen_print(">"); |
| 1173 | } |
| 1174 | |
| 1175 | if (iff->find(IFF::TypeID("Bfts"), size)) { |
| 1176 | screen_read_bfts(*iff->io(), size); |
| 1177 | } |
| 1178 | |
| 1179 | if (is_bfzs && !is_bfms) { |
| 1180 | // This must be the last restore call, since it can ultimately |
| 1181 | // wind up modifying the screen state in an irreversible way. |
| 1182 | read_bfzs_specific(*iff, savetype, saveopcode); |
| 1183 | } |
| 1184 | } catch (const RestoreError &e) { |
| 1185 | show_message("Save file error: %s", e.what()); |
| 1186 | |
| 1187 | // If a stash exists, then something vital has been scribbled upon. |
| 1188 | // Try to restore the stash, but if it can’t be restored, the only |
| 1189 | // course of action is to exit. |
| 1190 | if (stash.exists() && !stash.restore()) { |
| 1191 | die("the system is likely in an inconsistent state"); |
| 1192 | } |
| 1193 | |
| 1194 | // If an autosave fails, clear the save stacks: autosaves can |
| 1195 | // contain save data that might have been loaded already. These |
| 1196 | // could use the stash mechanism, but since autosaves are loaded |
| 1197 | // before anything happens, it is guaranteed that the stacks were |
| 1198 | // empty before the restore process started. This is faster and |
| 1199 | // simpler than stashing. |
| 1200 | if (is_bfzs && (savetype == SaveType::Autosave || savetype == SaveType::AutosaveLib)) { |
| 1201 | save_stacks[SaveStackType::Game].clear(); |
| 1202 | save_stacks[SaveStackType::User].clear(); |
| 1203 | } |
| 1204 | |
| 1205 | return false; |
| 1206 | } |
| 1207 | |
| 1208 | pc = newpc; |
| 1209 | |
| 1210 | // §8.6.1.3 |
| 1211 | // Except that for AutosaveLib, we’ll restore the upper window. |
| 1212 | if (close_window && zversion == 3 && savetype != SaveType::AutosaveLib) { |
| 1213 | close_upper_window(); |
| 1214 | } |
| 1215 | |
| 1216 | // For user saves, the game won’t know a restore occurred, so it |
| 1217 | // won’t redraw the status line. Set the “redraw status” bit of |
| 1218 | // Flags 2 to indicate a redraw is requested. The Z-Machine |
| 1219 | // Standards Document says this bit is for V6 only, but Infocom’s |
| 1220 | // documentation says V4+, and A Mind Forever Voyaging (which is V4) |
| 1221 | // checks it. |
| 1222 | if (zversion >= 4 && (savetype == SaveType::Autosave || savetype == SaveType::Meta)) { |
| 1223 | flags2 |= FLAGS2_STATUS; |
| 1224 | } |
| 1225 | |
| 1226 | if (savetype == SaveType::AutosaveLib) { |
| 1227 | // Use the save file’s FLAGS2_TRANSCRIPT. |
| 1228 | if (word(0x10) & FLAGS2_TRANSCRIPT) |
| 1229 | flags2 |= FLAGS2_TRANSCRIPT; |
| 1230 | else |
| 1231 | flags2 &= ~FLAGS2_TRANSCRIPT; |
| 1232 | } |
| 1233 | |
| 1234 | // §6.1.2.2: The save might be from a different interpreter with |
| 1235 | // different capabilities, so update the header to indicate what the |
| 1236 | // current capabilities are. |
| 1237 | // |
| 1238 | // Even for in-game saves (either via the game or user stack), |
| 1239 | // rewrite the header: the interpreter will probably be the same, |
| 1240 | // but the screen size might have changed. And, in fact, since these |
| 1241 | // stacks can be stored in autosaves, it’s technically possible they |
| 1242 | // COULD be running in another interpreter, or at least a future |
| 1243 | // version of this one. |
| 1244 | write_header(); |
| 1245 | |
| 1246 | // §6.1.2: Flags 2 should be preserved. |
| 1247 | store_word(0x10, flags2); |
| 1248 | |
| 1249 | return true; |
| 1250 | } |
| 1251 | |
| 1252 | static std::shared_ptr<IO> open_savefile(SaveType savetype, IO::Mode mode) |
| 1253 | { |
| 1254 | std::unique_ptr<std::string> filename; |
| 1255 | |
| 1256 | if (savetype == SaveType::Autosave || savetype == SaveType::AutosaveLib) { |
| 1257 | filename = zterp_os_autosave_name(); |
| 1258 | if (filename == nullptr) { |
| 1259 | return nullptr; |
| 1260 | } |
| 1261 | } |
| 1262 | |
| 1263 | try { |
| 1264 | return std::make_shared<IO>(filename.get(), mode, IO::Purpose::Save); |
| 1265 | } catch (const IO::OpenError &) { |
| 1266 | if (!(savetype == SaveType::Autosave || savetype == SaveType::AutosaveLib)) { |
| 1267 | warning("unable to open save file"); |
| 1268 | } |
| 1269 | |
| 1270 | return nullptr; |
| 1271 | } |
| 1272 | } |
| 1273 | |
| 1274 | // Perform all aspects of a save, apart from storing/branching. |
| 1275 | // Returns true if the save was success, false if not. |
| 1276 | bool do_save(SaveType savetype, SaveOpcode saveopcode) |
| 1277 | { |
| 1278 | auto savefile = open_savefile(savetype, IO::Mode::WriteOnly); |
| 1279 | if (savefile == nullptr) { |
| 1280 | return false; |
| 1281 | } |
| 1282 | |
| 1283 | if (!save_quetzal(*savefile, savetype, saveopcode, false)) { |
| 1284 | warning("error while writing save file"); |
| 1285 | return false; |
| 1286 | } |
| 1287 | |
| 1288 | #ifdef ZTERP_GLK |
| 1289 | if (savetype == SaveType::AutosaveLib) { |
| 1290 | if (!glkautosave_library_autosave()) { |
| 1291 | return false; |
| 1292 | } |
| 1293 | } |
| 1294 | #endif |
| 1295 | |
| 1296 | return true; |
| 1297 | } |
| 1298 | |
| 1299 | // The suggested filename is ignored, because Glk and, at least as of |
| 1300 | // right now, IO, do not provide a method to do this. |
| 1301 | // The “prompt” argument added by standard 1.1 is thus also ignored. |
| 1302 | void zsave() |
| 1303 | { |
| 1304 | if (in_interrupt()) { |
| 1305 | store(0); |
| 1306 | return; |
| 1307 | } |
| 1308 | |
| 1309 | // Autosave before blocking on the fileref prompt. (Which will |
| 1310 | // certainly happen down in the guts of do_save(), because there |
| 1311 | // is no suggested filename.) |
| 1312 | // |
| 1313 | // Yes, it’s goofy to call do_save() before do_save(), but that’s |
| 1314 | // what happens if you want to autosave every time the Z-machine |
| 1315 | // waits for input. |
| 1316 | // |
| 1317 | // (Note that we might have arrived here from zsave5().) |
| 1318 | // |
| 1319 | if (options.autosave && options.autosave_librarystate) { |
| 1320 | do_save(SaveType::AutosaveLib, SaveOpcode::Save); |
| 1321 | } |
| 1322 | |
| 1323 | bool success = do_save(SaveType::Normal, SaveOpcode::None); |
| 1324 | |
| 1325 | if (zversion <= 3) { |
| 1326 | branch_if(success); |
| 1327 | } else { |
| 1328 | store(success ? 1 : 0); |
| 1329 | } |
| 1330 | } |
| 1331 | |
| 1332 | // Perform all aspects of a restore, apart from storing/branching. |
| 1333 | // Returns true if the restore was success, false if not. |
| 1334 | // saveopcode will be set appropriately based on the type of save file |
| 1335 | // this is. |
| 1336 | bool do_restore(SaveType savetype, SaveOpcode &saveopcode) |
| 1337 | { |
| 1338 | #ifdef ZTERP_GLK |
| 1339 | if (savetype == SaveType::AutosaveLib) { |
| 1340 | if (!glkautosave_library_autorestore()) { |
| 1341 | return false; |
| 1342 | } |
| 1343 | } |
| 1344 | #endif |
| 1345 | |
| 1346 | auto savefile = open_savefile(savetype, IO::Mode::ReadOnly); |
| 1347 | if (savefile == nullptr) { |
| 1348 | return false; |
| 1349 | } |
| 1350 | |
| 1351 | return restore_quetzal(savefile, savetype, saveopcode, true); |
| 1352 | } |
| 1353 | |
| 1354 | void zrestore() |
| 1355 | { |
| 1356 | // Autosave before blocking on the fileref prompt. (Which will |
| 1357 | // certainly happen down in the guts of do_restore(), because there |
| 1358 | // is no suggested filename.) |
| 1359 | // |
| 1360 | // (Note that we might have arrived here from restore5().) |
| 1361 | // |
| 1362 | if (options.autosave && options.autosave_librarystate) { |
| 1363 | do_save(SaveType::AutosaveLib, SaveOpcode::Restore); |
| 1364 | } |
| 1365 | |
| 1366 | SaveOpcode saveopcode; |
| 1367 | bool success = do_restore(SaveType::Normal, saveopcode); |
| 1368 | |
| 1369 | if (zversion <= 3) { |
| 1370 | branch_if(success); |
| 1371 | } else { |
| 1372 | store(success ? 2 : 0); |
| 1373 | } |
| 1374 | |
| 1375 | // On a successful restore, we are outside of any interrupt (since |
| 1376 | // @save cannot be called inside an interrupt), so reset the level |
| 1377 | // back to zero. |
| 1378 | if (success) { |
| 1379 | throw Operation::Restore(saveopcode); |
| 1380 | } |
| 1381 | } |
| 1382 | |
| 1383 | // Push the current state onto the specified save stack. |
| 1384 | SaveResult push_save(SaveStackType type, SaveType savetype, SaveOpcode saveopcode, const char *desc) |
| 1385 | { |
| 1386 | SaveStack &s = save_stacks[type]; |
| 1387 | |
| 1388 | if (s.max == 0) { |
| 1389 | return SaveResult::Unavailable; |
| 1390 | } |
| 1391 | |
| 1392 | try { |
| 1393 | IO savefile(std::vector<uint8_t>(), IO::Mode::WriteOnly); |
| 1394 | |
| 1395 | if (!save_quetzal(savefile, savetype, saveopcode, true)) { |
| 1396 | return SaveResult::Failure; |
| 1397 | } |
| 1398 | |
| 1399 | SaveState newstate(savetype, desc, savefile.get_memory()); |
| 1400 | s.push(std::move(newstate)); |
| 1401 | |
| 1402 | return SaveResult::Success; |
| 1403 | } catch (const IO::OpenError &) { |
| 1404 | } catch (const std::bad_alloc &) { |
| 1405 | } |
| 1406 | |
| 1407 | return SaveResult::Failure; |
| 1408 | } |
| 1409 | |
| 1410 | // Pop the specified state from the specified stack and jump to it. |
| 1411 | // Indices start at 0, with 0 being the most recent save. |
| 1412 | bool pop_save(SaveStackType type, size_t saveno, SaveOpcode &saveopcode) |
| 1413 | { |
| 1414 | SaveStack &s = save_stacks[type]; |
| 1415 | std::shared_ptr<IO> savefile; |
| 1416 | |
| 1417 | if (saveno >= s.states.size()) { |
| 1418 | return false; |
| 1419 | } |
| 1420 | |
| 1421 | for (size_t i = 0; i < saveno; i++) { |
| 1422 | s.states.pop_front(); |
| 1423 | } |
| 1424 | |
| 1425 | auto p = std::move(s.states.front()); |
| 1426 | s.states.pop_front(); |
| 1427 | |
| 1428 | try { |
| 1429 | savefile = std::make_shared<IO>(p.quetzal, IO::Mode::ReadOnly); |
| 1430 | } catch (const IO::OpenError &) { |
| 1431 | return false; |
| 1432 | } |
| 1433 | |
| 1434 | return restore_quetzal(savefile, p.savetype, saveopcode, false); |
| 1435 | } |
| 1436 | |
| 1437 | // Wrapper around trim_saves which reports failure if the specified save |
| 1438 | // does not exist. |
| 1439 | bool drop_save(SaveStackType type, size_t i) |
| 1440 | { |
| 1441 | SaveStack &s = save_stacks[type]; |
| 1442 | |
| 1443 | if (i > s.states.size()) { |
| 1444 | return false; |
| 1445 | } |
| 1446 | |
| 1447 | s.trim_saves(i); |
| 1448 | |
| 1449 | return true; |
| 1450 | } |
| 1451 | |
| 1452 | void list_saves(SaveStackType type) |
| 1453 | { |
| 1454 | const SaveStack &s = save_stacks[type]; |
| 1455 | auto nsaves = s.states.size(); |
| 1456 | |
| 1457 | if (nsaves == 0) { |
| 1458 | screen_puts("[No saves available]"); |
| 1459 | return; |
| 1460 | } |
| 1461 | |
| 1462 | for (auto p = s.states.crbegin(); p != s.states.crend(); ++p) { |
| 1463 | std::string desc = std::to_string(nsaves) + ". " + (p->desc.empty() ? "<no description>" : p->desc); |
| 1464 | |
| 1465 | if (nsaves == 1) { |
| 1466 | desc += " *"; |
| 1467 | } |
| 1468 | |
| 1469 | screen_puts(desc); |
| 1470 | |
| 1471 | nsaves--; |
| 1472 | } |
| 1473 | } |
| 1474 | |
| 1475 | void zsave_undo() |
| 1476 | { |
| 1477 | if (in_interrupt()) { |
| 1478 | store(0); |
| 1479 | return; |
| 1480 | } |
| 1481 | |
| 1482 | // If override undo is set, all calls to @save_undo are reported as |
| 1483 | // failure; the interpreter still reports that @save_undo is |
| 1484 | // available, however. These values will be tuned if it becomes |
| 1485 | // necessary (i.e. if some games behave badly). |
| 1486 | if (options.override_undo) { |
| 1487 | store(0); |
| 1488 | } else { |
| 1489 | // On the first call to @save_undo, switch over to game-based save |
| 1490 | // states instead of interpreter-generated save states. |
| 1491 | if (!seen_save_undo) { |
| 1492 | save_stacks[SaveStackType::Game].clear(); |
| 1493 | seen_save_undo = true; |
| 1494 | } |
| 1495 | |
| 1496 | switch (push_save(SaveStackType::Game, SaveType::Normal, SaveOpcode::None, nullptr)) { |
| 1497 | case SaveResult::Success: |
| 1498 | store(1); |
| 1499 | break; |
| 1500 | case SaveResult::Failure: |
| 1501 | store(0); |
| 1502 | break; |
| 1503 | // @save_undo must return -1 if undo is not available. The only |
| 1504 | // time that’s the case with Bocfel is if the user has requested |
| 1505 | // 0 save slots. Otherwise, @save_undo might still fail as a |
| 1506 | // result of low memory, but that’s a transient failure for |
| 1507 | // which 0 will be returned. |
| 1508 | case SaveResult::Unavailable: |
| 1509 | store(0xffff); |
| 1510 | break; |
| 1511 | } |
| 1512 | } |
| 1513 | } |
| 1514 | |
| 1515 | void zrestore_undo() |
| 1516 | { |
| 1517 | // If @save_undo has not been called, @restore_undo should fail, even |
| 1518 | // if there are interpreter-generated save states available. |
| 1519 | if (!seen_save_undo) { |
| 1520 | store(0); |
| 1521 | } else { |
| 1522 | SaveOpcode saveopcode; |
| 1523 | bool success = pop_save(SaveStackType::Game, 0, saveopcode); |
| 1524 | |
| 1525 | store(success ? 2 : 0); |
| 1526 | |
| 1527 | if (success) { |
| 1528 | throw Operation::Restore(saveopcode); |
| 1529 | } |
| 1530 | } |
| 1531 | } |
| 1532 | |
| 1533 | class ArgsStasher : public Stasher { |
| 1534 | public: |
| 1535 | void backup() override { |
| 1536 | m_zargs.assign(zargs.begin(), zargs.begin() + znargs); |
| 1537 | } |
| 1538 | |
| 1539 | bool restore() override { |
| 1540 | std::copy(m_zargs.begin(), m_zargs.end(), zargs.begin()); |
| 1541 | znargs = m_zargs.size(); |
| 1542 | |
| 1543 | return true; |
| 1544 | } |
| 1545 | |
| 1546 | void free() override { |
| 1547 | m_zargs.clear(); |
| 1548 | } |
| 1549 | |
| 1550 | private: |
| 1551 | std::vector<uint16_t> m_zargs; |
| 1552 | }; |
| 1553 | |
| 1554 | class MemoryStasher : public Stasher { |
| 1555 | public: |
| 1556 | void backup() override { |
| 1557 | try { |
| 1558 | m_memory = std::make_unique<std::vector<uint8_t>>(memory.begin(), memory.begin() + header.static_start); |
| 1559 | } catch (std::bad_alloc &) { |
| 1560 | m_memory.reset(); |
| 1561 | } |
| 1562 | } |
| 1563 | |
| 1564 | bool restore() override { |
| 1565 | if (m_memory == nullptr) { |
| 1566 | return false; |
| 1567 | } |
| 1568 | |
| 1569 | std::copy(m_memory->begin(), m_memory->end(), memory.begin()); |
| 1570 | |
| 1571 | return true; |
| 1572 | } |
| 1573 | |
| 1574 | void free() override { |
| 1575 | m_memory.reset(); |
| 1576 | } |
| 1577 | |
| 1578 | private: |
| 1579 | std::unique_ptr<std::vector<uint8_t>> m_memory; |
| 1580 | }; |
| 1581 | |
| 1582 | class StackStasher : public Stasher { |
| 1583 | public: |
| 1584 | void backup() override { |
| 1585 | try { |
| 1586 | m_stack = std::make_unique<std::vector<uint16_t>>(stack, sp); |
| 1587 | } catch (const std::bad_alloc &) { |
| 1588 | m_stack.reset(); |
| 1589 | } |
| 1590 | } |
| 1591 | |
| 1592 | bool restore() override { |
| 1593 | if (m_stack == nullptr) { |
| 1594 | return false; |
| 1595 | } |
| 1596 | |
| 1597 | sp = BASE_OF_STACK + m_stack->size(); |
| 1598 | std::copy(m_stack->begin(), m_stack->end(), stack); |
| 1599 | |
| 1600 | return true; |
| 1601 | } |
| 1602 | |
| 1603 | void free() override { |
| 1604 | m_stack.reset(); |
| 1605 | } |
| 1606 | |
| 1607 | private: |
| 1608 | std::unique_ptr<std::vector<uint16_t>> m_stack; |
| 1609 | }; |
| 1610 | |
| 1611 | class FrameStasher : public Stasher { |
| 1612 | public: |
| 1613 | void backup() override { |
| 1614 | try { |
| 1615 | m_frames = std::make_unique<std::vector<CallFrame>>(frames, fp); |
| 1616 | } catch (const std::bad_alloc &) { |
| 1617 | m_frames.reset(); |
| 1618 | } |
| 1619 | } |
| 1620 | |
| 1621 | bool restore() override { |
| 1622 | if (m_frames == nullptr) { |
| 1623 | return false; |
| 1624 | } |
| 1625 | |
| 1626 | fp = BASE_OF_FRAMES + m_frames->size(); |
| 1627 | std::copy(m_frames->begin(), m_frames->end(), frames); |
| 1628 | |
| 1629 | return true; |
| 1630 | } |
| 1631 | |
| 1632 | void free() override { |
| 1633 | m_frames.reset(); |
| 1634 | } |
| 1635 | |
| 1636 | private: |
| 1637 | std::unique_ptr<std::vector<CallFrame>> m_frames; |
| 1638 | }; |
| 1639 | |
| 1640 | // Replace with std::clamp when switching to C++17. |
| 1641 | template <typename T> |
| 1642 | const T &clamp(const T &value, const T &min, const T &max) { |
| 1643 | return value < min ? min : value > max ? max : value; |
| 1644 | } |
| 1645 | |
| 1646 | void init_stack(bool first_run) |
| 1647 | { |
| 1648 | // Allocate space for the evaluation and call stacks. |
| 1649 | // Clamp the size between 1 and the largest value that will not |
| 1650 | // produce an overflow of size_t when multiplied by the size of the |
| 1651 | // type. |
| 1652 | // Also, the call stack can be no larger than 0xffff so that the |
| 1653 | // result of a @catch will fit into a 16-bit integer. |
| 1654 | if (first_run) { |
| 1655 | options.eval_stack_size = clamp<size_t>(options.eval_stack_size, 1, SIZE_MAX / sizeof *stack); |
| 1656 | try { |
| 1657 | stack = new uint16_t[options.eval_stack_size]; |
| 1658 | } catch (std::bad_alloc &) { |
| 1659 | die("unable to allocate %lu bytes for the evaluation stack", options.eval_stack_size * static_cast<unsigned long>(sizeof *stack)); |
| 1660 | } |
| 1661 | TOP_OF_STACK = &stack[options.eval_stack_size]; |
| 1662 | |
| 1663 | options.call_stack_size = clamp<size_t>(options.call_stack_size, 1, std::min<size_t>(0xffff, (SIZE_MAX / sizeof *frames) - 1)); |
| 1664 | try { |
| 1665 | // One extra to help with saving (thus the subtraction of 1 |
| 1666 | // above). |
| 1667 | frames = new CallFrame[options.call_stack_size + 1]; |
| 1668 | } catch (std::bad_alloc &) { |
| 1669 | die("unable to allocate %lu bytes for the call stack", (options.call_stack_size + 1) * static_cast<unsigned long>(sizeof *frames)); |
| 1670 | } |
| 1671 | TOP_OF_FRAMES = &frames[options.call_stack_size]; |
| 1672 | |
| 1673 | stash_register(std::make_unique<ArgsStasher>()); |
| 1674 | stash_register(std::make_unique<MemoryStasher>()); |
| 1675 | stash_register(std::make_unique<StackStasher>()); |
| 1676 | stash_register(std::make_unique<FrameStasher>()); |
| 1677 | } |
| 1678 | |
| 1679 | sp = BASE_OF_STACK; |
| 1680 | fp = BASE_OF_FRAMES; |
| 1681 | |
| 1682 | // Quetzal requires a dummy frame in non-V6 games, so do that here. |
| 1683 | if (zversion != 6) { |
| 1684 | add_frame(0, sp, 0, 0, 0); |
| 1685 | } |
| 1686 | |
| 1687 | // Free all @save_undo save states. |
| 1688 | save_stacks[SaveStackType::Game].clear(); |
| 1689 | save_stacks[SaveStackType::Game].max = options.undo_slots; |
| 1690 | seen_save_undo = false; |
| 1691 | |
| 1692 | // Free all /ps save states. |
| 1693 | save_stacks[SaveStackType::User].clear(); |
| 1694 | save_stacks[SaveStackType::User].max = 25; |
| 1695 | } |