OSDN Git Service

2006-01-24 Dirk Mueller <dmueller@suse.de>
[pf3gnuchains/gcc-fork.git] / gcc / java / zextract.c
1 /* Handle a .class file embedded in a .zip archive.
2    This extracts a member from a .zip file, but does not handle
3    uncompression (since that is not needed for classes.zip).
4    Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005
5    Free Software Foundation, Inc.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING.  If not, write to
21 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
22 Boston, MA 02110-1301, USA.  
23
24 Java and all Java-based marks are trademarks or registered trademarks
25 of Sun Microsystems, Inc. in the United States and other countries.
26 The Free Software Foundation is independent of Sun Microsystems, Inc.  */
27
28 /* Written by Per Bothner <bothner@cygnus.com>, February 1996. */
29
30 #include "config.h"
31 #include "system.h"
32 #include "coretypes.h"
33 #include "tm.h"
34 #include "zipfile.h"
35
36 /* This stuff is partly based on the 28 August 1994 public release of the
37 Info-ZIP group's portable UnZip zipfile-extraction program (and related
38 utilities). */
39
40 /*************/
41 /*  Defines  */
42 /*************/
43
44 #define UNZIP
45 #define UNZIP_VERSION     20   /* compatible with PKUNZIP 2.0 */
46 #define VMS_UNZIP_VERSION 42   /* if OS-needed-to-extract is VMS:  can do */
47
48
49 #define ZSUFX             ".zip"
50 #define CENTRAL_HDR_SIG   "\113\001\002"   /* the infamous "PK" signature */
51 #define LOCAL_HDR_SIG     "\113\003\004"   /*  bytes, sans "P" (so unzip */
52 #define END_CENTRAL_SIG   "\113\005\006"   /*  executable not mistaken for */
53 #define EXTD_LOCAL_SIG    "\113\007\010"   /*  zipfile itself) */
54
55 #define STORED            0    /* compression methods */
56 #define SHRUNK            1
57 #define REDUCED1          2
58 #define REDUCED2          3
59 #define REDUCED3          4
60 #define REDUCED4          5
61 #define IMPLODED          6
62 #define TOKENIZED         7
63 #define DEFLATED          8
64 #define NUM_METHODS       9    /* index of last method + 1 */
65 /* don't forget to update list_files() appropriately if NUM_METHODS changes */
66
67 #define PK_OK             0    /* no error */
68 #define PK_COOL           0    /* no error */
69 #define PK_GNARLY         0    /* no error */
70 #define PK_WARN           1    /* warning error */
71 #define PK_ERR            2    /* error in zipfile */
72 #define PK_BADERR         3    /* severe error in zipfile */
73 #define PK_MEM            4    /* insufficient memory */
74 #define PK_MEM2           5    /* insufficient memory */
75 #define PK_MEM3           6    /* insufficient memory */
76 #define PK_MEM4           7    /* insufficient memory */
77 #define PK_MEM5           8    /* insufficient memory */
78 #define PK_NOZIP          9    /* zipfile not found */
79 #define PK_PARAM          10   /* bad or illegal parameters specified */
80 #define PK_FIND           11   /* no files found */
81 #define PK_DISK           50   /* disk full */
82 #define PK_EOF            51   /* unexpected EOF */
83
84 /*---------------------------------------------------------------------------
85     True sizes of the various headers, as defined by PKWARE--so it is not
86     likely that these will ever change.  But if they do, make sure both these
87     defines AND the typedefs below get updated accordingly.
88   ---------------------------------------------------------------------------*/
89 #define LREC_SIZE     26    /* lengths of local file headers, central */
90 #define CREC_SIZE     42    /*  directory headers, and the end-of-    */
91 #define ECREC_SIZE    18    /*  central-dir record, respectively      */
92
93
94 #ifndef SEEK_SET
95 #  define SEEK_SET  0
96 #  define SEEK_CUR  1
97 #  define SEEK_END  2
98 #endif
99
100 /**************/
101 /*  Typedefs  */
102 /**************/
103
104 typedef char              boolean;
105 typedef unsigned char     uch;  /* code assumes unsigned bytes; these type-  */
106 typedef unsigned short    ush;  /*  defs replace byte/UWORD/ULONG (which are */
107 typedef unsigned long     ulg;  /*  predefined on some systems) & match zip  */
108
109 /*---------------------------------------------------------------------------
110     Zipfile layout declarations.  If these headers ever change, make sure the
111     xxREC_SIZE defines (above) change with them!
112   ---------------------------------------------------------------------------*/
113
114    typedef uch   local_byte_hdr[ LREC_SIZE ];
115 #      define L_VERSION_NEEDED_TO_EXTRACT_0     0
116 #      define L_VERSION_NEEDED_TO_EXTRACT_1     1
117 #      define L_GENERAL_PURPOSE_BIT_FLAG        2
118 #      define L_COMPRESSION_METHOD              4
119 #      define L_LAST_MOD_FILE_TIME              6
120 #      define L_LAST_MOD_FILE_DATE              8
121 #      define L_CRC32                           10
122 #      define L_COMPRESSED_SIZE                 14
123 #      define L_UNCOMPRESSED_SIZE               18
124 #      define L_FILENAME_LENGTH                 22
125 #      define L_EXTRA_FIELD_LENGTH              24
126
127   typedef uch   cdir_byte_hdr[ CREC_SIZE ];
128 #      define C_VERSION_MADE_BY_0               0
129 #      define C_VERSION_MADE_BY_1               1
130 #      define C_VERSION_NEEDED_TO_EXTRACT_0     2
131 #      define C_VERSION_NEEDED_TO_EXTRACT_1     3
132 #      define C_GENERAL_PURPOSE_BIT_FLAG        4
133 #      define C_COMPRESSION_METHOD              6
134 #      define C_LAST_MOD_FILE_TIME              8
135 #      define C_LAST_MOD_FILE_DATE              10
136 #      define C_CRC32                           12
137 #      define C_COMPRESSED_SIZE                 16
138 #      define C_UNCOMPRESSED_SIZE               20
139 #      define C_FILENAME_LENGTH                 24
140 #      define C_EXTRA_FIELD_LENGTH              26
141 #      define C_FILE_COMMENT_LENGTH             28
142 #      define C_DISK_NUMBER_START               30
143 #      define C_INTERNAL_FILE_ATTRIBUTES        32
144 #      define C_EXTERNAL_FILE_ATTRIBUTES        34
145 #      define C_RELATIVE_OFFSET_LOCAL_HEADER    38
146
147    typedef uch   ec_byte_rec[ ECREC_SIZE+4 ];
148 /*     define SIGNATURE                         0   space-holder only */
149 #      define NUMBER_THIS_DISK                  4
150 #      define NUM_DISK_WITH_START_CENTRAL_DIR   6
151 #      define NUM_ENTRIES_CENTRL_DIR_THS_DISK   8
152 #      define TOTAL_ENTRIES_CENTRAL_DIR         10
153 #      define SIZE_CENTRAL_DIRECTORY            12
154 #      define OFFSET_START_CENTRAL_DIRECTORY    16
155 #      define ZIPFILE_COMMENT_LENGTH            20
156
157
158    typedef struct local_file_header {                 /* LOCAL */
159        uch version_needed_to_extract[2];
160        ush general_purpose_bit_flag;
161        ush compression_method;
162        ush last_mod_file_time;
163        ush last_mod_file_date;
164        ulg crc32;
165        ulg csize;
166        ulg ucsize;
167        ush filename_length;
168        ush extra_field_length;
169    } local_file_hdr;
170
171    typedef struct central_directory_file_header {     /* CENTRAL */
172        uch version_made_by[2];
173        uch version_needed_to_extract[2];
174        ush general_purpose_bit_flag;
175        ush compression_method;
176        ush last_mod_file_time;
177        ush last_mod_file_date;
178        ulg crc32;
179        ulg csize;
180        ulg ucsize;
181        ush filename_length;
182        ush extra_field_length;
183        ush file_comment_length;
184        ush disk_number_start;
185        ush internal_file_attributes;
186        ulg external_file_attributes;
187        ulg relative_offset_local_header;
188    } cdir_file_hdr;
189
190    typedef struct end_central_dir_record {            /* END CENTRAL */
191        ush number_this_disk;
192        ush num_disk_with_start_central_dir;
193        ush num_entries_centrl_dir_ths_disk;
194        ush total_entries_central_dir;
195        ulg size_central_directory;
196        ulg offset_start_central_directory;
197        ush zipfile_comment_length;
198    } ecdir_rec;
199
200
201 /************/
202 /*  Macros  */
203 /************/
204
205 #ifndef MAX
206 #  define MAX(a,b)   ((a) > (b) ? (a) : (b))
207 #endif
208 #ifndef MIN
209 #  define MIN(a,b)   ((a) < (b) ? (a) : (b))
210 #endif
211
212
213 /***********************/
214 /* Prototypes          */
215 /***********************/
216
217 static ush makeword (const uch *);
218 static ulg makelong (const uch *);
219 static long find_zip_file_start (int fd, long offset);
220
221 /***********************/
222 /* Function makeword() */
223 /***********************/
224
225 static ush makeword(const uch *b)
226 {
227     /*
228      * Convert Intel style 'short' integer to non-Intel non-16-bit
229      * host format.  This routine also takes care of byte-ordering.
230      */
231     return (ush)((b[1] << 8) | b[0]);
232 }
233
234
235 /***********************/
236 /* Function makelong() */
237 /***********************/
238
239 static ulg
240 makelong (const uch *sig)
241 {
242     /*
243      * Convert intel style 'long' variable to non-Intel non-16-bit
244      * host format.  This routine also takes care of byte-ordering.
245      */
246     return (((ulg)sig[3]) << 24)
247         + (((ulg)sig[2]) << 16)
248         + (((ulg)sig[1]) << 8)
249         + ((ulg)sig[0]);
250 }
251
252 /* Examine file's header in zip file and return the offset of the
253    start of the actual data.  Return -1 on error.  OFFSET is the
254    offset from the beginning of the zip file of the file's header.  */
255 static long
256 find_zip_file_start (int fd, long offset)
257 {
258   int filename_length, extra_field_length;
259   unsigned char buffer[LREC_SIZE + 4];
260
261   if (lseek (fd, offset, SEEK_SET) < 0)
262     return -1;
263
264   if (read (fd, buffer, LREC_SIZE + 4) != LREC_SIZE + 4)
265     return -1;
266
267   if (buffer[0] != 'P' || strncmp ((const char *) &buffer[1], LOCAL_HDR_SIG, 3))
268     return -1;
269
270   filename_length = makeword (&buffer[4 + L_FILENAME_LENGTH]);
271   extra_field_length = makeword (&buffer[4 + L_EXTRA_FIELD_LENGTH]);
272
273   return offset + (4 + LREC_SIZE) + filename_length + extra_field_length;
274 }
275
276 int
277 read_zip_archive (ZipFile *zipf)
278 {
279   int i;
280   int dir_last_pad;
281   char *dir_ptr;
282   char buffer[100];
283
284   zipf->size = lseek (zipf->fd, 0L, SEEK_END);
285
286   if (zipf->size < (ECREC_SIZE+4) || lseek (zipf->fd, (long)(-(ECREC_SIZE+4)), SEEK_CUR) <= 0)
287     return -1;
288   if (read (zipf->fd, buffer, ECREC_SIZE+4) != ECREC_SIZE+4)
289     return -2;
290   if (buffer[0] != 'P'
291       || strncmp ((const char *) &buffer[1], END_CENTRAL_SIG, 3))
292     {
293       /* We could not find the end-central-header signature, probably
294          because a zipfile comment is present. Scan backwards until we
295          find the signature. */
296       if (lseek (zipf->fd, (long)(-ECREC_SIZE), SEEK_END) <= 0)
297         return -2;
298       while (buffer[0] != 'P'
299              || strncmp ((const char *) &buffer[1], END_CENTRAL_SIG, 3))
300         {
301           if (lseek (zipf->fd, -5, SEEK_CUR) < 0)
302             return -2;
303           if (read (zipf->fd, buffer, 4) != 4)
304             return -2;
305         }
306       if (read (zipf->fd, buffer + 4, ECREC_SIZE) != ECREC_SIZE)
307         return -2;
308     }
309   zipf->count = makeword((const uch *) &buffer[TOTAL_ENTRIES_CENTRAL_DIR]);
310   zipf->dir_size = makelong((const uch *) &buffer[SIZE_CENTRAL_DIRECTORY]);
311 #define ALLOC xmalloc
312   /* Allocate 1 more to allow appending '\0' to last filename. */
313   zipf->central_directory = ALLOC (zipf->dir_size+1);
314   if (lseek (zipf->fd, -(zipf->dir_size+ECREC_SIZE+4), SEEK_CUR) < 0)
315     return -2;
316   if (read (zipf->fd, zipf->central_directory, zipf->dir_size) < 0)
317     return -2;
318
319 #ifdef TEST
320   printf ("number_this_disk = %d\n", makeword(&buffer[NUMBER_THIS_DISK]));
321   printf ("num_disk_with_start_central_dir = %d\n", makeword(&buffer[NUM_DISK_WITH_START_CENTRAL_DIR]));
322
323   printf ("num_entries_centrl_dir_ths_disk = %d\n",
324         makeword(&buffer[NUM_ENTRIES_CENTRL_DIR_THS_DISK]));
325   printf ("total_entries_central_dir = %d\n",
326         makeword(&buffer[TOTAL_ENTRIES_CENTRAL_DIR]));
327   printf ("size_central_directory = %d\n",
328         makelong((const uch *) &buffer[SIZE_CENTRAL_DIRECTORY]));
329   printf ("offset_start_central_directory = %d\n",
330         makelong((const uch *) &buffer[OFFSET_START_CENTRAL_DIRECTORY]));
331   printf ("zipfile_comment_length = %d\n",
332         makeword(&buffer[ZIPFILE_COMMENT_LENGTH]));
333 #endif
334
335   dir_last_pad = 0;
336   dir_ptr = zipf->central_directory;
337   for (i = 0; i < zipf->count; i++)
338     {
339       ZipDirectory *zipd = (ZipDirectory*)(dir_ptr + dir_last_pad);
340       int compression_method = (int) dir_ptr[4+C_COMPRESSION_METHOD];
341       long size = makelong ((const uch *) &dir_ptr[4+C_COMPRESSED_SIZE]);
342       long uncompressed_size = makelong ((const uch *) &dir_ptr[4+C_UNCOMPRESSED_SIZE]);
343       long filename_length = makeword ((const uch *) &dir_ptr[4+C_FILENAME_LENGTH]);
344       long extra_field_length = makeword ((const uch *) &dir_ptr[4+C_EXTRA_FIELD_LENGTH]);
345       long file_offset = makelong ((const uch *) &dir_ptr[4+C_RELATIVE_OFFSET_LOCAL_HEADER]);
346       int unpadded_direntry_length;
347       if ((dir_ptr-zipf->central_directory)+filename_length+CREC_SIZE+4>zipf->dir_size)
348         return -1;
349
350       zipd->filename_length = filename_length;
351       zipd->compression_method = compression_method;
352       zipd->size = size;
353       zipd->uncompressed_size = uncompressed_size;
354       zipd->zipf = zipf;
355 #ifdef __GNUC__
356 #define DIR_ALIGN __alignof__(ZipDirectory)
357 #else
358 #define DIR_ALIGN sizeof(long)
359 #endif
360       zipd->filestart = find_zip_file_start (zipf->fd, file_offset);
361       zipd->filename_offset = CREC_SIZE+4 - dir_last_pad;
362       unpadded_direntry_length 
363           = zipd->filename_offset + zipd->filename_length + extra_field_length;
364       zipd->direntry_size =
365         ((unpadded_direntry_length + DIR_ALIGN) / DIR_ALIGN) * DIR_ALIGN;
366       dir_last_pad = zipd->direntry_size - unpadded_direntry_length;
367       dir_ptr = (char*)zipd + unpadded_direntry_length;
368       *dir_ptr = '\0';
369     }
370   return 0;
371 }
372
373 #ifdef TEST
374 main (void)
375 {
376   ZipFile zipf[1];
377   ZipDirectory *zipd;
378   int i;
379
380   zipf->fd = 0;
381
382   i = read_zip_archive (zipf);
383   if (i)
384     {
385       fprintf (stderr, "Bad zip file.\n");
386       exit (i);
387     }
388
389   zipd = (ZipDirectory*) zipf->central_directory;
390   for (i = 0; i < zipf->count; i++, zipd = ZIPDIR_NEXT (zipd))
391     {
392       printf ("%d: size:%d, name(#%d)%s, offset:%d\n",
393               i, zipd->size, zipd->filename_length,
394               ZIPDIR_FILENAME (zipd),
395               zipd->filestart);
396     }
397 }
398 #endif