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