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