vcomp: Better stub for omp_get_max_threads.
[wine] / dlls / kernel32 / lzexpand.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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * NOTES
21  *
22  * The LZ (Lempel Ziv) decompression was used in win16 installation programs.
23  * It is a simple tabledriven decompression engine, the algorithm is not
24  * documented as far as I know. WINE does not contain a compressor for
25  * this format.
26  *
27  * The implementation is complete and there have been no reports of failures
28  * for some time.
29  *
30  * TODO:
31  *
32  *   o Check whether the return values are correct
33  *
34  */
35
36 #include "config.h"
37
38 #include <string.h>
39 #include <ctype.h>
40 #include <sys/types.h>
41 #include <stdarg.h>
42 #include <stdio.h>
43 #ifdef HAVE_UNISTD_H
44 # include <unistd.h>
45 #endif
46
47 #include "windef.h"
48 #include "winbase.h"
49 #include "lzexpand.h"
50
51 #include "wine/unicode.h"
52 #include "wine/debug.h"
53
54 WINE_DEFAULT_DEBUG_CHANNEL(file);
55
56 /* The readahead length of the decompressor. Reading single bytes
57  * using _lread() would be SLOW.
58  */
59 #define GETLEN  2048
60
61 #define LZ_MAGIC_LEN    8
62 #define LZ_HEADER_LEN   14
63
64 /* Format of first 14 byte of LZ compressed file */
65 struct lzfileheader {
66         BYTE    magic[LZ_MAGIC_LEN];
67         BYTE    compressiontype;
68         CHAR    lastchar;
69         DWORD   reallength;
70 };
71 static const BYTE LZMagic[LZ_MAGIC_LEN]={'S','Z','D','D',0x88,0xf0,0x27,0x33};
72
73 #define LZ_TABLE_SIZE    0x1000
74
75 struct lzstate {
76         HFILE   realfd;         /* the real filedescriptor */
77         CHAR    lastchar;       /* the last char of the filename */
78
79         DWORD   reallength;     /* the decompressed length of the file */
80         DWORD   realcurrent;    /* the position the decompressor currently is */
81         DWORD   realwanted;     /* the position the user wants to read from */
82
83         BYTE    table[LZ_TABLE_SIZE];   /* the rotating LZ table */
84         UINT    curtabent;      /* CURrent TABle ENTry */
85
86         BYTE    stringlen;      /* length and position of current string */
87         DWORD   stringpos;      /* from stringtable */
88
89
90         WORD    bytetype;       /* bitmask within blocks */
91
92         BYTE    *get;           /* GETLEN bytes */
93         DWORD   getcur;         /* current read */
94         DWORD   getlen;         /* length last got */
95 };
96
97 #define MAX_LZSTATES 16
98 static struct lzstate *lzstates[MAX_LZSTATES];
99
100 #define LZ_MIN_HANDLE  0x400
101 #define IS_LZ_HANDLE(h) (((h) >= LZ_MIN_HANDLE) && ((h) < LZ_MIN_HANDLE+MAX_LZSTATES))
102 #define GET_LZ_STATE(h) (IS_LZ_HANDLE(h) ? lzstates[(h)-LZ_MIN_HANDLE] : NULL)
103
104 /* reads one compressed byte, including buffering */
105 #define GET(lzs,b)      _lzget(lzs,&b)
106 #define GET_FLUSH(lzs)  lzs->getcur=lzs->getlen;
107
108 static int
109 _lzget(struct lzstate *lzs,BYTE *b) {
110         if (lzs->getcur<lzs->getlen) {
111                 *b              = lzs->get[lzs->getcur++];
112                 return          1;
113         } else {
114                 int ret = _lread(lzs->realfd,lzs->get,GETLEN);
115                 if (ret==HFILE_ERROR)
116                         return HFILE_ERROR;
117                 if (ret==0)
118                         return 0;
119                 lzs->getlen     = ret;
120                 lzs->getcur     = 1;
121                 *b              = *(lzs->get);
122                 return 1;
123         }
124 }
125 /* internal function, reads lzheader
126  * returns BADINHANDLE for non filedescriptors
127  * return 0 for file not compressed using LZ
128  * return UNKNOWNALG for unknown algorithm
129  * returns lzfileheader in *head
130  */
131 static INT read_header(HFILE fd,struct lzfileheader *head)
132 {
133         BYTE    buf[LZ_HEADER_LEN];
134
135         if (_llseek(fd,0,SEEK_SET)==-1)
136                 return LZERROR_BADINHANDLE;
137
138         /* We can't directly read the lzfileheader struct due to
139          * structure element alignment
140          */
141         if (_lread(fd,buf,LZ_HEADER_LEN)<LZ_HEADER_LEN)
142                 return 0;
143         memcpy(head->magic,buf,LZ_MAGIC_LEN);
144         memcpy(&(head->compressiontype),buf+LZ_MAGIC_LEN,1);
145         memcpy(&(head->lastchar),buf+LZ_MAGIC_LEN+1,1);
146
147         /* FIXME: consider endianness on non-intel architectures */
148         memcpy(&(head->reallength),buf+LZ_MAGIC_LEN+2,4);
149
150         if (memcmp(head->magic,LZMagic,LZ_MAGIC_LEN))
151                 return 0;
152         if (head->compressiontype!='A')
153                 return LZERROR_UNKNOWNALG;
154         return 1;
155 }
156
157
158 /***********************************************************************
159  *           LZStart   (KERNEL32.@)
160  */
161 INT WINAPI LZStart(void)
162 {
163     TRACE("(void)\n");
164     return 1;
165 }
166
167
168 /***********************************************************************
169  *           LZInit   (KERNEL32.@)
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         int     i, ret;
185
186         TRACE("(%d)\n",hfSrc);
187         ret=read_header(hfSrc,&head);
188         if (ret<=0) {
189                 _llseek(hfSrc,0,SEEK_SET);
190                 return ret?ret:hfSrc;
191         }
192         for (i = 0; i < MAX_LZSTATES; i++) if (!lzstates[i]) break;
193         if (i == MAX_LZSTATES) return LZERROR_GLOBALLOC;
194         lzstates[i] = lzs = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*lzs) );
195         if(lzs == NULL) return LZERROR_GLOBALLOC;
196
197         lzs->realfd     = hfSrc;
198         lzs->lastchar   = head.lastchar;
199         lzs->reallength = head.reallength;
200
201         lzs->get        = HeapAlloc( GetProcessHeap(), 0, GETLEN );
202         lzs->getlen     = 0;
203         lzs->getcur     = 0;
204
205         if(lzs->get == NULL) {
206                 HeapFree(GetProcessHeap(), 0, lzs);
207                 lzstates[i] = NULL;
208                 return LZERROR_GLOBALLOC;
209         }
210
211         /* Yes, preinitialize with spaces */
212         memset(lzs->table,' ',LZ_TABLE_SIZE);
213         /* Yes, start 16 byte from the END of the table */
214         lzs->curtabent  = 0xff0;
215         return LZ_MIN_HANDLE + i;
216 }
217
218
219 /***********************************************************************
220  *           LZDone   (KERNEL32.@)
221  */
222 void WINAPI LZDone(void)
223 {
224     TRACE("(void)\n");
225 }
226
227
228 /***********************************************************************
229  *           GetExpandedNameA   (KERNEL32.@)
230  *
231  * gets the full filename of the compressed file 'in' by opening it
232  * and reading the header
233  *
234  * "file." is being translated to "file"
235  * "file.bl_" (with lastchar 'a') is being translated to "file.bla"
236  * "FILE.BL_" (with lastchar 'a') is being translated to "FILE.BLA"
237  */
238
239 INT WINAPI GetExpandedNameA( LPSTR in, LPSTR out )
240 {
241         struct lzfileheader     head;
242         HFILE           fd;
243         OFSTRUCT        ofs;
244         INT             fnislowercased,ret,len;
245         LPSTR           s,t;
246
247         TRACE("(%s)\n",in);
248         fd=OpenFile(in,&ofs,OF_READ);
249         if (fd==HFILE_ERROR)
250                 return (INT)(INT16)LZERROR_BADINHANDLE;
251         strcpy(out,in);
252         ret=read_header(fd,&head);
253         if (ret<=0) {
254                 /* not a LZ compressed file, so the expanded name is the same
255                  * as the input name */
256                 _lclose(fd);
257                 return 1;
258         }
259
260
261         /* look for directory prefix and skip it. */
262         s=out;
263         while (NULL!=(t=strpbrk(s,"/\\:")))
264                 s=t+1;
265
266         /* now mangle the basename */
267         if (!*s) {
268                 /* FIXME: hmm. shouldn't happen? */
269                 WARN("Specified a directory or what? (%s)\n",in);
270                 _lclose(fd);
271                 return 1;
272         }
273         /* see if we should use lowercase or uppercase on the last char */
274         fnislowercased=1;
275         t=s+strlen(s)-1;
276         while (t>=out) {
277                 if (!isalpha(*t)) {
278                         t--;
279                         continue;
280                 }
281                 fnislowercased=islower(*t);
282                 break;
283         }
284         if (isalpha(head.lastchar)) {
285                 if (fnislowercased)
286                         head.lastchar=tolower(head.lastchar);
287                 else
288                         head.lastchar=toupper(head.lastchar);
289         }
290
291         /* now look where to replace the last character */
292         if (NULL!=(t=strchr(s,'.'))) {
293                 if (t[1]=='\0') {
294                         t[0]='\0';
295                 } else {
296                         len=strlen(t)-1;
297                         if (t[len]=='_')
298                                 t[len]=head.lastchar;
299                 }
300         } /* else no modification necessary */
301         _lclose(fd);
302         return 1;
303 }
304
305
306 /***********************************************************************
307  *           GetExpandedNameW   (KERNEL32.@)
308  */
309 INT WINAPI GetExpandedNameW( LPWSTR in, LPWSTR out )
310 {
311     INT ret;
312     DWORD len = WideCharToMultiByte( CP_ACP, 0, in, -1, NULL, 0, NULL, NULL );
313     char *xin = HeapAlloc( GetProcessHeap(), 0, len );
314     char *xout = HeapAlloc( GetProcessHeap(), 0, len+3 );
315     WideCharToMultiByte( CP_ACP, 0, in, -1, xin, len, NULL, NULL );
316     if ((ret = GetExpandedNameA( xin, xout )) > 0)
317         MultiByteToWideChar( CP_ACP, 0, xout, -1, out, strlenW(in)+4 );
318     HeapFree( GetProcessHeap(), 0, xin );
319     HeapFree( GetProcessHeap(), 0, xout );
320     return ret;
321 }
322
323
324 /***********************************************************************
325  *           LZRead   (KERNEL32.@)
326  */
327 INT WINAPI LZRead( HFILE fd, LPSTR vbuf, INT toread )
328 {
329         int     howmuch;
330         BYTE    b,*buf;
331         struct  lzstate *lzs;
332
333         buf=(LPBYTE)vbuf;
334         TRACE("(%d,%p,%d)\n",fd,buf,toread);
335         howmuch=toread;
336         if (!(lzs = GET_LZ_STATE(fd))) return _lread(fd,buf,toread);
337
338 /* The decompressor itself is in a define, cause we need it twice
339  * in this function. (the decompressed byte will be in b)
340  */
341 #define DECOMPRESS_ONE_BYTE                                             \
342                 if (lzs->stringlen) {                                   \
343                         b               = lzs->table[lzs->stringpos];   \
344                         lzs->stringpos  = (lzs->stringpos+1)&0xFFF;     \
345                         lzs->stringlen--;                               \
346                 } else {                                                \
347                         if (!(lzs->bytetype&0x100)) {                   \
348                                 if (1!=GET(lzs,b))                      \
349                                         return toread-howmuch;          \
350                                 lzs->bytetype = b|0xFF00;               \
351                         }                                               \
352                         if (lzs->bytetype & 1) {                        \
353                                 if (1!=GET(lzs,b))                      \
354                                         return toread-howmuch;          \
355                         } else {                                        \
356                                 BYTE    b1,b2;                          \
357                                                                         \
358                                 if (1!=GET(lzs,b1))                     \
359                                         return toread-howmuch;          \
360                                 if (1!=GET(lzs,b2))                     \
361                                         return toread-howmuch;          \
362                                 /* Format:                              \
363                                  * b1 b2                                \
364                                  * AB CD                                \
365                                  * where CAB is the stringoffset in the table\
366                                  * and D+3 is the len of the string     \
367                                  */                                     \
368                                 lzs->stringpos  = b1|((b2&0xf0)<<4);    \
369                                 lzs->stringlen  = (b2&0xf)+2;           \
370                                 /* 3, but we use a  byte already below ... */\
371                                 b               = lzs->table[lzs->stringpos];\
372                                 lzs->stringpos  = (lzs->stringpos+1)&0xFFF;\
373                         }                                               \
374                         lzs->bytetype>>=1;                              \
375                 }                                                       \
376                 /* store b in table */                                  \
377                 lzs->table[lzs->curtabent++]= b;                        \
378                 lzs->curtabent  &= 0xFFF;                               \
379                 lzs->realcurrent++;
380
381         /* if someone has seeked, we have to bring the decompressor
382          * to that position
383          */
384         if (lzs->realcurrent!=lzs->realwanted) {
385                 /* if the wanted position is before the current position
386                  * I see no easy way to unroll ... We have to restart at
387                  * the beginning. *sigh*
388                  */
389                 if (lzs->realcurrent>lzs->realwanted) {
390                         /* flush decompressor state */
391                         _llseek(lzs->realfd,LZ_HEADER_LEN,SEEK_SET);
392                         GET_FLUSH(lzs);
393                         lzs->realcurrent= 0;
394                         lzs->bytetype   = 0;
395                         lzs->stringlen  = 0;
396                         memset(lzs->table,' ',LZ_TABLE_SIZE);
397                         lzs->curtabent  = 0xFF0;
398                 }
399                 while (lzs->realcurrent<lzs->realwanted) {
400                         DECOMPRESS_ONE_BYTE;
401                 }
402         }
403
404         while (howmuch) {
405                 DECOMPRESS_ONE_BYTE;
406                 lzs->realwanted++;
407                 *buf++          = b;
408                 howmuch--;
409         }
410         return  toread;
411 #undef DECOMPRESS_ONE_BYTE
412 }
413
414
415 /***********************************************************************
416  *           LZSeek   (KERNEL32.@)
417  */
418 LONG WINAPI LZSeek( HFILE fd, LONG off, INT type )
419 {
420         struct  lzstate *lzs;
421         LONG    newwanted;
422
423         TRACE("(%d,%d,%d)\n",fd,off,type);
424         /* not compressed? just use normal _llseek() */
425         if (!(lzs = GET_LZ_STATE(fd))) return _llseek(fd,off,type);
426         newwanted = lzs->realwanted;
427         switch (type) {
428         case 1: /* SEEK_CUR */
429                 newwanted      += off;
430                 break;
431         case 2: /* SEEK_END */
432                 newwanted       = lzs->reallength-off;
433                 break;
434         default:/* SEEK_SET */
435                 newwanted       = off;
436                 break;
437         }
438         if (newwanted>lzs->reallength)
439                 return LZERROR_BADVALUE;
440         if (newwanted<0)
441                 return LZERROR_BADVALUE;
442         lzs->realwanted = newwanted;
443         return newwanted;
444 }
445
446
447 /***********************************************************************
448  *           LZCopy   (KERNEL32.@)
449  *
450  * Copies everything from src to dest
451  * if src is a LZ compressed file, it will be uncompressed.
452  * will return the number of bytes written to dest or errors.
453  */
454 LONG WINAPI LZCopy( HFILE src, HFILE dest )
455 {
456         int     usedlzinit = 0, ret, wret;
457         LONG    len;
458         HFILE   oldsrc = src, srcfd;
459         FILETIME filetime;
460         struct  lzstate *lzs;
461 #define BUFLEN  1000
462         CHAR    buf[BUFLEN];
463         /* we need that weird typedef, for i can't seem to get function pointer
464          * casts right. (Or they probably just do not like WINAPI in general)
465          */
466         typedef UINT    (WINAPI *_readfun)(HFILE,LPVOID,UINT);
467
468         _readfun        xread;
469
470         TRACE("(%d,%d)\n",src,dest);
471         if (!IS_LZ_HANDLE(src)) {
472                 src = LZInit(src);
473                 if ((INT)src <= 0) return 0;
474                 if (src != oldsrc) usedlzinit=1;
475         }
476
477         /* not compressed? just copy */
478         if (!IS_LZ_HANDLE(src))
479                 xread=_lread;
480         else
481                 xread=(_readfun)LZRead;
482         len=0;
483         while (1) {
484                 ret=xread(src,buf,BUFLEN);
485                 if (ret<=0) {
486                         if (ret==0)
487                                 break;
488                         if (ret==-1)
489                                 return LZERROR_READ;
490                         return ret;
491                 }
492                 len    += ret;
493                 wret    = _lwrite(dest,buf,ret);
494                 if (wret!=ret)
495                         return LZERROR_WRITE;
496         }
497
498         /* Maintain the timestamp of source file to destination file */
499         srcfd = (!(lzs = GET_LZ_STATE(src))) ? src : lzs->realfd;
500         GetFileTime( LongToHandle(srcfd), NULL, NULL, &filetime );
501         SetFileTime( LongToHandle(dest), NULL, NULL, &filetime );
502
503         /* close handle */
504         if (usedlzinit)
505                 LZClose(src);
506         return len;
507 #undef BUFLEN
508 }
509
510 /* reverses GetExpandedPathname */
511 static LPSTR LZEXPAND_MangleName( LPCSTR fn )
512 {
513     char *p;
514     char *mfn = HeapAlloc( GetProcessHeap(), 0, strlen(fn) + 3 ); /* "._" and \0 */
515     if(mfn == NULL) return NULL;
516     strcpy( mfn, fn );
517     if (!(p = strrchr( mfn, '\\' ))) p = mfn;
518     if ((p = strchr( p, '.' )))
519     {
520         p++;
521         if (strlen(p) < 3) strcat( p, "_" );  /* append '_' */
522         else p[strlen(p)-1] = '_';  /* replace last character */
523     }
524     else strcat( mfn, "._" );   /* append "._" */
525     return mfn;
526 }
527
528
529 /***********************************************************************
530  *           LZOpenFileA   (KERNEL32.@)
531  *
532  * Opens a file. If not compressed, open it as a normal file.
533  */
534 HFILE WINAPI LZOpenFileA( LPSTR fn, LPOFSTRUCT ofs, WORD mode )
535 {
536         HFILE   fd,cfd;
537
538         TRACE("(%s,%p,%d)\n",fn,ofs,mode);
539         /* 0x70 represents all OF_SHARE_* flags, ignore them for the check */
540         fd=OpenFile(fn,ofs,mode);
541         if (fd==HFILE_ERROR)
542         {
543             LPSTR mfn = LZEXPAND_MangleName(fn);
544             fd = OpenFile(mfn,ofs,mode);
545             HeapFree( GetProcessHeap(), 0, mfn );
546         }
547         if ((mode&~0x70)!=OF_READ)
548                 return fd;
549         if (fd==HFILE_ERROR)
550                 return HFILE_ERROR;
551         cfd=LZInit(fd);
552         if ((INT)cfd <= 0) return fd;
553         return cfd;
554 }
555
556
557 /***********************************************************************
558  *           LZOpenFileW   (KERNEL32.@)
559  */
560 HFILE WINAPI LZOpenFileW( LPWSTR fn, LPOFSTRUCT ofs, WORD mode )
561 {
562     HFILE ret;
563     DWORD len = WideCharToMultiByte( CP_ACP, 0, fn, -1, NULL, 0, NULL, NULL );
564     LPSTR xfn = HeapAlloc( GetProcessHeap(), 0, len );
565     WideCharToMultiByte( CP_ACP, 0, fn, -1, xfn, len, NULL, NULL );
566     ret = LZOpenFileA(xfn,ofs,mode);
567     HeapFree( GetProcessHeap(), 0, xfn );
568     return ret;
569 }
570
571
572 /***********************************************************************
573  *           LZClose   (KERNEL32.@)
574  */
575 void WINAPI LZClose( HFILE fd )
576 {
577         struct lzstate *lzs;
578
579         TRACE("(%d)\n",fd);
580         if (!(lzs = GET_LZ_STATE(fd))) _lclose(fd);
581         else
582         {
583             HeapFree( GetProcessHeap(), 0, lzs->get );
584             CloseHandle( LongToHandle(lzs->realfd) );
585             lzstates[fd - LZ_MIN_HANDLE] = NULL;
586             HeapFree( GetProcessHeap(), 0, lzs );
587         }
588 }