Debian Codegraph @

terps/bocfel/io.cpp

raw symbols SCIP
1 // Copyright 2010-2025 Chris Spiegel.
2 //
3 // SPDX-License-Identifier: MIT
4
5 #include <climits>
6 #include <cstdio>
7 #include <cstring>
8 #include <new>
9 #include <stdexcept>
10 #include <vector>
11
12 #ifdef ZTERP_GLK
13 extern "C" {
14 #include <glk.h>
15 }
16 #else
17 #include <iostream>
18 #endif
19
20 #include "io.h"
21 #include "osdep.h"
22 #include "types.h"
23 #include "unicode.h"
24 #include "util.h"
25
26 #ifdef ZTERP_NO_STDIO
27 #pragma message("warning: macro ZTERP_NO_STDIO is deprecated in favor of ZTERP_GLK_NO_STDIO")
28 #define ZTERP_GLK_NO_STDIO
29 #endif
30
31 #ifdef ZTERP_GLK_NO_STDIO
32 #ifndef ZTERP_GLK_UNIX
33 #error ZTERP_GLK_NO_STDIO requires a Unix Glk
34 #endif
35
36 extern "C" {
37 #include <glkstart.h>
38 }
39
40 #ifndef GLKUNIX_FILEREF_CREATE_UNCLEANED
41 #error ZTERP_GLK_NO_STDIO requires the extension glkunix_fileref_create_by_name_uncleaned
42 // Prototype so that usage of this function doesn’t cause a compile error.
43 frefid_t glkunix_fileref_create_by_name_uncleaned(glui32 usage, const char *name, glui32 rock);
44 #endif
45 #endif
46
47 // Due to C++’s less-than-ideal type system, there’s no way to guarantee
48 // that an enum class actually contains a valid value. When checking the
49 // value of the I/O object’s type, this method is used as a sort of
50 // run-time type checker.
51 [[noreturn]]
52 void IO::bad_type() const {
53 die("internal error: unknown IO type %d", static_cast<int>(m_type));
54 }
55
56 // Certain streams are intended for use in text mode: stdin/stdout,
57 // transcripts, and command scripts. It is reasonable for users to
58 // expect newline translation to be properly handled in these cases,
59 // even though UNICODE_LINEFEED (10), as required by Glk (Glk API 0.7.0
60 // §2.2), is used internally.
61 bool IO::textmode() const {
62 return m_purpose == Purpose::Transcript || m_purpose == Purpose::Input;
63 }
64
65 // Glk does not like you to be able to pass a full filename to
66 // glk_fileref_create_by_name(); this means that Glk cannot be used to
67 // open arbitrary files. However, Glk is still required to prompt for
68 // files, such as in a save game situation. To allow I/O to work for
69 // opening files both with and without a prompt, it will use stdio when
70 // either Glk is not available, or when Glk is available but prompting
71 // is not necessary.
72 //
73 // This is needed because the IFF parser is required for both opening
74 // games (zblorb files) and for saving/restoring. The former needs to
75 // be able to access any file on the filesystem, and the latter needs to
76 // prompt. This is a headache.
77 //
78 // Prompting is assumed to be necessary if “filename” is null.
79 IO::IO(const std::string *filename, Mode mode, Purpose purpose, StreamRock namedglkrock) :
80 m_mode(mode),
81 m_purpose(purpose)
82 {
83
84 #if !defined(ZTERP_GLK) || !defined(ZTERP_GLK_NO_STDIO)
85 char smode[] = "wb";
86
87 if (m_mode == Mode::ReadOnly) {
88 smode[0] = 'r';
89 } else if (m_mode == Mode::Append) {
90 smode[0] = 'a';
91 }
92
93 if (textmode()) {
94 smode[1] = 0;
95 }
96 #endif
97
98 // No need to prompt.
99 if (filename != nullptr) {
100 // In no-stdio mode, always use Glk. Otherwise, if Glk is
101 // enabled, use Glk I/O if a rock is provided. If no rock is
102 // provided, use stdio.
103 #ifdef ZTERP_GLK_NO_STDIO
104 open_as_glk([&filename](glui32 usage, glui32) {
105 return glkunix_fileref_create_by_name_uncleaned(usage, filename->c_str(), 0);
106 }, namedglkrock);
107 #else
108 #if defined(ZTERP_GLK)
109 if (namedglkrock != StreamRock::None) {
110 open_as_glk([&filename](glui32 usage, glui32 filemode) {
111 return glk_fileref_create_by_name(usage, const_cast<char *>(filename->c_str()), 0);
112 }, namedglkrock);
113 } else
114 #endif
115 {
116 m_type = Type::StandardIO;
117 m_file = File(std::fopen(filename->c_str(), smode), true);
118 if (m_file.stdio == nullptr) {
119 throw OpenError();
120 }
121 }
122 #endif
123 } else { // Prompt.
124 #ifdef ZTERP_GLK
125 open_as_glk([](glui32 usage, glui32 filemode) {
126 return glk_fileref_create_by_prompt(usage, filemode, 0);
127 }, namedglkrock);
128 #else
129 std::string fn, prompt;
130
131 switch (m_purpose) {
132 case Purpose::Data:
133 prompt = "Enter filename for data: ";
134 break;
135 case Purpose::Save:
136 prompt = "Enter filename for save game: ";
137 break;
138 case Purpose::Transcript:
139 prompt = "Enter filename for transcript: ";
140 break;
141 case Purpose::Input:
142 prompt = "Enter filename for command record: ";
143 break;
144 default:
145 throw OpenError();
146 }
147
148 std::cout << std::endl << prompt << std::flush;
149 if (!std::getline(std::cin, fn) || fn.empty()) {
150 throw OpenError();
151 }
152
153 m_type = Type::StandardIO;
154 m_file = File(std::fopen(fn.c_str(), smode), true);
155 if (m_file.stdio == nullptr) {
156 throw OpenError();
157 }
158 #endif
159 }
160 }
161
162 #ifdef ZTERP_GLK
163 void IO::open_as_glk(const std::function<frefid_t(glui32 usage, glui32 filemode)> &create_fref, StreamRock rock)
164 {
165 glui32 usage = fileusage_BinaryMode, filemode;
166
167 switch (m_purpose) {
168 case Purpose::Data:
169 usage |= fileusage_Data;
170 break;
171 case Purpose::Save:
172 usage |= fileusage_SavedGame;
173 break;
174 case Purpose::Transcript:
175 usage |= fileusage_Transcript;
176 break;
177 case Purpose::Input:
178 usage |= fileusage_InputRecord;
179 break;
180 default:
181 throw OpenError();
182 }
183
184 switch (m_mode) {
185 case Mode::ReadOnly:
186 filemode = filemode_Read;
187 break;
188 case Mode::WriteOnly:
189 filemode = filemode_Write;
190 break;
191 case Mode::Append:
192 filemode = filemode_WriteAppend;
193 break;
194 default:
195 throw OpenError();
196 }
197
198 frefid_t ref = create_fref(usage, filemode);
199 if (ref == nullptr) {
200 throw OpenError();
201 }
202
203 m_type = Type::Glk;
204 m_file = File(glk_stream_open_file(ref, filemode, static_cast<glui32>(rock)));
205 glk_fileref_destroy(ref);
206 if (m_file.glk == nullptr) {
207 throw OpenError();
208 }
209 }
210 #endif
211
212 // Instead of being file-backed, indicate that this I/O object is
213 // memory-backed. This allows internal save states (for @save_undo as
214 // well as meta-saves created by /ps) to use Quetzal as their save
215 // format. This is helpful because meta-saves have to track extra
216 // information, and reusing the Quetzal code (plus extensions)
217 // eliminates the need for code duplication.
218 //
219 // The I/O object starts out with the contents of the passed-in buffer,
220 // which may be empty.
221 IO::IO(std::vector<uint8_t> buf, Mode mode) :
222 m_file(File(std::move(buf))),
223 m_type(Type::Memory),
224 m_mode(mode),
225 m_purpose(Purpose::Data)
226 {
227 if (mode == Mode::Append) {
228 m_file.backing.offset = m_file.backing.memory.size();
229 }
230 }
231
232 // Return a reference to the I/O instance’s internal buffer. This
233 // represents the state of the “file” at the time the function is
234 // called. The reference is only valid until the next call to an I/O
235 // method on this same I/O instance.
236 const std::vector<uint8_t> &IO::get_memory() const
237 {
238 if (m_type != Type::Memory) {
239 throw std::runtime_error("not a memory object");
240 }
241
242 return m_file.backing.memory;
243 }
244
245 void IO::seek(long offset, SeekFrom whence)
246 {
247 // To smooth over differences between Glk and standard I/O, don’t
248 // allow seeking in append-only streams.
249 if (m_mode == Mode::Append) {
250 throw IOError();
251 }
252
253 switch (m_type) {
254 case Type::StandardIO:
255 if (std::fseek(m_file.stdio.get(), offset, whence == SeekFrom::Start ? SEEK_SET : whence == SeekFrom::Current ? SEEK_CUR : SEEK_END) != 0) {
256 throw IOError();
257 }
258 return;
259 case Type::Memory:
260 // Negative offsets are unsupported because they aren’t used.
261 if (offset < 0) {
262 throw IOError();
263 }
264
265 if (whence == SeekFrom::Current) {
266 // Overflow.
267 if (LONG_MAX - offset < m_file.backing.offset) {
268 throw IOError();
269 }
270
271 offset = m_file.backing.offset + offset;
272 } else if (whence == SeekFrom::End) {
273 // SeekFrom::End is only used to seek directly to the end.
274 if (offset != 0) {
275 throw IOError();
276 }
277
278 offset = m_file.backing.memory.size();
279 } else if (whence == SeekFrom::Start) {
280 // Do nothing; offset is where it should be.
281 }
282
283 // If seeking beyond the end, write zeros.
284 while (offset > m_file.backing.memory.size()) {
285 write8(0);
286 }
287
288 m_file.backing.offset = offset;
289
290 return;
291 #ifdef ZTERP_GLK
292 case Type::Glk:
293 glk_stream_set_position(m_file.glk.get(), offset, whence == SeekFrom::Start ? seekmode_Start : whence == SeekFrom::Current ? seekmode_Current : seekmode_End);
294 return; // glk_stream_set_position can’t signal failure
295 #endif
296 default:
297 bad_type();
298 }
299 }
300
301 long IO::tell() const
302 {
303 switch (m_type) {
304 case Type::StandardIO: {
305 auto offset = std::ftell(m_file.stdio.get());
306 if (offset == -1) {
307 throw IOError();
308 }
309
310 return offset;
311 }
312 case Type::Memory:
313 return m_file.backing.offset;
314 #ifdef ZTERP_GLK
315 case Type::Glk: {
316 auto offset = glk_stream_get_position(m_file.glk.get());
317 #if LONG_MAX < UINT32_MAX
318 if (offset > LONG_MAX) {
319 throw IOError();
320 }
321 #endif
322
323 return offset;
324 }
325 #endif
326 default:
327 bad_type();
328 }
329 }
330
331 // read() and write() always operate in terms of bytes, not characters.
332 size_t IO::read(void *buf, size_t n)
333 {
334 size_t total = 0;
335
336 while (total < n) {
337 size_t s;
338
339 switch (m_type) {
340 case Type::StandardIO:
341 s = std::fread(buf, 1, n - total, m_file.stdio.get());
342 break;
343 case Type::Memory: {
344 Backing *b = &m_file.backing;
345 auto remaining = b->memory.size() - b->offset;
346
347 if (m_mode != Mode::ReadOnly) {
348 return 0;
349 }
350
351 s = remaining < n ? remaining : n;
352 if (s != 0) {
353 std::memcpy(buf, &b->memory[b->offset], s);
354 b->offset += s;
355 }
356
357 break;
358 }
359 #ifdef ZTERP_GLK
360 case Type::Glk: {
361 glui32 s32 = glk_get_buffer_stream(m_file.glk.get(), static_cast<char *>(buf), n - total);
362 // This should only happen if m_file.glk is invalid.
363 if (s32 == static_cast<glui32>(-1)) {
364 s = 0;
365 } else {
366 s = s32;
367 }
368
369 break;
370 }
371 #endif
372 default:
373 bad_type();
374 }
375
376 if (s == 0) {
377 break;
378 }
379 total += s;
380 buf = (static_cast<char *>(buf)) + s;
381 }
382
383 return total;
384 }
385
386 void IO::read_exact(void *buf, size_t n)
387 {
388 if (read(buf, n) != n) {
389 throw IOError();
390 }
391 }
392
393 size_t IO::write(const void *buf, size_t n)
394 {
395 if (n == 0) {
396 return 0;
397 }
398
399 switch (m_type) {
400 case Type::StandardIO: {
401 size_t s, total = 0;
402
403 while (total < n && (s = std::fwrite(buf, 1, n - total, m_file.stdio.get())) > 0) {
404 total += s;
405 buf = (static_cast<const char *>(buf)) + s;
406 }
407
408 return total;
409 }
410 case Type::Memory: {
411 Backing *b = &m_file.backing;
412 auto remaining = b->memory.size() - b->offset;
413
414 if (m_mode != Mode::WriteOnly && m_mode != Mode::Append) {
415 return 0;
416 }
417
418 if (n > remaining) {
419 try {
420 b->memory.resize(b->memory.size() + (n - remaining));
421 } catch (const std::bad_alloc &) {
422 throw IOError();
423 }
424 }
425
426 std::memcpy(&b->memory[b->offset], buf, n);
427
428 b->offset += n;
429
430 return n;
431 }
432 #ifdef ZTERP_GLK
433 case Type::Glk:
434 glk_put_buffer_stream(m_file.glk.get(), const_cast<char *>(static_cast<const char *>(buf)), n);
435 return n; // glk_put_buffer_stream() can’t signal a short write
436 #endif
437 default:
438 bad_type();
439 }
440 }
441
442 void IO::write_exact(const void *buf, size_t n)
443 {
444 if (write(buf, n) != n) {
445 throw IOError();
446 }
447 }
448
449 uint8_t IO::read8()
450 {
451 uint8_t v;
452
453 read_exact(&v, sizeof v);
454
455 return v;
456 }
457
458 uint16_t IO::read16()
459 {
460 uint8_t buf[2];
461
462 read_exact(buf, sizeof buf);
463
464 return (static_cast<uint16_t>(buf[0]) << 8) | (static_cast<uint16_t>(buf[1]));
465 }
466
467 uint32_t IO::read32()
468 {
469 uint8_t buf[4];
470
471 read_exact(buf, sizeof buf);
472
473 return ((static_cast<uint32_t>(buf[0])) << 24) |
474 ((static_cast<uint32_t>(buf[1])) << 16) |
475 ((static_cast<uint32_t>(buf[2])) << 8) |
476 ((static_cast<uint32_t>(buf[3])) );
477 }
478
479 void IO::write8(uint8_t v)
480 {
481 write_exact(&v, sizeof v);
482 }
483
484 void IO::write16(uint16_t v)
485 {
486 uint8_t buf[2];
487
488 buf[0] = v >> 8;
489 buf[1] = v & 0xff;
490
491 write_exact(buf, sizeof buf);
492 }
493
494 void IO::write32(uint32_t v)
495 {
496 uint8_t buf[4];
497
498 buf[0] = (v >> 24) & 0xff;
499 buf[1] = (v >> 16) & 0xff;
500 buf[2] = (v >> 8) & 0xff;
501 buf[3] = (v >> 0) & 0xff;
502
503 write_exact(buf, sizeof buf);
504 }
505
506 // getc() and putc() are meant to operate in terms of characters, not
507 // bytes. That is, unlike C++, bytes and characters are not equivalent
508 // as far as Zterp’s I/O system is concerned.
509
510 // Read a UTF-8 character, returning it. If limit16 is true, any Unicode
511 // values which are greater than UINT16_MAX will be converted to the
512 // Unicode replacement character. Otherwise, values are returned as-is.
513 // -1 is returned on EOF.
514 //
515 // If an invalid UTF-8 sequence is found, the Unicode replacement
516 // character is returned.
517 long IO::getc(bool limit16)
518 {
519 long ret;
520 uint8_t c;
521 class NotUnicode : public std::exception {};
522
523 try {
524 c = read8();
525 } catch (const IOError &) {
526 return -1;
527 }
528
529 // Read a byte and make sure it’s part of a valid UTF-8 sequence.
530 auto read_byte = [this] {
531 uint8_t b = read8();
532
533 if ((b & 0xc0) != 0x80) {
534 throw NotUnicode();
535 } else {
536 return b;
537 }
538 };
539
540 try {
541 if ((c & 0x80) == 0) { // One byte.
542 ret = c;
543 } else if ((c & 0xe0) == 0xc0) { // Two bytes.
544 ret = (c & 0x1f) << 6;
545 ret |= (read_byte() & 0x3f);
546 if (ret < 0x80) {
547 throw NotUnicode();
548 }
549 } else if ((c & 0xf0) == 0xe0) { // Three bytes.
550 ret = (c & 0x0f) << 12;
551 ret |= (read_byte() & 0x3f) << 6;
552 ret |= (read_byte() & 0x3f);
553 if (ret < 0x800) {
554 throw NotUnicode();
555 }
556 } else if ((c & 0xf8) == 0xf0) { // Four bytes.
557 ret = (static_cast<long>(c) & 0x07) << 18;
558 ret |= (read_byte() & 0x3f) << 12;
559 ret |= (read_byte() & 0x3f) << 6;
560 ret |= (read_byte() & 0x3f);
561 if (ret < 0x10000) {
562 throw NotUnicode();
563 }
564 } else { // Invalid value.
565 ret = UNICODE_REPLACEMENT;
566 }
567 } catch (const IOError &) {
568 return -1;
569 } catch (const NotUnicode &) {
570 return UNICODE_REPLACEMENT;
571 }
572
573 if (ret > (limit16 ? UINT16_MAX : 0x10ffff)) {
574 ret = UNICODE_REPLACEMENT;
575 }
576
577 if (textmode() && ret == '\n') {
578 ret = UNICODE_LINEFEED;
579 }
580
581 return ret;
582 }
583
584 // Write a Unicode character as UTF-8. If this fails it may write a
585 // partial character.
586 void IO::putc(uint32_t c)
587 {
588 if (textmode() && c == UNICODE_LINEFEED) {
589 c = '\n';
590 }
591
592 if (c >= 0x110000) {
593 c = UNICODE_REPLACEMENT;
594 }
595
596 if (c < 0x80) {
597 write8(c);
598 } else if (c < 0x800) {
599 write8(0xc0 | ((c >> 6) & 0x1f));
600 write8(0x80 | ((c ) & 0x3f));
601 } else if (c < 0x10000) {
602 write8(0xe0 | ((c >> 12) & 0x0f));
603 write8(0x80 | ((c >> 6) & 0x3f));
604 write8(0x80 | ((c ) & 0x3f));
605 } else if (c < 0x110000) {
606 write8(0xf0 | ((c >> 18) & 0x07));
607 write8(0x80 | ((c >> 12) & 0x3f));
608 write8(0x80 | ((c >> 6) & 0x3f));
609 write8(0x80 | ((c ) & 0x3f));
610 }
611 }
612
613 // Read and return a line, where a line is defined as a collection of
614 // characters terminated by a Unicode linefeed (0xa). If EOF is
615 // encountered at any point (including after characters have been read,
616 // but before a linefeed), EndOfFile is thrown, which means that all
617 // lines, including the last one, must end in a linefeed. If the last
618 // line does not end in a linefeed, its characters will be read, but
619 // ultimately discarded, so can be considered lost and unrecoverable.
620 std::vector<uint16_t> IO::readline()
621 {
622 std::vector<uint16_t> result;
623
624 while (true) {
625 long c = getc(true);
626
627 if (c == -1) {
628 throw EndOfFile();
629 }
630
631 if (c == UNICODE_LINEFEED) {
632 break;
633 }
634
635 result.push_back(c);
636 }
637
638 return result;
639 }
640
641 long IO::filesize() const
642 {
643 switch (m_type) {
644 case Type::StandardIO:
645 if (!textmode()) {
646 return zterp_os_filesize(m_file.stdio.get());
647 }
648 break;
649 case Type::Memory:
650 return m_file.backing.memory.size();
651 #ifdef ZTERP_GLK
652 case Type::Glk: {
653 auto orig = glk_stream_get_position(m_file.glk.get());
654 glk_stream_set_position(m_file.glk.get(), 0, seekmode_End);
655 long size = glk_stream_get_position(m_file.glk.get());
656 glk_stream_set_position(m_file.glk.get(), orig, seekmode_Start);
657 return size;
658 }
659 #endif
660 default:
661 bad_type();
662 }
663
664 return -1;
665 }
666
667 void IO::flush()
668 {
669 if (m_type == Type::StandardIO && (m_mode == Mode::WriteOnly || m_mode == Mode::Append)) {
670 std::fflush(m_file.stdio.get());
671 }
672 }