Release 980301
[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 <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <ctype.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include "windows.h"
18 #include "file.h"
19 #include "heap.h"
20 #include "ldt.h"
21 #include "lzexpand.h"
22 #include "debug.h"
23
24
25 /* The readahead length of the decompressor. Reading single bytes
26  * using _lread() would be SLOW.
27  */
28 #define GETLEN  2048
29
30 /* Format of first 14 byte of LZ compressed file */
31 struct lzfileheader {
32         BYTE    magic[8];
33         BYTE    compressiontype;
34         CHAR    lastchar;
35         DWORD   reallength;             
36 };
37 static BYTE LZMagic[8]={'S','Z','D','D',0x88,0xf0,0x27,0x33};
38
39 static struct lzstate {
40         HFILE32 lzfd;           /* the handle used by the program */
41         HFILE32 realfd;         /* the real filedescriptor */
42         CHAR    lastchar;       /* the last char of the filename */
43
44         DWORD   reallength;     /* the decompressed length of the file */
45         DWORD   realcurrent;    /* the position the decompressor currently is */
46         DWORD   realwanted;     /* the position the user wants to read from */
47
48         BYTE    table[0x1000];  /* the rotating LZ table */
49         UINT32  curtabent;      /* CURrent TABle ENTry */
50
51         BYTE    stringlen;      /* length and position of current string */ 
52         DWORD   stringpos;      /* from stringtable */
53
54
55         WORD    bytetype;       /* bitmask within blocks */
56
57         BYTE    *get;           /* GETLEN bytes */
58         DWORD   getcur;         /* current read */
59         DWORD   getlen;         /* length last got */
60 } *lzstates=NULL;
61 static int nroflzstates=0;
62
63 /* reads one compressed byte, including buffering */
64 #define GET(lzs,b)      _lzget(lzs,&b)
65 #define GET_FLUSH(lzs)  lzs->getcur=lzs->getlen;
66
67 static int
68 _lzget(struct lzstate *lzs,BYTE *b) {
69         if (lzs->getcur<lzs->getlen) {
70                 *b              = lzs->get[lzs->getcur++];
71                 return          1;
72         } else {
73                 int ret = _lread32(lzs->realfd,lzs->get,GETLEN);
74                 if (ret==HFILE_ERROR32)
75                         return HFILE_ERROR32;
76                 if (ret==0)
77                         return 0;
78                 lzs->getlen     = ret;
79                 lzs->getcur     = 1;
80                 *b              = *(lzs->get);
81                 return 1;
82         }
83 }
84 /* internal function, reads lzheader
85  * returns BADINHANDLE for non filedescriptors
86  * return 0 for file not compressed using LZ 
87  * return UNKNOWNALG for unknown algorithm
88  * returns lzfileheader in *head
89  */
90 static INT32 read_header(HFILE32 fd,struct lzfileheader *head)
91 {
92         BYTE    buf[14];
93
94         if (_llseek32(fd,0,SEEK_SET)==-1)
95                 return LZERROR_BADINHANDLE;
96
97         /* We can't directly read the lzfileheader struct due to 
98          * structure element alignment
99          */
100         if (_lread32(fd,buf,14)<14)
101                 return 0;
102         memcpy(head->magic,buf,8);
103         memcpy(&(head->compressiontype),buf+8,1);
104         memcpy(&(head->lastchar),buf+9,1);
105
106         /* FIXME: consider endianess on non-intel architectures */
107         memcpy(&(head->reallength),buf+10,4);
108
109         if (memcmp(head->magic,LZMagic,8))
110                 return 0;
111         if (head->compressiontype!='A')
112                 return LZERROR_UNKNOWNALG;
113         return 1;
114 }
115
116 /***********************************************************************
117  *           LZStart16   (LZEXPAND.7)
118  */
119 INT16 WINAPI LZStart16(void)
120 {
121     dprintf_info(file,"LZStart16(void)\n");
122     return 1;
123 }
124
125
126 /***********************************************************************
127  *           LZStart32   (LZ32.6)
128  */
129 INT32 WINAPI LZStart32(void)
130 {
131     dprintf_info(file,"LZStart32(void)\n");
132     return 1;
133 }
134
135
136 /***********************************************************************
137  *           LZInit16   (LZEXPAND.3)
138  */
139 HFILE16 WINAPI LZInit16( HFILE16 hfSrc )
140 {
141     return LZInit32( hfSrc );
142 }
143
144
145 /***********************************************************************
146  *           LZInit32   (LZ32.2)
147  *
148  * initializes internal decompression buffers, returns lzfiledescriptor.
149  * (return value the same as hfSrc, if hfSrc is not compressed)
150  * on failure, returns error code <0
151  * lzfiledescriptors range from 0x400 to 0x410 (only 16 open files per process)
152  * we use as much as we need, we just OR 0x400 to the passed HFILE.
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
164         dprintf_info(file,"LZInit(%d)\n",hfSrc);
165         ret=read_header(hfSrc,&head);
166         if (ret<=0) {
167                 _llseek32(hfSrc,0,SEEK_SET);
168                 return ret?ret:hfSrc;
169         }
170         lzstates = HeapReAlloc( SystemHeap, 0, lzstates,
171                                 (++nroflzstates)*sizeof(struct lzstate) );
172         lzs             = lzstates+(nroflzstates-1);
173
174         memset(lzs,'\0',sizeof(*lzs));
175         lzs->realfd     = hfSrc;
176         lzs->lzfd       = hfSrc | 0x400;
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 lzs->lzfd;
189 }
190
191
192 /***********************************************************************
193  *           LZDone   (LZEXPAND.9) (LZ32.8)
194  */
195 void WINAPI LZDone(void)
196 {
197     dprintf_info(file,"LZDone()\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         dprintf_info(file,"GetExpandedName(%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                 fprintf(stddeb,__FILE__":GetExpandedFileName(), 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     return LZRead32(fd,buf,toread);
312 }
313
314
315 /***********************************************************************
316  *           LZRead32   (LZ32.4)
317  */
318 INT32 WINAPI LZRead32( HFILE32 fd, LPVOID vbuf, UINT32 toread )
319 {
320         int     i,howmuch;
321         BYTE    b,*buf;
322         struct  lzstate *lzs;
323
324         buf=(LPBYTE)vbuf;
325         dprintf_info(file,"LZRead32(%d,%p,%d)\n",fd,buf,toread);
326         howmuch=toread;
327         for (i=0;i<nroflzstates;i++)
328                 if (lzstates[i].lzfd==fd)
329                         break;
330         if (i==nroflzstates)
331                 return _lread32(fd,buf,toread);
332         lzs=lzstates+i;
333
334 /* The decompressor itself is in a define, cause we need it twice
335  * in this function. (the decompressed byte will be in b)
336  */
337 #define DECOMPRESS_ONE_BYTE                                             \
338                 if (lzs->stringlen) {                                   \
339                         b               = lzs->table[lzs->stringpos];   \
340                         lzs->stringpos  = (lzs->stringpos+1)&0xFFF;     \
341                         lzs->stringlen--;                               \
342                 } else {                                                \
343                         if (!(lzs->bytetype&0x100)) {                   \
344                                 if (1!=GET(lzs,b))                      \
345                                         return toread-howmuch;          \
346                                 lzs->bytetype = b|0xFF00;               \
347                         }                                               \
348                         if (lzs->bytetype & 1) {                        \
349                                 if (1!=GET(lzs,b))                      \
350                                         return toread-howmuch;          \
351                         } else {                                        \
352                                 BYTE    b1,b2;                          \
353                                                                         \
354                                 if (1!=GET(lzs,b1))                     \
355                                         return toread-howmuch;          \
356                                 if (1!=GET(lzs,b2))                     \
357                                         return toread-howmuch;          \
358                                 /* Format:                              \
359                                  * b1 b2                                \
360                                  * AB CD                                \
361                                  * where CAB is the stringoffset in the table\
362                                  * and D+3 is the len of the string     \
363                                  */                                     \
364                                 lzs->stringpos  = b1|((b2&0xf0)<<4);    \
365                                 lzs->stringlen  = (b2&0xf)+2;           \
366                                 /* 3, but we use a  byte already below ... */\
367                                 b               = lzs->table[lzs->stringpos];\
368                                 lzs->stringpos  = (lzs->stringpos+1)&0xFFF;\
369                         }                                               \
370                         lzs->bytetype>>=1;                              \
371                 }                                                       \
372                 /* store b in table */                                  \
373                 lzs->table[lzs->curtabent++]= b;                        \
374                 lzs->curtabent  &= 0xFFF;                               \
375                 lzs->realcurrent++;
376
377         /* if someone has seeked, we have to bring the decompressor 
378          * to that position
379          */
380         if (lzs->realcurrent!=lzs->realwanted) {
381                 /* if the wanted position is before the current position 
382                  * I see no easy way to unroll ... We have to restart at
383                  * the beginning. *sigh*
384                  */
385                 if (lzs->realcurrent>lzs->realwanted) {
386                         /* flush decompressor state */
387                         _llseek32(lzs->realfd,14,SEEK_SET);
388                         GET_FLUSH(lzs);
389                         lzs->realcurrent= 0;
390                         lzs->bytetype   = 0;
391                         lzs->stringlen  = 0;
392                         memset(lzs->table,' ',0x1000);
393                         lzs->curtabent  = 0xFF0;
394                 }
395                 while (lzs->realcurrent<lzs->realwanted) {
396                         DECOMPRESS_ONE_BYTE;
397                 }
398         }
399
400         while (howmuch) {
401                 DECOMPRESS_ONE_BYTE;
402                 lzs->realwanted++;
403                 *buf++          = b;
404                 howmuch--;
405         }
406         return  toread;
407 #undef DECOMPRESS_ONE_BYTE
408 }
409
410
411 /***********************************************************************
412  *           LZSeek16   (LZEXPAND.4)
413  */
414 LONG WINAPI LZSeek16( HFILE16 fd, LONG off, INT16 type )
415 {
416     return LZSeek32( fd, off, type );
417 }
418
419
420 /***********************************************************************
421  *           LZSeek32   (LZ32.3)
422  */
423 LONG WINAPI LZSeek32( HFILE32 fd, LONG off, INT32 type )
424 {
425         int     i;
426         struct  lzstate *lzs;
427         LONG    newwanted;
428
429         dprintf_info(file,"LZSeek(%d,%ld,%d)\n",fd,off,type);
430         for (i=0;i<nroflzstates;i++)
431                 if (lzstates[i].lzfd==fd)
432                         break;
433         /* not compressed? just use normal _llseek() */
434         if (i==nroflzstates)
435                 return _llseek32(fd,off,type);
436         lzs             = lzstates+i;
437         newwanted       = lzs->realwanted;
438         switch (type) {
439         case 1: /* SEEK_CUR */
440                 newwanted      += off;
441                 break;
442         case 2: /* SEEK_END */
443                 newwanted       = lzs->reallength-off;
444                 break;
445         default:/* SEEK_SET */
446                 newwanted       = off;
447                 break;
448         }
449         if (newwanted>lzs->reallength)
450                 return LZERROR_BADVALUE;
451         if (newwanted<0)
452                 return LZERROR_BADVALUE;
453         lzs->realwanted = newwanted;
454         return newwanted;
455 }
456
457
458 /***********************************************************************
459  *           LZCopy16   (LZEXPAND.1)
460  */
461 LONG WINAPI LZCopy16( HFILE16 src, HFILE16 dest )
462 {
463     return LZCopy32( src, dest );
464 }
465
466
467 /***********************************************************************
468  *           LZCopy32   (LZ32.0)
469  *
470  * Copies everything from src to dest
471  * if src is a LZ compressed file, it will be uncompressed.
472  * will return the number of bytes written to dest or errors.
473  */
474 LONG WINAPI LZCopy32( HFILE32 src, HFILE32 dest )
475 {
476         int     i,ret,wret;
477         LONG    len;
478 #define BUFLEN  1000
479         BYTE    buf[BUFLEN];
480         INT32   WINAPI (*xread)(HFILE32,LPVOID,UINT32);
481
482         dprintf_info(file,"LZCopy(%d,%d)\n",src,dest);
483         for (i=0;i<nroflzstates;i++)
484                 if (src==lzstates[i].lzfd)
485                         break;
486
487         /* not compressed? just copy */
488         if (i==nroflzstates)
489                 xread=(INT32(*)(HFILE32,LPVOID,UINT32))_lread32;
490         else
491                 xread=LZRead32;
492         len=0;
493         while (1) {
494                 ret=xread(src,buf,BUFLEN);
495                 if (ret<=0) {
496                         if (ret==0)
497                                 break;
498                         if (ret==-1)
499                                 return LZERROR_READ;
500                         return ret;
501                 }
502                 len    += ret;
503                 wret    = _lwrite32(dest,buf,ret);
504                 if (wret!=ret)
505                         return LZERROR_WRITE;
506         }
507         return len;
508 #undef BUFLEN
509 }
510
511 /* reverses GetExpandedPathname */
512 static LPSTR LZEXPAND_MangleName( LPCSTR fn )
513 {
514     char *p;
515     char *mfn = (char *)HEAP_xalloc( GetProcessHeap(), 0,
516                                      strlen(fn) + 3 ); /* "._" and \0 */
517     strcpy( mfn, fn );
518     if (!(p = strrchr( mfn, '\\' ))) p = mfn;
519     if ((p = strchr( p, '.' )))
520     {
521         p++;
522         if (strlen(p) < 3) strcat( p, "_" );  /* append '_' */
523         else p[strlen(p)-1] = '_';  /* replace last character */
524     }
525     else strcat( mfn, "._" );   /* append "._" */
526     return mfn;
527 }
528
529
530 /***********************************************************************
531  *           LZOpenFile16   (LZEXPAND.2)
532  */
533 HFILE16 WINAPI LZOpenFile16( LPCSTR fn, LPOFSTRUCT ofs, UINT16 mode )
534 {
535     return LZOpenFile32A( fn, ofs, mode );
536 }
537
538
539 /***********************************************************************
540  *           LZOpenFile32A   (LZ32.1)
541  *
542  * Opens a file. If not compressed, open it as a normal file.
543  */
544 HFILE32 WINAPI LZOpenFile32A( LPCSTR fn, LPOFSTRUCT ofs, UINT32 mode )
545 {
546         HFILE32 fd,cfd;
547
548         dprintf_info(file,"LZOpenFile(%s,%p,%d)\n",fn,ofs,mode);
549         /* 0x70 represents all OF_SHARE_* flags, ignore them for the check */
550         fd=OpenFile32(fn,ofs,mode);
551         if (fd==HFILE_ERROR32)
552         {
553             LPSTR mfn = LZEXPAND_MangleName(fn);
554             fd = OpenFile32(mfn,ofs,mode);
555             HeapFree( GetProcessHeap(), 0, mfn );
556         }
557         if ((mode&~0x70)!=OF_READ)
558                 return fd;
559         if (fd==HFILE_ERROR32)
560                 return HFILE_ERROR32;
561         cfd=LZInit32(fd);
562         if (cfd<=0)
563                 return fd;
564         return cfd;
565 }
566
567
568 /***********************************************************************
569  *           LZOpenFile32W   (LZ32.10)
570  */
571 HFILE32 WINAPI LZOpenFile32W( LPCWSTR fn, LPOFSTRUCT ofs, UINT32 mode )
572 {
573         LPSTR   xfn;
574         LPWSTR  yfn;
575         HFILE32 ret;
576
577         xfn     = HEAP_strdupWtoA( GetProcessHeap(), 0, fn);
578         ret     = LZOpenFile16(xfn,ofs,mode);
579         HeapFree( GetProcessHeap(), 0, xfn );
580         if (ret!=HFILE_ERROR32) {
581                 /* ofs->szPathName is an array with the OFSTRUCT */
582                 yfn = HEAP_strdupAtoW( GetProcessHeap(), 0, ofs->szPathName );
583                 memcpy(ofs->szPathName,yfn,lstrlen32W(yfn)*2+2);
584                 HeapFree( GetProcessHeap(), 0, yfn );
585         }
586         return  ret;
587 }
588
589
590 /***********************************************************************
591  *           LZClose16   (LZEXPAND.6)
592  */
593 void WINAPI LZClose16( HFILE16 fd )
594 {
595     return LZClose32( fd );
596 }
597
598
599 /***********************************************************************
600  *           LZClose32   (LZ32.5)
601  */
602 void WINAPI LZClose32( HFILE32 fd )
603 {
604         int     i;
605
606         dprintf_info(file,"LZClose(%d)\n",fd);
607         for (i=0;i<nroflzstates;i++)
608                 if (lzstates[i].lzfd==fd)
609                         break;
610         if (i==nroflzstates) {
611                 _lclose32(fd);
612                 return;
613         }
614         if (lzstates[i].get)
615                 HeapFree( GetProcessHeap(), 0, lzstates[i].get );
616         _lclose32(lzstates[i].realfd);
617         memmove(lzstates+i,lzstates+i+1,
618                 sizeof(struct lzstate)*(nroflzstates-i-1));
619         nroflzstates--;
620         lzstates = HeapReAlloc( SystemHeap, 0, lzstates,
621                                 sizeof(struct lzstate)*nroflzstates );
622 }
623
624 /***********************************************************************
625  *           CopyLZFile16   (LZEXPAND.8)
626  */
627 LONG WINAPI CopyLZFile16( HFILE16 src, HFILE16 dest )
628 {
629     dprintf_info(file,"CopyLZFile16(%d,%d)\n",src,dest);
630     return LZCopy32(src,dest);
631 }
632
633
634 /***********************************************************************
635  *           CopyLZFile32  (LZ32.7)
636  *
637  * Copy src to dest (including uncompressing src).
638  * NOTE: Yes. This is exactly the same function as LZCopy.
639  */
640 LONG WINAPI CopyLZFile32( HFILE32 src, HFILE32 dest )
641 {
642     dprintf_info(file,"CopyLZFile32(%d,%d)\n",src,dest);
643     return LZCopy32(src,dest);
644 }