| 1 | // Copyright 2009-2024 Chris Spiegel. |
| 2 | // |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | |
| 5 | #include <algorithm> |
| 6 | #include <array> |
| 7 | #include <climits> |
| 8 | #include <cstdio> |
| 9 | #include <cstdlib> |
| 10 | #include <cstring> |
| 11 | #include <exception> |
| 12 | #include <iomanip> |
| 13 | #include <ios> |
| 14 | #include <iostream> |
| 15 | #include <memory> |
| 16 | #include <new> |
| 17 | #include <set> |
| 18 | #include <sstream> |
| 19 | #include <string> |
| 20 | #include <utility> |
| 21 | #include <vector> |
| 22 | |
| 23 | #include "zterp.h" |
| 24 | #include "blorb.h" |
| 25 | #include "branch.h" |
| 26 | #include "iff.h" |
| 27 | #include "io.h" |
| 28 | #include "memory.h" |
| 29 | #include "meta.h" |
| 30 | #include "options.h" |
| 31 | #include "osdep.h" |
| 32 | #include "patches.h" |
| 33 | #include "process.h" |
| 34 | #include "random.h" |
| 35 | #include "screen.h" |
| 36 | #include "sound.h" |
| 37 | #include "stack.h" |
| 38 | #include "types.h" |
| 39 | #include "unicode.h" |
| 40 | #include "util.h" |
| 41 | |
| 42 | #ifdef ZTERP_GLK |
| 43 | #include <glk.h> |
| 44 | #endif |
| 45 | |
| 46 | using namespace std::literals; |
| 47 | |
| 48 | std::string game_file; |
| 49 | |
| 50 | static std::string story_id; |
| 51 | |
| 52 | const std::string &get_story_id() |
| 53 | { |
| 54 | return story_id; |
| 55 | } |
| 56 | |
| 57 | // zversion stores the Z-machine version of the story: 1–6. |
| 58 | // |
| 59 | // Z-machine versions 7 and 8 are identical to version 5 but for a |
| 60 | // couple of tiny details. They are thus classified as version 5. |
| 61 | int zversion; |
| 62 | |
| 63 | Header header; |
| 64 | |
| 65 | static bool checksum_verified; |
| 66 | |
| 67 | // The null character in the alphabet table does not actually signify a |
| 68 | // null character: character 6 from A2 is special in that it specifies |
| 69 | // that the next two characters form a 10-bit ZSCII character (§3.4). |
| 70 | // The code that uses the alphabet table will step around this character |
| 71 | // when necessary, so it’s safe to use a null character here to mean |
| 72 | // “nothing”. |
| 73 | std::array<uint8_t, 26 * 3> atable = { |
| 74 | // A0 |
| 75 | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', |
| 76 | 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', |
| 77 | |
| 78 | // A1 |
| 79 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', |
| 80 | 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', |
| 81 | |
| 82 | // A2 |
| 83 | 0x0, 0xd, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', |
| 84 | ',', '!', '?', '_', '#', '\'','"', '/', '\\','-', ':', '(', ')', |
| 85 | }; |
| 86 | |
| 87 | static unsigned long unpack_multiplier; |
| 88 | |
| 89 | uint32_t unpack_routine(uint16_t addr) |
| 90 | { |
| 91 | return (addr * unpack_multiplier) + header.routines_offset; |
| 92 | } |
| 93 | |
| 94 | uint32_t unpack_string(uint16_t addr) |
| 95 | { |
| 96 | return (addr * unpack_multiplier) + header.strings_offset; |
| 97 | } |
| 98 | |
| 99 | void store(uint16_t v) |
| 100 | { |
| 101 | store_variable(byte(pc++), v); |
| 102 | } |
| 103 | |
| 104 | static std::set<Game> games; |
| 105 | |
| 106 | static void initialize_games() |
| 107 | { |
| 108 | // All V1234 games from Andrew Plotkin’s Obsessively Complete |
| 109 | // Infocom Catalog: https://eblong.com/infocom/ |
| 110 | static const std::set<std::string> infocom1234 = { |
| 111 | #include "v1234.h" |
| 112 | }; |
| 113 | |
| 114 | static const std::set<std::string> mysterious = { |
| 115 | "1-041209-e04a", |
| 116 | "1-041209-831b", |
| 117 | "1-041209-beb7", |
| 118 | "1-041209-c3e0", |
| 119 | "1-041209-2003", |
| 120 | "1-041209-f23c", |
| 121 | "1-041209-e38a", |
| 122 | "1-041209-90d8", |
| 123 | "1-041209-e644", |
| 124 | "1-041209-480b", |
| 125 | "1-041209-b1de", |
| 126 | }; |
| 127 | |
| 128 | static const std::vector<std::pair<Game, std::set<std::string>>> gamemap = { |
| 129 | { Game::Infocom1234, infocom1234 }, |
| 130 | { Game::Arthur, { "54-890606", "63-890622", "74-890714" } }, |
| 131 | { Game::Journey, { "26-890316", "30-890322", "77-890616", "83-890706" } }, |
| 132 | { Game::LurkingHorror, { "203-870506", "219-870912", "221-870918" } }, |
| 133 | { Game::Planetfall, { "1-830517", "20-830708", "26-831014", "29-840118", "37-851003", "39-880501" } }, |
| 134 | { Game::Shogun, { "292-890314", "295-890321", "311-890510", "322-890706" } }, |
| 135 | { Game::Stationfall, { "1-861017", "63-870218", "87-870326", "107-870430" } }, |
| 136 | { Game::ZorkZero, { "296-881019", "366-890323", "383-890602", "393-890714" } }, |
| 137 | { Game::ZorkZeroDOS, { "393-890714" } }, |
| 138 | { Game::MysteriousAdventures, mysterious }, |
| 139 | }; |
| 140 | |
| 141 | for (const auto &pair : gamemap) { |
| 142 | if (pair.second.find(story_id) != pair.second.end()) { |
| 143 | games.insert(pair.first); |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | bool is_game(Game game) |
| 149 | { |
| 150 | return games.find(game) != games.end(); |
| 151 | } |
| 152 | |
| 153 | // Find a story ID roughly in the form of an IFID according to §2.2.2.1 |
| 154 | // of revision 10 of the Treaty of Babel. |
| 155 | // |
| 156 | // This does not add a ZCODE- prefix, and will not search for a manually |
| 157 | // created IFID. |
| 158 | static void find_id() |
| 159 | { |
| 160 | std::string serial = "------"; |
| 161 | |
| 162 | // isalnum() cannot be used because it is locale-aware, and this |
| 163 | // must only check for A–Z, a–z, and 0–9. Because ASCII (or a |
| 164 | // compatible charset) is required, testing against 'a', 'z', etc. |
| 165 | // is OK. |
| 166 | std::copy_if(header.serial, header.serial + 6, serial.begin(), [](auto c) { |
| 167 | return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); |
| 168 | }); |
| 169 | |
| 170 | std::ostringstream ss; |
| 171 | ss << header.release << "-" << serial; |
| 172 | if ("012345679"s.find(serial[0]) != std::string::npos && |
| 173 | serial != "000000" && |
| 174 | serial != "999999" && |
| 175 | serial != "------") { |
| 176 | |
| 177 | ss << "-" << std::hex << std::setw(4) << std::setfill('0') << header.checksum; |
| 178 | } |
| 179 | story_id = ss.str(); |
| 180 | |
| 181 | initialize_games(); |
| 182 | } |
| 183 | |
| 184 | static bool have_statuswin = false; |
| 185 | static bool have_upperwin = false; |
| 186 | |
| 187 | static void write_flags1() |
| 188 | { |
| 189 | uint8_t flags1 = byte(0x01); |
| 190 | |
| 191 | if (zversion == 3) { |
| 192 | flags1 |= FLAGS1_NOSTATUS; |
| 193 | flags1 &= ~(FLAGS1_SCREENSPLIT | FLAGS1_VARIABLE); |
| 194 | |
| 195 | #ifdef GARGLK |
| 196 | // Assume that if Gargoyle is being used, the default font is not fixed. |
| 197 | flags1 |= FLAGS1_VARIABLE; |
| 198 | #endif |
| 199 | |
| 200 | if (have_statuswin) { |
| 201 | flags1 &= ~FLAGS1_NOSTATUS; |
| 202 | } |
| 203 | if (have_upperwin) { |
| 204 | flags1 |= FLAGS1_SCREENSPLIT; |
| 205 | } |
| 206 | if (options.enable_censorship) { |
| 207 | flags1 |= FLAGS1_CENSOR; |
| 208 | } |
| 209 | } else if (zversion >= 4) { |
| 210 | flags1 |= (FLAGS1_BOLD | FLAGS1_ITALIC | FLAGS1_FIXED); |
| 211 | flags1 &= ~FLAGS1_TIMED; |
| 212 | |
| 213 | if (zversion >= 5) { |
| 214 | flags1 &= ~FLAGS1_COLORS; |
| 215 | } |
| 216 | |
| 217 | if (zversion == 6) { |
| 218 | flags1 &= ~(FLAGS1_PICTURES | FLAGS1_SOUND); |
| 219 | #if defined(GLK_MODULE_IMAGE) && defined(ZTERP_GLK_BLORB) |
| 220 | if (glk_gestalt(gestalt_Graphics, 0)) { |
| 221 | flags1 |= FLAGS1_PICTURES; |
| 222 | } |
| 223 | #endif |
| 224 | if (sound_loaded()) { |
| 225 | flags1 |= FLAGS1_SOUND; |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | #ifdef ZTERP_GLK |
| 230 | if (glk_gestalt(gestalt_Timer, 0)) { |
| 231 | flags1 |= FLAGS1_TIMED; |
| 232 | } |
| 233 | #ifdef GLK_MODULE_GARGLKTEXT |
| 234 | if (zversion >= 5) { |
| 235 | flags1 |= FLAGS1_COLORS; |
| 236 | } |
| 237 | #endif |
| 238 | #else |
| 239 | if (!zterp_os_have_style(STYLE_BOLD)) { |
| 240 | flags1 &= ~FLAGS1_BOLD; |
| 241 | } |
| 242 | if (!zterp_os_have_style(STYLE_ITALIC)) { |
| 243 | flags1 &= ~FLAGS1_ITALIC; |
| 244 | } |
| 245 | if (zversion >= 5 && zterp_os_have_colors()) { |
| 246 | flags1 |= FLAGS1_COLORS; |
| 247 | } |
| 248 | #endif |
| 249 | |
| 250 | if (zversion >= 5 && options.disable_color) { |
| 251 | flags1 &= ~FLAGS1_COLORS; |
| 252 | } |
| 253 | if (options.disable_timed) { |
| 254 | flags1 &= ~FLAGS1_TIMED; |
| 255 | } |
| 256 | if (options.disable_fixed) { |
| 257 | flags1 &= ~FLAGS1_FIXED; |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | store_byte(0x01, flags1); |
| 262 | } |
| 263 | |
| 264 | static void write_flags2() |
| 265 | { |
| 266 | if (zversion >= 5) { |
| 267 | uint16_t flags2 = word(0x10); |
| 268 | |
| 269 | #ifdef ZTERP_GLK |
| 270 | if (!glk_gestalt(gestalt_MouseInput, wintype_TextGrid)) { |
| 271 | flags2 &= ~FLAGS2_MOUSE; |
| 272 | } |
| 273 | #else |
| 274 | flags2 &= ~FLAGS2_MOUSE; |
| 275 | #endif |
| 276 | if (!sound_loaded()) { |
| 277 | flags2 &= ~FLAGS2_SOUND; |
| 278 | } |
| 279 | if (zversion >= 6) { |
| 280 | flags2 &= ~FLAGS2_MENUS; |
| 281 | } |
| 282 | |
| 283 | if (options.disable_graphics_font) { |
| 284 | flags2 &= ~FLAGS2_PICTURES; |
| 285 | } |
| 286 | |
| 287 | if (options.undo_slots == 0) { |
| 288 | flags2 &= ~FLAGS2_UNDO; |
| 289 | } |
| 290 | |
| 291 | store_word(0x10, flags2); |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | static void write_header_extension_table() |
| 296 | { |
| 297 | if (header.extension_table == 0) { |
| 298 | return; |
| 299 | } |
| 300 | |
| 301 | // Flags3. |
| 302 | if (header.extension_entries >= 4) { |
| 303 | store_word(header.extension_table + (2 * 4), 0); |
| 304 | } |
| 305 | |
| 306 | // True default foreground color. |
| 307 | if (header.extension_entries >= 5) { |
| 308 | store_word(header.extension_table + (2 * 5), 0x0000); |
| 309 | } |
| 310 | |
| 311 | // True default background color. |
| 312 | if (header.extension_entries >= 6) { |
| 313 | store_word(header.extension_table + (2 * 6), 0x7fff); |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | // Various parts of the header (those marked “Rst” in §11) should be |
| 318 | // updated by the interpreter. This function does that. This is also |
| 319 | // used when restoring, because the save file might have come from an |
| 320 | // interpreter with vastly different settings. |
| 321 | void write_header() |
| 322 | { |
| 323 | write_flags1(); |
| 324 | write_flags2(); |
| 325 | write_header_extension_table(); |
| 326 | |
| 327 | if (zversion >= 4) { |
| 328 | unsigned int width, height; |
| 329 | |
| 330 | store_byte(0x1e, options.int_number); |
| 331 | store_byte(0x1f, options.int_version); |
| 332 | |
| 333 | get_screen_size(width, height); |
| 334 | |
| 335 | // Screen height and width. |
| 336 | // A height of 255 means infinite, so cap at 254. |
| 337 | store_byte(0x20, height > 254 ? 254 : height); |
| 338 | store_byte(0x21, width > 255 ? 255 : width); |
| 339 | |
| 340 | if (zversion >= 5) { |
| 341 | // Screen width and height in units. |
| 342 | store_word(0x22, width > UINT16_MAX ? UINT16_MAX : width); |
| 343 | store_word(0x24, height > UINT16_MAX ? UINT16_MAX : height); |
| 344 | |
| 345 | // Font width and height in units. |
| 346 | store_byte(0x26, 1); |
| 347 | store_byte(0x27, 1); |
| 348 | |
| 349 | // Default background and foreground colors. |
| 350 | store_byte(0x2c, 1); |
| 351 | store_byte(0x2d, 1); |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | // Standard revision # |
| 356 | store_byte(0x32, 1); |
| 357 | store_byte(0x33, 1); |
| 358 | |
| 359 | if (options.username != nullptr) { |
| 360 | options.username->resize(8, '\0'); |
| 361 | std::copy(options.username->begin(), options.username->end(), &memory[0x38]); |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | static void process_alphabet_table() |
| 366 | { |
| 367 | if (zversion == 1) { |
| 368 | std::memcpy(&atable[26 * 2], R"#( 0123456789.,!?_#'"/\<-:()")#", 26); |
| 369 | } else if (zversion >= 5 && word(0x34) != 0) { |
| 370 | if (word(0x34) + 26 * 3 > memory_size) { |
| 371 | die("corrupted story: alphabet table out of range"); |
| 372 | } |
| 373 | |
| 374 | std::memcpy(atable.data(), &memory[word(0x34)], 26 * 3); |
| 375 | |
| 376 | // Even with a new alphabet table, characters 6 and 7 from A2 must |
| 377 | // remain the same (§3.5.5.1). |
| 378 | atable[52] = 0x00; |
| 379 | atable[53] = 0x0d; |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | static uint16_t mouse_click_addr; |
| 384 | |
| 385 | static void read_header_extension_table() |
| 386 | { |
| 387 | if (header.extension_table == 0) { |
| 388 | return; |
| 389 | } |
| 390 | |
| 391 | if (header.extension_entries >= 2) { |
| 392 | mouse_click_addr = header.extension_table + 2; |
| 393 | } |
| 394 | |
| 395 | // Unicode table. |
| 396 | if (header.extension_entries >= 3 && word(header.extension_table + (2 * 3)) != 0) { |
| 397 | uint16_t utable = word(header.extension_table + (2 * 3)); |
| 398 | |
| 399 | parse_unicode_table(utable); |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | void zterp_mouse_click(uint16_t x, uint16_t y) |
| 404 | { |
| 405 | if (mouse_click_addr != 0) { |
| 406 | store_word(mouse_click_addr, x); |
| 407 | store_word(mouse_click_addr + 2, y); |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | static void calculate_checksum(IO &io, long offset) |
| 412 | { |
| 413 | uint32_t remaining = header.file_length - 0x40; |
| 414 | uint16_t checksum = 0; |
| 415 | |
| 416 | try { |
| 417 | io.seek(offset + 0x40, IO::SeekFrom::Start); |
| 418 | } catch (const IO::IOError &) { |
| 419 | return; |
| 420 | } |
| 421 | |
| 422 | while (remaining != 0) { |
| 423 | std::array<uint8_t, 8192> buf; |
| 424 | uint32_t to_read = remaining < buf.size() ? remaining : buf.size(); |
| 425 | |
| 426 | try { |
| 427 | io.read_exact(buf.data(), to_read); |
| 428 | } catch (const IO::IOError &) { |
| 429 | return; |
| 430 | } |
| 431 | |
| 432 | for (uint32_t i = 0; i < to_read; i++) { |
| 433 | checksum += buf[i]; |
| 434 | } |
| 435 | |
| 436 | remaining -= to_read; |
| 437 | } |
| 438 | |
| 439 | checksum_verified = checksum == header.checksum; |
| 440 | } |
| 441 | |
| 442 | static void process_story(IO &io, long offset) |
| 443 | { |
| 444 | try { |
| 445 | io.seek(offset, IO::SeekFrom::Start); |
| 446 | } catch (const IO::IOError &) { |
| 447 | die("unable to rewind story"); |
| 448 | } |
| 449 | |
| 450 | try { |
| 451 | io.read_exact(memory.data(), memory_size); |
| 452 | } catch (const IO::IOError &) { |
| 453 | die("unable to read from story file"); |
| 454 | } |
| 455 | |
| 456 | zversion = byte(0x00); |
| 457 | |
| 458 | #ifdef ZTERP_NO_V6 |
| 459 | if (zversion == 6) { |
| 460 | die("support for version 6 has been disabled in this build"); |
| 461 | } |
| 462 | #endif |
| 463 | |
| 464 | // The actual Z-machine version (differentiating 7 and 8 from 5) is |
| 465 | // only needed in this function, and only for 3 things: |
| 466 | // |
| 467 | // • The unpack multiplier |
| 468 | // • File length |
| 469 | // • Routine & string offsets for V6/7 |
| 470 | auto actual_zversion = zversion; |
| 471 | |
| 472 | if (zversion == 7 || zversion == 8) { |
| 473 | zversion = 5; |
| 474 | } |
| 475 | |
| 476 | switch (actual_zversion) { |
| 477 | case 1: case 2: case 3: |
| 478 | unpack_multiplier = 2; |
| 479 | break; |
| 480 | case 4: case 5: case 6: case 7: |
| 481 | unpack_multiplier = 4; |
| 482 | break; |
| 483 | case 8: |
| 484 | unpack_multiplier = 8; |
| 485 | break; |
| 486 | default: |
| 487 | die("only z-code versions 1-8 are supported"); |
| 488 | } |
| 489 | |
| 490 | header.pc = word(0x06); |
| 491 | if (header.pc >= memory_size) { |
| 492 | die("corrupted story: initial pc out of range"); |
| 493 | } |
| 494 | |
| 495 | if (zversion == 6 && header.pc == 0) { |
| 496 | die("corrupted story: packed address 0 is invalid for initial pc"); |
| 497 | } |
| 498 | |
| 499 | header.release = word(0x02); |
| 500 | header.dictionary = word(0x08); |
| 501 | header.objects = word(0x0a); |
| 502 | header.globals = word(0x0c); |
| 503 | header.abbr = word(0x18); |
| 504 | |
| 505 | // There is no explicit “end of static” tag; but it must end by 0xffff |
| 506 | // or the end of the story file, whichever is smaller. |
| 507 | header.static_start = word(0x0e); |
| 508 | header.static_end = memory_size < 0xffff ? memory_size : 0xffff; |
| 509 | |
| 510 | if (zversion >= 5) { |
| 511 | header.extension_table = word(0x36); |
| 512 | header.extension_entries = user_word(header.extension_table); |
| 513 | |
| 514 | if (header.extension_table + (2 * header.extension_entries) > memory_size) { |
| 515 | die("corrupted story: header extension table out of range"); |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | std::memcpy(header.serial, &memory[0x12], sizeof header.serial); |
| 520 | |
| 521 | unsigned long propsize = zversion <= 3 ? 62 : 126; |
| 522 | |
| 523 | // There must be at least enough room in dynamic memory for the header |
| 524 | // (64 bytes), the global variables table (480 bytes), and the |
| 525 | // property defaults table (62 or 126 bytes). |
| 526 | if (header.static_start < 64UL + 480UL + propsize) { |
| 527 | die("corrupted story: dynamic memory too small (%d bytes)", static_cast<int>(header.static_start)); |
| 528 | } |
| 529 | |
| 530 | if (header.static_start >= memory_size) { |
| 531 | die("corrupted story: static memory out of range"); |
| 532 | } |
| 533 | |
| 534 | if (header.dictionary != 0 && header.dictionary < header.static_start) { |
| 535 | die("corrupted story: dictionary is not in static memory"); |
| 536 | } |
| 537 | |
| 538 | if (header.objects < 64 || header.objects + propsize > header.static_start) { |
| 539 | die("corrupted story: object table is not in dynamic memory"); |
| 540 | } |
| 541 | |
| 542 | if (header.globals < 64 || header.globals + 480UL > header.static_start) { |
| 543 | die("corrupted story: global variables are not in dynamic memory"); |
| 544 | } |
| 545 | |
| 546 | if (header.abbr >= memory_size) { |
| 547 | die("corrupted story: abbreviation table out of range"); |
| 548 | } |
| 549 | |
| 550 | header.file_length = word(0x1a) * (actual_zversion <= 3 ? 2UL : actual_zversion <= 5 ? 4UL : 8UL); |
| 551 | if (header.file_length > memory_size) { |
| 552 | die("story's reported size (%lu) greater than file size (%lu)", static_cast<unsigned long>(header.file_length), static_cast<unsigned long>(memory_size)); |
| 553 | } |
| 554 | |
| 555 | header.checksum = word(0x1c); |
| 556 | |
| 557 | calculate_checksum(io, offset); |
| 558 | |
| 559 | if (actual_zversion == 6 || actual_zversion == 7) { |
| 560 | header.routines_offset = word(0x28) * 8UL; |
| 561 | header.strings_offset = word(0x2a) * 8UL; |
| 562 | } |
| 563 | |
| 564 | if (zversion >= 5 && !options.disable_term_keys) { |
| 565 | header.terminating_characters_table = word(0x2e); |
| 566 | } |
| 567 | |
| 568 | try { |
| 569 | dynamic_memory.assign(memory.begin(), memory.begin() + header.static_start); |
| 570 | } catch (const std::bad_alloc &) { |
| 571 | die("unable to allocate memory for dynamic memory"); |
| 572 | } |
| 573 | |
| 574 | process_alphabet_table(); |
| 575 | read_header_extension_table(); |
| 576 | |
| 577 | // The configuration file cannot be read until the ID of the current |
| 578 | // story is known, and the ID of the current story is not known until |
| 579 | // the file has been processed; so do both of those here. |
| 580 | find_id(); |
| 581 | #ifndef ZTERP_NO_OPTIONS |
| 582 | if (!options.disable_config) { |
| 583 | options.read_config(); |
| 584 | } |
| 585 | options.read_envvars(); |
| 586 | #endif |
| 587 | |
| 588 | // Most options directly set their respective variables, but a few |
| 589 | // require intervention. Delay that intervention until here so that |
| 590 | // the configuration file is taken into account. |
| 591 | if (!options.disable_sound) { |
| 592 | init_sound(); |
| 593 | } |
| 594 | |
| 595 | // Now that we have a Unicode table and the user’s Unicode |
| 596 | // preferences, build the ZSCII to Unicode and Unicode to ZSCII |
| 597 | // tables. |
| 598 | setup_tables(); |
| 599 | |
| 600 | if (!options.disable_patches) { |
| 601 | apply_patches(); |
| 602 | } |
| 603 | |
| 604 | // This is a slightly “hidden” feature to allow consumers of Bocfel |
| 605 | // (e.g. Gargoyle and Spatterlight) to provide their own patches for |
| 606 | // games. If the environment variable $BOCFEL_PATCH_FILE is set, |
| 607 | // patches will be loaded from that file. Otherwise, if a patch file |
| 608 | // path was selected at compile time, it will be used. |
| 609 | const char *patch_file = std::getenv("BOCFEL_PATCH_FILE"); |
| 610 | if (patch_file != nullptr) { |
| 611 | patch_load_file(patch_file); |
| 612 | } else { |
| 613 | #ifdef ZTERP_PATCH_FILE |
| 614 | patch_load_file(ZTERP_PATCH_FILE); |
| 615 | #endif |
| 616 | } |
| 617 | |
| 618 | if (!options.disable_v6_hacks) { |
| 619 | create_graphicswin(); |
| 620 | apply_v6_patches(); |
| 621 | } |
| 622 | |
| 623 | if (zversion <= 3) { |
| 624 | have_statuswin = create_statuswin(); |
| 625 | } |
| 626 | |
| 627 | if (zversion >= 3) { |
| 628 | have_upperwin = create_upperwin(); |
| 629 | } |
| 630 | |
| 631 | if (options.transcript_on) { |
| 632 | store_word(0x10, word(0x10) | FLAGS2_TRANSCRIPT); |
| 633 | } |
| 634 | |
| 635 | if (options.record_on) { |
| 636 | output_stream(OSTREAM_RECORD, 0); |
| 637 | } |
| 638 | |
| 639 | if (options.replay_on) { |
| 640 | input_stream(ISTREAM_FILE); |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | void start_story() |
| 645 | { |
| 646 | static bool first_run = true; |
| 647 | |
| 648 | pc = header.pc; |
| 649 | |
| 650 | // Reset dynamic memory. |
| 651 | // §6.1.3: Flags2 is preserved on a restart. This function is also |
| 652 | // used at the initial program start, but Flags2 should be preserved |
| 653 | // there, as well: the pictures bit and the transcript bit might |
| 654 | // have been set during story processing, and those should persist. |
| 655 | uint16_t flags2 = word(0x10); |
| 656 | std::copy(dynamic_memory.begin(), dynamic_memory.begin() + header.static_start, memory.begin()); |
| 657 | store_word(0x10, flags2); |
| 658 | |
| 659 | write_header(); |
| 660 | |
| 661 | // Put everything in a clean state. |
| 662 | init_stack(first_run); |
| 663 | init_screen(first_run); |
| 664 | init_random(first_run); |
| 665 | init_meta(first_run); |
| 666 | |
| 667 | if (zversion == 6) { |
| 668 | znargs = 1; |
| 669 | zargs[0] = pc; |
| 670 | start_v6(); |
| 671 | } |
| 672 | |
| 673 | first_run = false; |
| 674 | } |
| 675 | |
| 676 | void znop() |
| 677 | { |
| 678 | } |
| 679 | |
| 680 | void zrestart() |
| 681 | { |
| 682 | throw Operation::Restart(); |
| 683 | } |
| 684 | |
| 685 | void zquit() |
| 686 | { |
| 687 | // On @quit, remove the autosave (if any exists). First try to |
| 688 | // rename it to the original name plus .bak; this allows users to |
| 689 | // restore accidentally-deleted files. If the rename fails, though, |
| 690 | // just try to delete it. |
| 691 | if (options.autosave) { |
| 692 | auto autosave_name = zterp_os_autosave_name(); |
| 693 | if (autosave_name != nullptr) { |
| 694 | std::string backup_name = *autosave_name; |
| 695 | backup_name += ".bak"; |
| 696 | if (std::rename(autosave_name->c_str(), backup_name.c_str()) == -1) { |
| 697 | std::remove(autosave_name->c_str()); |
| 698 | } |
| 699 | } |
| 700 | } |
| 701 | |
| 702 | throw Operation::Quit(); |
| 703 | } |
| 704 | |
| 705 | void zverify() |
| 706 | { |
| 707 | branch_if(checksum_verified); |
| 708 | } |
| 709 | |
| 710 | static IO open_savefile(IO::Mode mode) |
| 711 | { |
| 712 | // When this is null, the user is prompted for a filename. |
| 713 | std::unique_ptr<std::string> suggested; |
| 714 | |
| 715 | // If no prompt argument is given, assume 0. |
| 716 | if (znargs == 3 || (znargs == 4 && zargs[3] == 0)) { |
| 717 | uint16_t addr = zargs[2]; |
| 718 | std::string filename; |
| 719 | |
| 720 | for (size_t i = 0; i < user_byte(addr); i++) { |
| 721 | uint8_t c = user_byte(addr + i + 1); |
| 722 | |
| 723 | // Convert non-printable (ASCII) characters to underscores. |
| 724 | if (c >= 32 && c <= 126) { |
| 725 | filename.push_back(c); |
| 726 | } else { |
| 727 | filename.push_back('_'); |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | if (filename.empty()) { |
| 732 | filename = "NULL"; |
| 733 | } |
| 734 | |
| 735 | auto aux = zterp_os_aux_file(filename); |
| 736 | if (aux != nullptr) { |
| 737 | suggested = std::make_unique<std::string>(*aux); |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | // If there is a suggested filename and “prompt” is 1, this should |
| 742 | // prompt the user with the suggested filename, but Glk doesn’t |
| 743 | // support that. |
| 744 | return IO(suggested.get(), mode, IO::Purpose::Data); |
| 745 | } |
| 746 | |
| 747 | void zsave5() |
| 748 | { |
| 749 | if (znargs == 0) { |
| 750 | zsave(); |
| 751 | return; |
| 752 | } |
| 753 | |
| 754 | ZASSERT(zargs[0] + zargs[1] < memory_size, "attempt to save beyond the end of memory"); |
| 755 | |
| 756 | try { |
| 757 | auto savefile = open_savefile(IO::Mode::WriteOnly); |
| 758 | savefile.write_exact(&memory[zargs[0]], zargs[1]); |
| 759 | store(1); |
| 760 | } catch (const IO::Error &) { |
| 761 | store(0); |
| 762 | } |
| 763 | } |
| 764 | |
| 765 | void zrestore5() |
| 766 | { |
| 767 | if (znargs == 0) { |
| 768 | zrestore(); |
| 769 | return; |
| 770 | } |
| 771 | |
| 772 | if (zargs[1] == 0) { |
| 773 | store(0); |
| 774 | return; |
| 775 | } |
| 776 | |
| 777 | try { |
| 778 | auto savefile = open_savefile(IO::Mode::ReadOnly); |
| 779 | std::vector<uint8_t> buf(zargs[1]); |
| 780 | |
| 781 | size_t n = savefile.read(buf.data(), zargs[1]); |
| 782 | for (size_t i = 0; i < n; i++) { |
| 783 | user_store_byte(zargs[0] + i, buf[i]); |
| 784 | } |
| 785 | |
| 786 | store(n); |
| 787 | } catch (const IO::OpenError &) { |
| 788 | store(0); |
| 789 | } catch (const std::bad_alloc &) { |
| 790 | store(0); |
| 791 | } |
| 792 | } |
| 793 | |
| 794 | void zpiracy() |
| 795 | { |
| 796 | branch_if(true); |
| 797 | } |
| 798 | |
| 799 | #ifdef ZTERP_GLK |
| 800 | static void real_main() |
| 801 | #else |
| 802 | static void real_main(int argc, char **argv) |
| 803 | #endif |
| 804 | { |
| 805 | struct { |
| 806 | std::shared_ptr<IO> io; |
| 807 | long offset = 0; |
| 808 | } story; |
| 809 | |
| 810 | #ifdef ZTERP_GLK |
| 811 | if (!create_mainwin()) { |
| 812 | return; |
| 813 | } |
| 814 | #endif |
| 815 | |
| 816 | #ifndef ZTERP_GLK |
| 817 | options.process_arguments(argc, argv); |
| 818 | #endif |
| 819 | |
| 820 | if (arg_status.any()) { |
| 821 | #ifdef ZTERP_GLK |
| 822 | glk_set_style(style_Preformatted); |
| 823 | #endif |
| 824 | |
| 825 | #ifndef ZTERP_NO_OPTIONS |
| 826 | for (const auto &error : options.errors()) { |
| 827 | screen_puts(error); |
| 828 | } |
| 829 | |
| 830 | if (arg_status.test(ArgStatus::BadOption)) { |
| 831 | if (!options.errors().empty()) { |
| 832 | screen_puts(""); |
| 833 | } |
| 834 | |
| 835 | options.help(); |
| 836 | } |
| 837 | #endif |
| 838 | |
| 839 | throw Exit(EXIT_FAILURE); |
| 840 | } |
| 841 | |
| 842 | #ifndef ZTERP_NO_OPTIONS |
| 843 | if (options.show_help) { |
| 844 | options.help(); |
| 845 | throw Exit(0); |
| 846 | } |
| 847 | #endif |
| 848 | |
| 849 | #ifndef ZTERP_GLK |
| 850 | zterp_os_init_term(); |
| 851 | #endif |
| 852 | |
| 853 | if (options.show_version) { |
| 854 | screen_puts("Bocfel " ZTERP_VERSION); |
| 855 | #ifdef ZTERP_NO_SAFETY_CHECKS |
| 856 | screen_puts("Runtime assertions disabled"); |
| 857 | #else |
| 858 | screen_puts("Runtime assertions enabled"); |
| 859 | #endif |
| 860 | #ifdef ZTERP_NO_CHEAT |
| 861 | screen_puts("Cheat support disabled"); |
| 862 | #else |
| 863 | screen_puts("Cheat support enabled"); |
| 864 | #endif |
| 865 | |
| 866 | auto config = zterp_os_rcfile(false); |
| 867 | if (config != nullptr) { |
| 868 | screen_printf("Configuration file: %s\n", config->c_str()); |
| 869 | } else { |
| 870 | screen_puts("Cannot determine configuration file location"); |
| 871 | } |
| 872 | |
| 873 | throw Exit(0); |
| 874 | } |
| 875 | |
| 876 | if (game_file.empty()) { |
| 877 | die("no story provided"); |
| 878 | } |
| 879 | |
| 880 | try { |
| 881 | story.io = std::make_shared<IO>(&game_file, IO::Mode::ReadOnly, IO::Purpose::Data); |
| 882 | } catch (const IO::OpenError &) { |
| 883 | die("cannot open file %s", game_file.c_str()); |
| 884 | } |
| 885 | |
| 886 | try { |
| 887 | Blorb blorb = Blorb(story.io); |
| 888 | |
| 889 | const auto *chunk = blorb.find(Blorb::Usage::Exec, 0); |
| 890 | if (chunk == nullptr) { |
| 891 | die("no Exec resource found"); |
| 892 | } |
| 893 | if (chunk->type != IFF::TypeID("ZCOD")) { |
| 894 | if (chunk->type == IFF::TypeID("GLUL")) { |
| 895 | die("Glulx stories are not supported (try git or glulxe)"); |
| 896 | } |
| 897 | |
| 898 | die("unknown story type: %s (0x%08lx)", chunk->type.name().c_str(), static_cast<unsigned long>(chunk->type.val())); |
| 899 | } |
| 900 | |
| 901 | #if UINT32_MAX > LONG_MAX |
| 902 | if (chunk->offset > LONG_MAX) { |
| 903 | die("zcode offset too large"); |
| 904 | } |
| 905 | #endif |
| 906 | |
| 907 | memory_size = chunk->size; |
| 908 | story.offset = chunk->offset; |
| 909 | } catch (const Blorb::InvalidFile &) { |
| 910 | long size = story.io->filesize(); |
| 911 | |
| 912 | if (size == -1) { |
| 913 | die("unable to determine file size"); |
| 914 | } |
| 915 | #if LONG_MAX > UINT32_MAX |
| 916 | if (size > UINT32_MAX) { |
| 917 | die("file too large"); |
| 918 | } |
| 919 | #endif |
| 920 | |
| 921 | memory_size = size; |
| 922 | story.offset = 0; |
| 923 | } |
| 924 | |
| 925 | if (memory_size < 64) { |
| 926 | die("story file too small"); |
| 927 | } |
| 928 | #if UINT32_MAX > SIZE_MAX - 22 |
| 929 | if (memory_size > SIZE_MAX - 22) { |
| 930 | die("story file too large"); |
| 931 | } |
| 932 | #endif |
| 933 | |
| 934 | // It’s possible for a story to be cut short in the middle of an |
| 935 | // instruction. If so, the processing loop will run past the end of |
| 936 | // memory. Either pc needs to be checked each and every time it is |
| 937 | // incremented, or a small guard needs to be placed at the end of |
| 938 | // memory that will trigger an illegal instruction error. The latter |
| 939 | // is done by filling the end of memory with zeroes, which do not |
| 940 | // represent a valid instruction. |
| 941 | // |
| 942 | // There need to be at least 22 bytes for the worst case: 0xec |
| 943 | // (call_vs2) as the last byte in memory. The next two bytes, which |
| 944 | // will be zeroes, indicate that 8 large constants, or 16 bytes, will |
| 945 | // be next. This is a store instruction, so one more byte will be |
| 946 | // read to determine where to store. Another byte is read to |
| 947 | // determine the next opcode; this will be zero, which is nominally a |
| 948 | // 2OP, requiring two more bytes to be read. At this point the opcode |
| 949 | // will be looked up, resulting in an illegal instruction error. |
| 950 | try { |
| 951 | memory.resize(memory_size + 22); |
| 952 | } catch (const std::bad_alloc &) { |
| 953 | die("unable to allocate memory for story file"); |
| 954 | } |
| 955 | std::fill(memory.begin() + memory_size, memory.begin() + memory_size + 22, 0); |
| 956 | |
| 957 | process_story(*story.io, story.offset); |
| 958 | |
| 959 | if (options.show_id) { |
| 960 | #ifdef ZTERP_GLK |
| 961 | glk_set_style(style_Preformatted); |
| 962 | #endif |
| 963 | screen_puts(story_id); |
| 964 | } else { |
| 965 | start_story(); |
| 966 | |
| 967 | // If header transcript/fixed bits have been set, either by the |
| 968 | // story or by the user, this will activate them. |
| 969 | user_store_word(0x10, word(0x10)); |
| 970 | |
| 971 | if (zversion == 6 && options.warn_on_v6) { |
| 972 | show_message("Version 6 of the Z-machine is only partially supported. Be aware that the game might not function properly."); |
| 973 | } |
| 974 | |
| 975 | setup_opcodes(); |
| 976 | process_loop(); |
| 977 | } |
| 978 | } |
| 979 | |
| 980 | #ifdef ZTERP_GLK |
| 981 | void glk_main() |
| 982 | #else |
| 983 | int main(int argc, char **argv) |
| 984 | #endif |
| 985 | { |
| 986 | std::set_terminate([]() { |
| 987 | try { |
| 988 | std::rethrow_exception(std::current_exception()); |
| 989 | } catch (const std::exception &e) { |
| 990 | std::cerr << "Unhandled exception: " << e.what() << std::endl; |
| 991 | } catch (...) { |
| 992 | std::cerr << "Unhandled exception" << std::endl; |
| 993 | } |
| 994 | |
| 995 | std::abort(); |
| 996 | }); |
| 997 | |
| 998 | #ifdef ZTERP_GLK |
| 999 | try { |
| 1000 | real_main(); |
| 1001 | } catch (const Exit &) { |
| 1002 | } |
| 1003 | #else |
| 1004 | try { |
| 1005 | real_main(argc, argv); |
| 1006 | return 0; |
| 1007 | } catch (const Exit &exit) { |
| 1008 | return exit.code(); |
| 1009 | } |
| 1010 | #endif |
| 1011 | } |