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