- New implementation of SendMessage, ReceiveMessage, ReplyMessage functions
[wine] / misc / lzexpand.c
1 /*
2  * LZ Decompression functions 
3  *
4  * Copyright 1996 Marcus Meissner
5  */
6 /* 
7  * FIXME: return values might be wrong
8  */
9
10 #include <string.h>
11 #include <ctype.h>
12 #include "windows.h"
13 #include "file.h"
14 #include "heap.h"
15 #include "lzexpand.h"
16 #include "debug.h"
17
18
19 /* The readahead length of the decompressor. Reading single bytes
20  * using _lread() would be SLOW.
21  */
22 #define GETLEN  2048
23
24 /* Format of first 14 byte of LZ compressed file */
25 struct lzfileheader {
26         BYTE    magic[8];
27         BYTE    compressiontype;
28         CHAR    lastchar;
29         DWORD   reallength;             
30 };
31 static BYTE LZMagic[8]={'S','Z','D','D',0x88,0xf0,0x27,0x33};
32
33 struct lzstate {
34         HFILE32 realfd;         /* the real filedescriptor */
35         CHAR    lastchar;       /* the last char of the filename */
36
37         DWORD   reallength;     /* the decompressed length of the file */
38         DWORD   realcurrent;    /* the position the decompressor currently is */
39         DWORD   realwanted;     /* the position the user wants to read from */
40
41         BYTE    table[0x1000];  /* the rotating LZ table */
42         UINT32  curtabent;      /* CURrent TABle ENTry */
43
44         BYTE    stringlen;      /* length and position of current string */ 
45         DWORD   stringpos;      /* from stringtable */
46
47
48         WORD    bytetype;       /* bitmask within blocks */
49
50         BYTE    *get;           /* GETLEN bytes */
51         DWORD   getcur;         /* current read */
52         DWORD   getlen;         /* length last got */
53 };
54
55 #define MAX_LZSTATES 16
56 static struct lzstate *lzstates[MAX_LZSTATES];
57
58 #define IS_LZ_HANDLE(h) (((h) >= 0x400) && ((h) < 0x400+MAX_LZSTATES))
59 #define GET_LZ_STATE(h) (IS_LZ_HANDLE(h) ? lzstates[(h)-0x400] : NULL)
60
61 /* reads one compressed byte, including buffering */
62 #define GET(lzs,b)      _lzget(lzs,&b)
63 #define GET_FLUSH(lzs)  lzs->getcur=lzs->getlen;
64
65 static int
66 _lzget(struct lzstate *lzs,BYTE *b) {
67         if (lzs->getcur<lzs->getlen) {
68                 *b              = lzs->get[lzs->getcur++];
69                 return          1;
70         } else {
71                 int ret = _lread32(lzs->realfd,lzs->get,GETLEN);
72                 if (ret==HFILE_ERROR32)
73                         return HFILE_ERROR32;
74                 if (ret==0)
75                         return 0;
76                 lzs->getlen     = ret;
77                 lzs->getcur     = 1;
78                 *b              = *(lzs->get);
79                 return 1;
80         }
81 }
82 /* internal function, reads lzheader
83  * returns BADINHANDLE for non filedescriptors
84  * return 0 for file not compressed using LZ 
85  * return UNKNOWNALG for unknown algorithm
86  * returns lzfileheader in *head
87  */
88 static INT32 read_header(HFILE32 fd,struct lzfileheader *head)
89 {
90         BYTE    buf[14];
91
92         if (_llseek32(fd,0,SEEK_SET)==-1)
93                 return LZERROR_BADINHANDLE;
94
95         /* We can't directly read the lzfileheader struct due to 
96          * structure element alignment
97          */
98         if (_lread32(fd,buf,14)<14)
99                 return 0;
100         memcpy(head->magic,buf,8);
101         memcpy(&(head->compressiontype),buf+8,1);
102         memcpy(&(head->lastchar),buf+9,1);
103
104         /* FIXME: consider endianess on non-intel architectures */
105         memcpy(&(head->reallength),buf+10,4);
106
107         if (memcmp(head->magic,LZMagic,8))
108                 return 0;
109         if (head->compressiontype!='A')
110                 return LZERROR_UNKNOWNALG;
111         return 1;
112 }
113
114 /***********************************************************************
115  *           LZStart16   (LZEXPAND.7)
116  */
117 INT16 WINAPI LZStart16(void)
118 {
119     TRACE(file,"(void)\n");
120     return 1;
121 }
122
123
124 /***********************************************************************
125  *           LZStart32   (LZ32.6)
126  */
127 INT32 WINAPI LZStart32(void)
128 {
129     TRACE(file,"(void)\n");
130     return 1;
131 }
132
133
134 /***********************************************************************
135  *           LZInit16   (LZEXPAND.3)
136  */
137 HFILE16 WINAPI LZInit16( HFILE16 hfSrc )
138 {
139     HFILE32 ret = LZInit32( FILE_GetHandle32(hfSrc) );
140     if (IS_LZ_HANDLE(ret)) return ret;
141     if ((INT32)ret <= 0) return ret;
142     return hfSrc;
143 }
144
145
146 /***********************************************************************
147  *           LZInit32   (LZ32.2)
148  *
149  * initializes internal decompression buffers, returns lzfiledescriptor.
150  * (return value the same as hfSrc, if hfSrc is not compressed)
151  * on failure, returns error code <0
152  * lzfiledescriptors range from 0x400 to 0x410 (only 16 open files per process)
153  *
154  * since _llseek uses the same types as libc.lseek, we just use the macros of 
155  *  libc
156  */
157 HFILE32 WINAPI LZInit32( HFILE32 hfSrc )
158 {
159
160         struct  lzfileheader    head;
161         struct  lzstate         *lzs;
162         DWORD   ret;
163         int i;
164
165         TRACE(file,"(%d)\n",hfSrc);
166         ret=read_header(hfSrc,&head);
167         if (ret<=0) {
168                 _llseek32(hfSrc,0,SEEK_SET);
169                 return ret?ret:hfSrc;
170         }
171         for (i = 0; i < MAX_LZSTATES; i++) if (!lzstates[i]) break;
172         if (i == MAX_LZSTATES) return LZERROR_GLOBALLOC;
173         lzstates[i] = lzs = HeapAlloc( SystemHeap, 0, sizeof(struct lzstate) );
174
175         memset(lzs,'\0',sizeof(*lzs));
176         lzs->realfd     = hfSrc;
177         lzs->lastchar   = head.lastchar;
178         lzs->reallength = head.reallength;
179
180         lzs->get        = HEAP_xalloc( GetProcessHeap(), 0, GETLEN );
181         lzs->getlen     = 0;
182         lzs->getcur     = 0;
183
184         /* Yes, preinitialize with spaces */
185         memset(lzs->table,' ',0x1000);
186         /* Yes, start 16 byte from the END of the table */
187         lzs->curtabent  = 0xff0; 
188         return 0x400 + i;
189 }
190
191
192 /***********************************************************************
193  *           LZDone   (LZEXPAND.9) (LZ32.8)
194  */
195 void WINAPI LZDone(void)
196 {
197     TRACE(file,"(void)\n");
198 }
199
200
201 /***********************************************************************
202  *           GetExpandedName16   (LZEXPAND.10)
203  */
204 INT16 WINAPI GetExpandedName16( LPCSTR in, LPSTR out )
205 {
206     return (INT16)GetExpandedName32A( in, out );
207 }
208
209
210 /***********************************************************************
211  *           GetExpandedName32A   (LZ32.9)
212  *
213  * gets the full filename of the compressed file 'in' by opening it
214  * and reading the header
215  *
216  * "file." is being translated to "file"
217  * "file.bl_" (with lastchar 'a') is being translated to "file.bla"
218  * "FILE.BL_" (with lastchar 'a') is being translated to "FILE.BLA"
219  */
220
221 INT32 WINAPI GetExpandedName32A( LPCSTR in, LPSTR out )
222 {
223         struct lzfileheader     head;
224         HFILE32         fd;
225         OFSTRUCT        ofs;
226         INT32           fnislowercased,ret,len;
227         LPSTR           s,t;
228
229         TRACE(file,"(%s)\n",in);
230         fd=OpenFile32(in,&ofs,OF_READ);
231         if (fd==HFILE_ERROR32)
232                 return (INT32)(INT16)LZERROR_BADINHANDLE;
233         strcpy(out,in);
234         ret=read_header(fd,&head);
235         if (ret<=0) {
236                 /* not a LZ compressed file, so the expanded name is the same
237                  * as the input name */
238                 _lclose32(fd);
239                 return 1;
240         }
241
242
243         /* look for directory prefix and skip it. */
244         s=out;
245         while (NULL!=(t=strpbrk(s,"/\\:")))
246                 s=t+1;
247
248         /* now mangle the basename */
249         if (!*s) {
250                 /* FIXME: hmm. shouldn't happen? */
251                 WARN(file,"Specified a directory or what? (%s)\n",in);
252                 _lclose32(fd);
253                 return 1;
254         }
255         /* see if we should use lowercase or uppercase on the last char */
256         fnislowercased=1;
257         t=s+strlen(s)-1;
258         while (t>=out) {
259                 if (!isalpha(*t)) {
260                         t--;
261                         continue;
262                 }
263                 fnislowercased=islower(*t);
264                 break;
265         }
266         if (isalpha(head.lastchar)) {
267                 if (fnislowercased)
268                         head.lastchar=tolower(head.lastchar);
269                 else
270                         head.lastchar=toupper(head.lastchar);
271         }       
272
273         /* now look where to replace the last character */
274         if (NULL!=(t=strchr(s,'.'))) {
275                 if (t[1]=='\0') {
276                         t[0]='\0';
277                 } else {
278                         len=strlen(t)-1;
279                         if (t[len]=='_')
280                                 t[len]=head.lastchar;
281                 }
282         } /* else no modification necessary */
283         _lclose32(fd);
284         return 1;
285 }
286
287
288 /***********************************************************************
289  *           GetExpandedName32W   (LZ32.11)
290  */
291 INT32 WINAPI GetExpandedName32W( LPCWSTR in, LPWSTR out )
292 {
293         char    *xin,*xout;
294         INT32   ret;
295
296         xout    = HeapAlloc( GetProcessHeap(), 0, lstrlen32W(in)+3 );
297         xin     = HEAP_strdupWtoA( GetProcessHeap(), 0, in );
298         ret     = GetExpandedName16(xin,xout);
299         if (ret>0) lstrcpyAtoW(out,xout);
300         HeapFree( GetProcessHeap(), 0, xin );
301         HeapFree( GetProcessHeap(), 0, xout );
302         return  ret;
303 }
304
305
306 /***********************************************************************
307  *           LZRead16   (LZEXPAND.5)
308  */
309 INT16 WINAPI LZRead16( HFILE16 fd, LPVOID buf, UINT16 toread )
310 {
311     if (IS_LZ_HANDLE(fd)) return LZRead32( fd, buf, toread );
312     return _lread16( fd, buf, toread );
313 }
314
315
316 /***********************************************************************
317  *           LZRead32   (LZ32.4)
318  */
319 INT32 WINAPI LZRead32( HFILE32 fd, LPVOID vbuf, UINT32 toread )
320 {
321         int     howmuch;
322         BYTE    b,*buf;
323         struct  lzstate *lzs;
324
325         buf=(LPBYTE)vbuf;
326         TRACE(file,"(%d,%p,%d)\n",fd,buf,toread);
327         howmuch=toread;
328         if (!(lzs = GET_LZ_STATE(fd))) return _lread32(fd,buf,toread);
329
330 /* The decompressor itself is in a define, cause we need it twice
331  * in this function. (the decompressed byte will be in b)
332  */
333 #define DECOMPRESS_ONE_BYTE                                             \
334                 if (lzs->stringlen) {                                   \
335                         b               = lzs->table[lzs->stringpos];   \
336                         lzs->stringpos  = (lzs->stringpos+1)&0xFFF;     \
337                         lzs->stringlen--;                               \
338                 } else {                                                \
339                         if (!(lzs->bytetype&0x100)) {                   \
340                                 if (1!=GET(lzs,b))                      \
341                                         return toread-howmuch;          \
342                                 lzs->bytetype = b|0xFF00;               \
343                         }                                               \
344                         if (lzs->bytetype & 1) {                        \
345                                 if (1!=GET(lzs,b))                      \
346                                         return toread-howmuch;          \
347                         } else {                                        \
348                                 BYTE    b1,b2;                          \
349                                                                         \
350                                 if (1!=GET(lzs,b1))                     \
351                                         return toread-howmuch;          \
352                                 if (1!=GET(lzs,b2))                     \
353                                         return toread-howmuch;          \
354                                 /* Format:                              \
355                                  * b1 b2                                \
356                                  * AB CD                                \
357                                  * where CAB is the stringoffset in the table\
358                                  * and D+3 is the len of the string     \
359                                  */                                     \
360                                 lzs->stringpos  = b1|((b2&0xf0)<<4);    \
361                                 lzs->stringlen  = (b2&0xf)+2;           \
362                                 /* 3, but we use a  byte already below ... */\
363                                 b               = lzs->table[lzs->stringpos];\
364                                 lzs->stringpos  = (lzs->stringpos+1)&0xFFF;\
365                         }                                               \
366                         lzs->bytetype>>=1;                              \
367                 }                                                       \
368                 /* store b in table */                                  \
369                 lzs->table[lzs->curtabent++]= b;                        \
370                 lzs->curtabent  &= 0xFFF;                               \
371                 lzs->realcurrent++;
372
373         /* if someone has seeked, we have to bring the decompressor 
374          * to that position
375          */
376         if (lzs->realcurrent!=lzs->realwanted) {
377                 /* if the wanted position is before the current position 
378                  * I see no easy way to unroll ... We have to restart at
379                  * the beginning. *sigh*
380                  */
381                 if (lzs->realcurrent>lzs->realwanted) {
382                         /* flush decompressor state */
383                         _llseek32(lzs->realfd,14,SEEK_SET);
384                         GET_FLUSH(lzs);
385                         lzs->realcurrent= 0;
386                         lzs->bytetype   = 0;
387                         lzs->stringlen  = 0;
388                         memset(lzs->table,' ',0x1000);
389                         lzs->curtabent  = 0xFF0;
390                 }
391                 while (lzs->realcurrent<lzs->realwanted) {
392                         DECOMPRESS_ONE_BYTE;
393                 }
394         }
395
396         while (howmuch) {
397                 DECOMPRESS_ONE_BYTE;
398                 lzs->realwanted++;
399                 *buf++          = b;
400                 howmuch--;
401         }
402         return  toread;
403 #undef DECOMPRESS_ONE_BYTE
404 }
405
406
407 /***********************************************************************
408  *           LZSeek16   (LZEXPAND.4)
409  */
410 LONG WINAPI LZSeek16( HFILE16 fd, LONG off, INT16 type )
411 {
412     if (IS_LZ_HANDLE(fd)) return LZSeek32( fd, off, type );
413     return _llseek16( fd, off, type );
414 }
415
416
417 /***********************************************************************
418  *           LZSeek32   (LZ32.3)
419  */
420 LONG WINAPI LZSeek32( HFILE32 fd, LONG off, INT32 type )
421 {
422         struct  lzstate *lzs;
423         LONG    newwanted;
424
425         TRACE(file,"(%d,%ld,%d)\n",fd,off,type);
426         /* not compressed? just use normal _llseek() */
427         if (!(lzs = GET_LZ_STATE(fd))) return _llseek32(fd,off,type);
428         newwanted = lzs->realwanted;
429         switch (type) {
430         case 1: /* SEEK_CUR */
431                 newwanted      += off;
432                 break;
433         case 2: /* SEEK_END */
434                 newwanted       = lzs->reallength-off;
435                 break;
436         default:/* SEEK_SET */
437                 newwanted       = off;
438                 break;
439         }
440         if (newwanted>lzs->reallength)
441                 return LZERROR_BADVALUE;
442         if (newwanted<0)
443                 return LZERROR_BADVALUE;
444         lzs->realwanted = newwanted;
445         return newwanted;
446 }
447
448
449 /***********************************************************************
450  *           LZCopy16   (LZEXPAND.1)
451  *
452  */
453 LONG WINAPI LZCopy16( HFILE16 src, HFILE16 dest )
454 {
455     /* already a LZ handle? */
456     if (IS_LZ_HANDLE(src)) return LZCopy32( src, FILE_GetHandle32(dest) );
457
458     /* no, try to open one */
459     src = LZInit16(src);
460     if ((INT16)src <= 0) return 0;
461     if (IS_LZ_HANDLE(src))
462     {
463         LONG ret = LZCopy32( src, FILE_GetHandle32(dest) );
464         LZClose32( src );
465         return ret;
466     }
467     /* it was not a compressed file */
468     return LZCopy32( FILE_GetHandle32(src), FILE_GetHandle32(dest) );
469 }
470
471
472 /***********************************************************************
473  *           LZCopy32   (LZ32.0)
474  *
475  * Copies everything from src to dest
476  * if src is a LZ compressed file, it will be uncompressed.
477  * will return the number of bytes written to dest or errors.
478  */
479 LONG WINAPI LZCopy32( HFILE32 src, HFILE32 dest )
480 {
481         int     usedlzinit=0,ret,wret;
482         LONG    len;
483         HFILE32 oldsrc = src;
484 #define BUFLEN  1000
485         BYTE    buf[BUFLEN];
486         UINT32  WINAPI (*xread)(HFILE32,LPVOID,UINT32);
487
488         TRACE(file,"(%d,%d)\n",src,dest);
489         if (!IS_LZ_HANDLE(src)) {
490                 src = LZInit32(src);
491                 if ((INT32)src <= 0) return 0;
492                 if (src != oldsrc) usedlzinit=1;
493         }
494
495         /* not compressed? just copy */
496         if (!IS_LZ_HANDLE(src))
497                 xread=_lread32;
498         else    /* Note: Ignore warning, just mismatched INT/UINT */
499                 xread=LZRead32; 
500         len=0;
501         while (1) {
502                 ret=xread(src,buf,BUFLEN);
503                 if (ret<=0) {
504                         if (ret==0)
505                                 break;
506                         if (ret==-1)
507                                 return LZERROR_READ;
508                         return ret;
509                 }
510                 len    += ret;
511                 wret    = _lwrite32(dest,buf,ret);
512                 if (wret!=ret)
513                         return LZERROR_WRITE;
514         }
515         if (usedlzinit)
516                 LZClose32(src);
517         return len;
518 #undef BUFLEN
519 }
520
521 /* reverses GetExpandedPathname */
522 static LPSTR LZEXPAND_MangleName( LPCSTR fn )
523 {
524     char *p;
525     char *mfn = (char *)HEAP_xalloc( GetProcessHeap(), 0,
526                                      strlen(fn) + 3 ); /* "._" and \0 */
527     strcpy( mfn, fn );
528     if (!(p = strrchr( mfn, '\\' ))) p = mfn;
529     if ((p = strchr( p, '.' )))
530     {
531         p++;
532         if (strlen(p) < 3) strcat( p, "_" );  /* append '_' */
533         else p[strlen(p)-1] = '_';  /* replace last character */
534     }
535     else strcat( mfn, "._" );   /* append "._" */
536     return mfn;
537 }
538
539
540 /***********************************************************************
541  *           LZOpenFile16   (LZEXPAND.2)
542  */
543 HFILE16 WINAPI LZOpenFile16( LPCSTR fn, LPOFSTRUCT ofs, UINT16 mode )
544 {
545     HFILE32 hfret = LZOpenFile32A( fn, ofs, mode );
546     /* return errors and LZ handles unmodified */
547     if ((INT32)hfret <= 0) return hfret;
548     if (IS_LZ_HANDLE(hfret)) return hfret;
549     /* but allocate a dos handle for 'normal' files */
550     return FILE_AllocDosHandle(hfret);
551 }
552
553
554 /***********************************************************************
555  *           LZOpenFile32A   (LZ32.1)
556  *
557  * Opens a file. If not compressed, open it as a normal file.
558  */
559 HFILE32 WINAPI LZOpenFile32A( LPCSTR fn, LPOFSTRUCT ofs, UINT32 mode )
560 {
561         HFILE32 fd,cfd;
562
563         TRACE(file,"(%s,%p,%d)\n",fn,ofs,mode);
564         /* 0x70 represents all OF_SHARE_* flags, ignore them for the check */
565         fd=OpenFile32(fn,ofs,mode);
566         if (fd==HFILE_ERROR32)
567         {
568             LPSTR mfn = LZEXPAND_MangleName(fn);
569             fd = OpenFile32(mfn,ofs,mode);
570             HeapFree( GetProcessHeap(), 0, mfn );
571         }
572         if ((mode&~0x70)!=OF_READ)
573                 return fd;
574         if (fd==HFILE_ERROR32)
575                 return HFILE_ERROR32;
576         cfd=LZInit32(fd);
577         if ((INT32)cfd <= 0) return fd;
578         return cfd;
579 }
580
581
582 /***********************************************************************
583  *           LZOpenFile32W   (LZ32.10)
584  */
585 HFILE32 WINAPI LZOpenFile32W( LPCWSTR fn, LPOFSTRUCT ofs, UINT32 mode )
586 {
587         LPSTR   xfn;
588         LPWSTR  yfn;
589         HFILE32 ret;
590
591         xfn     = HEAP_strdupWtoA( GetProcessHeap(), 0, fn);
592         ret     = LZOpenFile16(xfn,ofs,mode);
593         HeapFree( GetProcessHeap(), 0, xfn );
594         if (ret!=HFILE_ERROR32) {
595                 /* ofs->szPathName is an array with the OFSTRUCT */
596                 yfn = HEAP_strdupAtoW( GetProcessHeap(), 0, ofs->szPathName );
597                 memcpy(ofs->szPathName,yfn,lstrlen32W(yfn)*2+2);
598                 HeapFree( GetProcessHeap(), 0, yfn );
599         }
600         return  ret;
601 }
602
603
604 /***********************************************************************
605  *           LZClose16   (LZEXPAND.6)
606  */
607 void WINAPI LZClose16( HFILE16 fd )
608 {
609     if (IS_LZ_HANDLE(fd)) LZClose32( fd );
610     else _lclose16( fd );
611 }
612
613
614 /***********************************************************************
615  *           LZClose32   (LZ32.5)
616  */
617 void WINAPI LZClose32( HFILE32 fd )
618 {
619         struct lzstate *lzs;
620
621         TRACE(file,"(%d)\n",fd);
622         if (!(lzs = GET_LZ_STATE(fd))) _lclose32(fd);
623         else
624         {
625             if (lzs->get) HeapFree( GetProcessHeap(), 0, lzs->get );
626             CloseHandle(lzs->realfd);
627             lzstates[fd - 0x400] = NULL;
628             HeapFree( SystemHeap, 0, lzs );
629         }
630 }
631
632 /***********************************************************************
633  *           CopyLZFile16   (LZEXPAND.8)
634  */
635 LONG WINAPI CopyLZFile16( HFILE16 src, HFILE16 dest )
636 {
637     TRACE(file,"(%d,%d)\n",src,dest);
638     return LZCopy16(src,dest);
639 }
640
641
642 /***********************************************************************
643  *           CopyLZFile32  (LZ32.7)
644  *
645  * Copy src to dest (including uncompressing src).
646  * NOTE: Yes. This is exactly the same function as LZCopy.
647  */
648 LONG WINAPI CopyLZFile32( HFILE32 src, HFILE32 dest )
649 {
650     TRACE(file,"(%d,%d)\n",src,dest);
651     return LZCopy32(src,dest);
652 }