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
36 * modify it under the terms of the GNU Lesser General Public
37 * License as published by the Free Software Foundation; either
38 * version 2.1 of the License, or (at your option) any later version.
40 * This library is distributed in the hope that it will be useful,
41 * but WITHOUT ANY WARRANTY; without even the implied warranty of
42 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
43 * Lesser General Public License for more details.
45 * You should have received a copy of the GNU Lesser General Public
46 * License along with this library; if not, write to the Free Software
47 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
49 ***************************************************************************/
51 /***************************************************************************
53 * Adapted for Wine by Mike McCormack *
55 ***************************************************************************/
70 #define CHM_ACQUIRE_LOCK(a) do { \
71 EnterCriticalSection(&(a)); \
73 #define CHM_RELEASE_LOCK(a) do { \
74 LeaveCriticalSection(&(a)); \
77 #define CHM_NULL_FD (INVALID_HANDLE_VALUE)
78 #define CHM_CLOSE_FILE(fd) CloseHandle((fd))
81 * defines related to tuning
83 #ifndef CHM_MAX_BLOCKS_CACHED
84 #define CHM_MAX_BLOCKS_CACHED 5
86 #define CHM_PARAM_MAX_BLOCKS_CACHED 0
89 * architecture specific defines
91 * Note: as soon as C99 is more widespread, the below defines should
92 * probably just use the C99 sized-int types.
94 * The following settings will probably work for many platforms. The sizes
95 * don't have to be exactly correct, but the types must accommodate at least as
96 * many bits as they specify.
99 /* i386, 32-bit, Windows */
102 typedef USHORT UInt16
;
104 typedef DWORD UInt32
;
105 typedef LONGLONG Int64
;
106 typedef ULONGLONG UInt64
;
108 /* utilities for unmarshalling data */
109 static BOOL
_unmarshal_char_array(unsigned char **pData
,
110 unsigned int *pLenRemain
,
114 if (count
<= 0 || (unsigned int)count
> *pLenRemain
)
116 memcpy(dest
, (*pData
), count
);
118 *pLenRemain
-= count
;
122 static BOOL
_unmarshal_uchar_array(unsigned char **pData
,
123 unsigned int *pLenRemain
,
127 if (count
<= 0 || (unsigned int)count
> *pLenRemain
)
129 memcpy(dest
, (*pData
), count
);
131 *pLenRemain
-= count
;
135 static BOOL
_unmarshal_int32(unsigned char **pData
,
136 unsigned int *pLenRemain
,
141 *dest
= (*pData
)[0] | (*pData
)[1]<<8 | (*pData
)[2]<<16 | (*pData
)[3]<<24;
147 static BOOL
_unmarshal_uint32(unsigned char **pData
,
148 unsigned int *pLenRemain
,
153 *dest
= (*pData
)[0] | (*pData
)[1]<<8 | (*pData
)[2]<<16 | (*pData
)[3]<<24;
159 static BOOL
_unmarshal_int64(unsigned char **pData
,
160 unsigned int *pLenRemain
,
171 temp
|= (*pData
)[i
-1];
179 static BOOL
_unmarshal_uint64(unsigned char **pData
,
180 unsigned int *pLenRemain
,
191 temp
|= (*pData
)[i
-1];
199 static BOOL
_unmarshal_uuid(unsigned char **pData
,
200 unsigned int *pDataLen
,
203 return _unmarshal_uchar_array(pData
, pDataLen
, dest
, 16);
206 /* names of sections essential to decompression */
207 static const WCHAR _CHMU_RESET_TABLE
[] = {
208 ':',':','D','a','t','a','S','p','a','c','e','/',
209 'S','t','o','r','a','g','e','/',
210 'M','S','C','o','m','p','r','e','s','s','e','d','/',
211 'T','r','a','n','s','f','o','r','m','/',
212 '{','7','F','C','2','8','9','4','0','-','9','D','3','1',
213 '-','1','1','D','0','-','9','B','2','7','-',
214 '0','0','A','0','C','9','1','E','9','C','7','C','}','/',
215 'I','n','s','t','a','n','c','e','D','a','t','a','/',
216 'R','e','s','e','t','T','a','b','l','e',0
218 static const WCHAR _CHMU_LZXC_CONTROLDATA
[] = {
219 ':',':','D','a','t','a','S','p','a','c','e','/',
220 'S','t','o','r','a','g','e','/',
221 'M','S','C','o','m','p','r','e','s','s','e','d','/',
222 'C','o','n','t','r','o','l','D','a','t','a',0
224 static const WCHAR _CHMU_CONTENT
[] = {
225 ':',':','D','a','t','a','S','p','a','c','e','/',
226 'S','t','o','r','a','g','e','/',
227 'M','S','C','o','m','p','r','e','s','s','e','d','/',
228 'C','o','n','t','e','n','t',0
232 * structures local to this module
235 /* structure of ITSF headers */
236 #define _CHM_ITSF_V2_LEN (0x58)
237 #define _CHM_ITSF_V3_LEN (0x60)
240 char signature
[4]; /* 0 (ITSF) */
241 Int32 version
; /* 4 */
242 Int32 header_len
; /* 8 */
243 Int32 unknown_000c
; /* c */
244 UInt32 last_modified
; /* 10 */
245 UInt32 lang_id
; /* 14 */
246 UChar dir_uuid
[16]; /* 18 */
247 UChar stream_uuid
[16]; /* 28 */
248 UInt64 unknown_offset
; /* 38 */
249 UInt64 unknown_len
; /* 40 */
250 UInt64 dir_offset
; /* 48 */
251 UInt64 dir_len
; /* 50 */
252 UInt64 data_offset
; /* 58 (Not present before V3) */
253 }; /* __attribute__ ((aligned (1))); */
255 static BOOL
_unmarshal_itsf_header(unsigned char **pData
,
256 unsigned int *pDataLen
,
257 struct chmItsfHeader
*dest
)
259 /* we only know how to deal with the 0x58 and 0x60 byte structures */
260 if (*pDataLen
!= _CHM_ITSF_V2_LEN
&& *pDataLen
!= _CHM_ITSF_V3_LEN
)
263 /* unmarshal common fields */
264 _unmarshal_char_array(pData
, pDataLen
, dest
->signature
, 4);
265 _unmarshal_int32 (pData
, pDataLen
, &dest
->version
);
266 _unmarshal_int32 (pData
, pDataLen
, &dest
->header_len
);
267 _unmarshal_int32 (pData
, pDataLen
, &dest
->unknown_000c
);
268 _unmarshal_uint32 (pData
, pDataLen
, &dest
->last_modified
);
269 _unmarshal_uint32 (pData
, pDataLen
, &dest
->lang_id
);
270 _unmarshal_uuid (pData
, pDataLen
, dest
->dir_uuid
);
271 _unmarshal_uuid (pData
, pDataLen
, dest
->stream_uuid
);
272 _unmarshal_uint64 (pData
, pDataLen
, &dest
->unknown_offset
);
273 _unmarshal_uint64 (pData
, pDataLen
, &dest
->unknown_len
);
274 _unmarshal_uint64 (pData
, pDataLen
, &dest
->dir_offset
);
275 _unmarshal_uint64 (pData
, pDataLen
, &dest
->dir_len
);
277 /* error check the data */
278 /* XXX: should also check UUIDs, probably, though with a version 3 file,
279 * current MS tools do not seem to use them.
281 if (memcmp(dest
->signature
, "ITSF", 4) != 0)
283 if (dest
->version
== 2)
285 if (dest
->header_len
< _CHM_ITSF_V2_LEN
)
288 else if (dest
->version
== 3)
290 if (dest
->header_len
< _CHM_ITSF_V3_LEN
)
296 /* now, if we have a V3 structure, unmarshal the rest.
297 * otherwise, compute it
299 if (dest
->version
== 3)
302 _unmarshal_uint64(pData
, pDataLen
, &dest
->data_offset
);
307 dest
->data_offset
= dest
->dir_offset
+ dest
->dir_len
;
312 /* structure of ITSP headers */
313 #define _CHM_ITSP_V1_LEN (0x54)
316 char signature
[4]; /* 0 (ITSP) */
317 Int32 version
; /* 4 */
318 Int32 header_len
; /* 8 */
319 Int32 unknown_000c
; /* c */
320 UInt32 block_len
; /* 10 */
321 Int32 blockidx_intvl
; /* 14 */
322 Int32 index_depth
; /* 18 */
323 Int32 index_root
; /* 1c */
324 Int32 index_head
; /* 20 */
325 Int32 unknown_0024
; /* 24 */
326 UInt32 num_blocks
; /* 28 */
327 Int32 unknown_002c
; /* 2c */
328 UInt32 lang_id
; /* 30 */
329 UChar system_uuid
[16]; /* 34 */
330 UChar unknown_0044
[16]; /* 44 */
331 }; /* __attribute__ ((aligned (1))); */
333 static BOOL
_unmarshal_itsp_header(unsigned char **pData
,
334 unsigned int *pDataLen
,
335 struct chmItspHeader
*dest
)
337 /* we only know how to deal with a 0x54 byte structures */
338 if (*pDataLen
!= _CHM_ITSP_V1_LEN
)
341 /* unmarshal fields */
342 _unmarshal_char_array(pData
, pDataLen
, dest
->signature
, 4);
343 _unmarshal_int32 (pData
, pDataLen
, &dest
->version
);
344 _unmarshal_int32 (pData
, pDataLen
, &dest
->header_len
);
345 _unmarshal_int32 (pData
, pDataLen
, &dest
->unknown_000c
);
346 _unmarshal_uint32 (pData
, pDataLen
, &dest
->block_len
);
347 _unmarshal_int32 (pData
, pDataLen
, &dest
->blockidx_intvl
);
348 _unmarshal_int32 (pData
, pDataLen
, &dest
->index_depth
);
349 _unmarshal_int32 (pData
, pDataLen
, &dest
->index_root
);
350 _unmarshal_int32 (pData
, pDataLen
, &dest
->index_head
);
351 _unmarshal_int32 (pData
, pDataLen
, &dest
->unknown_0024
);
352 _unmarshal_uint32 (pData
, pDataLen
, &dest
->num_blocks
);
353 _unmarshal_int32 (pData
, pDataLen
, &dest
->unknown_002c
);
354 _unmarshal_uint32 (pData
, pDataLen
, &dest
->lang_id
);
355 _unmarshal_uuid (pData
, pDataLen
, dest
->system_uuid
);
356 _unmarshal_uchar_array(pData
, pDataLen
, dest
->unknown_0044
, 16);
358 /* error check the data */
359 if (memcmp(dest
->signature
, "ITSP", 4) != 0)
361 if (dest
->version
!= 1)
363 if (dest
->header_len
!= _CHM_ITSP_V1_LEN
)
369 /* structure of PMGL headers */
370 static const char _chm_pmgl_marker
[4] = "PMGL";
371 #define _CHM_PMGL_LEN (0x14)
374 char signature
[4]; /* 0 (PMGL) */
375 UInt32 free_space
; /* 4 */
376 UInt32 unknown_0008
; /* 8 */
377 Int32 block_prev
; /* c */
378 Int32 block_next
; /* 10 */
379 }; /* __attribute__ ((aligned (1))); */
381 static BOOL
_unmarshal_pmgl_header(unsigned char **pData
,
382 unsigned int *pDataLen
,
383 struct chmPmglHeader
*dest
)
385 /* we only know how to deal with a 0x14 byte structures */
386 if (*pDataLen
!= _CHM_PMGL_LEN
)
389 /* unmarshal fields */
390 _unmarshal_char_array(pData
, pDataLen
, dest
->signature
, 4);
391 _unmarshal_uint32 (pData
, pDataLen
, &dest
->free_space
);
392 _unmarshal_uint32 (pData
, pDataLen
, &dest
->unknown_0008
);
393 _unmarshal_int32 (pData
, pDataLen
, &dest
->block_prev
);
394 _unmarshal_int32 (pData
, pDataLen
, &dest
->block_next
);
396 /* check structure */
397 if (memcmp(dest
->signature
, _chm_pmgl_marker
, 4) != 0)
403 /* structure of PMGI headers */
404 static const char _chm_pmgi_marker
[4] = "PMGI";
405 #define _CHM_PMGI_LEN (0x08)
408 char signature
[4]; /* 0 (PMGI) */
409 UInt32 free_space
; /* 4 */
410 }; /* __attribute__ ((aligned (1))); */
412 static BOOL
_unmarshal_pmgi_header(unsigned char **pData
,
413 unsigned int *pDataLen
,
414 struct chmPmgiHeader
*dest
)
416 /* we only know how to deal with a 0x8 byte structures */
417 if (*pDataLen
!= _CHM_PMGI_LEN
)
420 /* unmarshal fields */
421 _unmarshal_char_array(pData
, pDataLen
, dest
->signature
, 4);
422 _unmarshal_uint32 (pData
, pDataLen
, &dest
->free_space
);
424 /* check structure */
425 if (memcmp(dest
->signature
, _chm_pmgi_marker
, 4) != 0)
431 /* structure of LZXC reset table */
432 #define _CHM_LZXC_RESETTABLE_V1_LEN (0x28)
433 struct chmLzxcResetTable
439 UInt64 uncompressed_len
;
440 UInt64 compressed_len
;
442 }; /* __attribute__ ((aligned (1))); */
444 static BOOL
_unmarshal_lzxc_reset_table(unsigned char **pData
,
445 unsigned int *pDataLen
,
446 struct chmLzxcResetTable
*dest
)
448 /* we only know how to deal with a 0x28 byte structures */
449 if (*pDataLen
!= _CHM_LZXC_RESETTABLE_V1_LEN
)
452 /* unmarshal fields */
453 _unmarshal_uint32 (pData
, pDataLen
, &dest
->version
);
454 _unmarshal_uint32 (pData
, pDataLen
, &dest
->block_count
);
455 _unmarshal_uint32 (pData
, pDataLen
, &dest
->unknown
);
456 _unmarshal_uint32 (pData
, pDataLen
, &dest
->table_offset
);
457 _unmarshal_uint64 (pData
, pDataLen
, &dest
->uncompressed_len
);
458 _unmarshal_uint64 (pData
, pDataLen
, &dest
->compressed_len
);
459 _unmarshal_uint64 (pData
, pDataLen
, &dest
->block_len
);
461 /* check structure */
462 if (dest
->version
!= 2)
468 /* structure of LZXC control data block */
469 #define _CHM_LZXC_MIN_LEN (0x18)
470 #define _CHM_LZXC_V2_LEN (0x1c)
471 struct chmLzxcControlData
474 char signature
[4]; /* 4 (LZXC) */
475 UInt32 version
; /* 8 */
476 UInt32 resetInterval
; /* c */
477 UInt32 windowSize
; /* 10 */
478 UInt32 windowsPerReset
; /* 14 */
479 UInt32 unknown_18
; /* 18 */
482 static BOOL
_unmarshal_lzxc_control_data(unsigned char **pData
,
483 unsigned int *pDataLen
,
484 struct chmLzxcControlData
*dest
)
486 /* we want at least 0x18 bytes */
487 if (*pDataLen
< _CHM_LZXC_MIN_LEN
)
490 /* unmarshal fields */
491 _unmarshal_uint32 (pData
, pDataLen
, &dest
->size
);
492 _unmarshal_char_array(pData
, pDataLen
, dest
->signature
, 4);
493 _unmarshal_uint32 (pData
, pDataLen
, &dest
->version
);
494 _unmarshal_uint32 (pData
, pDataLen
, &dest
->resetInterval
);
495 _unmarshal_uint32 (pData
, pDataLen
, &dest
->windowSize
);
496 _unmarshal_uint32 (pData
, pDataLen
, &dest
->windowsPerReset
);
498 if (*pDataLen
>= _CHM_LZXC_V2_LEN
)
499 _unmarshal_uint32 (pData
, pDataLen
, &dest
->unknown_18
);
501 dest
->unknown_18
= 0;
503 if (dest
->version
== 2)
505 dest
->resetInterval
*= 0x8000;
506 dest
->windowSize
*= 0x8000;
508 if (dest
->windowSize
== 0 || dest
->resetInterval
== 0)
511 /* for now, only support resetInterval a multiple of windowSize/2 */
512 if (dest
->windowSize
== 1)
514 if ((dest
->resetInterval
% (dest
->windowSize
/2)) != 0)
517 /* check structure */
518 if (memcmp(dest
->signature
, "LZXC", 4) != 0)
524 /* the structure used for chm file handles */
529 CRITICAL_SECTION mutex
;
530 CRITICAL_SECTION lzx_mutex
;
531 CRITICAL_SECTION cache_mutex
;
541 struct chmUnitInfo rt_unit
;
542 struct chmUnitInfo cn_unit
;
543 struct chmLzxcResetTable reset_table
;
545 /* LZX control data */
546 int compression_enabled
;
548 UInt32 reset_interval
;
549 UInt32 reset_blkcount
;
551 /* decompressor state */
552 struct LZXstate
*lzx_state
;
555 /* cache for decompressed blocks */
556 UChar
**cache_blocks
;
557 Int64
*cache_block_indices
;
558 Int32 cache_num_blocks
;
562 * utility functions local to this module
565 /* utility function to handle differences between {pread,read}(64)? */
566 static Int64
_chm_fetch_bytes(struct chmFile
*h
,
572 if (h
->fd
== CHM_NULL_FD
)
575 CHM_ACQUIRE_LOCK(h
->mutex
);
576 /* NOTE: this might be better done with CreateFileMapping, et cetera... */
578 LARGE_INTEGER old_pos
, new_pos
;
581 /* awkward Win32 Seek/Tell */
582 new_pos
.QuadPart
= 0;
583 SetFilePointerEx( h
->fd
, new_pos
, &old_pos
, FILE_CURRENT
);
584 new_pos
.QuadPart
= os
;
585 SetFilePointerEx( h
->fd
, new_pos
, NULL
, FILE_BEGIN
);
597 /* restore original position */
598 SetFilePointerEx( h
->fd
, old_pos
, NULL
, FILE_BEGIN
);
600 CHM_RELEASE_LOCK(h
->mutex
);
605 * set a parameter on the file handle.
606 * valid parameter types:
607 * CHM_PARAM_MAX_BLOCKS_CACHED:
608 * how many decompressed blocks should be cached? A simple
609 * caching scheme is used, wherein the index of the block is
610 * used as a hash value, and hash collision results in the
611 * invalidation of the previously cached block.
613 static void chm_set_param(struct chmFile
*h
,
619 case CHM_PARAM_MAX_BLOCKS_CACHED
:
620 CHM_ACQUIRE_LOCK(h
->cache_mutex
);
621 if (paramVal
!= h
->cache_num_blocks
)
627 /* allocate new cached blocks */
628 newBlocks
= HeapAlloc(GetProcessHeap(), 0, paramVal
* sizeof (UChar
*));
629 newIndices
= HeapAlloc(GetProcessHeap(), 0, paramVal
* sizeof (UInt64
));
630 for (i
=0; i
<paramVal
; i
++)
636 /* re-distribute old cached blocks */
639 for (i
=0; i
<h
->cache_num_blocks
; i
++)
641 int newSlot
= (int)(h
->cache_block_indices
[i
] % paramVal
);
643 if (h
->cache_blocks
[i
])
645 /* in case of collision, destroy newcomer */
646 if (newBlocks
[newSlot
])
648 HeapFree(GetProcessHeap(), 0, h
->cache_blocks
[i
]);
649 h
->cache_blocks
[i
] = NULL
;
653 newBlocks
[newSlot
] = h
->cache_blocks
[i
];
654 newIndices
[newSlot
] =
655 h
->cache_block_indices
[i
];
660 HeapFree(GetProcessHeap(), 0, h
->cache_blocks
);
661 HeapFree(GetProcessHeap(), 0, h
->cache_block_indices
);
664 /* now, set new values */
665 h
->cache_blocks
= newBlocks
;
666 h
->cache_block_indices
= newIndices
;
667 h
->cache_num_blocks
= paramVal
;
669 CHM_RELEASE_LOCK(h
->cache_mutex
);
677 /* open an ITS archive */
678 struct chmFile
*chm_openW(const WCHAR
*filename
)
680 unsigned char sbuffer
[256];
681 unsigned int sremain
;
682 unsigned char *sbufpos
;
683 struct chmFile
*newHandle
=NULL
;
684 struct chmItsfHeader itsfHeader
;
685 struct chmItspHeader itspHeader
;
687 struct chmUnitInfo uiSpan
;
689 struct chmUnitInfo uiLzxc
;
690 struct chmLzxcControlData ctlData
;
692 /* allocate handle */
693 newHandle
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct chmFile
));
694 newHandle
->fd
= CHM_NULL_FD
;
695 newHandle
->lzx_state
= NULL
;
696 newHandle
->cache_blocks
= NULL
;
697 newHandle
->cache_block_indices
= NULL
;
698 newHandle
->cache_num_blocks
= 0;
701 if ((newHandle
->fd
=CreateFileW(filename
,
706 FILE_ATTRIBUTE_NORMAL
,
707 NULL
)) == CHM_NULL_FD
)
709 HeapFree(GetProcessHeap(), 0, newHandle
);
713 /* initialize mutexes, if needed */
714 InitializeCriticalSection(&newHandle
->mutex
);
715 newHandle
->mutex
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": chmFile.mutex");
716 InitializeCriticalSection(&newHandle
->lzx_mutex
);
717 newHandle
->lzx_mutex
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": chmFile.lzx_mutex");
718 InitializeCriticalSection(&newHandle
->cache_mutex
);
719 newHandle
->cache_mutex
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": chmFile.cache_mutex");
721 /* read and verify header */
722 sremain
= _CHM_ITSF_V3_LEN
;
724 if (_chm_fetch_bytes(newHandle
, sbuffer
, 0, sremain
) != sremain
||
725 !_unmarshal_itsf_header(&sbufpos
, &sremain
, &itsfHeader
))
727 chm_close(newHandle
);
731 /* stash important values from header */
732 newHandle
->dir_offset
= itsfHeader
.dir_offset
;
733 newHandle
->dir_len
= itsfHeader
.dir_len
;
734 newHandle
->data_offset
= itsfHeader
.data_offset
;
736 /* now, read and verify the directory header chunk */
737 sremain
= _CHM_ITSP_V1_LEN
;
739 if (_chm_fetch_bytes(newHandle
, sbuffer
,
740 itsfHeader
.dir_offset
, sremain
) != sremain
||
741 !_unmarshal_itsp_header(&sbufpos
, &sremain
, &itspHeader
))
743 chm_close(newHandle
);
747 /* grab essential information from ITSP header */
748 newHandle
->dir_offset
+= itspHeader
.header_len
;
749 newHandle
->dir_len
-= itspHeader
.header_len
;
750 newHandle
->index_root
= itspHeader
.index_root
;
751 newHandle
->index_head
= itspHeader
.index_head
;
752 newHandle
->block_len
= itspHeader
.block_len
;
754 /* if the index root is -1, this means we don't have any PMGI blocks.
755 * as a result, we must use the sole PMGL block as the index root
757 if (newHandle
->index_root
== -1)
758 newHandle
->index_root
= newHandle
->index_head
;
760 /* initialize cache */
761 chm_set_param(newHandle
, CHM_PARAM_MAX_BLOCKS_CACHED
,
762 CHM_MAX_BLOCKS_CACHED
);
764 /* By default, compression is enabled. */
765 newHandle
->compression_enabled
= 1;
767 /* prefetch most commonly needed unit infos */
768 if (CHM_RESOLVE_SUCCESS
!= chm_resolve_object(newHandle
,
770 &newHandle
->rt_unit
) ||
771 newHandle
->rt_unit
.space
== CHM_COMPRESSED
||
772 CHM_RESOLVE_SUCCESS
!= chm_resolve_object(newHandle
,
774 &newHandle
->cn_unit
) ||
775 newHandle
->cn_unit
.space
== CHM_COMPRESSED
||
776 CHM_RESOLVE_SUCCESS
!= chm_resolve_object(newHandle
,
777 _CHMU_LZXC_CONTROLDATA
,
779 uiLzxc
.space
== CHM_COMPRESSED
)
781 newHandle
->compression_enabled
= 0;
784 /* read reset table info */
785 if (newHandle
->compression_enabled
)
787 sremain
= _CHM_LZXC_RESETTABLE_V1_LEN
;
789 if (chm_retrieve_object(newHandle
, &newHandle
->rt_unit
, sbuffer
,
790 0, sremain
) != sremain
||
791 !_unmarshal_lzxc_reset_table(&sbufpos
, &sremain
,
792 &newHandle
->reset_table
))
794 newHandle
->compression_enabled
= 0;
798 /* read control data */
799 if (newHandle
->compression_enabled
)
801 sremain
= (unsigned long)uiLzxc
.length
;
803 if (chm_retrieve_object(newHandle
, &uiLzxc
, sbuffer
,
804 0, sremain
) != sremain
||
805 !_unmarshal_lzxc_control_data(&sbufpos
, &sremain
,
808 newHandle
->compression_enabled
= 0;
811 newHandle
->window_size
= ctlData
.windowSize
;
812 newHandle
->reset_interval
= ctlData
.resetInterval
;
814 /* Jed, Mon Jun 28: Experimentally, it appears that the reset block count */
815 /* must be multiplied by this formerly unknown ctrl data field in */
816 /* order to decompress some files. */
818 newHandle
->reset_blkcount
= newHandle
->reset_interval
/
819 (newHandle
->window_size
/ 2);
821 newHandle
->reset_blkcount
= newHandle
->reset_interval
/
822 (newHandle
->window_size
/ 2) *
823 ctlData
.windowsPerReset
;
830 /* Duplicate an ITS archive handle */
831 struct chmFile
*chm_dup(struct chmFile
*oldHandle
)
833 struct chmFile
*newHandle
=NULL
;
835 newHandle
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct chmFile
));
836 *newHandle
= *oldHandle
;
838 /* duplicate fd handle */
839 DuplicateHandle(GetCurrentProcess(), oldHandle
->fd
,
840 GetCurrentProcess(), &(newHandle
->fd
),
841 0, FALSE
, DUPLICATE_SAME_ACCESS
);
842 newHandle
->lzx_state
= NULL
;
843 newHandle
->cache_blocks
= NULL
;
844 newHandle
->cache_block_indices
= NULL
;
845 newHandle
->cache_num_blocks
= 0;
847 /* initialize mutexes, if needed */
848 InitializeCriticalSection(&newHandle
->mutex
);
849 newHandle
->mutex
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": chmFile.mutex");
850 InitializeCriticalSection(&newHandle
->lzx_mutex
);
851 newHandle
->lzx_mutex
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": chmFile.lzx_mutex");
852 InitializeCriticalSection(&newHandle
->cache_mutex
);
853 newHandle
->cache_mutex
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": chmFile.cache_mutex");
855 /* initialize cache */
856 chm_set_param(newHandle
, CHM_PARAM_MAX_BLOCKS_CACHED
,
857 CHM_MAX_BLOCKS_CACHED
);
862 /* close an ITS archive */
863 void chm_close(struct chmFile
*h
)
867 if (h
->fd
!= CHM_NULL_FD
)
868 CHM_CLOSE_FILE(h
->fd
);
871 h
->mutex
.DebugInfo
->Spare
[0] = 0;
872 DeleteCriticalSection(&h
->mutex
);
873 h
->lzx_mutex
.DebugInfo
->Spare
[0] = 0;
874 DeleteCriticalSection(&h
->lzx_mutex
);
875 h
->cache_mutex
.DebugInfo
->Spare
[0] = 0;
876 DeleteCriticalSection(&h
->cache_mutex
);
879 LZXteardown(h
->lzx_state
);
885 for (i
=0; i
<h
->cache_num_blocks
; i
++)
887 HeapFree(GetProcessHeap(), 0, h
->cache_blocks
[i
]);
889 HeapFree(GetProcessHeap(), 0, h
->cache_blocks
);
890 h
->cache_blocks
= NULL
;
893 HeapFree(GetProcessHeap(), 0, h
->cache_block_indices
);
894 h
->cache_block_indices
= NULL
;
896 HeapFree(GetProcessHeap(), 0, h
);
901 * helper methods for chm_resolve_object
904 /* skip a compressed dword */
905 static void _chm_skip_cword(UChar
**pEntry
)
907 while (*(*pEntry
)++ >= 0x80)
911 /* skip the data from a PMGL entry */
912 static void _chm_skip_PMGL_entry_data(UChar
**pEntry
)
914 _chm_skip_cword(pEntry
);
915 _chm_skip_cword(pEntry
);
916 _chm_skip_cword(pEntry
);
919 /* parse a compressed dword */
920 static UInt64
_chm_parse_cword(UChar
**pEntry
)
924 while ((temp
=*(*pEntry
)++) >= 0x80)
927 accum
+= temp
& 0x7f;
930 return (accum
<< 7) + temp
;
933 /* parse a utf-8 string into an ASCII char buffer */
934 static BOOL
_chm_parse_UTF8(UChar
**pEntry
, UInt64 count
, WCHAR
*path
)
936 DWORD length
= MultiByteToWideChar(CP_UTF8
, 0, (char *)*pEntry
, count
, path
, CHM_MAX_PATHLEN
);
942 /* parse a PMGL entry into a chmUnitInfo struct; return 1 on success. */
943 static BOOL
_chm_parse_PMGL_entry(UChar
**pEntry
, struct chmUnitInfo
*ui
)
948 strLen
= _chm_parse_cword(pEntry
);
949 if (strLen
> CHM_MAX_PATHLEN
)
953 if (! _chm_parse_UTF8(pEntry
, strLen
, ui
->path
))
957 ui
->space
= (int)_chm_parse_cword(pEntry
);
958 ui
->start
= _chm_parse_cword(pEntry
);
959 ui
->length
= _chm_parse_cword(pEntry
);
963 /* find an exact entry in PMGL; return NULL if we fail */
964 static UChar
*_chm_find_in_PMGL(UChar
*page_buf
,
966 const WCHAR
*objPath
)
968 /* XXX: modify this to do a binary search using the nice index structure
969 * that is provided for us.
971 struct chmPmglHeader header
;
977 WCHAR buffer
[CHM_MAX_PATHLEN
+1];
979 /* figure out where to start and end */
981 hremain
= _CHM_PMGL_LEN
;
982 if (! _unmarshal_pmgl_header(&cur
, &hremain
, &header
))
984 end
= page_buf
+ block_len
- (header
.free_space
);
986 /* now, scan progressively */
991 strLen
= _chm_parse_cword(&cur
);
992 if (! _chm_parse_UTF8(&cur
, strLen
, buffer
))
995 /* check if it is the right name */
996 if (! wcsicmp(buffer
, objPath
))
999 _chm_skip_PMGL_entry_data(&cur
);
1005 /* find which block should be searched next for the entry; -1 if no block */
1006 static Int32
_chm_find_in_PMGI(UChar
*page_buf
,
1008 const WCHAR
*objPath
)
1010 /* XXX: modify this to do a binary search using the nice index structure
1011 * that is provided for us
1013 struct chmPmgiHeader header
;
1019 WCHAR buffer
[CHM_MAX_PATHLEN
+1];
1021 /* figure out where to start and end */
1023 hremain
= _CHM_PMGI_LEN
;
1024 if (! _unmarshal_pmgi_header(&cur
, &hremain
, &header
))
1026 end
= page_buf
+ block_len
- (header
.free_space
);
1028 /* now, scan progressively */
1032 strLen
= _chm_parse_cword(&cur
);
1033 if (! _chm_parse_UTF8(&cur
, strLen
, buffer
))
1036 /* check if it is the right name */
1037 if (wcsicmp(buffer
, objPath
) > 0)
1040 /* load next value for path */
1041 page
= (int)_chm_parse_cword(&cur
);
1047 /* resolve a particular object from the archive */
1048 int chm_resolve_object(struct chmFile
*h
,
1049 const WCHAR
*objPath
,
1050 struct chmUnitInfo
*ui
)
1053 * XXX: implement caching scheme for dir pages
1058 /* buffer to hold whatever page we're looking at */
1059 UChar
*page_buf
= HeapAlloc(GetProcessHeap(), 0, h
->block_len
);
1062 curPage
= h
->index_root
;
1064 /* until we have either returned or given up */
1065 while (curPage
!= -1)
1068 /* try to fetch the index page */
1069 if (_chm_fetch_bytes(h
, page_buf
,
1070 h
->dir_offset
+ (UInt64
)curPage
*h
->block_len
,
1071 h
->block_len
) != h
->block_len
)
1073 HeapFree(GetProcessHeap(), 0, page_buf
);
1074 return CHM_RESOLVE_FAILURE
;
1077 /* now, if it is a leaf node: */
1078 if (memcmp(page_buf
, _chm_pmgl_marker
, 4) == 0)
1081 UChar
*pEntry
= _chm_find_in_PMGL(page_buf
,
1086 HeapFree(GetProcessHeap(), 0, page_buf
);
1087 return CHM_RESOLVE_FAILURE
;
1090 /* parse entry and return */
1091 _chm_parse_PMGL_entry(&pEntry
, ui
);
1092 HeapFree(GetProcessHeap(), 0, page_buf
);
1093 return CHM_RESOLVE_SUCCESS
;
1096 /* else, if it is a branch node: */
1097 else if (memcmp(page_buf
, _chm_pmgi_marker
, 4) == 0)
1098 curPage
= _chm_find_in_PMGI(page_buf
, h
->block_len
, objPath
);
1100 /* else, we are confused. give up. */
1103 HeapFree(GetProcessHeap(), 0, page_buf
);
1104 return CHM_RESOLVE_FAILURE
;
1108 /* didn't find anything. fail. */
1109 HeapFree(GetProcessHeap(), 0, page_buf
);
1110 return CHM_RESOLVE_FAILURE
;
1114 * utility methods for dealing with compressed data
1117 /* get the bounds of a compressed block. Returns FALSE on failure */
1118 static BOOL
_chm_get_cmpblock_bounds(struct chmFile
*h
,
1123 UChar buffer
[8], *dummy
;
1126 /* for all but the last block, use the reset table */
1127 if (block
< h
->reset_table
.block_count
-1)
1129 /* unpack the start address */
1132 if (_chm_fetch_bytes(h
, buffer
,
1135 + h
->reset_table
.table_offset
1137 remain
) != remain
||
1138 !_unmarshal_uint64(&dummy
, &remain
, start
))
1141 /* unpack the end address */
1144 if (_chm_fetch_bytes(h
, buffer
,
1147 + h
->reset_table
.table_offset
1149 remain
) != remain
||
1150 !_unmarshal_int64(&dummy
, &remain
, len
))
1154 /* for the last block, use the span in addition to the reset table */
1157 /* unpack the start address */
1160 if (_chm_fetch_bytes(h
, buffer
,
1163 + h
->reset_table
.table_offset
1165 remain
) != remain
||
1166 !_unmarshal_uint64(&dummy
, &remain
, start
))
1169 *len
= h
->reset_table
.compressed_len
;
1172 /* compute the length and absolute start address */
1174 *start
+= h
->data_offset
+ h
->cn_unit
.start
;
1179 /* decompress the block. must have lzx_mutex. */
1180 static Int64
_chm_decompress_block(struct chmFile
*h
,
1184 UChar
*cbuffer
= HeapAlloc( GetProcessHeap(), 0,
1185 ((unsigned int)h
->reset_table
.block_len
+ 6144));
1186 UInt64 cmpStart
; /* compressed start */
1187 Int64 cmpLen
; /* compressed len */
1188 int indexSlot
; /* cache index slot */
1189 UChar
*lbuffer
; /* local buffer ptr */
1190 UInt32 blockAlign
= (UInt32
)(block
% h
->reset_blkcount
); /* reset interval align */
1191 UInt32 i
; /* local loop index */
1193 /* let the caching system pull its weight! */
1194 if (block
- blockAlign
<= h
->lzx_last_block
&&
1195 block
>= h
->lzx_last_block
)
1196 blockAlign
= (block
- h
->lzx_last_block
);
1198 /* check if we need previous blocks */
1199 if (blockAlign
!= 0)
1201 /* fetch all required previous blocks since last reset */
1202 for (i
= blockAlign
; i
> 0; i
--)
1204 UInt32 curBlockIdx
= block
- i
;
1206 /* check if we most recently decompressed the previous block */
1207 if (h
->lzx_last_block
!= curBlockIdx
)
1209 if ((curBlockIdx
% h
->reset_blkcount
) == 0)
1212 fprintf(stderr
, "***RESET (1)***\n");
1214 LZXreset(h
->lzx_state
);
1217 indexSlot
= (int)((curBlockIdx
) % h
->cache_num_blocks
);
1218 h
->cache_block_indices
[indexSlot
] = curBlockIdx
;
1219 if (! h
->cache_blocks
[indexSlot
])
1220 h
->cache_blocks
[indexSlot
] =
1221 HeapAlloc(GetProcessHeap(), 0,
1222 (unsigned int)(h
->reset_table
.block_len
));
1223 lbuffer
= h
->cache_blocks
[indexSlot
];
1225 /* decompress the previous block */
1227 fprintf(stderr
, "Decompressing block #%4d (EXTRA)\n", curBlockIdx
);
1229 if (!_chm_get_cmpblock_bounds(h
, curBlockIdx
, &cmpStart
, &cmpLen
) ||
1230 _chm_fetch_bytes(h
, cbuffer
, cmpStart
, cmpLen
) != cmpLen
||
1231 LZXdecompress(h
->lzx_state
, cbuffer
, lbuffer
, (int)cmpLen
,
1232 (int)h
->reset_table
.block_len
) != DECR_OK
)
1235 fprintf(stderr
, " (DECOMPRESS FAILED!)\n");
1237 HeapFree(GetProcessHeap(), 0, cbuffer
);
1241 h
->lzx_last_block
= (int)curBlockIdx
;
1247 if ((block
% h
->reset_blkcount
) == 0)
1250 fprintf(stderr
, "***RESET (2)***\n");
1252 LZXreset(h
->lzx_state
);
1256 /* allocate slot in cache */
1257 indexSlot
= (int)(block
% h
->cache_num_blocks
);
1258 h
->cache_block_indices
[indexSlot
] = block
;
1259 if (! h
->cache_blocks
[indexSlot
])
1260 h
->cache_blocks
[indexSlot
] =
1261 HeapAlloc(GetProcessHeap(), 0, ((unsigned int)h
->reset_table
.block_len
));
1262 lbuffer
= h
->cache_blocks
[indexSlot
];
1265 /* decompress the block we actually want */
1267 fprintf(stderr
, "Decompressing block #%4d (REAL )\n", block
);
1269 if (! _chm_get_cmpblock_bounds(h
, block
, &cmpStart
, &cmpLen
) ||
1270 _chm_fetch_bytes(h
, cbuffer
, cmpStart
, cmpLen
) != cmpLen
||
1271 LZXdecompress(h
->lzx_state
, cbuffer
, lbuffer
, (int)cmpLen
,
1272 (int)h
->reset_table
.block_len
) != DECR_OK
)
1275 fprintf(stderr
, " (DECOMPRESS FAILED!)\n");
1277 HeapFree(GetProcessHeap(), 0, cbuffer
);
1280 h
->lzx_last_block
= (int)block
;
1282 /* XXX: modify LZX routines to return the length of the data they
1283 * decompressed and return that instead, for an extra sanity check.
1285 HeapFree(GetProcessHeap(), 0, cbuffer
);
1286 return h
->reset_table
.block_len
;
1289 /* grab a region from a compressed block */
1290 static Int64
_chm_decompress_region(struct chmFile
*h
,
1295 UInt64 nBlock
, nOffset
;
1298 UChar
*ubuffer
= NULL
;
1303 /* figure out what we need to read */
1304 nBlock
= start
/ h
->reset_table
.block_len
;
1305 nOffset
= start
% h
->reset_table
.block_len
;
1307 if (nLen
> (h
->reset_table
.block_len
- nOffset
))
1308 nLen
= h
->reset_table
.block_len
- nOffset
;
1310 /* if block is cached, return data from it. */
1311 CHM_ACQUIRE_LOCK(h
->lzx_mutex
);
1312 CHM_ACQUIRE_LOCK(h
->cache_mutex
);
1313 if (h
->cache_block_indices
[nBlock
% h
->cache_num_blocks
] == nBlock
&&
1314 h
->cache_blocks
[nBlock
% h
->cache_num_blocks
] != NULL
)
1317 h
->cache_blocks
[nBlock
% h
->cache_num_blocks
] + nOffset
,
1318 (unsigned int)nLen
);
1319 CHM_RELEASE_LOCK(h
->cache_mutex
);
1320 CHM_RELEASE_LOCK(h
->lzx_mutex
);
1323 CHM_RELEASE_LOCK(h
->cache_mutex
);
1325 /* data request not satisfied, so... start up the decompressor machine */
1328 h
->lzx_last_block
= -1;
1329 h
->lzx_state
= LZXinit(h
->window_size
);
1332 /* decompress some data */
1333 gotLen
= _chm_decompress_block(h
, nBlock
, &ubuffer
);
1336 memcpy(buf
, ubuffer
+nOffset
, (unsigned int)nLen
);
1337 CHM_RELEASE_LOCK(h
->lzx_mutex
);
1341 /* retrieve (part of) an object */
1342 LONGINT64
chm_retrieve_object(struct chmFile
*h
,
1343 struct chmUnitInfo
*ui
,
1348 /* must be valid file handle */
1352 /* starting address must be in correct range */
1353 if (addr
>= ui
->length
)
1357 if (addr
+ len
> ui
->length
)
1358 len
= ui
->length
- addr
;
1360 /* if the file is uncompressed, it's simple */
1361 if (ui
->space
== CHM_UNCOMPRESSED
)
1364 return _chm_fetch_bytes(h
,
1366 h
->data_offset
+ ui
->start
+ addr
,
1370 /* else if the file is compressed, it's a little trickier */
1371 else /* ui->space == CHM_COMPRESSED */
1373 Int64 swath
=0, total
=0;
1375 /* if compression is not enabled for this file... */
1376 if (! h
->compression_enabled
)
1381 /* swill another mouthful */
1382 swath
= _chm_decompress_region(h
, buf
, ui
->start
+ addr
, len
);
1384 /* if we didn't get any... */
1400 BOOL
chm_enumerate_dir(struct chmFile
*h
,
1401 const WCHAR
*prefix
,
1407 * XXX: do this efficiently (i.e. using the tree index)
1412 /* buffer to hold whatever page we're looking at */
1413 UChar
*page_buf
= HeapAlloc(GetProcessHeap(), 0, h
->block_len
);
1414 struct chmPmglHeader header
;
1417 unsigned int lenRemain
;
1419 /* set to TRUE once we've started */
1420 BOOL it_has_begun
= FALSE
;
1422 /* the current ui */
1423 struct chmUnitInfo ui
;
1427 /* the length of the prefix */
1428 WCHAR prefixRectified
[CHM_MAX_PATHLEN
+1];
1430 WCHAR lastPath
[CHM_MAX_PATHLEN
];
1434 curPage
= h
->index_head
;
1436 /* initialize pathname state */
1437 lstrcpynW(prefixRectified
, prefix
, CHM_MAX_PATHLEN
);
1438 prefixLen
= lstrlenW(prefixRectified
);
1441 if (prefixRectified
[prefixLen
-1] != '/')
1443 prefixRectified
[prefixLen
] = '/';
1444 prefixRectified
[prefixLen
+1] = '\0';
1451 /* until we have either returned or given up */
1452 while (curPage
!= -1)
1455 /* try to fetch the index page */
1456 if (_chm_fetch_bytes(h
,
1458 h
->dir_offset
+ (UInt64
)curPage
*h
->block_len
,
1459 h
->block_len
) != h
->block_len
)
1461 HeapFree(GetProcessHeap(), 0, page_buf
);
1465 /* figure out start and end for this page */
1467 lenRemain
= _CHM_PMGL_LEN
;
1468 if (! _unmarshal_pmgl_header(&cur
, &lenRemain
, &header
))
1470 HeapFree(GetProcessHeap(), 0, page_buf
);
1473 end
= page_buf
+ h
->block_len
- (header
.free_space
);
1475 /* loop over this page */
1478 if (! _chm_parse_PMGL_entry(&cur
, &ui
))
1480 HeapFree(GetProcessHeap(), 0, page_buf
);
1484 /* check if we should start */
1487 if (ui
.length
== 0 && _wcsnicmp(ui
.path
, prefixRectified
, prefixLen
) == 0)
1488 it_has_begun
= TRUE
;
1492 if (ui
.path
[prefixLen
] == '\0')
1496 /* check if we should stop */
1499 if (_wcsnicmp(ui
.path
, prefixRectified
, prefixLen
) != 0)
1501 HeapFree(GetProcessHeap(), 0, page_buf
);
1506 /* check if we should include this path */
1507 if (lastPathLen
!= -1)
1509 if (_wcsnicmp(ui
.path
, lastPath
, lastPathLen
) == 0)
1512 lstrcpyW(lastPath
, ui
.path
);
1513 lastPathLen
= lstrlenW(lastPath
);
1515 /* get the length of the path */
1516 ui_path_len
= lstrlenW(ui
.path
)-1;
1518 /* check for DIRS */
1519 if (ui
.path
[ui_path_len
] == '/' && !(what
& CHM_ENUMERATE_DIRS
))
1522 /* check for FILES */
1523 if (ui
.path
[ui_path_len
] != '/' && !(what
& CHM_ENUMERATE_FILES
))
1526 /* check for NORMAL vs. META */
1527 if (ui
.path
[0] == '/')
1530 /* check for NORMAL vs. SPECIAL */
1531 if (ui
.path
[1] == '#' || ui
.path
[1] == '$')
1532 flag
= CHM_ENUMERATE_SPECIAL
;
1534 flag
= CHM_ENUMERATE_NORMAL
;
1537 flag
= CHM_ENUMERATE_META
;
1538 if (! (what
& flag
))
1541 /* call the enumerator */
1543 int status
= (*e
)(h
, &ui
, context
);
1546 case CHM_ENUMERATOR_FAILURE
:
1547 HeapFree(GetProcessHeap(), 0, page_buf
);
1549 case CHM_ENUMERATOR_CONTINUE
:
1551 case CHM_ENUMERATOR_SUCCESS
:
1552 HeapFree(GetProcessHeap(), 0, page_buf
);
1560 /* advance to next page */
1561 curPage
= header
.block_next
;
1564 HeapFree(GetProcessHeap(), 0, page_buf
);