makefiles: Don't use standard libs for programs that specify -nodefaultlibs.
[wine/zf.git] / dlls / kernel32 / lzexpand.c
blob73c9ddc031b8c30dc4b434633ca40fce11620d8e
1 /*
2 * LZ Decompression functions
4 * Copyright 1996 Marcus Meissner
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * NOTES
22 * The LZ (Lempel Ziv) decompression was used in win16 installation programs.
23 * It is a simple tabledriven decompression engine, the algorithm is not
24 * documented as far as I know. WINE does not contain a compressor for
25 * this format.
27 * The implementation is complete and there have been no reports of failures
28 * for some time.
30 * TODO:
32 * o Check whether the return values are correct
36 #include "config.h"
38 #include <string.h>
39 #include <ctype.h>
40 #include <sys/types.h>
41 #include <stdarg.h>
42 #include <stdio.h>
43 #ifdef HAVE_UNISTD_H
44 # include <unistd.h>
45 #endif
47 #include "windef.h"
48 #include "winbase.h"
49 #include "winternl.h"
50 #include "lzexpand.h"
52 #include "wine/unicode.h"
53 #include "wine/debug.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(file);
57 /* The readahead length of the decompressor. Reading single bytes
58 * using _lread() would be SLOW.
60 #define GETLEN 2048
62 #define LZ_MAGIC_LEN 8
63 #define LZ_HEADER_LEN 14
65 /* Format of first 14 byte of LZ compressed file */
66 struct lzfileheader {
67 BYTE magic[LZ_MAGIC_LEN];
68 BYTE compressiontype;
69 CHAR lastchar;
70 DWORD reallength;
72 static const BYTE LZMagic[LZ_MAGIC_LEN]={'S','Z','D','D',0x88,0xf0,0x27,0x33};
74 #define LZ_TABLE_SIZE 0x1000
76 struct lzstate {
77 HFILE realfd; /* the real filedescriptor */
78 CHAR lastchar; /* the last char of the filename */
80 DWORD reallength; /* the decompressed length of the file */
81 DWORD realcurrent; /* the position the decompressor currently is */
82 DWORD realwanted; /* the position the user wants to read from */
84 BYTE table[LZ_TABLE_SIZE]; /* the rotating LZ table */
85 UINT curtabent; /* CURrent TABle ENTry */
87 BYTE stringlen; /* length and position of current string */
88 DWORD stringpos; /* from stringtable */
91 WORD bytetype; /* bitmask within blocks */
93 BYTE *get; /* GETLEN bytes */
94 DWORD getcur; /* current read */
95 DWORD getlen; /* length last got */
98 #define MAX_LZSTATES 16
99 static struct lzstate *lzstates[MAX_LZSTATES];
101 #define LZ_MIN_HANDLE 0x400
102 #define IS_LZ_HANDLE(h) (((h) >= LZ_MIN_HANDLE) && ((h) < LZ_MIN_HANDLE+MAX_LZSTATES))
103 #define GET_LZ_STATE(h) (IS_LZ_HANDLE(h) ? lzstates[(h)-LZ_MIN_HANDLE] : NULL)
105 /* reads one compressed byte, including buffering */
106 #define GET(lzs,b) _lzget(lzs,&b)
107 #define GET_FLUSH(lzs) lzs->getcur=lzs->getlen;
109 static int
110 _lzget(struct lzstate *lzs,BYTE *b) {
111 if (lzs->getcur<lzs->getlen) {
112 *b = lzs->get[lzs->getcur++];
113 return 1;
114 } else {
115 int ret = _lread(lzs->realfd,lzs->get,GETLEN);
116 if (ret==HFILE_ERROR)
117 return HFILE_ERROR;
118 if (ret==0)
119 return 0;
120 lzs->getlen = ret;
121 lzs->getcur = 1;
122 *b = *(lzs->get);
123 return 1;
126 /* internal function, reads lzheader
127 * returns BADINHANDLE for non filedescriptors
128 * return 0 for file not compressed using LZ
129 * return UNKNOWNALG for unknown algorithm
130 * returns lzfileheader in *head
132 static INT read_header(HFILE fd,struct lzfileheader *head)
134 BYTE buf[LZ_HEADER_LEN];
136 if (_llseek(fd,0,SEEK_SET)==-1)
137 return LZERROR_BADINHANDLE;
139 /* We can't directly read the lzfileheader struct due to
140 * structure element alignment
142 if (_lread(fd,buf,LZ_HEADER_LEN) != LZ_HEADER_LEN)
143 return 0;
144 memcpy(head->magic,buf,LZ_MAGIC_LEN);
145 memcpy(&(head->compressiontype),buf+LZ_MAGIC_LEN,1);
146 memcpy(&(head->lastchar),buf+LZ_MAGIC_LEN+1,1);
148 /* FIXME: consider endianness on non-intel architectures */
149 memcpy(&(head->reallength),buf+LZ_MAGIC_LEN+2,4);
151 if (memcmp(head->magic,LZMagic,LZ_MAGIC_LEN))
152 return 0;
153 if (head->compressiontype!='A')
154 return LZERROR_UNKNOWNALG;
155 return 1;
159 /***********************************************************************
160 * LZStart (KERNEL32.@)
162 INT WINAPI LZStart(void)
164 TRACE("(void)\n");
165 return 1;
169 /***********************************************************************
170 * LZInit (KERNEL32.@)
172 * initializes internal decompression buffers, returns lzfiledescriptor.
173 * (return value the same as hfSrc, if hfSrc is not compressed)
174 * on failure, returns error code <0
175 * lzfiledescriptors range from 0x400 to 0x410 (only 16 open files per process)
177 * since _llseek uses the same types as libc.lseek, we just use the macros of
178 * libc
180 HFILE WINAPI LZInit( HFILE hfSrc )
183 struct lzfileheader head;
184 struct lzstate *lzs;
185 int i, ret;
187 TRACE("(%d)\n",hfSrc);
188 ret=read_header(hfSrc,&head);
189 if (ret<=0) {
190 _llseek(hfSrc,0,SEEK_SET);
191 return ret?ret:hfSrc;
193 for (i = 0; i < MAX_LZSTATES; i++) if (!lzstates[i]) break;
194 if (i == MAX_LZSTATES) return LZERROR_GLOBALLOC;
195 lzstates[i] = lzs = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*lzs) );
196 if(lzs == NULL) return LZERROR_GLOBALLOC;
198 lzs->realfd = hfSrc;
199 lzs->lastchar = head.lastchar;
200 lzs->reallength = head.reallength;
202 lzs->get = HeapAlloc( GetProcessHeap(), 0, GETLEN );
203 lzs->getlen = 0;
204 lzs->getcur = 0;
206 if(lzs->get == NULL) {
207 HeapFree(GetProcessHeap(), 0, lzs);
208 lzstates[i] = NULL;
209 return LZERROR_GLOBALLOC;
212 /* Yes, preinitialize with spaces */
213 memset(lzs->table,' ',LZ_TABLE_SIZE);
214 /* Yes, start 16 byte from the END of the table */
215 lzs->curtabent = 0xff0;
216 return LZ_MIN_HANDLE + i;
220 /***********************************************************************
221 * LZDone (KERNEL32.@)
223 void WINAPI LZDone(void)
225 TRACE("(void)\n");
229 /***********************************************************************
230 * GetExpandedNameA (KERNEL32.@)
232 * gets the full filename of the compressed file 'in' by opening it
233 * and reading the header
235 * "file." is being translated to "file"
236 * "file.bl_" (with lastchar 'a') is being translated to "file.bla"
237 * "FILE.BL_" (with lastchar 'a') is being translated to "FILE.BLA"
240 INT WINAPI GetExpandedNameA( LPSTR in, LPSTR out )
242 struct lzfileheader head;
243 HFILE fd;
244 OFSTRUCT ofs;
245 INT fnislowercased,ret,len;
246 LPSTR s,t;
248 TRACE("(%s)\n",in);
249 fd=OpenFile(in,&ofs,OF_READ);
250 if (fd==HFILE_ERROR)
251 return (INT)(INT16)LZERROR_BADINHANDLE;
252 strcpy(out,in);
253 ret=read_header(fd,&head);
254 if (ret<=0) {
255 /* not a LZ compressed file, so the expanded name is the same
256 * as the input name */
257 _lclose(fd);
258 return 1;
262 /* look for directory prefix and skip it. */
263 s=out;
264 while (NULL!=(t=strpbrk(s,"/\\:")))
265 s=t+1;
267 /* now mangle the basename */
268 if (!*s) {
269 /* FIXME: hmm. shouldn't happen? */
270 WARN("Specified a directory or what? (%s)\n",in);
271 _lclose(fd);
272 return 1;
274 /* see if we should use lowercase or uppercase on the last char */
275 fnislowercased=1;
276 t=s+strlen(s)-1;
277 while (t>=out) {
278 if (!isalpha(*t)) {
279 t--;
280 continue;
282 fnislowercased=islower(*t);
283 break;
285 if (isalpha(head.lastchar)) {
286 if (fnislowercased)
287 head.lastchar=tolower(head.lastchar);
288 else
289 head.lastchar=RtlUpperChar(head.lastchar);
292 /* now look where to replace the last character */
293 if (NULL!=(t=strchr(s,'.'))) {
294 if (t[1]=='\0') {
295 t[0]='\0';
296 } else {
297 len=strlen(t)-1;
298 if (t[len]=='_')
299 t[len]=head.lastchar;
301 } /* else no modification necessary */
302 _lclose(fd);
303 return 1;
307 /***********************************************************************
308 * GetExpandedNameW (KERNEL32.@)
310 INT WINAPI GetExpandedNameW( LPWSTR in, LPWSTR out )
312 INT ret;
313 DWORD len = WideCharToMultiByte( CP_ACP, 0, in, -1, NULL, 0, NULL, NULL );
314 char *xin = HeapAlloc( GetProcessHeap(), 0, len );
315 char *xout = HeapAlloc( GetProcessHeap(), 0, len+3 );
316 WideCharToMultiByte( CP_ACP, 0, in, -1, xin, len, NULL, NULL );
317 if ((ret = GetExpandedNameA( xin, xout )) > 0)
318 MultiByteToWideChar( CP_ACP, 0, xout, -1, out, strlenW(in)+4 );
319 HeapFree( GetProcessHeap(), 0, xin );
320 HeapFree( GetProcessHeap(), 0, xout );
321 return ret;
325 /***********************************************************************
326 * LZRead (KERNEL32.@)
328 INT WINAPI LZRead( HFILE fd, LPSTR vbuf, INT toread )
330 int howmuch;
331 BYTE b,*buf;
332 struct lzstate *lzs;
334 buf=(LPBYTE)vbuf;
335 TRACE("(%d,%p,%d)\n",fd,buf,toread);
336 howmuch=toread;
337 if (!(lzs = GET_LZ_STATE(fd))) return _lread(fd,buf,toread);
339 /* The decompressor itself is in a define, cause we need it twice
340 * in this function. (the decompressed byte will be in b)
342 #define DECOMPRESS_ONE_BYTE \
343 if (lzs->stringlen) { \
344 b = lzs->table[lzs->stringpos]; \
345 lzs->stringpos = (lzs->stringpos+1)&0xFFF; \
346 lzs->stringlen--; \
347 } else { \
348 if (!(lzs->bytetype&0x100)) { \
349 if (1!=GET(lzs,b)) \
350 return toread-howmuch; \
351 lzs->bytetype = b|0xFF00; \
353 if (lzs->bytetype & 1) { \
354 if (1!=GET(lzs,b)) \
355 return toread-howmuch; \
356 } else { \
357 BYTE b1,b2; \
359 if (1!=GET(lzs,b1)) \
360 return toread-howmuch; \
361 if (1!=GET(lzs,b2)) \
362 return toread-howmuch; \
363 /* Format: \
364 * b1 b2 \
365 * AB CD \
366 * where CAB is the stringoffset in the table\
367 * and D+3 is the len of the string \
368 */ \
369 lzs->stringpos = b1|((b2&0xf0)<<4); \
370 lzs->stringlen = (b2&0xf)+2; \
371 /* 3, but we use a byte already below ... */\
372 b = lzs->table[lzs->stringpos];\
373 lzs->stringpos = (lzs->stringpos+1)&0xFFF;\
375 lzs->bytetype>>=1; \
377 /* store b in table */ \
378 lzs->table[lzs->curtabent++]= b; \
379 lzs->curtabent &= 0xFFF; \
380 lzs->realcurrent++;
382 /* if someone has seeked, we have to bring the decompressor
383 * to that position
385 if (lzs->realcurrent!=lzs->realwanted) {
386 /* if the wanted position is before the current position
387 * I see no easy way to unroll ... We have to restart at
388 * the beginning. *sigh*
390 if (lzs->realcurrent>lzs->realwanted) {
391 /* flush decompressor state */
392 _llseek(lzs->realfd,LZ_HEADER_LEN,SEEK_SET);
393 GET_FLUSH(lzs);
394 lzs->realcurrent= 0;
395 lzs->bytetype = 0;
396 lzs->stringlen = 0;
397 memset(lzs->table,' ',LZ_TABLE_SIZE);
398 lzs->curtabent = 0xFF0;
400 while (lzs->realcurrent<lzs->realwanted) {
401 DECOMPRESS_ONE_BYTE;
405 while (howmuch) {
406 DECOMPRESS_ONE_BYTE;
407 lzs->realwanted++;
408 *buf++ = b;
409 howmuch--;
411 return toread;
412 #undef DECOMPRESS_ONE_BYTE
416 /***********************************************************************
417 * LZSeek (KERNEL32.@)
419 LONG WINAPI LZSeek( HFILE fd, LONG off, INT type )
421 struct lzstate *lzs;
422 LONG newwanted;
424 TRACE("(%d,%d,%d)\n",fd,off,type);
425 /* not compressed? just use normal _llseek() */
426 if (!(lzs = GET_LZ_STATE(fd))) return _llseek(fd,off,type);
427 newwanted = lzs->realwanted;
428 switch (type) {
429 case 1: /* SEEK_CUR */
430 newwanted += off;
431 break;
432 case 2: /* SEEK_END */
433 newwanted = lzs->reallength-off;
434 break;
435 default:/* SEEK_SET */
436 newwanted = off;
437 break;
439 if (newwanted>lzs->reallength)
440 return LZERROR_BADVALUE;
441 if (newwanted<0)
442 return LZERROR_BADVALUE;
443 lzs->realwanted = newwanted;
444 return newwanted;
448 /***********************************************************************
449 * LZCopy (KERNEL32.@)
451 * Copies everything from src to dest
452 * if src is a LZ compressed file, it will be uncompressed.
453 * will return the number of bytes written to dest or errors.
455 LONG WINAPI LZCopy( HFILE src, HFILE dest )
457 int usedlzinit = 0, ret, wret;
458 LONG len;
459 HFILE oldsrc = src, srcfd;
460 FILETIME filetime;
461 struct lzstate *lzs;
462 #define BUFLEN 1000
463 CHAR buf[BUFLEN];
464 /* we need that weird typedef, for i can't seem to get function pointer
465 * casts right. (Or they probably just do not like WINAPI in general)
467 typedef UINT (WINAPI *_readfun)(HFILE,LPVOID,UINT);
469 _readfun xread;
471 TRACE("(%d,%d)\n",src,dest);
472 if (!IS_LZ_HANDLE(src)) {
473 src = LZInit(src);
474 if ((INT)src <= 0) return 0;
475 if (src != oldsrc) usedlzinit=1;
478 /* not compressed? just copy */
479 if (!IS_LZ_HANDLE(src))
480 xread=_lread;
481 else
482 xread=(_readfun)LZRead;
483 len=0;
484 while (1) {
485 ret=xread(src,buf,BUFLEN);
486 if (ret<=0) {
487 if (ret==0)
488 break;
489 if (ret==-1)
490 return LZERROR_READ;
491 return ret;
493 len += ret;
494 wret = _lwrite(dest,buf,ret);
495 if (wret!=ret)
496 return LZERROR_WRITE;
499 /* Maintain the timestamp of source file to destination file */
500 srcfd = (!(lzs = GET_LZ_STATE(src))) ? src : lzs->realfd;
501 GetFileTime( LongToHandle(srcfd), NULL, NULL, &filetime );
502 SetFileTime( LongToHandle(dest), NULL, NULL, &filetime );
504 /* close handle */
505 if (usedlzinit)
506 LZClose(src);
507 return len;
508 #undef BUFLEN
511 /* reverses GetExpandedPathname */
512 static LPSTR LZEXPAND_MangleName( LPCSTR fn )
514 char *p;
515 char *mfn = HeapAlloc( GetProcessHeap(), 0, strlen(fn) + 3 ); /* "._" and \0 */
516 if(mfn == NULL) return NULL;
517 strcpy( mfn, fn );
518 if (!(p = strrchr( mfn, '\\' ))) p = mfn;
519 if ((p = strchr( p, '.' )))
521 p++;
522 if (strlen(p) < 3) strcat( p, "_" ); /* append '_' */
523 else p[strlen(p)-1] = '_'; /* replace last character */
525 else strcat( mfn, "._" ); /* append "._" */
526 return mfn;
530 /***********************************************************************
531 * LZOpenFileA (KERNEL32.@)
533 * Opens a file. If not compressed, open it as a normal file.
535 HFILE WINAPI LZOpenFileA( LPSTR fn, LPOFSTRUCT ofs, WORD mode )
537 HFILE fd,cfd;
538 BYTE ofs_cBytes = ofs->cBytes;
540 TRACE("(%s,%p,%d)\n",fn,ofs,mode);
541 /* 0x70 represents all OF_SHARE_* flags, ignore them for the check */
542 fd=OpenFile(fn,ofs,mode);
543 if (fd==HFILE_ERROR)
545 LPSTR mfn = LZEXPAND_MangleName(fn);
546 fd = OpenFile(mfn,ofs,mode);
547 HeapFree( GetProcessHeap(), 0, mfn );
549 if (fd==HFILE_ERROR)
550 ofs->cBytes = ofs_cBytes;
551 if ((mode&~0x70)!=OF_READ)
552 return fd;
553 if (fd==HFILE_ERROR)
554 return HFILE_ERROR;
555 cfd=LZInit(fd);
556 if ((INT)cfd <= 0) return fd;
557 return cfd;
561 /***********************************************************************
562 * LZOpenFileW (KERNEL32.@)
564 HFILE WINAPI LZOpenFileW( LPWSTR fn, LPOFSTRUCT ofs, WORD mode )
566 HFILE ret;
567 DWORD len = WideCharToMultiByte( CP_ACP, 0, fn, -1, NULL, 0, NULL, NULL );
568 LPSTR xfn = HeapAlloc( GetProcessHeap(), 0, len );
569 WideCharToMultiByte( CP_ACP, 0, fn, -1, xfn, len, NULL, NULL );
570 ret = LZOpenFileA(xfn,ofs,mode);
571 HeapFree( GetProcessHeap(), 0, xfn );
572 return ret;
576 /***********************************************************************
577 * LZClose (KERNEL32.@)
579 void WINAPI LZClose( HFILE fd )
581 struct lzstate *lzs;
583 TRACE("(%d)\n",fd);
584 if (!(lzs = GET_LZ_STATE(fd))) _lclose(fd);
585 else
587 HeapFree( GetProcessHeap(), 0, lzs->get );
588 CloseHandle( LongToHandle(lzs->realfd) );
589 lzstates[fd - LZ_MIN_HANDLE] = NULL;
590 HeapFree( GetProcessHeap(), 0, lzs );