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