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