* configure.ac: New switch for disabling -O2 (--disable-optimizations).
[cacao.git] / src / vm / zip.cpp
1 /* src/vm/zip.cpp - 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 <unistd.h>
31 #include <zlib.h>
32
33 #include "vm/types.h"
34
35 #include "vm/descriptor.hpp" /* needed to prevent circular dependency */
36 #include "toolbox/hashtable.h"
37
38 #include "mm/memory.hpp"
39
40 #include "vm/global.h"
41 #include "vm/os.hpp"
42 #include "vm/suck.hpp"
43 #include "vm/utf8.h"
44 #include "vm/vm.hpp"
45 #include "vm/zip.hpp"
46
47
48 /* start size for classes hashtable *******************************************/
49
50 #define HASHTABLE_CLASSES_SIZE    (1 << 10)
51
52
53 /* info taken from:
54    http://www.pkware.com/business_and_developers/developer/popups/appnote.txt
55 */
56
57 /* all signatures in the ZIP file have a length of 4 bytes ********************/
58
59 #define SIGNATURE_LENGTH    4
60
61 /* Central directory structure *************************************************
62
63    [file header 1]
64    .
65    .
66    . 
67    [file header n]
68    [digital signature] 
69    
70    File header:
71    
72      central file header signature   4 bytes  (0x02014b50)
73      version made by                 2 bytes
74      version needed to extract       2 bytes
75      general purpose bit flag        2 bytes
76      compression method              2 bytes
77      last mod file time              2 bytes
78      last mod file date              2 bytes
79      crc-32                          4 bytes
80      compressed size                 4 bytes
81      uncompressed size               4 bytes
82      file name length                2 bytes
83      extra field length              2 bytes
84      file comment length             2 bytes
85      disk number start               2 bytes
86      internal file attributes        2 bytes
87      external file attributes        4 bytes
88      relative offset of local header 4 bytes
89    
90      file name (variable size)
91      extra field (variable size)
92      file comment (variable size)
93
94    Digital signature:
95    
96      header signature                4 bytes  (0x05054b50)
97      size of data                    2 bytes
98      signature data (variable size)
99
100 *******************************************************************************/
101
102 #define CDSFH_HEADER_SIZE            46
103
104 #define CDSFH_SIGNATURE              0x02014b50
105 #define CDSFH_COMPRESSION_METHOD     10
106 #define CDSFH_COMPRESSED_SIZE        20
107 #define CDSFH_UNCOMPRESSED_SIZE      24
108 #define CDSFH_FILE_NAME_LENGTH       28
109 #define CDSFH_EXTRA_FIELD_LENGTH     30
110 #define CDSFH_FILE_COMMENT_LENGTH    32
111 #define CDSFH_RELATIVE_OFFSET        42
112 #define CDSFH_FILENAME               46
113
114 typedef struct cdsfh cdsfh;
115
116 struct cdsfh {
117         u2 compressionmethod;
118         u4 compressedsize;
119         u4 uncompressedsize;
120         u2 filenamelength;
121         u2 extrafieldlength;
122         u2 filecommentlength;
123         u4 relativeoffset;
124 };
125
126
127 /* End of central directory record *********************************************
128
129    end of central dir signature    4 bytes  (0x06054b50)
130    number of this disk             2 bytes
131    number of the disk with the
132    start of the central directory  2 bytes
133    total number of entries in the
134    central directory on this disk  2 bytes
135    total number of entries in
136    the central directory           2 bytes
137    size of the central directory   4 bytes
138    offset of start of central
139    directory with respect to
140    the starting disk number        4 bytes
141    .ZIP file comment length        2 bytes
142    .ZIP file comment       (variable size)
143
144 *******************************************************************************/
145
146 #define EOCDR_SIGNATURE              0x06054b50
147 #define EOCDR_ENTRIES                10
148 #define EOCDR_OFFSET                 16
149
150 typedef struct eocdr eocdr;
151
152 struct eocdr {
153         u2 entries;
154         u4 offset;
155 };
156
157 #if defined(__cplusplus)
158 extern "C" {
159 #endif
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 = (u1*) 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 = (hashtable_zipfile_entry*) 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 = (hashtable_zipfile_entry*) 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->clazz = 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 #if defined(__cplusplus)
450 }
451 #endif
452
453 /*
454  * These are local overrides for various environment variables in Emacs.
455  * Please do not remove this and leave it at the end of the file, where
456  * Emacs will automagically detect them.
457  * ---------------------------------------------------------------------
458  * Local variables:
459  * mode: c++
460  * indent-tabs-mode: t
461  * c-basic-offset: 4
462  * tab-width: 4
463  * End:
464  * vim:noexpandtab:sw=4:ts=4:
465  */