1 /***************************************************************************
2 * chm_lib.c - CHM archive manipulation routines *
3 * ------------------- *
5 * author: Jed Wing <jedwin@ugcs.caltech.edu> *
7 * notes: These routines are meant for the manipulation of microsoft *
8 * .chm (compiled html help) files, but may likely be used *
9 * for the manipulation of any ITSS archive, if ever ITSS *
10 * archives are used for any other purpose. *
12 * Note also that the section names are statically handled. *
13 * To be entirely correct, the section names should be read *
14 * from the section names meta-file, and then the various *
15 * content sections and the "transforms" to apply to the data *
16 * they contain should be inferred from the section name and *
17 * the meta-files referenced using that name; however, all of *
18 * the files I've been able to get my hands on appear to have *
19 * only two sections: Uncompressed and MSCompressed. *
20 * Additionally, the ITSS.DLL file included with Windows does *
21 * not appear to handle any different transforms than the *
22 * simple LZX-transform. Furthermore, the list of transforms *
23 * to apply is broken, in that only half the required space *
24 * is allocated for the list. (It appears as though the *
25 * space is allocated for ASCII strings, but the strings are *
26 * written as unicode. As a result, only the first half of *
27 * the string appears.) So this is probably not too big of *
28 * a deal, at least until CHM v4 (MS .lit files), which also *
29 * incorporate encryption, of some description. *
31 ***************************************************************************/
33 /***************************************************************************
35 * This library is free software; you can redistribute it and/or modify *
36 * it under the terms of the GNU Lesser General Public License as *
37 * published by the Free Software Foundation; either version 2.1 of the *
38 * License, or (at your option) any later version. *
40 ***************************************************************************/
42 /***************************************************************************
44 * Adapted for Wine by Mike McCormack *
46 ***************************************************************************/
49 #include "wine/port.h"
58 #include "wine/unicode.h"
63 #define CHM_ACQUIRE_LOCK(a) do { \
64 EnterCriticalSection(&(a)); \
66 #define CHM_RELEASE_LOCK(a) do { \
67 LeaveCriticalSection(&(a)); \
70 #define CHM_NULL_FD (INVALID_HANDLE_VALUE)
71 #define CHM_CLOSE_FILE(fd) CloseHandle((fd))
74 * defines related to tuning
76 #ifndef CHM_MAX_BLOCKS_CACHED
77 #define CHM_MAX_BLOCKS_CACHED 5
79 #define CHM_PARAM_MAX_BLOCKS_CACHED 0
82 * architecture specific defines
84 * Note: as soon as C99 is more widespread, the below defines should
85 * probably just use the C99 sized-int types.
87 * The following settings will probably work for many platforms. The sizes
88 * don't have to be exactly correct, but the types must accommodate at least as
89 * many bits as they specify.
92 /* i386, 32-bit, Windows */
95 typedef USHORT UInt16;
98 typedef LONGLONG Int64;
99 typedef ULONGLONG UInt64;
101 /* utilities for unmarshalling data */
102 static int _unmarshal_char_array(unsigned char **pData,
103 unsigned int *pLenRemain,
107 if (count <= 0 || (unsigned int)count > *pLenRemain)
109 memcpy(dest, (*pData), count);
111 *pLenRemain -= count;
115 static int _unmarshal_uchar_array(unsigned char **pData,
116 unsigned int *pLenRemain,
120 if (count <= 0 || (unsigned int)count > *pLenRemain)
122 memcpy(dest, (*pData), count);
124 *pLenRemain -= count;
128 static int _unmarshal_int32(unsigned char **pData,
129 unsigned int *pLenRemain,
134 *dest = (*pData)[0] | (*pData)[1]<<8 | (*pData)[2]<<16 | (*pData)[3]<<24;
140 static int _unmarshal_uint32(unsigned char **pData,
141 unsigned int *pLenRemain,
146 *dest = (*pData)[0] | (*pData)[1]<<8 | (*pData)[2]<<16 | (*pData)[3]<<24;
152 static int _unmarshal_int64(unsigned char **pData,
153 unsigned int *pLenRemain,
164 temp |= (*pData)[i-1];
172 static int _unmarshal_uint64(unsigned char **pData,
173 unsigned int *pLenRemain,
184 temp |= (*pData)[i-1];
192 static int _unmarshal_uuid(unsigned char **pData,
193 unsigned int *pDataLen,
196 return _unmarshal_uchar_array(pData, pDataLen, dest, 16);
199 /* names of sections essential to decompression */
200 static const WCHAR _CHMU_RESET_TABLE[] = {
201 ':',':','D','a','t','a','S','p','a','c','e','/',
202 'S','t','o','r','a','g','e','/',
203 'M','S','C','o','m','p','r','e','s','s','e','d','/',
204 'T','r','a','n','s','f','o','r','m','/',
205 '{','7','F','C','2','8','9','4','0','-','9','D','3','1',
206 '-','1','1','D','0','-','9','B','2','7','-',
207 '0','0','A','0','C','9','1','E','9','C','7','C','}','/',
208 'I','n','s','t','a','n','c','e','D','a','t','a','/',
209 'R','e','s','e','t','T','a','b','l','e',0
211 static const WCHAR _CHMU_LZXC_CONTROLDATA[] = {
212 ':',':','D','a','t','a','S','p','a','c','e','/',
213 'S','t','o','r','a','g','e','/',
214 'M','S','C','o','m','p','r','e','s','s','e','d','/',
215 'C','o','n','t','r','o','l','D','a','t','a',0
217 static const WCHAR _CHMU_CONTENT[] = {
218 ':',':','D','a','t','a','S','p','a','c','e','/',
219 'S','t','o','r','a','g','e','/',
220 'M','S','C','o','m','p','r','e','s','s','e','d','/',
221 'C','o','n','t','e','n','t',0
225 * structures local to this module
228 /* structure of ITSF headers */
229 #define _CHM_ITSF_V2_LEN (0x58)
230 #define _CHM_ITSF_V3_LEN (0x60)
233 char signature[4]; /* 0 (ITSF) */
234 Int32 version; /* 4 */
235 Int32 header_len; /* 8 */
236 Int32 unknown_000c; /* c */
237 UInt32 last_modified; /* 10 */
238 UInt32 lang_id; /* 14 */
239 UChar dir_uuid[16]; /* 18 */
240 UChar stream_uuid[16]; /* 28 */
241 UInt64 unknown_offset; /* 38 */
242 UInt64 unknown_len; /* 40 */
243 UInt64 dir_offset; /* 48 */
244 UInt64 dir_len; /* 50 */
245 UInt64 data_offset; /* 58 (Not present before V3) */
246 }; /* __attribute__ ((aligned (1))); */
248 static int _unmarshal_itsf_header(unsigned char **pData,
249 unsigned int *pDataLen,
250 struct chmItsfHeader *dest)
252 /* we only know how to deal with the 0x58 and 0x60 byte structures */
253 if (*pDataLen != _CHM_ITSF_V2_LEN && *pDataLen != _CHM_ITSF_V3_LEN)
256 /* unmarshal common fields */
257 _unmarshal_char_array(pData, pDataLen, dest->signature, 4);
258 _unmarshal_int32 (pData, pDataLen, &dest->version);
259 _unmarshal_int32 (pData, pDataLen, &dest->header_len);
260 _unmarshal_int32 (pData, pDataLen, &dest->unknown_000c);
261 _unmarshal_uint32 (pData, pDataLen, &dest->last_modified);
262 _unmarshal_uint32 (pData, pDataLen, &dest->lang_id);
263 _unmarshal_uuid (pData, pDataLen, dest->dir_uuid);
264 _unmarshal_uuid (pData, pDataLen, dest->stream_uuid);
265 _unmarshal_uint64 (pData, pDataLen, &dest->unknown_offset);
266 _unmarshal_uint64 (pData, pDataLen, &dest->unknown_len);
267 _unmarshal_uint64 (pData, pDataLen, &dest->dir_offset);
268 _unmarshal_uint64 (pData, pDataLen, &dest->dir_len);
270 /* error check the data */
271 /* XXX: should also check UUIDs, probably, though with a version 3 file,
272 * current MS tools do not seem to use them.
274 if (memcmp(dest->signature, "ITSF", 4) != 0)
276 if (dest->version == 2)
278 if (dest->header_len < _CHM_ITSF_V2_LEN)
281 else if (dest->version == 3)
283 if (dest->header_len < _CHM_ITSF_V3_LEN)
289 /* now, if we have a V3 structure, unmarshal the rest.
290 * otherwise, compute it
292 if (dest->version == 3)
295 _unmarshal_uint64(pData, pDataLen, &dest->data_offset);
300 dest->data_offset = dest->dir_offset + dest->dir_len;
305 /* structure of ITSP headers */
306 #define _CHM_ITSP_V1_LEN (0x54)
309 char signature[4]; /* 0 (ITSP) */
310 Int32 version; /* 4 */
311 Int32 header_len; /* 8 */
312 Int32 unknown_000c; /* c */
313 UInt32 block_len; /* 10 */
314 Int32 blockidx_intvl; /* 14 */
315 Int32 index_depth; /* 18 */
316 Int32 index_root; /* 1c */
317 Int32 index_head; /* 20 */
318 Int32 unknown_0024; /* 24 */
319 UInt32 num_blocks; /* 28 */
320 Int32 unknown_002c; /* 2c */
321 UInt32 lang_id; /* 30 */
322 UChar system_uuid[16]; /* 34 */
323 UChar unknown_0044[16]; /* 44 */
324 }; /* __attribute__ ((aligned (1))); */
326 static int _unmarshal_itsp_header(unsigned char **pData,
327 unsigned int *pDataLen,
328 struct chmItspHeader *dest)
330 /* we only know how to deal with a 0x54 byte structures */
331 if (*pDataLen != _CHM_ITSP_V1_LEN)
334 /* unmarshal fields */
335 _unmarshal_char_array(pData, pDataLen, dest->signature, 4);
336 _unmarshal_int32 (pData, pDataLen, &dest->version);
337 _unmarshal_int32 (pData, pDataLen, &dest->header_len);
338 _unmarshal_int32 (pData, pDataLen, &dest->unknown_000c);
339 _unmarshal_uint32 (pData, pDataLen, &dest->block_len);
340 _unmarshal_int32 (pData, pDataLen, &dest->blockidx_intvl);
341 _unmarshal_int32 (pData, pDataLen, &dest->index_depth);
342 _unmarshal_int32 (pData, pDataLen, &dest->index_root);
343 _unmarshal_int32 (pData, pDataLen, &dest->index_head);
344 _unmarshal_int32 (pData, pDataLen, &dest->unknown_0024);
345 _unmarshal_uint32 (pData, pDataLen, &dest->num_blocks);
346 _unmarshal_int32 (pData, pDataLen, &dest->unknown_002c);
347 _unmarshal_uint32 (pData, pDataLen, &dest->lang_id);
348 _unmarshal_uuid (pData, pDataLen, dest->system_uuid);
349 _unmarshal_uchar_array(pData, pDataLen, dest->unknown_0044, 16);
351 /* error check the data */
352 if (memcmp(dest->signature, "ITSP", 4) != 0)
354 if (dest->version != 1)
356 if (dest->header_len != _CHM_ITSP_V1_LEN)
362 /* structure of PMGL headers */
363 static const char _chm_pmgl_marker[4] = "PMGL";
364 #define _CHM_PMGL_LEN (0x14)
367 char signature[4]; /* 0 (PMGL) */
368 UInt32 free_space; /* 4 */
369 UInt32 unknown_0008; /* 8 */
370 Int32 block_prev; /* c */
371 Int32 block_next; /* 10 */
372 }; /* __attribute__ ((aligned (1))); */
374 static int _unmarshal_pmgl_header(unsigned char **pData,
375 unsigned int *pDataLen,
376 struct chmPmglHeader *dest)
378 /* we only know how to deal with a 0x14 byte structures */
379 if (*pDataLen != _CHM_PMGL_LEN)
382 /* unmarshal fields */
383 _unmarshal_char_array(pData, pDataLen, dest->signature, 4);
384 _unmarshal_uint32 (pData, pDataLen, &dest->free_space);
385 _unmarshal_uint32 (pData, pDataLen, &dest->unknown_0008);
386 _unmarshal_int32 (pData, pDataLen, &dest->block_prev);
387 _unmarshal_int32 (pData, pDataLen, &dest->block_next);
389 /* check structure */
390 if (memcmp(dest->signature, _chm_pmgl_marker, 4) != 0)
396 /* structure of PMGI headers */
397 static const char _chm_pmgi_marker[4] = "PMGI";
398 #define _CHM_PMGI_LEN (0x08)
401 char signature[4]; /* 0 (PMGI) */
402 UInt32 free_space; /* 4 */
403 }; /* __attribute__ ((aligned (1))); */
405 static int _unmarshal_pmgi_header(unsigned char **pData,
406 unsigned int *pDataLen,
407 struct chmPmgiHeader *dest)
409 /* we only know how to deal with a 0x8 byte structures */
410 if (*pDataLen != _CHM_PMGI_LEN)
413 /* unmarshal fields */
414 _unmarshal_char_array(pData, pDataLen, dest->signature, 4);
415 _unmarshal_uint32 (pData, pDataLen, &dest->free_space);
417 /* check structure */
418 if (memcmp(dest->signature, _chm_pmgi_marker, 4) != 0)
424 /* structure of LZXC reset table */
425 #define _CHM_LZXC_RESETTABLE_V1_LEN (0x28)
426 struct chmLzxcResetTable
432 UInt64 uncompressed_len;
433 UInt64 compressed_len;
435 }; /* __attribute__ ((aligned (1))); */
437 static int _unmarshal_lzxc_reset_table(unsigned char **pData,
438 unsigned int *pDataLen,
439 struct chmLzxcResetTable *dest)
441 /* we only know how to deal with a 0x28 byte structures */
442 if (*pDataLen != _CHM_LZXC_RESETTABLE_V1_LEN)
445 /* unmarshal fields */
446 _unmarshal_uint32 (pData, pDataLen, &dest->version);
447 _unmarshal_uint32 (pData, pDataLen, &dest->block_count);
448 _unmarshal_uint32 (pData, pDataLen, &dest->unknown);
449 _unmarshal_uint32 (pData, pDataLen, &dest->table_offset);
450 _unmarshal_uint64 (pData, pDataLen, &dest->uncompressed_len);
451 _unmarshal_uint64 (pData, pDataLen, &dest->compressed_len);
452 _unmarshal_uint64 (pData, pDataLen, &dest->block_len);
454 /* check structure */
455 if (dest->version != 2)
461 /* structure of LZXC control data block */
462 #define _CHM_LZXC_MIN_LEN (0x18)
463 #define _CHM_LZXC_V2_LEN (0x1c)
464 struct chmLzxcControlData
467 char signature[4]; /* 4 (LZXC) */
468 UInt32 version; /* 8 */
469 UInt32 resetInterval; /* c */
470 UInt32 windowSize; /* 10 */
471 UInt32 windowsPerReset; /* 14 */
472 UInt32 unknown_18; /* 18 */
475 static int _unmarshal_lzxc_control_data(unsigned char **pData,
476 unsigned int *pDataLen,
477 struct chmLzxcControlData *dest)
479 /* we want at least 0x18 bytes */
480 if (*pDataLen < _CHM_LZXC_MIN_LEN)
483 /* unmarshal fields */
484 _unmarshal_uint32 (pData, pDataLen, &dest->size);
485 _unmarshal_char_array(pData, pDataLen, dest->signature, 4);
486 _unmarshal_uint32 (pData, pDataLen, &dest->version);
487 _unmarshal_uint32 (pData, pDataLen, &dest->resetInterval);
488 _unmarshal_uint32 (pData, pDataLen, &dest->windowSize);
489 _unmarshal_uint32 (pData, pDataLen, &dest->windowsPerReset);
491 if (*pDataLen >= _CHM_LZXC_V2_LEN)
492 _unmarshal_uint32 (pData, pDataLen, &dest->unknown_18);
494 dest->unknown_18 = 0;
496 if (dest->version == 2)
498 dest->resetInterval *= 0x8000;
499 dest->windowSize *= 0x8000;
501 if (dest->windowSize == 0 || dest->resetInterval == 0)
504 /* for now, only support resetInterval a multiple of windowSize/2 */
505 if (dest->windowSize == 1)
507 if ((dest->resetInterval % (dest->windowSize/2)) != 0)
510 /* check structure */
511 if (memcmp(dest->signature, "LZXC", 4) != 0)
517 /* the structure used for chm file handles */
522 CRITICAL_SECTION mutex;
523 CRITICAL_SECTION lzx_mutex;
524 CRITICAL_SECTION cache_mutex;
534 struct chmUnitInfo rt_unit;
535 struct chmUnitInfo cn_unit;
536 struct chmLzxcResetTable reset_table;
538 /* LZX control data */
539 int compression_enabled;
541 UInt32 reset_interval;
542 UInt32 reset_blkcount;
544 /* decompressor state */
545 struct LZXstate *lzx_state;
548 /* cache for decompressed blocks */
549 UChar **cache_blocks;
550 Int64 *cache_block_indices;
551 Int32 cache_num_blocks;
555 * utility functions local to this module
558 /* utility function to handle differences between {pread,read}(64)? */
559 static Int64 _chm_fetch_bytes(struct chmFile *h,
565 if (h->fd == CHM_NULL_FD)
568 CHM_ACQUIRE_LOCK(h->mutex);
569 /* NOTE: this might be better done with CreateFileMapping, et cetera... */
571 LARGE_INTEGER old_pos, new_pos;
574 /* awkward Win32 Seek/Tell */
575 new_pos.QuadPart = 0;
576 SetFilePointerEx( h->fd, new_pos, &old_pos, FILE_CURRENT );
577 new_pos.QuadPart = os;
578 SetFilePointerEx( h->fd, new_pos, NULL, FILE_BEGIN );
590 /* restore original position */
591 SetFilePointerEx( h->fd, old_pos, NULL, FILE_BEGIN );
593 CHM_RELEASE_LOCK(h->mutex);
598 * set a parameter on the file handle.
599 * valid parameter types:
600 * CHM_PARAM_MAX_BLOCKS_CACHED:
601 * how many decompressed blocks should be cached? A simple
602 * caching scheme is used, wherein the index of the block is
603 * used as a hash value, and hash collision results in the
604 * invalidation of the previously cached block.
606 static void chm_set_param(struct chmFile *h,
612 case CHM_PARAM_MAX_BLOCKS_CACHED:
613 CHM_ACQUIRE_LOCK(h->cache_mutex);
614 if (paramVal != h->cache_num_blocks)
620 /* allocate new cached blocks */
621 newBlocks = malloc(paramVal * sizeof (UChar *));
622 newIndices = malloc(paramVal * sizeof (UInt64));
623 for (i=0; i<paramVal; i++)
629 /* re-distribute old cached blocks */
632 for (i=0; i<h->cache_num_blocks; i++)
634 int newSlot = (int)(h->cache_block_indices[i] % paramVal);
636 if (h->cache_blocks[i])
638 /* in case of collision, destroy newcomer */
639 if (newBlocks[newSlot])
641 free(h->cache_blocks[i]);
642 h->cache_blocks[i] = NULL;
646 newBlocks[newSlot] = h->cache_blocks[i];
647 newIndices[newSlot] =
648 h->cache_block_indices[i];
653 free(h->cache_blocks);
654 free(h->cache_block_indices);
657 /* now, set new values */
658 h->cache_blocks = newBlocks;
659 h->cache_block_indices = newIndices;
660 h->cache_num_blocks = paramVal;
662 CHM_RELEASE_LOCK(h->cache_mutex);
670 /* open an ITS archive */
671 struct chmFile *chm_openW(const WCHAR *filename)
673 unsigned char sbuffer[256];
674 unsigned int sremain;
675 unsigned char *sbufpos;
676 struct chmFile *newHandle=NULL;
677 struct chmItsfHeader itsfHeader;
678 struct chmItspHeader itspHeader;
680 struct chmUnitInfo uiSpan;
682 struct chmUnitInfo uiLzxc;
683 struct chmLzxcControlData ctlData;
685 /* allocate handle */
686 newHandle = malloc(sizeof(struct chmFile));
687 newHandle->fd = CHM_NULL_FD;
688 newHandle->lzx_state = NULL;
689 newHandle->cache_blocks = NULL;
690 newHandle->cache_block_indices = NULL;
691 newHandle->cache_num_blocks = 0;
694 if ((newHandle->fd=CreateFileW(filename,
699 FILE_ATTRIBUTE_NORMAL,
700 NULL)) == CHM_NULL_FD)
706 /* initialize mutexes, if needed */
707 InitializeCriticalSection(&newHandle->mutex);
708 InitializeCriticalSection(&newHandle->lzx_mutex);
709 InitializeCriticalSection(&newHandle->cache_mutex);
711 /* read and verify header */
712 sremain = _CHM_ITSF_V3_LEN;
714 if (_chm_fetch_bytes(newHandle, sbuffer, (UInt64)0, sremain) != sremain ||
715 !_unmarshal_itsf_header(&sbufpos, &sremain, &itsfHeader))
717 chm_close(newHandle);
721 /* stash important values from header */
722 newHandle->dir_offset = itsfHeader.dir_offset;
723 newHandle->dir_len = itsfHeader.dir_len;
724 newHandle->data_offset = itsfHeader.data_offset;
726 /* now, read and verify the directory header chunk */
727 sremain = _CHM_ITSP_V1_LEN;
729 if (_chm_fetch_bytes(newHandle, sbuffer,
730 (UInt64)itsfHeader.dir_offset, sremain) != sremain ||
731 !_unmarshal_itsp_header(&sbufpos, &sremain, &itspHeader))
733 chm_close(newHandle);
737 /* grab essential information from ITSP header */
738 newHandle->dir_offset += itspHeader.header_len;
739 newHandle->dir_len -= itspHeader.header_len;
740 newHandle->index_root = itspHeader.index_root;
741 newHandle->index_head = itspHeader.index_head;
742 newHandle->block_len = itspHeader.block_len;
744 /* if the index root is -1, this means we don't have any PMGI blocks.
745 * as a result, we must use the sole PMGL block as the index root
747 if (newHandle->index_root == -1)
748 newHandle->index_root = newHandle->index_head;
750 /* By default, compression is enabled. */
751 newHandle->compression_enabled = 1;
753 /* prefetch most commonly needed unit infos */
754 if (CHM_RESOLVE_SUCCESS != chm_resolve_object(newHandle,
756 &newHandle->rt_unit) ||
757 newHandle->rt_unit.space == CHM_COMPRESSED ||
758 CHM_RESOLVE_SUCCESS != chm_resolve_object(newHandle,
760 &newHandle->cn_unit) ||
761 newHandle->cn_unit.space == CHM_COMPRESSED ||
762 CHM_RESOLVE_SUCCESS != chm_resolve_object(newHandle,
763 _CHMU_LZXC_CONTROLDATA,
765 uiLzxc.space == CHM_COMPRESSED)
767 newHandle->compression_enabled = 0;
770 /* read reset table info */
771 if (newHandle->compression_enabled)
773 sremain = _CHM_LZXC_RESETTABLE_V1_LEN;
775 if (chm_retrieve_object(newHandle, &newHandle->rt_unit, sbuffer,
776 0, sremain) != sremain ||
777 !_unmarshal_lzxc_reset_table(&sbufpos, &sremain,
778 &newHandle->reset_table))
780 newHandle->compression_enabled = 0;
784 /* read control data */
785 if (newHandle->compression_enabled)
787 sremain = (unsigned long)uiLzxc.length;
789 if (chm_retrieve_object(newHandle, &uiLzxc, sbuffer,
790 0, sremain) != sremain ||
791 !_unmarshal_lzxc_control_data(&sbufpos, &sremain,
794 newHandle->compression_enabled = 0;
797 newHandle->window_size = ctlData.windowSize;
798 newHandle->reset_interval = ctlData.resetInterval;
800 /* Jed, Mon Jun 28: Experimentally, it appears that the reset block count */
801 /* must be multiplied by this formerly unknown ctrl data field in */
802 /* order to decompress some files. */
804 newHandle->reset_blkcount = newHandle->reset_interval /
805 (newHandle->window_size / 2);
807 newHandle->reset_blkcount = newHandle->reset_interval /
808 (newHandle->window_size / 2) *
809 ctlData.windowsPerReset;
813 /* initialize cache */
814 chm_set_param(newHandle, CHM_PARAM_MAX_BLOCKS_CACHED,
815 CHM_MAX_BLOCKS_CACHED);
820 /* close an ITS archive */
821 void chm_close(struct chmFile *h)
825 if (h->fd != CHM_NULL_FD)
826 CHM_CLOSE_FILE(h->fd);
829 DeleteCriticalSection(&h->mutex);
830 DeleteCriticalSection(&h->lzx_mutex);
831 DeleteCriticalSection(&h->cache_mutex);
834 LZXteardown(h->lzx_state);
840 for (i=0; i<h->cache_num_blocks; i++)
842 if (h->cache_blocks[i])
843 free(h->cache_blocks[i]);
845 free(h->cache_blocks);
846 h->cache_blocks = NULL;
849 free(h->cache_block_indices);
850 h->cache_block_indices = NULL;
857 * helper methods for chm_resolve_object
860 /* skip a compressed dword */
861 static void _chm_skip_cword(UChar **pEntry)
863 while (*(*pEntry)++ >= 0x80)
867 /* skip the data from a PMGL entry */
868 static void _chm_skip_PMGL_entry_data(UChar **pEntry)
870 _chm_skip_cword(pEntry);
871 _chm_skip_cword(pEntry);
872 _chm_skip_cword(pEntry);
875 /* parse a compressed dword */
876 static UInt64 _chm_parse_cword(UChar **pEntry)
880 while ((temp=*(*pEntry)++) >= 0x80)
883 accum += temp & 0x7f;
886 return (accum << 7) + temp;
889 /* parse a utf-8 string into an ASCII char buffer */
890 static int _chm_parse_UTF8(UChar **pEntry, UInt64 count, WCHAR *path)
892 /* MJM - Modified to return real Unicode strings */
895 *path++ = (*(*pEntry)++);
903 /* parse a PMGL entry into a chmUnitInfo struct; return 1 on success. */
904 static int _chm_parse_PMGL_entry(UChar **pEntry, struct chmUnitInfo *ui)
909 strLen = _chm_parse_cword(pEntry);
910 if (strLen > CHM_MAX_PATHLEN)
914 if (! _chm_parse_UTF8(pEntry, strLen, ui->path))
918 ui->space = (int)_chm_parse_cword(pEntry);
919 ui->start = _chm_parse_cword(pEntry);
920 ui->length = _chm_parse_cword(pEntry);
924 /* find an exact entry in PMGL; return NULL if we fail */
925 static UChar *_chm_find_in_PMGL(UChar *page_buf,
927 const WCHAR *objPath)
929 /* XXX: modify this to do a binary search using the nice index structure
930 * that is provided for us.
932 struct chmPmglHeader header;
938 WCHAR buffer[CHM_MAX_PATHLEN+1];
940 /* figure out where to start and end */
942 hremain = _CHM_PMGL_LEN;
943 if (! _unmarshal_pmgl_header(&cur, &hremain, &header))
945 end = page_buf + block_len - (header.free_space);
947 /* now, scan progressively */
952 strLen = _chm_parse_cword(&cur);
953 if (! _chm_parse_UTF8(&cur, strLen, buffer))
956 /* check if it is the right name */
957 if (! strcmpiW(buffer, objPath))
960 _chm_skip_PMGL_entry_data(&cur);
966 /* find which block should be searched next for the entry; -1 if no block */
967 static Int32 _chm_find_in_PMGI(UChar *page_buf,
969 const WCHAR *objPath)
971 /* XXX: modify this to do a binary search using the nice index structure
972 * that is provided for us
974 struct chmPmgiHeader header;
980 WCHAR buffer[CHM_MAX_PATHLEN+1];
982 /* figure out where to start and end */
984 hremain = _CHM_PMGI_LEN;
985 if (! _unmarshal_pmgi_header(&cur, &hremain, &header))
987 end = page_buf + block_len - (header.free_space);
989 /* now, scan progressively */
993 strLen = _chm_parse_cword(&cur);
994 if (! _chm_parse_UTF8(&cur, strLen, buffer))
997 /* check if it is the right name */
998 if (strcmpiW(buffer, objPath) > 0)
1001 /* load next value for path */
1002 page = (int)_chm_parse_cword(&cur);
1008 /* resolve a particular object from the archive */
1009 int chm_resolve_object(struct chmFile *h,
1010 const WCHAR *objPath,
1011 struct chmUnitInfo *ui)
1014 * XXX: implement caching scheme for dir pages
1019 /* buffer to hold whatever page we're looking at */
1020 UChar *page_buf = HeapAlloc(GetProcessHeap(), 0, h->block_len);
1023 curPage = h->index_root;
1025 /* until we have either returned or given up */
1026 while (curPage != -1)
1029 /* try to fetch the index page */
1030 if (_chm_fetch_bytes(h, page_buf,
1031 (UInt64)h->dir_offset + (UInt64)curPage*h->block_len,
1032 h->block_len) != h->block_len)
1034 HeapFree(GetProcessHeap(), 0, page_buf);
1035 return CHM_RESOLVE_FAILURE;
1038 /* now, if it is a leaf node: */
1039 if (memcmp(page_buf, _chm_pmgl_marker, 4) == 0)
1042 UChar *pEntry = _chm_find_in_PMGL(page_buf,
1047 HeapFree(GetProcessHeap(), 0, page_buf);
1048 return CHM_RESOLVE_FAILURE;
1051 /* parse entry and return */
1052 _chm_parse_PMGL_entry(&pEntry, ui);
1053 HeapFree(GetProcessHeap(), 0, page_buf);
1054 return CHM_RESOLVE_SUCCESS;
1057 /* else, if it is a branch node: */
1058 else if (memcmp(page_buf, _chm_pmgi_marker, 4) == 0)
1059 curPage = _chm_find_in_PMGI(page_buf, h->block_len, objPath);
1061 /* else, we are confused. give up. */
1064 HeapFree(GetProcessHeap(), 0, page_buf);
1065 return CHM_RESOLVE_FAILURE;
1069 /* didn't find anything. fail. */
1070 HeapFree(GetProcessHeap(), 0, page_buf);
1071 return CHM_RESOLVE_FAILURE;
1075 * utility methods for dealing with compressed data
1078 /* get the bounds of a compressed block. return 0 on failure */
1079 static int _chm_get_cmpblock_bounds(struct chmFile *h,
1084 UChar buffer[8], *dummy;
1087 /* for all but the last block, use the reset table */
1088 if (block < h->reset_table.block_count-1)
1090 /* unpack the start address */
1093 if (_chm_fetch_bytes(h, buffer,
1094 (UInt64)h->data_offset
1095 + (UInt64)h->rt_unit.start
1096 + (UInt64)h->reset_table.table_offset
1098 remain) != remain ||
1099 !_unmarshal_uint64(&dummy, &remain, start))
1102 /* unpack the end address */
1105 if (_chm_fetch_bytes(h, buffer,
1106 (UInt64)h->data_offset
1107 + (UInt64)h->rt_unit.start
1108 + (UInt64)h->reset_table.table_offset
1109 + (UInt64)block*8 + 8,
1110 remain) != remain ||
1111 !_unmarshal_int64(&dummy, &remain, len))
1115 /* for the last block, use the span in addition to the reset table */
1118 /* unpack the start address */
1121 if (_chm_fetch_bytes(h, buffer,
1122 (UInt64)h->data_offset
1123 + (UInt64)h->rt_unit.start
1124 + (UInt64)h->reset_table.table_offset
1126 remain) != remain ||
1127 !_unmarshal_uint64(&dummy, &remain, start))
1130 *len = h->reset_table.compressed_len;
1133 /* compute the length and absolute start address */
1135 *start += h->data_offset + h->cn_unit.start;
1140 /* decompress the block. must have lzx_mutex. */
1141 static Int64 _chm_decompress_block(struct chmFile *h,
1145 UChar *cbuffer = HeapAlloc( GetProcessHeap(), 0,
1146 ((unsigned int)h->reset_table.block_len + 6144));
1147 UInt64 cmpStart; /* compressed start */
1148 Int64 cmpLen; /* compressed len */
1149 int indexSlot; /* cache index slot */
1150 UChar *lbuffer; /* local buffer ptr */
1151 UInt32 blockAlign = (UInt32)(block % h->reset_blkcount); /* reset intvl. aln. */
1152 UInt32 i; /* local loop index */
1154 /* let the caching system pull its weight! */
1155 if (block - blockAlign <= h->lzx_last_block &&
1156 block >= h->lzx_last_block)
1157 blockAlign = (block - h->lzx_last_block);
1159 /* check if we need previous blocks */
1160 if (blockAlign != 0)
1162 /* fetch all required previous blocks since last reset */
1163 for (i = blockAlign; i > 0; i--)
1165 UInt32 curBlockIdx = block - i;
1167 /* check if we most recently decompressed the previous block */
1168 if (h->lzx_last_block != curBlockIdx)
1170 if ((curBlockIdx % h->reset_blkcount) == 0)
1173 fprintf(stderr, "***RESET (1)***\n");
1175 LZXreset(h->lzx_state);
1178 indexSlot = (int)((curBlockIdx) % h->cache_num_blocks);
1179 h->cache_block_indices[indexSlot] = curBlockIdx;
1180 if (! h->cache_blocks[indexSlot])
1181 h->cache_blocks[indexSlot] = malloc( (unsigned int)(h->reset_table.block_len));
1182 lbuffer = h->cache_blocks[indexSlot];
1184 /* decompress the previous block */
1186 fprintf(stderr, "Decompressing block #%4d (EXTRA)\n", curBlockIdx);
1188 if (!_chm_get_cmpblock_bounds(h, curBlockIdx, &cmpStart, &cmpLen) ||
1189 _chm_fetch_bytes(h, cbuffer, cmpStart, cmpLen) != cmpLen ||
1190 LZXdecompress(h->lzx_state, cbuffer, lbuffer, (int)cmpLen,
1191 (int)h->reset_table.block_len) != DECR_OK)
1194 fprintf(stderr, " (DECOMPRESS FAILED!)\n");
1196 HeapFree(GetProcessHeap(), 0, cbuffer);
1200 h->lzx_last_block = (int)curBlockIdx;
1206 if ((block % h->reset_blkcount) == 0)
1209 fprintf(stderr, "***RESET (2)***\n");
1211 LZXreset(h->lzx_state);
1215 /* allocate slot in cache */
1216 indexSlot = (int)(block % h->cache_num_blocks);
1217 h->cache_block_indices[indexSlot] = block;
1218 if (! h->cache_blocks[indexSlot])
1219 h->cache_blocks[indexSlot] = malloc( ((unsigned int)h->reset_table.block_len));
1220 lbuffer = h->cache_blocks[indexSlot];
1223 /* decompress the block we actually want */
1225 fprintf(stderr, "Decompressing block #%4d (REAL )\n", block);
1227 if (! _chm_get_cmpblock_bounds(h, block, &cmpStart, &cmpLen) ||
1228 _chm_fetch_bytes(h, cbuffer, cmpStart, cmpLen) != cmpLen ||
1229 LZXdecompress(h->lzx_state, cbuffer, lbuffer, (int)cmpLen,
1230 (int)h->reset_table.block_len) != DECR_OK)
1233 fprintf(stderr, " (DECOMPRESS FAILED!)\n");
1235 HeapFree(GetProcessHeap(), 0, cbuffer);
1238 h->lzx_last_block = (int)block;
1240 /* XXX: modify LZX routines to return the length of the data they
1241 * decompressed and return that instead, for an extra sanity check.
1243 HeapFree(GetProcessHeap(), 0, cbuffer);
1244 return h->reset_table.block_len;
1247 /* grab a region from a compressed block */
1248 static Int64 _chm_decompress_region(struct chmFile *h,
1253 UInt64 nBlock, nOffset;
1256 UChar *ubuffer = NULL;
1261 /* figure out what we need to read */
1262 nBlock = start / h->reset_table.block_len;
1263 nOffset = start % h->reset_table.block_len;
1265 if (nLen > (h->reset_table.block_len - nOffset))
1266 nLen = h->reset_table.block_len - nOffset;
1268 /* if block is cached, return data from it. */
1269 CHM_ACQUIRE_LOCK(h->lzx_mutex);
1270 CHM_ACQUIRE_LOCK(h->cache_mutex);
1271 if (h->cache_block_indices[nBlock % h->cache_num_blocks] == nBlock &&
1272 h->cache_blocks[nBlock % h->cache_num_blocks] != NULL)
1275 h->cache_blocks[nBlock % h->cache_num_blocks] + nOffset,
1276 (unsigned int)nLen);
1277 CHM_RELEASE_LOCK(h->cache_mutex);
1278 CHM_RELEASE_LOCK(h->lzx_mutex);
1281 CHM_RELEASE_LOCK(h->cache_mutex);
1283 /* data request not satisfied, so... start up the decompressor machine */
1286 int window_size = ffs(h->window_size) - 1;
1287 h->lzx_last_block = -1;
1288 h->lzx_state = LZXinit(window_size);
1291 /* decompress some data */
1292 gotLen = _chm_decompress_block(h, nBlock, &ubuffer);
1295 memcpy(buf, ubuffer+nOffset, (unsigned int)nLen);
1296 CHM_RELEASE_LOCK(h->lzx_mutex);
1300 /* retrieve (part of) an object */
1301 LONGINT64 chm_retrieve_object(struct chmFile *h,
1302 struct chmUnitInfo *ui,
1307 /* must be valid file handle */
1311 /* starting address must be in correct range */
1312 if (addr < 0 || addr >= ui->length)
1316 if (addr + len > ui->length)
1317 len = ui->length - addr;
1319 /* if the file is uncompressed, it's simple */
1320 if (ui->space == CHM_UNCOMPRESSED)
1323 return _chm_fetch_bytes(h,
1325 (UInt64)h->data_offset + (UInt64)ui->start + (UInt64)addr,
1329 /* else if the file is compressed, it's a little trickier */
1330 else /* ui->space == CHM_COMPRESSED */
1332 Int64 swath=0, total=0;
1334 /* if compression is not enabled for this file... */
1335 if (! h->compression_enabled)
1340 /* swill another mouthful */
1341 swath = _chm_decompress_region(h, buf, ui->start + addr, len);
1343 /* if we didn't get any... */
1359 /* enumerate the objects in the .chm archive */
1360 int chm_enumerate(struct chmFile *h,
1367 /* buffer to hold whatever page we're looking at */
1368 UChar *page_buf = HeapAlloc(GetProcessHeap(), 0, (unsigned int)h->block_len);
1369 struct chmPmglHeader header;
1372 unsigned int lenRemain;
1375 /* the current ui */
1376 struct chmUnitInfo ui;
1380 curPage = h->index_head;
1382 /* until we have either returned or given up */
1383 while (curPage != -1)
1386 /* try to fetch the index page */
1387 if (_chm_fetch_bytes(h,
1389 (UInt64)h->dir_offset + (UInt64)curPage*h->block_len,
1390 h->block_len) != h->block_len)
1392 HeapFree(GetProcessHeap(), 0, page_buf);
1396 /* figure out start and end for this page */
1398 lenRemain = _CHM_PMGL_LEN;
1399 if (! _unmarshal_pmgl_header(&cur, &lenRemain, &header))
1401 HeapFree(GetProcessHeap(), 0, page_buf);
1404 end = page_buf + h->block_len - (header.free_space);
1406 /* loop over this page */
1409 if (! _chm_parse_PMGL_entry(&cur, &ui))
1411 HeapFree(GetProcessHeap(), 0, page_buf);
1415 /* get the length of the path */
1416 ui_path_len = strlenW(ui.path)-1;
1418 /* check for DIRS */
1419 if (ui.path[ui_path_len] == '/' && !(what & CHM_ENUMERATE_DIRS))
1422 /* check for FILES */
1423 if (ui.path[ui_path_len] != '/' && !(what & CHM_ENUMERATE_FILES))
1426 /* check for NORMAL vs. META */
1427 if (ui.path[0] == '/')
1430 /* check for NORMAL vs. SPECIAL */
1431 if (ui.path[1] == '#' || ui.path[1] == '$')
1432 flag = CHM_ENUMERATE_SPECIAL;
1434 flag = CHM_ENUMERATE_NORMAL;
1437 flag = CHM_ENUMERATE_META;
1438 if (! (what & flag))
1441 /* call the enumerator */
1443 int status = (*e)(h, &ui, context);
1446 case CHM_ENUMERATOR_FAILURE:
1447 HeapFree(GetProcessHeap(), 0, page_buf);
1449 case CHM_ENUMERATOR_CONTINUE:
1451 case CHM_ENUMERATOR_SUCCESS:
1452 HeapFree(GetProcessHeap(), 0, page_buf);
1460 /* advance to next page */
1461 curPage = header.block_next;
1464 HeapFree(GetProcessHeap(), 0, page_buf);
1468 int chm_enumerate_dir(struct chmFile *h,
1469 const WCHAR *prefix,
1475 * XXX: do this efficiently (i.e. using the tree index)
1480 /* buffer to hold whatever page we're looking at */
1481 UChar *page_buf = HeapAlloc(GetProcessHeap(), 0, (unsigned int)h->block_len);
1482 struct chmPmglHeader header;
1485 unsigned int lenRemain;
1487 /* set to 1 once we've started */
1490 /* the current ui */
1491 struct chmUnitInfo ui;
1495 /* the length of the prefix */
1496 WCHAR prefixRectified[CHM_MAX_PATHLEN+1];
1498 WCHAR lastPath[CHM_MAX_PATHLEN];
1502 curPage = h->index_head;
1504 /* initialize pathname state */
1505 lstrcpynW(prefixRectified, prefix, CHM_MAX_PATHLEN);
1506 prefixLen = strlenW(prefixRectified);
1509 if (prefixRectified[prefixLen-1] != '/')
1511 prefixRectified[prefixLen] = '/';
1512 prefixRectified[prefixLen+1] = '\0';
1519 /* until we have either returned or given up */
1520 while (curPage != -1)
1523 /* try to fetch the index page */
1524 if (_chm_fetch_bytes(h,
1526 (UInt64)h->dir_offset + (UInt64)curPage*h->block_len,
1527 h->block_len) != h->block_len)
1529 HeapFree(GetProcessHeap(), 0, page_buf);
1533 /* figure out start and end for this page */
1535 lenRemain = _CHM_PMGL_LEN;
1536 if (! _unmarshal_pmgl_header(&cur, &lenRemain, &header))
1538 HeapFree(GetProcessHeap(), 0, page_buf);
1541 end = page_buf + h->block_len - (header.free_space);
1543 /* loop over this page */
1546 if (! _chm_parse_PMGL_entry(&cur, &ui))
1548 HeapFree(GetProcessHeap(), 0, page_buf);
1552 /* check if we should start */
1555 if (ui.length == 0 && strncmpiW(ui.path, prefixRectified, prefixLen) == 0)
1560 if (ui.path[prefixLen] == '\0')
1564 /* check if we should stop */
1567 if (strncmpiW(ui.path, prefixRectified, prefixLen) != 0)
1569 HeapFree(GetProcessHeap(), 0, page_buf);
1574 /* check if we should include this path */
1575 if (lastPathLen != -1)
1577 if (strncmpiW(ui.path, lastPath, lastPathLen) == 0)
1580 strcpyW(lastPath, ui.path);
1581 lastPathLen = strlenW(lastPath);
1583 /* get the length of the path */
1584 ui_path_len = strlenW(ui.path)-1;
1586 /* check for DIRS */
1587 if (ui.path[ui_path_len] == '/' && !(what & CHM_ENUMERATE_DIRS))
1590 /* check for FILES */
1591 if (ui.path[ui_path_len] != '/' && !(what & CHM_ENUMERATE_FILES))
1594 /* check for NORMAL vs. META */
1595 if (ui.path[0] == '/')
1598 /* check for NORMAL vs. SPECIAL */
1599 if (ui.path[1] == '#' || ui.path[1] == '$')
1600 flag = CHM_ENUMERATE_SPECIAL;
1602 flag = CHM_ENUMERATE_NORMAL;
1605 flag = CHM_ENUMERATE_META;
1606 if (! (what & flag))
1609 /* call the enumerator */
1611 int status = (*e)(h, &ui, context);
1614 case CHM_ENUMERATOR_FAILURE:
1615 HeapFree(GetProcessHeap(), 0, page_buf);
1617 case CHM_ENUMERATOR_CONTINUE:
1619 case CHM_ENUMERATOR_SUCCESS:
1620 HeapFree(GetProcessHeap(), 0, page_buf);
1628 /* advance to next page */
1629 curPage = header.block_next;
1632 HeapFree(GetProcessHeap(), 0, page_buf);