* Removed all Id tags.
[cacao.git] / src / vmcore / zip.c
1 /* src/vmcore/zip.c - ZIP file handling for bootstrap classloader
2
3    Copyright (C) 1996-2005, 2006, 2007 R. Grafl, A. Krall, C. Kruegel,
4    C. Oates, R. Obermaisser, M. Platter, M. Probst, S. Ring,
5    E. Steiner, C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich,
6    J. Wenninger, Institut f. Computersprachen - TU Wien
7
8    This file is part of CACAO.
9
10    This program is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License as
12    published by the Free Software Foundation; either version 2, or (at
13    your option) any later version.
14
15    This program is distributed in the hope that it will be useful, but
16    WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23    02110-1301, USA.
24
25 */
26
27
28 #include "config.h"
29
30 #include <assert.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34 #include <zlib.h>
35 #include <sys/mman.h>
36
37 #include "vm/types.h"
38
39 #include "toolbox/hashtable.h"
40
41 #include "mm/memory.h"
42
43 #include "vm/global.h"
44 #include "vm/vm.h"
45
46 #include "vmcore/suck.h"
47 #include "vmcore/utf8.h"
48 #include "vmcore/zip.h"
49
50
51 /* start size for classes hashtable *******************************************/
52
53 #define HASHTABLE_CLASSES_SIZE    (1 << 10)
54
55
56 /* info taken from:
57    http://www.pkware.com/business_and_developers/developer/popups/appnote.txt
58 */
59
60 /* all signatures in the ZIP file have a length of 4 bytes ********************/
61
62 #define SIGNATURE_LENGTH    4
63
64 /* Central directory structure *************************************************
65
66    [file header 1]
67    .
68    .
69    . 
70    [file header n]
71    [digital signature] 
72    
73    File header:
74    
75      central file header signature   4 bytes  (0x02014b50)
76      version made by                 2 bytes
77      version needed to extract       2 bytes
78      general purpose bit flag        2 bytes
79      compression method              2 bytes
80      last mod file time              2 bytes
81      last mod file date              2 bytes
82      crc-32                          4 bytes
83      compressed size                 4 bytes
84      uncompressed size               4 bytes
85      file name length                2 bytes
86      extra field length              2 bytes
87      file comment length             2 bytes
88      disk number start               2 bytes
89      internal file attributes        2 bytes
90      external file attributes        4 bytes
91      relative offset of local header 4 bytes
92    
93      file name (variable size)
94      extra field (variable size)
95      file comment (variable size)
96
97    Digital signature:
98    
99      header signature                4 bytes  (0x05054b50)
100      size of data                    2 bytes
101      signature data (variable size)
102
103 *******************************************************************************/
104
105 #define CDSFH_HEADER_SIZE            46
106
107 #define CDSFH_SIGNATURE              0x02014b50
108 #define CDSFH_COMPRESSION_METHOD     10
109 #define CDSFH_COMPRESSED_SIZE        20
110 #define CDSFH_UNCOMPRESSED_SIZE      24
111 #define CDSFH_FILE_NAME_LENGTH       28
112 #define CDSFH_EXTRA_FIELD_LENGTH     30
113 #define CDSFH_FILE_COMMENT_LENGTH    32
114 #define CDSFH_RELATIVE_OFFSET        42
115 #define CDSFH_FILENAME               46
116
117 typedef struct cdsfh cdsfh;
118
119 struct cdsfh {
120         u2 compressionmethod;
121         u4 compressedsize;
122         u4 uncompressedsize;
123         u2 filenamelength;
124         u2 extrafieldlength;
125         u2 filecommentlength;
126         u4 relativeoffset;
127 };
128
129
130 /* End of central directory record *********************************************
131
132    end of central dir signature    4 bytes  (0x06054b50)
133    number of this disk             2 bytes
134    number of the disk with the
135    start of the central directory  2 bytes
136    total number of entries in the
137    central directory on this disk  2 bytes
138    total number of entries in
139    the central directory           2 bytes
140    size of the central directory   4 bytes
141    offset of start of central
142    directory with respect to
143    the starting disk number        4 bytes
144    .ZIP file comment length        2 bytes
145    .ZIP file comment       (variable size)
146
147 *******************************************************************************/
148
149 #define EOCDR_SIGNATURE              0x06054b50
150 #define EOCDR_ENTRIES                10
151 #define EOCDR_OFFSET                 16
152
153 typedef struct eocdr eocdr;
154
155 struct eocdr {
156         u2 entries;
157         u4 offset;
158 };
159
160
161 /* zip_open ********************************************************************
162
163    XXX
164
165 *******************************************************************************/
166
167 hashtable *zip_open(char *path)
168 {
169         hashtable               *ht;
170         hashtable_zipfile_entry *htzfe;
171         int                      fd;
172         u1                       lfh_signature[SIGNATURE_LENGTH];
173         off_t                    len;
174         u1                      *filep;
175         s4                       i;
176         u1                      *p;
177         eocdr                    eocdr;
178         cdsfh                    cdsfh;
179         const char              *filename;
180         const char              *classext;
181         utf                     *u;
182         u4                       key;       /* hashkey computed from utf-text     */
183         u4                       slot;      /* slot in hashtable                  */
184
185         /* first of all, open the file */
186
187         if ((fd = open(path, O_RDONLY)) == -1)
188                 return NULL;
189
190         /* check for signature in first local file header */
191
192         if (read(fd, lfh_signature, SIGNATURE_LENGTH) != SIGNATURE_LENGTH)
193                 return NULL;
194
195         if (SUCK_LE_U4(lfh_signature) != LFH_SIGNATURE)
196                 return NULL;
197
198         /* get the file length */
199
200         if ((len = lseek(fd, 0, SEEK_END)) == -1)
201                 return NULL;
202
203         /* we better mmap the file */
204
205         filep = mmap(0, len, PROT_READ, MAP_PRIVATE, fd, 0);
206
207         /* some older compilers, like DEC OSF cc, don't like comparisons
208        on void* types */
209
210         if ((ptrint) filep == (ptrint) MAP_FAILED)
211                 return NULL;
212
213         /* find end of central directory record */
214
215         for (p = filep + len; p >= filep; p--)
216                 if (SUCK_LE_U4(p) == EOCDR_SIGNATURE)
217                         break;
218
219         /* get number of entries in central directory */
220
221         eocdr.entries = SUCK_LE_U2(p + EOCDR_ENTRIES);
222         eocdr.offset  = SUCK_LE_U4(p + EOCDR_OFFSET);
223
224         /* create hashtable for filenames */
225
226         ht = NEW(hashtable);
227
228         hashtable_create(ht, HASHTABLE_CLASSES_SIZE);
229
230         /* add all file entries into the hashtable */
231
232         for (i = 0, p = filep + eocdr.offset; i < eocdr.entries; i++) {
233                 /* check file header signature */
234
235                 if (SUCK_LE_U4(p) != CDSFH_SIGNATURE)
236                         return NULL;
237
238                 /* we found an entry */
239
240                 cdsfh.compressionmethod = SUCK_LE_U2(p + CDSFH_COMPRESSION_METHOD);
241                 cdsfh.compressedsize    = SUCK_LE_U4(p + CDSFH_COMPRESSED_SIZE);
242                 cdsfh.uncompressedsize  = SUCK_LE_U4(p + CDSFH_UNCOMPRESSED_SIZE);
243                 cdsfh.filenamelength    = SUCK_LE_U2(p + CDSFH_FILE_NAME_LENGTH);
244                 cdsfh.extrafieldlength  = SUCK_LE_U2(p + CDSFH_EXTRA_FIELD_LENGTH);
245                 cdsfh.filecommentlength = SUCK_LE_U2(p + CDSFH_FILE_COMMENT_LENGTH);
246                 cdsfh.relativeoffset    = SUCK_LE_U4(p + CDSFH_RELATIVE_OFFSET);
247
248                 /* create utf8 string of filename, strip .class from classes */
249
250                 filename = (const char *) (p + CDSFH_FILENAME);
251                 classext = filename + cdsfh.filenamelength - strlen(".class");
252
253                 /* skip directory entries */
254
255                 if (filename[cdsfh.filenamelength - 1] != '/') {
256                         if (strncmp(classext, ".class", strlen(".class")) == 0)
257                                 u = utf_new(filename, cdsfh.filenamelength - strlen(".class"));
258                         else
259                                 u = utf_new(filename, cdsfh.filenamelength);
260
261                         /* insert class into hashtable */
262
263                         htzfe = NEW(hashtable_zipfile_entry);
264
265                         htzfe->filename          = u;
266                         htzfe->compressionmethod = cdsfh.compressionmethod;
267                         htzfe->compressedsize    = cdsfh.compressedsize;
268                         htzfe->uncompressedsize  = cdsfh.uncompressedsize;
269                         htzfe->data              = filep + cdsfh.relativeoffset;
270
271                         /* get hashtable slot */
272
273                         key  = utf_hashkey(u->text, u->blength);
274                         slot = key & (ht->size - 1);
275
276                         /* insert into external chain */
277
278                         htzfe->hashlink = ht->ptr[slot];
279
280                         /* insert hashtable zipfile entry */
281
282                         ht->ptr[slot] = htzfe;
283                         ht->entries++;
284                 }
285
286                 /* move to next central directory structure file header */
287
288                 p = p +
289                         CDSFH_HEADER_SIZE +
290                         cdsfh.filenamelength +
291                         cdsfh.extrafieldlength +
292                         cdsfh.filecommentlength;
293         }
294
295         /* return pointer to hashtable */
296
297         return ht;
298 }
299
300
301 /* zip_find ********************************************************************
302
303    Search for the given filename in the classpath entries of a zip file.
304
305    NOTE: The '.class' extension is stripped when reading a zip file, so if
306    you want to find a .class file, you must search for its name _without_
307    the '.class' extension. 
308    XXX I dont like that, it makes foo and foo.class ambiguous. -Edwin
309
310    IN:
311       lce..........the classpath entries for the zip file
312           u............the filename to look for
313
314    RETURN VALUE:
315       hashtable_zipfile_entry * of the entry if found, or
316           NULL if not found
317
318 *******************************************************************************/
319
320 hashtable_zipfile_entry *zip_find(list_classpath_entry *lce, utf *u)
321 {
322         hashtable               *ht;
323         u4                       key;       /* hashkey computed from utf-text     */
324         u4                       slot;      /* slot in hashtable                  */
325         hashtable_zipfile_entry *htzfe;     /* hashtable element                  */
326
327         /* get classes hashtable from the classpath entry */
328
329         ht = lce->htclasses;
330
331         /* get the hashtable slot of the name searched */
332
333         key   = utf_hashkey(u->text, u->blength);
334         slot  = key & (ht->size - 1);
335         htzfe = ht->ptr[slot];
336
337         /* search external hash chain for utf-symbol */
338
339         while (htzfe) {
340                 if (htzfe->filename == u)
341                         return htzfe;
342
343                 /* next element in external chain */
344
345                 htzfe = htzfe->hashlink;
346         }
347
348         /* file not found in this archive */
349
350         return NULL;
351 }
352
353
354 /* zip_get ********************************************************************
355
356    XXX
357
358 *******************************************************************************/
359
360 classbuffer *zip_get(list_classpath_entry *lce, classinfo *c)
361 {
362         hashtable_zipfile_entry *htzfe;
363         lfh                      lfh;
364         u1                      *indata;
365         u1                      *outdata;
366         z_stream                 zs;
367         int                      err;
368         classbuffer             *cb;
369
370         /* try to find the class in the current archive */
371
372         htzfe = zip_find(lce, c->name);
373
374         if (htzfe == NULL)
375                 return NULL;
376
377         /* read stuff from local file header */
378
379         lfh.filenamelength   = SUCK_LE_U2(htzfe->data + LFH_FILE_NAME_LENGTH);
380         lfh.extrafieldlength = SUCK_LE_U2(htzfe->data + LFH_EXTRA_FIELD_LENGTH);
381
382         indata = htzfe->data +
383                 LFH_HEADER_SIZE +
384                 lfh.filenamelength +
385                 lfh.extrafieldlength;
386
387         /* allocate buffer for uncompressed data */
388
389         outdata = MNEW(u1, htzfe->uncompressedsize);
390
391         /* how is the file stored? */
392
393         switch (htzfe->compressionmethod) {
394         case Z_DEFLATED:
395                 /* fill z_stream structure */
396
397                 zs.next_in   = indata;
398                 zs.avail_in  = htzfe->compressedsize;
399                 zs.next_out  = outdata;
400                 zs.avail_out = htzfe->uncompressedsize;
401
402                 zs.zalloc = Z_NULL;
403                 zs.zfree  = Z_NULL;
404                 zs.opaque = Z_NULL;
405
406                 /* initialize this inflate run */
407
408                 if (inflateInit2(&zs, -MAX_WBITS) != Z_OK)
409                         vm_abort("zip_get: inflateInit2 failed: %s", strerror(errno));
410
411                 /* decompress the file into buffer */
412
413                 err = inflate(&zs, Z_SYNC_FLUSH);
414
415                 if ((err != Z_STREAM_END) && (err != Z_OK))
416                         vm_abort("zip_get: inflate failed: %s", strerror(errno));
417
418                 /* finish this inflate run */
419
420                 if (inflateEnd(&zs) != Z_OK)
421                         vm_abort("zip_get: inflateEnd failed: %s", strerror(errno));
422                 break;
423
424         case 0:
425                 /* uncompressed file, just copy the data */
426                 MCOPY(outdata, indata, u1, htzfe->compressedsize);
427                 break;
428
429         default:
430                 vm_abort("zip_get: unknown compression method %d",
431                                  htzfe->compressionmethod);
432         }
433         
434         /* allocate classbuffer */
435
436         cb = NEW(classbuffer);
437
438         cb->class = c;
439         cb->size  = htzfe->uncompressedsize;
440         cb->data  = outdata;
441         cb->pos   = outdata;
442         cb->path  = lce->path;
443
444         /* return the filled classbuffer structure */
445
446         return cb;
447 }
448
449
450 /*
451  * These are local overrides for various environment variables in Emacs.
452  * Please do not remove this and leave it at the end of the file, where
453  * Emacs will automagically detect them.
454  * ---------------------------------------------------------------------
455  * Local variables:
456  * mode: c
457  * indent-tabs-mode: t
458  * c-basic-offset: 4
459  * tab-width: 4
460  * End:
461  * vim:noexpandtab:sw=4:ts=4:
462  */