Debian Codegraph @

src/libchdr_chd.c

raw symbols SCIP
1 /***************************************************************************
2
3 chd.c
4
5 MAME Compressed Hunks of Data file format
6
7 ****************************************************************************
8
9 Copyright Aaron Giles
10 All rights reserved.
11
12 Redistribution and use in source and binary forms, with or without
13 modification, are permitted provided that the following conditions are
14 met:
15
16 * Redistributions of source code must retain the above copyright
17 notice, this list of conditions and the following disclaimer.
18 * Redistributions in binary form must reproduce the above copyright
19 notice, this list of conditions and the following disclaimer in
20 the documentation and/or other materials provided with the
21 distribution.
22 * Neither the name 'MAME' nor the names of its contributors may be
23 used to endorse or promote products derived from this software
24 without specific prior written permission.
25
26 THIS SOFTWARE IS PROVIDED BY AARON GILES ''AS IS'' AND ANY EXPRESS OR
27 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
28 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
29 DISCLAIMED. IN NO EVENT SHALL AARON GILES BE LIABLE FOR ANY DIRECT,
30 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
31 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
32 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
34 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
35 IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 POSSIBILITY OF SUCH DAMAGE.
37
38 ***************************************************************************/
39
40 /* Feature test macros: must come before any system header.
41 * Ensures fseeko/ftello are declared under strict C99/C11 and
42 * that 64-bit file offsets are used on 32-bit platforms (armhf,
43 * i386, and other time64/LFS rebuilds). */
44 #if !defined(_WIN32) && !defined(__PS3__) && !defined(__SWITCH__) && !defined(__vita__)
45 # ifndef _POSIX_C_SOURCE
46 # define _POSIX_C_SOURCE 200809L
47 # endif
48 # ifndef _FILE_OFFSET_BITS
49 # define _FILE_OFFSET_BITS 64
50 # endif
51 #endif
52
53 #include <stddef.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <limits.h>
58 #include <time.h>
59
60 #include "../include/libchdr/chd.h"
61 #include "../include/libchdr/cdrom.h"
62 #include "codec_cdfl.h"
63 #include "codec_cdlz.h"
64 #include "codec_cdzl.h"
65 #include "codec_cdzs.h"
66 #include "codec_flac.h"
67 #include "codec_huff.h"
68 #include "codec_lzma.h"
69 #include "codec_zlib.h"
70 #include "codec_zstd.h"
71 #include "../include/libchdr/huffman.h"
72 #include "../include/libchdr/macros.h"
73
74 #include "../deps/lzma-25.01/include/LzmaDec.h"
75
76 #undef TRUE
77 #undef FALSE
78 #define TRUE 1
79 #define FALSE 0
80
81 #define SHA1_DIGEST_SIZE 20
82
83 /***************************************************************************
84 CONSTANTS
85 ***************************************************************************/
86
87 #define MAP_STACK_ENTRIES 512 /* max number of entries to use on the stack */
88 #define MAP_ENTRY_SIZE 16 /* V3 and later */
89 #define OLD_MAP_ENTRY_SIZE 8 /* V1-V2 */
90 #define METADATA_HEADER_SIZE 16 /* metadata header size */
91
92 #define MAP_ENTRY_FLAG_TYPE_MASK 0x0f /* what type of hunk */
93 #define MAP_ENTRY_FLAG_NO_CRC 0x10 /* no CRC is present */
94
95 #define CHD_V1_SECTOR_SIZE 512 /* size of a "sector" in the V1 header */
96
97 #define CHD_MAX_HUNK_SIZE (128 * 1024 * 1024) /* hunk size probably shouldn't be more than 128MB */
98
99 /* Sanity cap on logical (decompressed) CHD size. Large enough to cover
100 * any realistic disc image: BD50 PS3 ISOs (50 GB), arcade laserdisc
101 * CHDs, and future-proofing for larger optical formats. 1 TB is well
102 * under any integer-overflow threshold, and actual allocation safety
103 * is further bounded by CHD_MAX_HUNK_SIZE and the totalhunks check in
104 * header_read. Previously 10 GB, which rejected legitimate PS3 ISOs
105 * (#147). */
106 #define CHD_MAX_FILE_SIZE (1024ULL * 1024 * 1024 * 1024)
107
108 #define COOKIE_VALUE 0xbaadf00d
109
110 #define END_OF_LIST_COOKIE "EndOfListCookie"
111
112 #define NO_MATCH (~0)
113
114 /* V3-V4 entry types */
115 enum
116 {
117 V34_MAP_ENTRY_TYPE_INVALID = 0, /* invalid type */
118 V34_MAP_ENTRY_TYPE_COMPRESSED = 1, /* standard compression */
119 V34_MAP_ENTRY_TYPE_UNCOMPRESSED = 2, /* uncompressed data */
120 V34_MAP_ENTRY_TYPE_MINI = 3, /* mini: use offset as raw data */
121 V34_MAP_ENTRY_TYPE_SELF_HUNK = 4, /* same as another hunk in this file */
122 V34_MAP_ENTRY_TYPE_PARENT_HUNK = 5, /* same as a hunk in the parent file */
123 V34_MAP_ENTRY_TYPE_2ND_COMPRESSED = 6 /* compressed with secondary algorithm (usually FLAC CDDA) */
124 };
125
126 /* V5 compression types */
127 enum
128 {
129 /* codec #0
130 * these types are live when running */
131 COMPRESSION_TYPE_0 = 0,
132 /* codec #1 */
133 COMPRESSION_TYPE_1 = 1,
134 /* codec #2 */
135 COMPRESSION_TYPE_2 = 2,
136 /* codec #3 */
137 COMPRESSION_TYPE_3 = 3,
138 /* no compression; implicit length = hunkbytes */
139 COMPRESSION_NONE = 4,
140 /* same as another block in this chd */
141 COMPRESSION_SELF = 5,
142 /* same as a hunk's worth of units in the parent chd */
143 COMPRESSION_PARENT = 6,
144
145 /* start of small RLE run (4-bit length)
146 * these additional pseudo-types are used for compressed encodings: */
147 COMPRESSION_RLE_SMALL,
148 /* start of large RLE run (8-bit length) */
149 COMPRESSION_RLE_LARGE,
150 /* same as the last COMPRESSION_SELF block */
151 COMPRESSION_SELF_0,
152 /* same as the last COMPRESSION_SELF block + 1 */
153 COMPRESSION_SELF_1,
154 /* same block in the parent */
155 COMPRESSION_PARENT_SELF,
156 /* same as the last COMPRESSION_PARENT block */
157 COMPRESSION_PARENT_0,
158 /* same as the last COMPRESSION_PARENT block + 1 */
159 COMPRESSION_PARENT_1
160 };
161
162 /***************************************************************************
163 MACROS
164 ***************************************************************************/
165
166 #define EARLY_EXIT(x) do { (void)(x); goto cleanup; } while (0)
167
168 /***************************************************************************
169 TYPE DEFINITIONS
170 ***************************************************************************/
171
172 /* interface to a codec */
173 typedef struct _codec_interface codec_interface;
174 struct _codec_interface
175 {
176 uint32_t compression; /* type of compression */
177 const char *compname; /* name of the algorithm */
178 uint8_t lossy; /* is this a lossy algorithm? */
179 chd_error (*init)(void *codec, uint32_t hunkbytes); /* codec initialize */
180 void (*free)(void *codec); /* codec free */
181 chd_codec_interface_decompress decompress; /* decompress data */
182 chd_error (*config)(void *codec, int param, void *config); /* configure */
183 };
184
185 /* a single map entry */
186 typedef struct _map_entry map_entry;
187 struct _map_entry
188 {
189 uint64_t offset; /* offset within the file of the data */
190 uint32_t crc; /* 32-bit CRC of the data */
191 uint32_t length; /* length of the data */
192 uint8_t flags; /* misc flags */
193 };
194
195 /* a single metadata entry */
196 typedef struct _metadata_entry metadata_entry;
197 struct _metadata_entry
198 {
199 uint64_t offset; /* offset within the file of the header */
200 uint64_t next; /* offset within the file of the next header */
201 uint64_t prev; /* offset within the file of the previous header */
202 uint32_t length; /* length of the metadata */
203 uint32_t metatag; /* metadata tag */
204 uint8_t flags; /* flag bits */
205 };
206
207 /* internal representation of an open CHD file */
208 struct _chd_file
209 {
210 uint32_t cookie; /* cookie, should equal COOKIE_VALUE */
211
212 core_file_callbacks_and_argp file; /* handle to the open core file */
213 uint64_t file_size; /* size of the core file */
214 chd_header header; /* header, extracted from file */
215
216 chd_file * parent; /* pointer to parent file, or NULL */
217
218 map_entry * map; /* array of map entries */
219
220 uint8_t * compressed; /* pointer to buffer for compressed data */
221 const codec_interface * codecintf[4]; /* interface to the codec */
222
223 struct
224 {
225 zlib_codec_data zlib; /* zlib codec data */
226 lzma_codec_data lzma; /* lzma codec data */
227 huff_codec_data huff; /* huff codec data */
228 flac_codec_data flac; /* flac codec data */
229 zstd_codec_data zstd; /* zstd codec data */
230 cdzl_codec_data cdzl; /* cdzl codec data */
231 cdlz_codec_data cdlz; /* cdlz codec data */
232 cdfl_codec_data cdfl; /* cdfl codec data */
233 cdzs_codec_data cdzs; /* cdzs codec data */
234 } codec_data;
235
236 uint8_t * file_cache; /* cache of underlying file */
237 };
238
239
240 /***************************************************************************
241 GLOBAL VARIABLES
242 ***************************************************************************/
243
244 static const uint8_t nullmd5[CHD_MD5_BYTES] = { 0 };
245 static const uint8_t nullsha1[CHD_SHA1_BYTES] = { 0 };
246
247 /***************************************************************************
248 PROTOTYPES
249 ***************************************************************************/
250
251 /* core_file_callbacks wrappers over stdio */
252 static void *core_stdio_fopen(char const *path);
253 static uint64_t core_stdio_fsize(void *file);
254 static size_t core_stdio_fread(void *ptr, size_t size, size_t nmemb, void *file);
255 static int core_stdio_fclose(void *file);
256 static int core_stdio_fclose_nonowner(void *file); /* alternate fclose used by chd_open_file */
257 static int core_stdio_fseek(void* file, int64_t offset, int whence);
258
259 /* Legacy core_file wrappers */
260 static uint64_t core_legacy_fsize(void *file);
261 static size_t core_legacy_fread(void *ptr, size_t size, size_t nmemb, void *file);
262 static int core_legacy_fclose(void *file);
263 static int core_legacy_fseek(void* file, int64_t offset, int whence);
264
265 /* internal header operations */
266 static chd_error header_read(chd_file *chd);
267
268 /* internal hunk read/write */
269 static chd_error hunk_read_into_memory(chd_file *chd, uint32_t hunknum, uint8_t *dest);
270
271 /* internal map access */
272 static chd_error map_read(chd_file *chd);
273
274 /* metadata management */
275 static chd_error metadata_find_entry(chd_file *chd, uint32_t metatag, uint32_t metaindex, metadata_entry *metaentry);
276
277
278 /***************************************************************************
279 CODEC INTERFACES
280 ***************************************************************************/
281
282 static const codec_interface codec_interfaces[] =
283 {
284 /* "none" or no compression */
285 {
286 CHDCOMPRESSION_NONE,
287 "none",
288 FALSE,
289 NULL,
290 NULL,
291 NULL,
292 NULL
293 },
294
295 /* standard zlib compression */
296 {
297 CHDCOMPRESSION_ZLIB,
298 "zlib",
299 FALSE,
300 zlib_codec_init,
301 zlib_codec_free,
302 zlib_codec_decompress,
303 NULL
304 },
305
306 /* zlib+ compression */
307 {
308 CHDCOMPRESSION_ZLIB_PLUS,
309 "zlib+",
310 FALSE,
311 zlib_codec_init,
312 zlib_codec_free,
313 zlib_codec_decompress,
314 NULL
315 },
316
317 /* V5 zlib compression */
318 {
319 CHD_CODEC_ZLIB,
320 "zlib (Deflate)",
321 FALSE,
322 zlib_codec_init,
323 zlib_codec_free,
324 zlib_codec_decompress,
325 NULL
326 },
327
328 /* V5 lzma compression */
329 {
330 CHD_CODEC_LZMA,
331 "lzma (LZMA)",
332 FALSE,
333 lzma_codec_init,
334 lzma_codec_free,
335 lzma_codec_decompress,
336 NULL
337 },
338
339 /* V5 huffman compression */
340 {
341 CHD_CODEC_HUFFMAN,
342 "Huffman",
343 FALSE,
344 huff_codec_init,
345 huff_codec_free,
346 huff_codec_decompress,
347 NULL
348 },
349
350 /* V5 flac compression */
351 {
352 CHD_CODEC_FLAC,
353 "flac (FLAC)",
354 FALSE,
355 flac_codec_init,
356 flac_codec_free,
357 flac_codec_decompress,
358 NULL
359 },
360 /* V5 zstd compression */
361 {
362 CHD_CODEC_ZSTD,
363 "ZStandard",
364 FALSE,
365 zstd_codec_init,
366 zstd_codec_free,
367 zstd_codec_decompress,
368 NULL
369 },
370
371 /* V5 CD zlib compression */
372 {
373 CHD_CODEC_CD_ZLIB,
374 "cdzl (CD Deflate)",
375 FALSE,
376 cdzl_codec_init,
377 cdzl_codec_free,
378 cdzl_codec_decompress,
379 NULL
380 },
381
382 /* V5 CD lzma compression */
383 {
384 CHD_CODEC_CD_LZMA,
385 "cdlz (CD LZMA)",
386 FALSE,
387 cdlz_codec_init,
388 cdlz_codec_free,
389 cdlz_codec_decompress,
390 NULL
391 },
392
393 /* V5 CD flac compression */
394 {
395 CHD_CODEC_CD_FLAC,
396 "cdfl (CD FLAC)",
397 FALSE,
398 cdfl_codec_init,
399 cdfl_codec_free,
400 cdfl_codec_decompress,
401 NULL
402 },
403 /* V5 CD zstd compression */
404 {
405 CHD_CODEC_CD_ZSTD,
406 "cdzs (CD ZStandard)",
407 FALSE,
408 cdzs_codec_init,
409 cdzs_codec_free,
410 cdzs_codec_decompress,
411 NULL
412 }
413
414 };
415
416 /***************************************************************************
417 INLINE FUNCTIONS
418 ***************************************************************************/
419
420 /*-------------------------------------------------
421 seek_and_read - read data from file at
422 specified position
423 -------------------------------------------------*/
424
425 static CHDR_INLINE int seek_and_read(chd_file *chd, uint64_t position, void *buffer, size_t total_bytes)
426 {
427 if (core_fseek(&chd->file, position, SEEK_SET) != 0)
428 return FALSE;
429 if (core_fread(&chd->file, buffer, total_bytes) != total_bytes)
430 return FALSE;
431
432 return TRUE;
433 }
434
435 /*-------------------------------------------------
436 get_bigendian_uint64_t - fetch a uint64_t from
437 the data stream in bigendian order
438 -------------------------------------------------*/
439
440 static CHDR_INLINE uint64_t get_bigendian_uint64_t(const uint8_t *base)
441 {
442 return ((uint64_t)base[0] << 56) | ((uint64_t)base[1] << 48) | ((uint64_t)base[2] << 40) | ((uint64_t)base[3] << 32) |
443 ((uint64_t)base[4] << 24) | ((uint64_t)base[5] << 16) | ((uint64_t)base[6] << 8) | (uint64_t)base[7];
444 }
445
446 /*-------------------------------------------------
447 put_bigendian_uint64_t - write a uint64_t to
448 the data stream in bigendian order
449 -------------------------------------------------*/
450
451 static CHDR_INLINE void put_bigendian_uint64_t(uint8_t *base, uint64_t value)
452 {
453 base[0] = value >> 56;
454 base[1] = value >> 48;
455 base[2] = value >> 40;
456 base[3] = value >> 32;
457 base[4] = value >> 24;
458 base[5] = value >> 16;
459 base[6] = value >> 8;
460 base[7] = value;
461 }
462
463 /*-------------------------------------------------
464 get_bigendian_uint48 - fetch a UINT48 from
465 the data stream in bigendian order
466 -------------------------------------------------*/
467
468 static CHDR_INLINE uint64_t get_bigendian_uint48(const uint8_t *base)
469 {
470 return ((uint64_t)base[0] << 40) | ((uint64_t)base[1] << 32) |
471 ((uint64_t)base[2] << 24) | ((uint64_t)base[3] << 16) | ((uint64_t)base[4] << 8) | (uint64_t)base[5];
472 }
473
474 /*-------------------------------------------------
475 put_bigendian_uint48 - write a UINT48 to
476 the data stream in bigendian order
477 -------------------------------------------------*/
478
479 static CHDR_INLINE void put_bigendian_uint48(uint8_t *base, uint64_t value)
480 {
481 value &= 0xffffffffffff;
482 base[0] = value >> 40;
483 base[1] = value >> 32;
484 base[2] = value >> 24;
485 base[3] = value >> 16;
486 base[4] = value >> 8;
487 base[5] = value;
488 }
489 /*-------------------------------------------------
490 get_bigendian_uint32_t - fetch a uint32_t from
491 the data stream in bigendian order
492 -------------------------------------------------*/
493
494 static CHDR_INLINE uint32_t get_bigendian_uint32_t(const uint8_t *base)
495 {
496 return (base[0] << 24) | (base[1] << 16) | (base[2] << 8) | base[3];
497 }
498
499 /*-------------------------------------------------
500 put_bigendian_uint32_t - write a uint32_t to
501 the data stream in bigendian order
502 -------------------------------------------------*/
503
504 static CHDR_INLINE void put_bigendian_uint32_t(uint8_t *base, uint32_t value)
505 {
506 base[0] = value >> 24;
507 base[1] = value >> 16;
508 base[2] = value >> 8;
509 base[3] = value;
510 }
511
512 /*-------------------------------------------------
513 put_bigendian_uint24 - write a UINT24 to
514 the data stream in bigendian order
515 -------------------------------------------------*/
516
517 static CHDR_INLINE void put_bigendian_uint24(uint8_t *base, uint32_t value)
518 {
519 value &= 0xffffff;
520 base[0] = value >> 16;
521 base[1] = value >> 8;
522 base[2] = value;
523 }
524
525 /*-------------------------------------------------
526 get_bigendian_uint24 - fetch a UINT24 from
527 the data stream in bigendian order
528 -------------------------------------------------*/
529
530 static CHDR_INLINE uint32_t get_bigendian_uint24(const uint8_t *base)
531 {
532 return (base[0] << 16) | (base[1] << 8) | base[2];
533 }
534
535 /*-------------------------------------------------
536 get_bigendian_uint16 - fetch a uint16_t from
537 the data stream in bigendian order
538 -------------------------------------------------*/
539
540 static CHDR_INLINE uint16_t get_bigendian_uint16(const uint8_t *base)
541 {
542 return (base[0] << 8) | base[1];
543 }
544
545 /*-------------------------------------------------
546 put_bigendian_uint16 - write a uint16_t to
547 the data stream in bigendian order
548 -------------------------------------------------*/
549
550 static CHDR_INLINE void put_bigendian_uint16(uint8_t *base, uint16_t value)
551 {
552 base[0] = value >> 8;
553 base[1] = value;
554 }
555
556 /*-------------------------------------------------
557 map_extract - extract a single map
558 entry from the datastream
559 -------------------------------------------------*/
560
561 static CHDR_INLINE void map_extract(const uint8_t *base, map_entry *entry)
562 {
563 entry->offset = get_bigendian_uint64_t(&base[0]);
564 entry->crc = get_bigendian_uint32_t(&base[8]);
565 entry->length = get_bigendian_uint16(&base[12]) | (base[14] << 16);
566 entry->flags = base[15];
567 }
568
569 /*-------------------------------------------------
570 map_size_v5 - calculate CHDv5 map size
571 -------------------------------------------------*/
572 static CHDR_INLINE int map_size_v5(chd_header* header, size_t *size)
573 {
574 /* Avoid overflow due to corrupted data. */
575 const size_t max_hunkcount = ((size_t)-1 / header->mapentrybytes);
576 if (header->hunkcount > max_hunkcount)
577 return FALSE;
578
579 *size = (size_t)header->hunkcount * header->mapentrybytes;
580 return TRUE;
581 }
582
583 /*-------------------------------------------------
584 crc16 - calculate CRC16 (from hashing.cpp)
585 -------------------------------------------------*/
586 uint16_t crc16(const void *data, uint32_t length)
587 {
588 uint16_t crc = 0xffff;
589
590 static const uint16_t s_table[256] =
591 {
592 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
593 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
594 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
595 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
596 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
597 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
598 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
599 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
600 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
601 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
602 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
603 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
604 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
605 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
606 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
607 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
608 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
609 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
610 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
611 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
612 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
613 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
614 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
615 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
616 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
617 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
618 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
619 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
620 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
621 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
622 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
623 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
624 };
625
626 const uint8_t *src = (uint8_t*)data;
627
628 /* fetch the current value into a local and rip through the source data */
629 while (length-- != 0)
630 crc = (crc << 8) ^ s_table[(crc >> 8) ^ *src++];
631 return crc;
632 }
633
634 /*-------------------------------------------------
635 compressed - test if CHD file is compressed
636 +-------------------------------------------------*/
637 static CHDR_INLINE int chd_compressed(chd_header* header) {
638 return header->compression[0] != CHD_CODEC_NONE;
639 }
640
641 /*-------------------------------------------------
642 decompress_v5_map - decompress the v5 map
643 -------------------------------------------------*/
644
645 static chd_error decompress_v5_map(chd_file* chd, chd_header* header)
646 {
647 uint32_t hunknum;
648 int repcount = 0;
649 uint8_t lastcomp = 0;
650 uint32_t last_self = 0;
651 uint64_t last_parent = 0;
652 struct bitstream* bitbuf;
653 uint32_t mapbytes;
654 uint64_t firstoffs;
655 uint16_t mapcrc;
656 uint8_t lengthbits;
657 uint8_t selfbits;
658 uint8_t parentbits;
659 uint8_t *compressed_ptr;
660 uint8_t rawbuf[16];
661 struct huffman_decoder* decoder;
662 enum huffman_error err;
663 uint64_t curoffset;
664 size_t rawmapsize;
665
666 if (!map_size_v5(header, &rawmapsize))
667 return CHDERR_INVALID_FILE;
668
669 if (!chd_compressed(header))
670 {
671 if ((header->mapoffset + rawmapsize) >= chd->file_size || (header->mapoffset + rawmapsize) < header->mapoffset)
672 return CHDERR_INVALID_FILE;
673
674 header->rawmap = (uint8_t*)malloc(rawmapsize);
675 if (header->rawmap == NULL)
676 return CHDERR_OUT_OF_MEMORY;
677 if (!seek_and_read(chd, header->mapoffset, header->rawmap, rawmapsize))
678 return CHDERR_READ_ERROR;
679 return CHDERR_NONE;
680 }
681
682 /* read the header */
683 if (!seek_and_read(chd, header->mapoffset, rawbuf, sizeof(rawbuf)))
684 return CHDERR_READ_ERROR;
685 mapbytes = get_bigendian_uint32_t(&rawbuf[0]);
686 firstoffs = get_bigendian_uint48(&rawbuf[4]);
687 mapcrc = get_bigendian_uint16(&rawbuf[10]);
688 lengthbits = rawbuf[12];
689 selfbits = rawbuf[13];
690 parentbits = rawbuf[14];
691
692 /* now read the map */
693 if ((header->mapoffset + mapbytes) < header->mapoffset || (header->mapoffset + mapbytes) >= chd->file_size)
694 return CHDERR_INVALID_FILE;
695 compressed_ptr = (uint8_t*)malloc(sizeof(uint8_t) * mapbytes);
696 if (compressed_ptr == NULL)
697 return CHDERR_OUT_OF_MEMORY;
698 if (!seek_and_read(chd, header->mapoffset + 16, compressed_ptr, mapbytes))
699 {
700 free(compressed_ptr);
701 return CHDERR_READ_ERROR;
702 }
703 bitbuf = create_bitstream(compressed_ptr, sizeof(uint8_t) * mapbytes);
704 header->rawmap = (uint8_t*)malloc(rawmapsize);
705 if (header->rawmap == NULL)
706 {
707 free(compressed_ptr);
708 free(bitbuf);
709 return CHDERR_OUT_OF_MEMORY;
710 }
711
712 /* first decode the compression types */
713 decoder = create_huffman_decoder(16, 8);
714 if (decoder == NULL)
715 {
716 free(compressed_ptr);
717 free(bitbuf);
718 return CHDERR_OUT_OF_MEMORY;
719 }
720
721 err = huffman_import_tree_rle(decoder, bitbuf);
722 if (err != HUFFERR_NONE)
723 {
724 free(compressed_ptr);
725 free(bitbuf);
726 delete_huffman_decoder(decoder);
727 return CHDERR_DECOMPRESSION_ERROR;
728 }
729
730 for (hunknum = 0; hunknum < header->hunkcount; hunknum++)
731 {
732 uint8_t *rawmap = header->rawmap + (hunknum * 12);
733 if (repcount > 0)
734 rawmap[0] = lastcomp, repcount--;
735 else
736 {
737 uint8_t val;
738 if (bitstream_overflow(bitbuf))
739 {
740 free(compressed_ptr);
741 free(bitbuf);
742 delete_huffman_decoder(decoder);
743 return CHDERR_DECOMPRESSION_ERROR;
744 }
745
746 val = huffman_decode_one(decoder, bitbuf);
747 if (val == COMPRESSION_RLE_SMALL)
748 rawmap[0] = lastcomp, repcount = 2 + huffman_decode_one(decoder, bitbuf);
749 else if (val == COMPRESSION_RLE_LARGE)
750 rawmap[0] = lastcomp, repcount = 2 + 16 + (huffman_decode_one(decoder, bitbuf) << 4), repcount += huffman_decode_one(decoder, bitbuf);
751 else
752 rawmap[0] = lastcomp = val;
753 }
754 }
755
756 /* then iterate through the hunks and extract the needed data */
757 curoffset = firstoffs;
758 for (hunknum = 0; hunknum < header->hunkcount; hunknum++)
759 {
760 uint8_t *rawmap = header->rawmap + (hunknum * 12);
761 uint64_t offset = curoffset;
762 uint32_t length = 0;
763 uint16_t crc = 0;
764 switch (rawmap[0])
765 {
766 /* base types */
767 case COMPRESSION_TYPE_0:
768 case COMPRESSION_TYPE_1:
769 case COMPRESSION_TYPE_2:
770 case COMPRESSION_TYPE_3:
771 curoffset += length = bitstream_read(bitbuf, lengthbits);
772 crc = bitstream_read(bitbuf, 16);
773 break;
774
775 case COMPRESSION_NONE:
776 curoffset += length = header->hunkbytes;
777 crc = bitstream_read(bitbuf, 16);
778 break;
779
780 case COMPRESSION_SELF:
781 last_self = offset = bitstream_read(bitbuf, selfbits);
782 break;
783
784 case COMPRESSION_PARENT:
785 offset = bitstream_read(bitbuf, parentbits);
786 last_parent = offset;
787 break;
788
789 /* pseudo-types; convert into base types */
790 case COMPRESSION_SELF_1:
791 last_self++;
792 /* Fallthrough */
793 case COMPRESSION_SELF_0:
794 rawmap[0] = COMPRESSION_SELF;
795 offset = last_self;
796 break;
797
798 case COMPRESSION_PARENT_SELF:
799 rawmap[0] = COMPRESSION_PARENT;
800 last_parent = offset = ( ((uint64_t)hunknum) * ((uint64_t)header->hunkbytes) ) / header->unitbytes;
801 break;
802
803 case COMPRESSION_PARENT_1:
804 last_parent += header->hunkbytes / header->unitbytes;
805 /* Fallthrough */
806 case COMPRESSION_PARENT_0:
807 rawmap[0] = COMPRESSION_PARENT;
808 offset = last_parent;
809 break;
810 }
811 /* UINT24 length */
812 put_bigendian_uint24(&rawmap[1], length);
813
814 /* UINT48 offset */
815 put_bigendian_uint48(&rawmap[4], offset);
816
817 /* crc16 */
818 put_bigendian_uint16(&rawmap[10], crc);
819 }
820
821 /* free memory */
822 free(compressed_ptr);
823 free(bitbuf);
824 delete_huffman_decoder(decoder);
825
826 /* verify the final CRC */
827 if (crc16(&header->rawmap[0], header->hunkcount * 12) != mapcrc)
828 return CHDERR_DECOMPRESSION_ERROR;
829
830 return CHDERR_NONE;
831 }
832
833 /*-------------------------------------------------
834 map_extract_old - extract a single map
835 entry in old format from the datastream
836 -------------------------------------------------*/
837
838 static CHDR_INLINE void map_extract_old(const uint8_t *base, map_entry *entry, uint32_t hunkbytes)
839 {
840 entry->offset = get_bigendian_uint64_t(&base[0]);
841 entry->crc = 0;
842 entry->length = entry->offset >> 44;
843 entry->flags = MAP_ENTRY_FLAG_NO_CRC | ((entry->length == hunkbytes) ? V34_MAP_ENTRY_TYPE_UNCOMPRESSED : V34_MAP_ENTRY_TYPE_COMPRESSED);
844 #ifdef __MWERKS__
845 entry->offset = entry->offset & 0x00000FFFFFFFFFFFLL;
846 #else
847 entry->offset = (entry->offset << 20) >> 20;
848 #endif
849 }
850
851 /***************************************************************************
852 CHD FILE MANAGEMENT
853 ***************************************************************************/
854
855 static const core_file_callbacks core_stdio = {
856 core_stdio_fsize,
857 core_stdio_fread,
858 core_stdio_fclose,
859 core_stdio_fseek
860 };
861
862 static const core_file_callbacks core_stdio_nonowner = {
863 core_stdio_fsize,
864 core_stdio_fread,
865 core_stdio_fclose_nonowner,
866 core_stdio_fseek
867 };
868
869 static const core_file_callbacks core_legacy = {
870 core_legacy_fsize,
871 core_legacy_fread,
872 core_legacy_fclose,
873 core_legacy_fseek
874 };
875
876 /*-------------------------------------------------
877 chd_open_file - open a CHD file for access
878 -------------------------------------------------*/
879
880 CHD_EXPORT chd_error chd_open_file(FILE *file, int mode, chd_file *parent, chd_file **chd) {
881 return chd_open_core_file_callbacks(&core_stdio_nonowner, file, mode, parent, chd);
882 }
883
884 /*-------------------------------------------------
885 chd_open_core_file - open a CHD file for access
886 -------------------------------------------------*/
887
888 CHD_EXPORT chd_error chd_open_core_file(core_file *file, int mode, chd_file *parent, chd_file **chd)
889 {
890 if (file == NULL)
891 return CHDERR_INVALID_PARAMETER;
892
893 return chd_open_core_file_callbacks(&core_legacy, file, mode, parent, chd);
894 }
895
896 /*-------------------------------------------------
897 chd_open_core_file_callbacks - open a CHD file for access
898 -------------------------------------------------*/
899
900 CHD_EXPORT chd_error chd_open_core_file_callbacks(const core_file_callbacks *callbacks, const void *user_data, int mode, chd_file *parent, chd_file **chd)
901 {
902 chd_file *newchd = NULL;
903 chd_error err;
904
905 /* verify parameters */
906 if (callbacks == NULL)
907 EARLY_EXIT(err = CHDERR_INVALID_PARAMETER);
908
909 /* punt if invalid parent */
910 if (parent != NULL && parent->cookie != COOKIE_VALUE)
911 EARLY_EXIT(err = CHDERR_INVALID_PARAMETER);
912
913 /* allocate memory for the final result */
914 newchd = (chd_file *)malloc(sizeof(**chd));
915 if (newchd == NULL)
916 EARLY_EXIT(err = CHDERR_OUT_OF_MEMORY);
917 memset(newchd, 0, sizeof(*newchd));
918 newchd->cookie = COOKIE_VALUE;
919 newchd->parent = parent;
920 newchd->file.callbacks = callbacks;
921 newchd->file.argp = (void*)user_data;
922 newchd->file_size = core_fsize(&newchd->file);
923 if ((int64_t)newchd->file_size <= 0)
924 EARLY_EXIT(err = CHDERR_INVALID_FILE);
925
926 /* now attempt to read the header */
927 err = header_read(newchd);
928 if (err != CHDERR_NONE)
929 EARLY_EXIT(err);
930
931 /* make sure we don't open a read-only file writeable */
932 if (mode == CHD_OPEN_READWRITE && !(newchd->header.flags & CHDFLAGS_IS_WRITEABLE))
933 EARLY_EXIT(err = CHDERR_FILE_NOT_WRITEABLE);
934
935 /* also, never open an older version writeable */
936 if (mode == CHD_OPEN_READWRITE && newchd->header.version < CHD_HEADER_VERSION)
937 EARLY_EXIT(err = CHDERR_UNSUPPORTED_VERSION);
938
939 /* if we need a parent, make sure we have one */
940 if (parent == NULL)
941 {
942 /* Detect parent requirement for versions below 5 */
943 if (newchd->header.version < 5 && newchd->header.flags & CHDFLAGS_HAS_PARENT)
944 EARLY_EXIT(err = CHDERR_REQUIRES_PARENT);
945 /* Detection for version 5 and above - if parentsha1 != 0, we have a parent */
946 else if (newchd->header.version >= 5 && memcmp(nullsha1, newchd->header.parentsha1, sizeof(newchd->header.parentsha1)) != 0)
947 EARLY_EXIT(err = CHDERR_REQUIRES_PARENT);
948 }
949
950 /* make sure we have a valid parent */
951 if (parent != NULL)
952 {
953 /* check MD5 if it isn't empty */
954 if (memcmp(nullmd5, newchd->header.parentmd5, sizeof(newchd->header.parentmd5)) != 0 &&
955 memcmp(nullmd5, newchd->parent->header.md5, sizeof(newchd->parent->header.md5)) != 0 &&
956 memcmp(newchd->parent->header.md5, newchd->header.parentmd5, sizeof(newchd->header.parentmd5)) != 0)
957 EARLY_EXIT(err = CHDERR_INVALID_PARENT);
958
959 /* check SHA1 if it isn't empty */
960 if (memcmp(nullsha1, newchd->header.parentsha1, sizeof(newchd->header.parentsha1)) != 0 &&
961 memcmp(nullsha1, newchd->parent->header.sha1, sizeof(newchd->parent->header.sha1)) != 0 &&
962 memcmp(newchd->parent->header.sha1, newchd->header.parentsha1, sizeof(newchd->header.parentsha1)) != 0)
963 EARLY_EXIT(err = CHDERR_INVALID_PARENT);
964 }
965
966 /* now read the hunk map */
967 if (newchd->header.version < 5)
968 {
969 err = map_read(newchd);
970 if (err != CHDERR_NONE)
971 EARLY_EXIT(err);
972 }
973 else
974 {
975 err = decompress_v5_map(newchd, &(newchd->header));
976 }
977 if (err != CHDERR_NONE)
978 EARLY_EXIT(err);
979
980 /* allocate the temporary compressed buffer */
981 newchd->compressed = (uint8_t *)malloc(newchd->header.hunkbytes);
982 if (newchd->compressed == NULL)
983 EARLY_EXIT(err = CHDERR_OUT_OF_MEMORY);
984
985 /* find the codec interface */
986 if (newchd->header.version < 5)
987 {
988 size_t intfnum;
989 for (intfnum = 0; intfnum < ARRAY_LENGTH(codec_interfaces); intfnum++)
990 {
991 if (codec_interfaces[intfnum].compression == newchd->header.compression[0])
992 {
993 newchd->codecintf[0] = &codec_interfaces[intfnum];
994 break;
995 }
996 }
997
998 if (intfnum == ARRAY_LENGTH(codec_interfaces))
999 EARLY_EXIT(err = CHDERR_UNSUPPORTED_FORMAT);
1000
1001 /* initialize the codec */
1002 if (newchd->codecintf[0]->init != NULL)
1003 {
1004 err = newchd->codecintf[0]->init(&newchd->codec_data.zlib, newchd->header.hunkbytes);
1005 if (err != CHDERR_NONE)
1006 EARLY_EXIT(err);
1007 }
1008 }
1009 else
1010 {
1011 size_t decompnum;
1012 int needsinit;
1013
1014 /* verify the compression types and initialize the codecs */
1015 for (decompnum = 0; decompnum < ARRAY_LENGTH(newchd->header.compression); decompnum++)
1016 {
1017 size_t i;
1018 for (i = 0 ; i < ARRAY_LENGTH(codec_interfaces) ; i++)
1019 {
1020 if (codec_interfaces[i].compression == newchd->header.compression[decompnum])
1021 {
1022 newchd->codecintf[decompnum] = &codec_interfaces[i];
1023 break;
1024 }
1025 }
1026
1027 if (newchd->codecintf[decompnum] == NULL && newchd->header.compression[decompnum] != 0)
1028 EARLY_EXIT(err = CHDERR_UNSUPPORTED_FORMAT);
1029
1030 /* ensure we don't try to initialize the same codec twice */
1031 /* this is "normal" for chds where the user overrides the codecs, it'll have none repeated */
1032 needsinit = (newchd->codecintf[decompnum]->init != NULL);
1033 for (i = 0; i < decompnum; i++)
1034 {
1035 if (newchd->codecintf[decompnum] == newchd->codecintf[i])
1036 {
1037 /* already initialized */
1038 needsinit = FALSE;
1039 break;
1040 }
1041 }
1042
1043 /* initialize the codec */
1044 if (needsinit)
1045 {
1046 void* codec = NULL;
1047 switch (newchd->header.compression[decompnum])
1048 {
1049 case CHD_CODEC_ZLIB:
1050 codec = &newchd->codec_data.zlib;
1051 break;
1052
1053 case CHD_CODEC_LZMA:
1054 codec = &newchd->codec_data.lzma;
1055 break;
1056
1057 case CHD_CODEC_HUFFMAN:
1058 codec = &newchd->codec_data.huff;
1059 break;
1060
1061 case CHD_CODEC_FLAC:
1062 codec = &newchd->codec_data.flac;
1063 break;
1064
1065 case CHD_CODEC_ZSTD:
1066 codec = &newchd->codec_data.zstd;
1067 break;
1068
1069 case CHD_CODEC_CD_ZLIB:
1070 codec = &newchd->codec_data.cdzl;
1071 break;
1072
1073 case CHD_CODEC_CD_LZMA:
1074 codec = &newchd->codec_data.cdlz;
1075 break;
1076
1077 case CHD_CODEC_CD_FLAC:
1078 codec = &newchd->codec_data.cdfl;
1079 break;
1080
1081 case CHD_CODEC_CD_ZSTD:
1082 codec = &newchd->codec_data.cdzs;
1083 break;
1084 }
1085
1086 if (codec == NULL)
1087 EARLY_EXIT(err = CHDERR_UNSUPPORTED_FORMAT);
1088
1089 err = newchd->codecintf[decompnum]->init(codec, newchd->header.hunkbytes);
1090 if (err != CHDERR_NONE)
1091 EARLY_EXIT(err);
1092 }
1093 }
1094 }
1095
1096 /* all done */
1097 *chd = newchd;
1098 return CHDERR_NONE;
1099
1100 cleanup:
1101 if (newchd != NULL)
1102 chd_close(newchd);
1103 return err;
1104 }
1105
1106 /*-------------------------------------------------
1107 chd_precache - precache underlying file in
1108 memory
1109 -------------------------------------------------*/
1110
1111 CHD_EXPORT chd_error chd_precache(chd_file *chd)
1112 {
1113 if (chd->file_cache == NULL)
1114 {
1115 chd->file_cache = (uint8_t*)malloc(chd->file_size);
1116 if (chd->file_cache == NULL)
1117 return CHDERR_OUT_OF_MEMORY;
1118 if (!seek_and_read(chd, 0, chd->file_cache, chd->file_size))
1119 {
1120 free(chd->file_cache);
1121 chd->file_cache = NULL;
1122 return CHDERR_READ_ERROR;
1123 }
1124 }
1125
1126 return CHDERR_NONE;
1127 }
1128
1129 /*-------------------------------------------------
1130 chd_open - open a CHD file by
1131 filename
1132 -------------------------------------------------*/
1133
1134 CHD_EXPORT chd_error chd_open(const char *filename, int mode, chd_file *parent, chd_file **chd)
1135 {
1136 chd_error err;
1137 void *file = NULL;
1138
1139 if (filename == NULL)
1140 EARLY_EXIT(err = CHDERR_INVALID_PARAMETER);
1141
1142 /* choose the proper mode */
1143 switch(mode)
1144 {
1145 case CHD_OPEN_READ:
1146 break;
1147
1148 default:
1149 EARLY_EXIT(err = CHDERR_INVALID_PARAMETER);
1150 }
1151
1152 /* open the file */
1153 file = core_stdio_fopen(filename);
1154 if (file == NULL)
1155 EARLY_EXIT(err = CHDERR_FILE_NOT_FOUND);
1156
1157 /* now open the CHD */
1158 return chd_open_core_file_callbacks(&core_stdio, file, mode, parent, chd);
1159
1160 cleanup:
1161 if ((err != CHDERR_NONE) && (file != NULL))
1162 core_stdio_fclose(file);
1163 return err;
1164 }
1165
1166 /*-------------------------------------------------
1167 chd_close - close a CHD file for access
1168 -------------------------------------------------*/
1169
1170 CHD_EXPORT void chd_close(chd_file *chd)
1171 {
1172 /* punt if NULL or invalid */
1173 if (chd == NULL || chd->cookie != COOKIE_VALUE)
1174 return;
1175
1176 /* deinit the codec */
1177 if (chd->header.version < 5)
1178 {
1179 if (chd->codecintf[0] != NULL && chd->codecintf[0]->free != NULL)
1180 chd->codecintf[0]->free(&chd->codec_data.zlib);
1181 }
1182 else
1183 {
1184 size_t i;
1185 /* Free the codecs */
1186 for (i = 0 ; i < ARRAY_LENGTH(chd->codecintf); i++)
1187 {
1188 void* codec = NULL;
1189 size_t j;
1190 int needsfree;
1191
1192 if (chd->codecintf[i] == NULL)
1193 continue;
1194
1195 /* only free each codec at max once */
1196 needsfree = 1;
1197 for (j = 0; j < i; j++)
1198 {
1199 if (chd->codecintf[i] == chd->codecintf[j])
1200 {
1201 needsfree = FALSE;
1202 break;
1203 }
1204 }
1205 if (!needsfree)
1206 continue;
1207
1208 switch (chd->codecintf[i]->compression)
1209 {
1210 case CHD_CODEC_ZLIB:
1211 codec = &chd->codec_data.zlib;
1212 break;
1213
1214 case CHD_CODEC_LZMA:
1215 codec = &chd->codec_data.lzma;
1216 break;
1217
1218 case CHD_CODEC_HUFFMAN:
1219 codec = &chd->codec_data.huff;
1220 break;
1221
1222 case CHD_CODEC_FLAC:
1223 codec = &chd->codec_data.flac;
1224 break;
1225
1226 case CHD_CODEC_ZSTD:
1227 codec = &chd->codec_data.zstd;
1228 break;
1229
1230 case CHD_CODEC_CD_ZLIB:
1231 codec = &chd->codec_data.cdzl;
1232 break;
1233
1234 case CHD_CODEC_CD_LZMA:
1235 codec = &chd->codec_data.cdlz;
1236 break;
1237
1238 case CHD_CODEC_CD_FLAC:
1239 codec = &chd->codec_data.cdfl;
1240 break;
1241
1242 case CHD_CODEC_CD_ZSTD:
1243 codec = &chd->codec_data.cdzs;
1244 break;
1245 }
1246
1247 if (codec)
1248 {
1249 chd->codecintf[i]->free(codec);
1250 }
1251 }
1252
1253 /* Free the raw map */
1254 if (chd->header.rawmap != NULL)
1255 free(chd->header.rawmap);
1256 }
1257
1258 /* free the compressed data buffer */
1259 if (chd->compressed != NULL)
1260 free(chd->compressed);
1261
1262 /* free the hunk map */
1263 if (chd->map != NULL)
1264 free(chd->map);
1265
1266 /* close the file */
1267 if (chd->file.callbacks != NULL)
1268 core_fclose(&chd->file);
1269
1270 if (chd->file_cache)
1271 free(chd->file_cache);
1272
1273 if (chd->parent)
1274 chd_close(chd->parent);
1275
1276 /* free our memory */
1277 free(chd);
1278 }
1279
1280 /*-------------------------------------------------
1281 chd_core_file - return the associated
1282 core_file
1283 -------------------------------------------------*/
1284
1285 CHD_EXPORT core_file *chd_core_file(chd_file *chd)
1286 {
1287 if (chd->file.callbacks != &core_legacy)
1288 return NULL;
1289
1290 return (core_file*)chd->file.argp;
1291 }
1292
1293 /*-------------------------------------------------
1294 chd_error_string - return an error string for
1295 the given CHD error
1296 -------------------------------------------------*/
1297
1298 CHD_EXPORT const char *chd_error_string(chd_error err)
1299 {
1300 switch (err)
1301 {
1302 case CHDERR_NONE: return "no error";
1303 case CHDERR_NO_INTERFACE: return "no drive interface";
1304 case CHDERR_OUT_OF_MEMORY: return "out of memory";
1305 case CHDERR_INVALID_FILE: return "invalid file";
1306 case CHDERR_INVALID_PARAMETER: return "invalid parameter";
1307 case CHDERR_INVALID_DATA: return "invalid data";
1308 case CHDERR_FILE_NOT_FOUND: return "file not found";
1309 case CHDERR_REQUIRES_PARENT: return "requires parent";
1310 case CHDERR_FILE_NOT_WRITEABLE: return "file not writeable";
1311 case CHDERR_READ_ERROR: return "read error";
1312 case CHDERR_WRITE_ERROR: return "write error";
1313 case CHDERR_CODEC_ERROR: return "codec error";
1314 case CHDERR_INVALID_PARENT: return "invalid parent";
1315 case CHDERR_HUNK_OUT_OF_RANGE: return "hunk out of range";
1316 case CHDERR_DECOMPRESSION_ERROR: return "decompression error";
1317 case CHDERR_COMPRESSION_ERROR: return "compression error";
1318 case CHDERR_CANT_CREATE_FILE: return "can't create file";
1319 case CHDERR_CANT_VERIFY: return "can't verify file";
1320 case CHDERR_NOT_SUPPORTED: return "operation not supported";
1321 case CHDERR_METADATA_NOT_FOUND: return "can't find metadata";
1322 case CHDERR_INVALID_METADATA_SIZE: return "invalid metadata size";
1323 case CHDERR_UNSUPPORTED_VERSION: return "unsupported CHD version";
1324 case CHDERR_VERIFY_INCOMPLETE: return "incomplete verify";
1325 case CHDERR_INVALID_METADATA: return "invalid metadata";
1326 case CHDERR_INVALID_STATE: return "invalid state";
1327 case CHDERR_OPERATION_PENDING: return "operation pending";
1328 case CHDERR_NO_ASYNC_OPERATION: return "no async operation in progress";
1329 case CHDERR_UNSUPPORTED_FORMAT: return "unsupported format";
1330 default: return "undocumented error";
1331 }
1332 }
1333
1334 /***************************************************************************
1335 CHD HEADER MANAGEMENT
1336 ***************************************************************************/
1337
1338 /*-------------------------------------------------
1339 chd_get_header - return a pointer to the
1340 extracted header data
1341 -------------------------------------------------*/
1342
1343 CHD_EXPORT const chd_header *chd_get_header(chd_file *chd)
1344 {
1345 /* punt if NULL or invalid */
1346 if (chd == NULL || chd->cookie != COOKIE_VALUE)
1347 return NULL;
1348
1349 return &chd->header;
1350 }
1351
1352 /*-------------------------------------------------
1353 chd_read_header_core_file_callbacks - read CHD header data
1354 from file into the pointed struct
1355 -------------------------------------------------*/
1356
1357 CHD_EXPORT chd_error chd_read_header_core_file_callbacks(const core_file_callbacks *callbacks, const void *user_data, chd_header *header)
1358 {
1359 chd_error err;
1360 chd_file chd;
1361
1362 /* verify parameters */
1363 if (callbacks == NULL || header == NULL)
1364 return CHDERR_INVALID_PARAMETER;
1365
1366 chd.file.callbacks = callbacks;
1367 chd.file.argp = (void*)user_data;
1368
1369 /* attempt to read the header */
1370 err = header_read(&chd);
1371 if (err != CHDERR_NONE)
1372 return err;
1373 *header = chd.header;
1374 return CHDERR_NONE;
1375 }
1376
1377 /*-------------------------------------------------
1378 chd_read_header_core_file - read CHD header data
1379 from file into the pointed struct
1380 -------------------------------------------------*/
1381
1382 CHD_EXPORT chd_error chd_read_header_core_file(core_file *file, chd_header *header)
1383 {
1384 if (file == NULL)
1385 return CHDERR_INVALID_PARAMETER;
1386
1387 return chd_read_header_core_file_callbacks(&core_legacy, file, header);
1388 }
1389
1390 /*-------------------------------------------------
1391 chd_read_header - read CHD header data
1392 from file into the pointed struct
1393 -------------------------------------------------*/
1394
1395 CHD_EXPORT chd_error chd_read_header_file(FILE *file, chd_header *header)
1396 {
1397 return chd_read_header_core_file_callbacks(&core_stdio_nonowner, file, header);
1398 }
1399
1400 /*-------------------------------------------------
1401 chd_read_header - read CHD header data
1402 from file into the pointed struct
1403 -------------------------------------------------*/
1404
1405 CHD_EXPORT chd_error chd_read_header(const char *filename, chd_header *header)
1406 {
1407 chd_error err;
1408 void *file = NULL;
1409
1410 if (filename == NULL)
1411 EARLY_EXIT(err = CHDERR_INVALID_PARAMETER);
1412
1413 /* open the file */
1414 file = core_stdio_fopen(filename);
1415 if (file == NULL)
1416 EARLY_EXIT(err = CHDERR_FILE_NOT_FOUND);
1417
1418 err = chd_read_header_core_file_callbacks(&core_stdio, file, header);
1419
1420 cleanup:
1421 if (file != NULL)
1422 core_stdio_fclose(file);
1423 return err;
1424 }
1425
1426 /***************************************************************************
1427 CORE DATA READ/WRITE
1428 ***************************************************************************/
1429
1430 /*-------------------------------------------------
1431 chd_read - read a single hunk from the CHD
1432 file
1433 -------------------------------------------------*/
1434
1435 CHD_EXPORT chd_error chd_read(chd_file *chd, uint32_t hunknum, void *buffer)
1436 {
1437 /* punt if NULL or invalid */
1438 if (chd == NULL || chd->cookie != COOKIE_VALUE)
1439 return CHDERR_INVALID_PARAMETER;
1440
1441 /* if we're past the end, fail */
1442 if (hunknum >= chd->header.totalhunks)
1443 return CHDERR_HUNK_OUT_OF_RANGE;
1444
1445 /* perform the read */
1446 return hunk_read_into_memory(chd, hunknum, (uint8_t *)buffer);
1447 }
1448
1449 /***************************************************************************
1450 METADATA MANAGEMENT
1451 ***************************************************************************/
1452
1453 /*-------------------------------------------------
1454 chd_get_metadata - get the indexed metadata
1455 of the given type
1456 -------------------------------------------------*/
1457
1458 CHD_EXPORT chd_error chd_get_metadata(chd_file *chd, uint32_t searchtag, uint32_t searchindex, void *output, uint32_t outputlen, uint32_t *resultlen, uint32_t *resulttag, uint8_t *resultflags)
1459 {
1460 metadata_entry metaentry;
1461 chd_error err;
1462
1463 /* if we didn't find it, just return */
1464 err = metadata_find_entry(chd, searchtag, searchindex, &metaentry);
1465 if (err != CHDERR_NONE)
1466 {
1467 /* unless we're an old version and they are requesting hard disk metadata */
1468 if (chd->header.version < 3 && (searchtag == HARD_DISK_METADATA_TAG || searchtag == CHDMETATAG_WILDCARD) && searchindex == 0)
1469 {
1470 char faux_metadata[256];
1471 uint32_t faux_length;
1472
1473 /* fill in the faux metadata */
1474 snprintf(faux_metadata, sizeof(faux_metadata), HARD_DISK_METADATA_FORMAT, chd->header.obsolete_cylinders, chd->header.obsolete_heads, chd->header.obsolete_sectors, (chd->header.obsolete_hunksize != 0) ? (chd->header.hunkbytes / chd->header.obsolete_hunksize) : 0);
1475 faux_length = (uint32_t)strlen(faux_metadata) + 1;
1476
1477 /* copy the metadata itself */
1478 memcpy(output, faux_metadata, MIN(outputlen, faux_length));
1479
1480 /* return the length of the data and the tag */
1481 if (resultlen != NULL)
1482 *resultlen = faux_length;
1483 if (resulttag != NULL)
1484 *resulttag = HARD_DISK_METADATA_TAG;
1485 return CHDERR_NONE;
1486 }
1487 return err;
1488 }
1489
1490 /* read the metadata */
1491 outputlen = MIN(outputlen, metaentry.length);
1492 if (!seek_and_read(chd, metaentry.offset + METADATA_HEADER_SIZE, output, outputlen))
1493 return CHDERR_READ_ERROR;
1494
1495 /* return the length of the data and the tag */
1496 if (resultlen != NULL)
1497 *resultlen = metaentry.length;
1498 if (resulttag != NULL)
1499 *resulttag = metaentry.metatag;
1500 if (resultflags != NULL)
1501 *resultflags = metaentry.flags;
1502 return CHDERR_NONE;
1503 }
1504
1505 /***************************************************************************
1506 INTERNAL HEADER OPERATIONS
1507 ***************************************************************************/
1508
1509 /*-------------------------------------------------
1510 header_guess_unitbytes - for older CHD formats,
1511 guess at the bytes/unit based on metadata
1512 -------------------------------------------------*/
1513
1514 static uint32_t header_guess_unitbytes(chd_file *chd)
1515 {
1516 /* look for hard disk metadata; if found, then the unit size == sector size */
1517 char metadata[512];
1518 int i0, i1, i2, i3;
1519 if (chd_get_metadata(chd, HARD_DISK_METADATA_TAG, 0, metadata, sizeof(metadata), NULL, NULL, NULL) == CHDERR_NONE &&
1520 sscanf(metadata, HARD_DISK_METADATA_FORMAT, &i0, &i1, &i2, &i3) == 4)
1521 return i3;
1522
1523 /* look for CD-ROM metadata; if found, then the unit size == CD frame size */
1524 if (chd_get_metadata(chd, CDROM_OLD_METADATA_TAG, 0, metadata, sizeof(metadata), NULL, NULL, NULL) == CHDERR_NONE ||
1525 chd_get_metadata(chd, CDROM_TRACK_METADATA_TAG, 0, metadata, sizeof(metadata), NULL, NULL, NULL) == CHDERR_NONE ||
1526 chd_get_metadata(chd, CDROM_TRACK_METADATA2_TAG, 0, metadata, sizeof(metadata), NULL, NULL, NULL) == CHDERR_NONE ||
1527 chd_get_metadata(chd, GDROM_OLD_METADATA_TAG, 0, metadata, sizeof(metadata), NULL, NULL, NULL) == CHDERR_NONE ||
1528 chd_get_metadata(chd, GDROM_TRACK_METADATA_TAG, 0, metadata, sizeof(metadata), NULL, NULL, NULL) == CHDERR_NONE)
1529 return CD_FRAME_SIZE;
1530
1531 /* otherwise, just map 1:1 with the hunk size */
1532 return chd->header.hunkbytes;
1533 }
1534
1535 /*-------------------------------------------------
1536 header_read - read a CHD header into the
1537 internal data structure and perform validation
1538 -------------------------------------------------*/
1539
1540 static chd_error header_read(chd_file *chd)
1541 {
1542 static const uint32_t header_sizes[CHD_HEADER_VERSION] = {
1543 CHD_V1_HEADER_SIZE,
1544 CHD_V2_HEADER_SIZE,
1545 CHD_V3_HEADER_SIZE,
1546 CHD_V4_HEADER_SIZE,
1547 CHD_V5_HEADER_SIZE,
1548 };
1549
1550 uint8_t rawheader[CHD_MAX_HEADER_SIZE];
1551
1552 /* punt if NULL */
1553 if (chd == NULL)
1554 return CHDERR_INVALID_PARAMETER;
1555
1556 /* punt if invalid file */
1557 if (chd->file.callbacks == NULL)
1558 return CHDERR_INVALID_FILE;
1559
1560 /* read the start of the header */
1561 if (!seek_and_read(chd, 0, rawheader, 8 + 4 + 4))
1562 return CHDERR_READ_ERROR;
1563
1564 /* verify the tag */
1565 if (memcmp(rawheader, "MComprHD", 8) != 0)
1566 return CHDERR_INVALID_DATA;
1567
1568 /* extract the direct data */
1569 chd_header *header = &chd->header;
1570 memset(header, 0, sizeof(*header));
1571 header->length = get_bigendian_uint32_t(&rawheader[8]);
1572 header->version = get_bigendian_uint32_t(&rawheader[12]);
1573
1574 /* Unknown version */
1575 if (header->version == 0 || header->version > ARRAY_LENGTH(header_sizes))
1576 return CHDERR_UNSUPPORTED_VERSION;
1577
1578 /* make sure the length is expected */
1579 if (header->length != header_sizes[header->version - 1])
1580 return CHDERR_INVALID_DATA;
1581
1582 /* read the full header, now that we know its size */
1583 if (!seek_and_read(chd, 0, rawheader, header->length))
1584 return CHDERR_READ_ERROR;
1585
1586 switch (header->version)
1587 {
1588 default:
1589 /* Unknown version */
1590 return CHDERR_UNSUPPORTED_VERSION;
1591
1592 case 1:
1593 case 2:
1594 header->flags = get_bigendian_uint32_t(&rawheader[16]);
1595 header->compression[0] = get_bigendian_uint32_t(&rawheader[20]);
1596 header->obsolete_hunksize = get_bigendian_uint32_t(&rawheader[24]);
1597 header->totalhunks = get_bigendian_uint32_t(&rawheader[28]);
1598 header->obsolete_cylinders = get_bigendian_uint32_t(&rawheader[32]);
1599 header->obsolete_heads = get_bigendian_uint32_t(&rawheader[36]);
1600 header->obsolete_sectors = get_bigendian_uint32_t(&rawheader[40]);
1601 memcpy(header->md5, &rawheader[44], CHD_MD5_BYTES);
1602 memcpy(header->parentmd5, &rawheader[60], CHD_MD5_BYTES);
1603 {
1604 uint32_t seclen = (header->version == 1) ? CHD_V1_SECTOR_SIZE : get_bigendian_uint32_t(&rawheader[76]);
1605 uint64_t hunkbytes64 = (uint64_t)seclen * (uint64_t)header->obsolete_hunksize;
1606 header->logicalbytes = (uint64_t)header->obsolete_cylinders * (uint64_t)header->obsolete_heads * (uint64_t)header->obsolete_sectors * (uint64_t)seclen;
1607 /* reject malformed headers where hunkbytes would overflow uint32_t or is zero */
1608 if (hunkbytes64 == 0 || hunkbytes64 > UINT32_MAX)
1609 return CHDERR_INVALID_DATA;
1610 header->hunkbytes = (uint32_t)hunkbytes64;
1611 }
1612 header->unitbytes = header_guess_unitbytes(chd);
1613 if (header->unitbytes == 0)
1614 return CHDERR_INVALID_DATA;
1615 header->unitcount = (header->logicalbytes + header->unitbytes - 1) / header->unitbytes;
1616 header->metaoffset = 0;
1617
1618 break;
1619
1620 case 3:
1621 header->flags = get_bigendian_uint32_t(&rawheader[16]);
1622 header->compression[0] = get_bigendian_uint32_t(&rawheader[20]);
1623 header->totalhunks = get_bigendian_uint32_t(&rawheader[24]);
1624 header->logicalbytes = get_bigendian_uint64_t(&rawheader[28]);
1625 header->metaoffset = get_bigendian_uint64_t(&rawheader[36]);
1626 memcpy(header->md5, &rawheader[44], CHD_MD5_BYTES);
1627 memcpy(header->parentmd5, &rawheader[60], CHD_MD5_BYTES);
1628 header->hunkbytes = get_bigendian_uint32_t(&rawheader[76]);
1629 header->unitbytes = header_guess_unitbytes(chd);
1630 if (header->unitbytes == 0)
1631 return CHDERR_INVALID_DATA;
1632 header->unitcount = (header->logicalbytes + header->unitbytes - 1) / header->unitbytes;
1633 memcpy(header->sha1, &rawheader[80], CHD_SHA1_BYTES);
1634 memcpy(header->parentsha1, &rawheader[100], CHD_SHA1_BYTES);
1635
1636 break;
1637
1638 case 4:
1639 header->flags = get_bigendian_uint32_t(&rawheader[16]);
1640 header->compression[0] = get_bigendian_uint32_t(&rawheader[20]);
1641 header->totalhunks = get_bigendian_uint32_t(&rawheader[24]);
1642 header->logicalbytes = get_bigendian_uint64_t(&rawheader[28]);
1643 header->metaoffset = get_bigendian_uint64_t(&rawheader[36]);
1644 header->hunkbytes = get_bigendian_uint32_t(&rawheader[44]);
1645 header->unitbytes = header_guess_unitbytes(chd);
1646 if (header->unitbytes == 0)
1647 return CHDERR_INVALID_DATA;
1648 header->unitcount = (header->logicalbytes + header->unitbytes - 1) / header->unitbytes;
1649 memcpy(header->sha1, &rawheader[48], CHD_SHA1_BYTES);
1650 memcpy(header->parentsha1, &rawheader[68], CHD_SHA1_BYTES);
1651 memcpy(header->rawsha1, &rawheader[88], CHD_SHA1_BYTES);
1652
1653 break;
1654
1655 case 5:
1656 header->compression[0] = get_bigendian_uint32_t(&rawheader[16]);
1657 header->compression[1] = get_bigendian_uint32_t(&rawheader[20]);
1658 header->compression[2] = get_bigendian_uint32_t(&rawheader[24]);
1659 header->compression[3] = get_bigendian_uint32_t(&rawheader[28]);
1660 header->logicalbytes = get_bigendian_uint64_t(&rawheader[32]);
1661 header->mapoffset = get_bigendian_uint64_t(&rawheader[40]);
1662 header->metaoffset = get_bigendian_uint64_t(&rawheader[48]);
1663 header->hunkbytes = get_bigendian_uint32_t(&rawheader[56]);
1664 if (header->hunkbytes == 0)
1665 return CHDERR_INVALID_DATA;
1666 header->hunkcount = (header->logicalbytes + header->hunkbytes - 1) / header->hunkbytes;
1667 header->unitbytes = get_bigendian_uint32_t(&rawheader[60]);
1668 if (header->unitbytes == 0)
1669 return CHDERR_INVALID_DATA;
1670 header->unitcount = (header->logicalbytes + header->unitbytes - 1) / header->unitbytes;
1671 memcpy(header->sha1, &rawheader[84], CHD_SHA1_BYTES);
1672 memcpy(header->parentsha1, &rawheader[104], CHD_SHA1_BYTES);
1673 memcpy(header->rawsha1, &rawheader[64], CHD_SHA1_BYTES);
1674
1675 /* determine properties of map entries */
1676 header->mapentrybytes = chd_compressed(header) ? 12 : 4;
1677
1678 /* hack */
1679 header->totalhunks = header->hunkcount;
1680
1681 break;
1682 }
1683
1684 /* Do not validate v5 header */
1685 if (header->version <= 4)
1686 {
1687 size_t intfnum;
1688
1689 /* require valid flags */
1690 if (header->flags & CHDFLAGS_UNDEFINED)
1691 return CHDERR_INVALID_DATA;
1692
1693 /* require a supported compression mechanism */
1694 for (intfnum = 0; intfnum < ARRAY_LENGTH(codec_interfaces); intfnum++)
1695 if (codec_interfaces[intfnum].compression == header->compression[0])
1696 break;
1697
1698 if (intfnum == ARRAY_LENGTH(codec_interfaces))
1699 return CHDERR_INVALID_DATA;
1700
1701 /* require a valid hunksize */
1702 if (header->hunkbytes == 0 || header->hunkbytes >= 65536 * 256)
1703 return CHDERR_INVALID_DATA;
1704
1705 /* require a valid hunk count */
1706 if (header->totalhunks == 0)
1707 return CHDERR_INVALID_DATA;
1708
1709 /* require a valid MD5 and/or SHA1 if we're using a parent */
1710 if ((header->flags & CHDFLAGS_HAS_PARENT) && memcmp(header->parentmd5, nullmd5, sizeof(nullmd5)) == 0 && memcmp(header->parentsha1, nullsha1, sizeof(nullsha1)) == 0)
1711 return CHDERR_INVALID_DATA;
1712
1713 /* if we're V3 or later, the obsolete fields must be 0 */
1714 if (header->version >= 3 &&
1715 (header->obsolete_cylinders != 0 || header->obsolete_sectors != 0 ||
1716 header->obsolete_heads != 0 || header->obsolete_hunksize != 0))
1717 return CHDERR_INVALID_DATA;
1718
1719 /* if we're pre-V3, the obsolete fields must NOT be 0 */
1720 if (header->version < 3 &&
1721 (header->obsolete_cylinders == 0 || header->obsolete_sectors == 0 ||
1722 header->obsolete_heads == 0 || header->obsolete_hunksize == 0))
1723 return CHDERR_INVALID_DATA;
1724 }
1725
1726 /* some basic size checks to prevent huge mallocs */
1727 if (header->hunkbytes >= CHD_MAX_HUNK_SIZE || ((uint64_t)header->hunkbytes * (uint64_t)header->totalhunks) >= CHD_MAX_FILE_SIZE)
1728 return CHDERR_INVALID_DATA;
1729
1730 /* totalhunks is used to size the map allocation; a malformed header
1731 * can otherwise request multi-GB allocations for map[] even when the
1732 * file itself is tiny. Every hunk map entry consumes at least one bit
1733 * in the compressed on-disk map, so totalhunks cannot legitimately
1734 * exceed file_size * 8. */
1735 if ((uint64_t)header->totalhunks > chd->file_size * 8)
1736 return CHDERR_INVALID_DATA;
1737
1738 /* guess it worked */
1739 return CHDERR_NONE;
1740 }
1741
1742 /***************************************************************************
1743 INTERNAL HUNK READ/WRITE
1744 ***************************************************************************/
1745
1746 /*-------------------------------------------------
1747 hunk_read_compressed - read a compressed
1748 hunk
1749 -------------------------------------------------*/
1750
1751 static uint8_t* hunk_read_compressed(chd_file *chd, uint64_t offset, size_t size)
1752 {
1753 if (chd->file_cache != NULL)
1754 {
1755 if ((offset + size) > chd->file_size || (offset + size) < offset)
1756 return NULL;
1757 else
1758 return chd->file_cache + offset;
1759 }
1760 else
1761 {
1762 /* make sure it isn't larger than the compressed buffer */
1763 if (size > chd->header.hunkbytes)
1764 return NULL;
1765
1766 if (!seek_and_read(chd, offset, chd->compressed, size))
1767 return NULL;
1768 return chd->compressed;
1769 }
1770 }
1771
1772 /*-------------------------------------------------
1773 hunk_read_uncompressed - read an uncompressed
1774 hunk
1775 -------------------------------------------------*/
1776
1777 static chd_error hunk_read_uncompressed(chd_file *chd, uint64_t offset, size_t size, uint8_t *dest)
1778 {
1779 if (chd->file_cache != NULL)
1780 {
1781 if ((offset + size) > chd->file_size || (offset + size) < offset)
1782 return CHDERR_READ_ERROR;
1783
1784 memcpy(dest, chd->file_cache + offset, size);
1785 }
1786 else
1787 {
1788 if (!seek_and_read(chd, offset, dest, size))
1789 return CHDERR_READ_ERROR;
1790 }
1791 return CHDERR_NONE;
1792 }
1793
1794 /*-------------------------------------------------
1795 hunk_read_into_memory - read a hunk into
1796 memory at the given location
1797 -------------------------------------------------*/
1798
1799 static chd_error hunk_read_into_memory(chd_file *chd, uint32_t hunknum, uint8_t *dest)
1800 {
1801 chd_error err;
1802
1803 /* punt if no file */
1804 if (chd->file.callbacks == NULL)
1805 return CHDERR_INVALID_FILE;
1806
1807 /* return an error if out of range */
1808 if (hunknum >= chd->header.totalhunks)
1809 return CHDERR_HUNK_OUT_OF_RANGE;
1810
1811 if (dest == NULL)
1812 return CHDERR_INVALID_PARAMETER;
1813
1814 if (chd->header.version < 5)
1815 {
1816 map_entry *entry = &chd->map[hunknum];
1817 uint32_t bytes;
1818 uint8_t* compressed_bytes;
1819
1820 /* switch off the entry type */
1821 switch (entry->flags & MAP_ENTRY_FLAG_TYPE_MASK)
1822 {
1823 /* compressed data */
1824 case V34_MAP_ENTRY_TYPE_COMPRESSED:
1825 {
1826 void *codec = NULL;
1827
1828 /* read it into the decompression buffer */
1829 compressed_bytes = hunk_read_compressed(chd, entry->offset, entry->length);
1830 if (compressed_bytes == NULL)
1831 return CHDERR_READ_ERROR;
1832
1833 /* now decompress using the codec */
1834 err = CHDERR_NONE;
1835 codec = &chd->codec_data.zlib;
1836 if (chd->codecintf[0]->decompress != NULL)
1837 err = chd->codecintf[0]->decompress(codec, compressed_bytes, entry->length, dest, chd->header.hunkbytes);
1838 if (err != CHDERR_NONE)
1839 return err;
1840 break;
1841 }
1842
1843 /* uncompressed data */
1844 case V34_MAP_ENTRY_TYPE_UNCOMPRESSED:
1845 err = hunk_read_uncompressed(chd, entry->offset, chd->header.hunkbytes, dest);
1846 if (err != CHDERR_NONE)
1847 return err;
1848 break;
1849
1850 /* mini-compressed data */
1851 case V34_MAP_ENTRY_TYPE_MINI:
1852 put_bigendian_uint64_t(&dest[0], entry->offset);
1853 for (bytes = 8; bytes < chd->header.hunkbytes; bytes++)
1854 dest[bytes] = dest[bytes - 8];
1855 break;
1856
1857 /* self-referenced data */
1858 case V34_MAP_ENTRY_TYPE_SELF_HUNK:
1859 return hunk_read_into_memory(chd, entry->offset, dest);
1860
1861 /* parent-referenced data */
1862 case V34_MAP_ENTRY_TYPE_PARENT_HUNK:
1863 err = hunk_read_into_memory(chd->parent, entry->offset, dest);
1864 if (err != CHDERR_NONE)
1865 return err;
1866 break;
1867 }
1868 return CHDERR_NONE;
1869 }
1870 else
1871 {
1872 void* codec = NULL;
1873 /* get a pointer to the map entry */
1874 uint64_t blockoffs;
1875 uint32_t blocklen;
1876 #if VERIFY_BLOCK_CRC
1877 uint16_t blockcrc;
1878 #endif
1879 uint8_t *rawmap = &chd->header.rawmap[chd->header.mapentrybytes * hunknum];
1880 uint8_t* compressed_bytes;
1881
1882 /* uncompressed case */
1883 if (!chd_compressed(&chd->header))
1884 {
1885 blockoffs = (uint64_t)get_bigendian_uint32_t(rawmap) * (uint64_t)chd->header.hunkbytes;
1886 if (blockoffs != 0) {
1887 if (!seek_and_read(chd, blockoffs, dest, chd->header.hunkbytes))
1888 return CHDERR_READ_ERROR;
1889 /* TODO
1890 else if (m_parent_missing)
1891 throw CHDERR_REQUIRES_PARENT; */
1892 } else if (chd->parent) {
1893 err = hunk_read_into_memory(chd->parent, hunknum, dest);
1894 if (err != CHDERR_NONE)
1895 return err;
1896 } else {
1897 memset(dest, 0, chd->header.hunkbytes);
1898 }
1899
1900 return CHDERR_NONE;
1901 }
1902
1903 /* compressed case */
1904 blocklen = get_bigendian_uint24(&rawmap[1]);
1905 blockoffs = get_bigendian_uint48(&rawmap[4]);
1906 #if VERIFY_BLOCK_CRC
1907 blockcrc = get_bigendian_uint16(&rawmap[10]);
1908 #endif
1909 codec = NULL;
1910 switch (rawmap[0])
1911 {
1912 case COMPRESSION_TYPE_0:
1913 case COMPRESSION_TYPE_1:
1914 case COMPRESSION_TYPE_2:
1915 case COMPRESSION_TYPE_3:
1916 compressed_bytes = hunk_read_compressed(chd, blockoffs, blocklen);
1917 if (compressed_bytes == NULL)
1918 return CHDERR_READ_ERROR;
1919 switch (chd->codecintf[rawmap[0]]->compression)
1920 {
1921 case CHD_CODEC_ZLIB:
1922 codec = &chd->codec_data.zlib;
1923 break;
1924
1925 case CHD_CODEC_LZMA:
1926 codec = &chd->codec_data.lzma;
1927 break;
1928
1929 case CHD_CODEC_HUFFMAN:
1930 codec = &chd->codec_data.huff;
1931 break;
1932
1933 case CHD_CODEC_FLAC:
1934 codec = &chd->codec_data.flac;
1935 break;
1936
1937 case CHD_CODEC_ZSTD:
1938 codec = &chd->codec_data.zstd;
1939 break;
1940
1941 case CHD_CODEC_CD_ZLIB:
1942 codec = &chd->codec_data.cdzl;
1943 break;
1944
1945 case CHD_CODEC_CD_LZMA:
1946 codec = &chd->codec_data.cdlz;
1947 break;
1948
1949 case CHD_CODEC_CD_FLAC:
1950 codec = &chd->codec_data.cdfl;
1951 break;
1952
1953 case CHD_CODEC_CD_ZSTD:
1954 codec = &chd->codec_data.cdzs;
1955 break;
1956 }
1957 if (codec==NULL)
1958 return CHDERR_CODEC_ERROR;
1959 err = chd->codecintf[rawmap[0]]->decompress(codec, compressed_bytes, blocklen, dest, chd->header.hunkbytes);
1960 if (err != CHDERR_NONE)
1961 return err;
1962 #if VERIFY_BLOCK_CRC
1963 if (crc16(dest, chd->header.hunkbytes) != blockcrc)
1964 return CHDERR_DECOMPRESSION_ERROR;
1965 #endif
1966 return CHDERR_NONE;
1967
1968 case COMPRESSION_NONE:
1969 err = hunk_read_uncompressed(chd, blockoffs, blocklen, dest);
1970 if (err != CHDERR_NONE)
1971 return err;
1972 #if VERIFY_BLOCK_CRC
1973 if (crc16(dest, chd->header.hunkbytes) != blockcrc)
1974 return CHDERR_DECOMPRESSION_ERROR;
1975 #endif
1976 return CHDERR_NONE;
1977
1978 case COMPRESSION_SELF:
1979 return hunk_read_into_memory(chd, blockoffs, dest);
1980
1981 case COMPRESSION_PARENT:
1982 {
1983 uint8_t units_in_hunk;
1984
1985 if (chd->parent == NULL)
1986 return CHDERR_REQUIRES_PARENT;
1987 units_in_hunk = chd->header.hunkbytes / chd->header.unitbytes;
1988
1989 /* blockoffs is aligned to units_in_hunk */
1990 if (blockoffs % units_in_hunk == 0) {
1991 return hunk_read_into_memory(chd->parent, blockoffs / units_in_hunk, dest);
1992 /* blockoffs is not aligned to units_in_hunk */
1993 } else {
1994 uint32_t unit_in_hunk = blockoffs % units_in_hunk;
1995 uint8_t *buf = (uint8_t*)malloc(chd->header.hunkbytes);
1996 /* Read first half of hunk which contains blockoffs */
1997 err = hunk_read_into_memory(chd->parent, blockoffs / units_in_hunk, buf);
1998 if (err != CHDERR_NONE) {
1999 free(buf);
2000 return err;
2001 }
2002 memcpy(dest, buf + unit_in_hunk * chd->header.unitbytes, (units_in_hunk - unit_in_hunk) * chd->header.unitbytes);
2003 /* Read second half of hunk which contains blockoffs */
2004 err = hunk_read_into_memory(chd->parent, (blockoffs / units_in_hunk) + 1, buf);
2005 if (err != CHDERR_NONE) {
2006 free(buf);
2007 return err;
2008 }
2009 memcpy(dest + (units_in_hunk - unit_in_hunk) * chd->header.unitbytes, buf, unit_in_hunk * chd->header.unitbytes);
2010 free(buf);
2011 }
2012 break;
2013 }
2014 }
2015 return CHDERR_NONE;
2016 }
2017
2018 /* We should not reach this code */
2019 return CHDERR_DECOMPRESSION_ERROR;
2020 }
2021
2022 /***************************************************************************
2023 INTERNAL MAP ACCESS
2024 ***************************************************************************/
2025
2026 /*-------------------------------------------------
2027 map_read - read the initial sector map
2028 -------------------------------------------------*/
2029
2030 static chd_error map_read(chd_file *chd)
2031 {
2032 uint32_t entrysize = (chd->header.version < 3) ? OLD_MAP_ENTRY_SIZE : MAP_ENTRY_SIZE;
2033 uint8_t raw_map_entries[MAP_STACK_ENTRIES * MAP_ENTRY_SIZE];
2034 uint64_t fileoffset, maxoffset = 0;
2035 uint8_t cookie[MAP_ENTRY_SIZE];
2036 chd_error err;
2037 uint32_t i;
2038
2039 /* first allocate memory */
2040 chd->map = (map_entry *)malloc(sizeof(chd->map[0]) * chd->header.totalhunks);
2041 if (!chd->map)
2042 return CHDERR_OUT_OF_MEMORY;
2043
2044 /* read the map entries in in chunks and extract to the map list */
2045 fileoffset = chd->header.length;
2046 for (i = 0; i < chd->header.totalhunks; i += MAP_STACK_ENTRIES)
2047 {
2048 /* compute how many entries this time */
2049 int entries = chd->header.totalhunks - i, j;
2050 if (entries > MAP_STACK_ENTRIES)
2051 entries = MAP_STACK_ENTRIES;
2052
2053 /* read that many */
2054 if (!seek_and_read(chd, fileoffset, raw_map_entries, entries * entrysize))
2055 EARLY_EXIT(err = CHDERR_READ_ERROR);
2056 fileoffset += entries * entrysize;
2057
2058 /* process that many */
2059 if (entrysize == MAP_ENTRY_SIZE)
2060 {
2061 for (j = 0; j < entries; j++)
2062 map_extract(&raw_map_entries[j * MAP_ENTRY_SIZE], &chd->map[i + j]);
2063 }
2064 else
2065 {
2066 for (j = 0; j < entries; j++)
2067 map_extract_old(&raw_map_entries[j * OLD_MAP_ENTRY_SIZE], &chd->map[i + j], chd->header.hunkbytes);
2068 }
2069
2070 /* track the maximum offset */
2071 for (j = 0; j < entries; j++)
2072 if ((chd->map[i + j].flags & MAP_ENTRY_FLAG_TYPE_MASK) == V34_MAP_ENTRY_TYPE_COMPRESSED ||
2073 (chd->map[i + j].flags & MAP_ENTRY_FLAG_TYPE_MASK) == V34_MAP_ENTRY_TYPE_UNCOMPRESSED)
2074 maxoffset = MAX(maxoffset, chd->map[i + j].offset + chd->map[i + j].length);
2075 }
2076
2077 /* verify the cookie */
2078 if (!seek_and_read(chd, fileoffset, &cookie, entrysize) || memcmp(&cookie, END_OF_LIST_COOKIE, entrysize))
2079 EARLY_EXIT(err = CHDERR_INVALID_FILE);
2080
2081 /* verify the length */
2082 if (maxoffset > chd->file_size)
2083 EARLY_EXIT(err = CHDERR_INVALID_FILE);
2084 return CHDERR_NONE;
2085
2086 cleanup:
2087 if (chd->map)
2088 free(chd->map);
2089 chd->map = NULL;
2090 return err;
2091 }
2092
2093 /***************************************************************************
2094 INTERNAL METADATA ACCESS
2095 ***************************************************************************/
2096
2097 /*-------------------------------------------------
2098 metadata_find_entry - find a metadata entry
2099 -------------------------------------------------*/
2100
2101 static chd_error metadata_find_entry(chd_file *chd, uint32_t metatag, uint32_t metaindex, metadata_entry *metaentry)
2102 {
2103 /* cap traversal to guard against malformed CHDs with cyclic metadata chains */
2104 uint32_t iter = 0;
2105 #define CHD_MAX_METADATA_ENTRIES 65536
2106
2107 /* start at the beginning */
2108 metaentry->offset = chd->header.metaoffset;
2109 metaentry->prev = 0;
2110
2111 /* loop until we run out of options */
2112 while (metaentry->offset != 0)
2113 {
2114 uint8_t raw_meta_header[METADATA_HEADER_SIZE];
2115
2116 if (++iter > CHD_MAX_METADATA_ENTRIES)
2117 return CHDERR_INVALID_DATA;
2118
2119 /* read the raw header */
2120 if (!seek_and_read(chd, metaentry->offset, raw_meta_header, sizeof(raw_meta_header)))
2121 break;
2122
2123 /* extract the data */
2124 metaentry->metatag = get_bigendian_uint32_t(&raw_meta_header[0]);
2125 metaentry->length = get_bigendian_uint32_t(&raw_meta_header[4]);
2126 metaentry->next = get_bigendian_uint64_t(&raw_meta_header[8]);
2127
2128 /* flags are encoded in the high byte of length */
2129 metaentry->flags = metaentry->length >> 24;
2130 metaentry->length &= 0x00ffffff;
2131
2132 /* if we got a match, proceed */
2133 if (metatag == CHDMETATAG_WILDCARD || metaentry->metatag == metatag)
2134 if (metaindex-- == 0)
2135 return CHDERR_NONE;
2136
2137 /* no match, fetch the next link */
2138 metaentry->prev = metaentry->offset;
2139 metaentry->offset = metaentry->next;
2140 }
2141
2142 /* if we get here, we didn't find it */
2143 return CHDERR_METADATA_NOT_FOUND;
2144 }
2145
2146 /***************************************************************************
2147 CORE FILE
2148 ***************************************************************************/
2149
2150 /*-------------------------------------------------
2151 core_stdio_fopen - core_file wrapper over fopen
2152 -------------------------------------------------*/
2153 static void *core_stdio_fopen(char const *path) {
2154 return fopen(path, "rb");
2155 }
2156
2157 /*-------------------------------------------------
2158 core_stdio_fsize - core_file function for
2159 getting file size with stdio
2160 -------------------------------------------------*/
2161 static uint64_t core_stdio_fsize(void *file) {
2162 #if defined USE_LIBRETRO_VFS
2163 #define core_stdio_fseek_impl fseek
2164 #define core_stdio_ftell_impl ftell
2165 #elif defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WIN64__)
2166 #define core_stdio_fseek_impl _fseeki64
2167 #define core_stdio_ftell_impl _ftelli64
2168 #elif defined(__PS3__) && !defined(__PSL1GHT__) || defined(__SWITCH__) || defined(__vita__)
2169 #define core_stdio_fseek_impl(x,y,z) fseek(x,(off_t)y,z)
2170 #define core_stdio_ftell_impl(x) (off_t)ftell(x)
2171 #else
2172 /* With _FILE_OFFSET_BITS=64 defined at the top of this TU, glibc
2173 * aliases fseeko/ftello to the 64-bit variants, so no *64 suffix
2174 * is needed. This is also the time64-safe spelling on armhf. */
2175 #define core_stdio_fseek_impl fseeko
2176 #define core_stdio_ftell_impl ftello
2177 #endif
2178 FILE *fp;
2179 uint64_t p, rv;
2180 fp = (FILE*)file;
2181
2182 p = core_stdio_ftell_impl(fp);
2183 core_stdio_fseek_impl(fp, 0, SEEK_END);
2184 rv = core_stdio_ftell_impl(fp);
2185 core_stdio_fseek_impl(fp, p, SEEK_SET);
2186 return rv;
2187 }
2188
2189 /*-------------------------------------------------
2190 core_stdio_fread - core_file wrapper over fread
2191 -------------------------------------------------*/
2192 static size_t core_stdio_fread(void *ptr, size_t size, size_t nmemb, void *file) {
2193 return fread(ptr, size, nmemb, (FILE*)file);
2194 }
2195
2196 /*-------------------------------------------------
2197 core_stdio_fclose - core_file wrapper over fclose
2198 -------------------------------------------------*/
2199 static int core_stdio_fclose(void *file) {
2200 return fclose((FILE*)file);
2201 }
2202
2203 /*-------------------------------------------------
2204 core_stdio_fclose_nonowner - don't call fclose because
2205 we don't own the underlying file.
2206 -------------------------------------------------*/
2207 static int core_stdio_fclose_nonowner(void *file) {
2208 (void)file;
2209 return 0;
2210 }
2211
2212 /*-------------------------------------------------
2213 core_stdio_fseek - core_file wrapper over fclose
2214 -------------------------------------------------*/
2215 static int core_stdio_fseek(void* file, int64_t offset, int whence) {
2216 return core_stdio_fseek_impl((FILE*)file, offset, whence);
2217 }
2218
2219 /*-------------------------------------------------
2220 core_legacy_fsize - legacy core_file wrapper
2221 -------------------------------------------------*/
2222 static uint64_t core_legacy_fsize(void *file) {
2223 core_file* const core = (core_file*)file;
2224 return core->fsize(core);
2225 }
2226
2227 /*-------------------------------------------------
2228 core_legacy_fread - legacy core_file wrapper
2229 -------------------------------------------------*/
2230 static size_t core_legacy_fread(void *ptr, size_t size, size_t nmemb, void *file) {
2231 core_file* const core = (core_file*)file;
2232 return core->fread(ptr, size, nmemb, core);
2233 }
2234
2235 /*-------------------------------------------------
2236 core_legacy_fclose - legacy core_file wrapper
2237 -------------------------------------------------*/
2238 static int core_legacy_fclose(void *file) {
2239 core_file* const core = (core_file*)file;
2240 return core->fclose(core);
2241 }
2242
2243 /*-------------------------------------------------
2244 core_legacy_fseek - legacy core_file wrapper
2245 -------------------------------------------------*/
2246 static int core_legacy_fseek(void* file, int64_t offset, int whence) {
2247 core_file* const core = (core_file*)file;
2248 return core->fseek(core, offset, whence);
2249 }