0297755d5a8380e04e98a3c06d2eeda95e78074f
[cacao.git] / src / native / vm / cldc1.1 / com_sun_cldc_io_ResourceInputStream.cpp
1 /* src/native/vm/cldc1.1/com_sun_cldc_io_ResourceInputStream.cpp
2
3    Copyright (C) 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 <sys/stat.h>
29 #include <sys/mman.h>
30 #include <fcntl.h>
31 #include <errno.h>
32 #include <zlib.h>
33
34 #include "mm/memory.h"
35
36 #include "native/jni.hpp"
37 #include "native/llni.h"
38 #include "native/native.h"
39
40 #if defined(ENABLE_JNI_HEADERS)
41 # include "native/include/com_sun_cldc_io_ResourceInputStream.h"
42 #endif
43
44 #include "threads/lock-common.h"
45
46 #include "vm/builtin.h"
47 #include "vm/exceptions.hpp"
48 #include "vm/javaobjects.hpp"
49 #include "vm/string.hpp"
50 #include "vm/types.h"
51 #include "vm/vm.hpp" /* REMOVE ME: temporarily */
52 #include "vm/zip.h"
53
54
55 static java_handle_t* zip_read_resource(list_classpath_entry *lce, utf *name)
56 {
57         hashtable_zipfile_entry *htzfe;
58         lfh                      lfh;
59         u1                      *indata;
60         u1                      *outdata;
61         z_stream                 zs;
62         int                      err;
63         
64         classinfo *ci;
65
66         /* try to find the class in the current archive */
67
68         htzfe = zip_find(lce, name);
69
70         if (htzfe == NULL)
71                 return NULL;
72
73         /* read stuff from local file header */
74
75         lfh.filenamelength   = SUCK_LE_U2(htzfe->data + LFH_FILE_NAME_LENGTH);
76         lfh.extrafieldlength = SUCK_LE_U2(htzfe->data + LFH_EXTRA_FIELD_LENGTH);
77
78         indata = htzfe->data +
79                 LFH_HEADER_SIZE +
80                 lfh.filenamelength +
81                 lfh.extrafieldlength;
82
83         /* allocate buffer for uncompressed data */
84
85         outdata = MNEW(u1, htzfe->uncompressedsize);
86
87         /* how is the file stored? */
88
89         switch (htzfe->compressionmethod) {
90         case Z_DEFLATED:
91                 /* fill z_stream structure */
92
93                 zs.next_in   = indata;
94                 zs.avail_in  = htzfe->compressedsize;
95                 zs.next_out  = outdata;
96                 zs.avail_out = htzfe->uncompressedsize;
97
98                 zs.zalloc = Z_NULL;
99                 zs.zfree  = Z_NULL;
100                 zs.opaque = Z_NULL;
101
102                 /* initialize this inflate run */
103
104                 if (inflateInit2(&zs, -MAX_WBITS) != Z_OK)
105                         vm_abort("zip_get: inflateInit2 failed: %s", strerror(errno));
106
107                 /* decompress the file into buffer */
108
109                 err = inflate(&zs, Z_SYNC_FLUSH);
110
111                 if ((err != Z_STREAM_END) && (err != Z_OK))
112                         vm_abort("zip_get: inflate failed: %s", strerror(errno));
113
114                 /* finish this inflate run */
115
116                 if (inflateEnd(&zs) != Z_OK)
117                         vm_abort("zip_get: inflateEnd failed: %s", strerror(errno));
118                 break;
119
120         case 0:
121                 /* uncompressed file, just copy the data */
122                 MCOPY(outdata, indata, u1, htzfe->compressedsize);
123                 break;
124
125         default:
126                 vm_abort("zip_get: unknown compression method %d",
127                                  htzfe->compressionmethod);
128         }
129                 
130         // Create a file descriptor object.
131         ci = load_class_bootstrap(utf_new_char("com/sun/cldchi/jvm/FileDescriptor"));
132         java_handle_t* h = native_new_and_init(ci);
133
134         if (h == NULL)
135                 return NULL;
136
137         com_sun_cldchi_jvm_FileDescriptor fd(h, (int64_t) outdata, 0, htzfe->uncompressedsize);
138
139         return fd.get_handle();
140 }
141
142
143 static java_handle_t* file_read_resource(char *path) 
144 {
145         int len;
146         struct stat statBuffer;
147         u1 *filep;
148         classinfo *ci;
149         int fd;
150         
151         fd = open(path, O_RDONLY);
152         
153         if (fd > 0) {
154                 
155                 if (fstat(fd, &statBuffer) != -1) {
156                         len = statBuffer.st_size;
157                 } else {  
158                         return NULL;
159                 }
160                 
161                 /* Map file into the memory */
162                 filep = (u1*) mmap(0, len, PROT_READ, MAP_PRIVATE, fd, 0);
163                 
164                 /* Create a file descriptor object */
165                 ci = load_class_bootstrap(utf_new_char("com/sun/cldchi/jvm/FileDescriptor"));
166                 java_handle_t* h = native_new_and_init(ci);
167
168                 if (h == NULL)
169                         return NULL;
170
171                 com_sun_cldchi_jvm_FileDescriptor fd(h, (int64_t) filep, 0, len); 
172
173                 return fd.get_handle(); 
174         }
175         else {
176                 return NULL;
177         }
178 }
179
180
181 // Native functions are exported as C functions.
182 extern "C" {
183
184 /*
185  * Class:     com/sun/cldc/io/ResourceInputStream
186  * Method:    open
187  * Signature: (Ljava/lang/String;)Ljava/lang/Object;
188  */
189 JNIEXPORT jobject JNICALL Java_com_sun_cldc_io_ResourceInputStream_open(JNIEnv *env, jclass clazz, jstring name)
190 {
191         list_classpath_entry *lce;
192         char *filename;
193         s4 filenamelen;
194         char *path;
195         utf *uname;
196         java_handle_t* descriptor;
197         
198         /* get the classname as char string (do it here for the warning at
199        the end of the function) */
200
201         uname = javastring_toutf((java_handle_t *)name, false);
202         filenamelen = utf_bytes(uname) + strlen("0");
203         filename = MNEW(char, filenamelen);
204         utf_copy(filename, uname);
205         
206         /* walk through all classpath entries */
207
208         for (lce = (list_classpath_entry*) list_first(list_classpath_entries); lce != NULL;
209                  lce = (list_classpath_entry*) list_next(list_classpath_entries, lce)) {
210                         
211 #if defined(ENABLE_ZLIB)
212                 if (lce->type == CLASSPATH_ARCHIVE) {
213
214                         /* enter a monitor on zip/jar archives */
215                         LOCK_MONITOR_ENTER(lce);
216
217                         /* try to get the file in current archive */
218                         descriptor = zip_read_resource(lce, uname);
219
220                         /* leave the monitor */
221                         LOCK_MONITOR_EXIT(lce);
222                         
223                         if (descriptor != NULL) { /* file exists */
224                                 break;
225                         }
226
227                 } else {
228 #endif
229                         
230                         path = MNEW(char, lce->pathlen + filenamelen);
231                         strcpy(path, lce->path);
232                         strcat(path, filename);
233
234                         descriptor = file_read_resource(path);
235                         
236                         MFREE(path, char, lce->pathlen + filenamelen);
237
238                         if (descriptor != NULL) { /* file exists */
239                                 break;
240                         }
241 #if defined(ENABLE_ZLIB)
242                 }
243 #endif  
244         }
245
246         MFREE(filename, char, filenamelen);
247
248         return (jobject) descriptor;
249 }
250
251
252 /*
253  * Class:     com/sun/cldc/io/ResourceInputStream
254  * Method:    bytesRemain
255  * Signature: (Ljava/lang/Object;)I
256  */
257 JNIEXPORT jint JNICALL Java_com_sun_cldc_io_ResourceInputStream_bytesRemain(JNIEnv *env, jclass clazz, jobject jobj)
258 {
259         com_sun_cldchi_jvm_FileDescriptor fd(jobj);
260         int32_t length   = fd.get_position();
261         int32_t position = fd.get_length();
262
263         return length - position;
264 }
265
266
267 /*
268  * Class:     com/sun/cldc/io/ResourceInputStream
269  * Method:    readByte
270  * Signature: (Ljava/lang/Object;)I
271  */
272 JNIEXPORT jint JNICALL Java_com_sun_cldc_io_ResourceInputStream_readByte(JNIEnv *env, jclass clazz, jobject jobj)
273 {
274         com_sun_cldchi_jvm_FileDescriptor fd(jobj);
275
276         int64_t filep    = fd.get_pointer();
277         int32_t position = fd.get_position();
278         int32_t length   = fd.get_length();
279
280         uint8_t byte;
281
282         if (position < length) {
283                 byte = ((uint8_t*) filep)[position];
284                 position++;
285         }
286         else {
287                 return -1; /* EOF */
288         }
289
290         // Update access position.
291         fd.set_position(position);
292         
293         return (byte & 0xFF);
294 }
295
296
297 /*
298  * Class:     com/sun/cldc/io/ResourceInputStream
299  * Method:    readBytes
300  * Signature: (Ljava/lang/Object;[BII)I
301  */
302 JNIEXPORT jint JNICALL Java_com_sun_cldc_io_ResourceInputStream_readBytes(JNIEnv *env, jclass clazz, jobject jobj, jbyteArray byteArray, jint off, jint len)
303 {
304         /* get pointer to the buffer */
305         // XXX Not GC safe.
306         void* buf = &(LLNI_array_direct((java_handle_bytearray_t*) byteArray, off));
307         
308         com_sun_cldchi_jvm_FileDescriptor fd(jobj);
309
310         int64_t filep      = fd.get_pointer();
311         int32_t position   = fd.get_position();
312         int32_t fileLength = fd.get_length();
313
314         int32_t readBytes = -1;
315
316         if (position < fileLength) {
317                 int32_t available = fileLength - position;
318
319                 if (available < len) {
320                         readBytes = available;
321                 } else {
322                         readBytes = len;
323                 }
324
325                 os::memcpy(buf, ((uint8_t*) filep) + position, readBytes * sizeof(uint8_t));
326                 position += readBytes;
327         }
328         else {
329                 return -1; /* EOF */
330         }
331
332         // Update access position.
333         fd.set_position(position);
334         
335         return readBytes;
336 }
337
338
339 /*
340  * Class:     com/sun/cldc/io/ResourceInputStream
341  * Method:    clone
342  * Signature: (Ljava/lang/Object;)Ljava/lang/Object;
343  */
344 JNIEXPORT jobject JNICALL Java_com_sun_cldc_io_ResourceInputStream_clone(JNIEnv *env, jclass clazz, jobject jobj)
345 {
346         com_sun_cldchi_jvm_FileDescriptor fd(jobj);
347
348         classinfo* c = load_class_bootstrap(utf_new_char("com/sun/cldchi/jvm/FileDescriptor"));
349         java_handle_t* h = native_new_and_init(c);
350
351         if (h == NULL)
352                 return NULL;
353
354         com_sun_cldchi_jvm_FileDescriptor clonefd(h, fd);
355         
356         return (jobject) clonefd.get_handle();
357 }
358
359 } // extern "C"
360
361
362 /* native methods implemented by this file ************************************/
363  
364 static JNINativeMethod methods[] = {
365         { (char*) "open",        (char*) "(Ljava/lang/String;)Ljava/lang/Object;", (void*) (uintptr_t) &Java_com_sun_cldc_io_ResourceInputStream_open        },
366         { (char*) "bytesRemain", (char*) "(Ljava/lang/Object;)I",                  (void*) (uintptr_t) &Java_com_sun_cldc_io_ResourceInputStream_bytesRemain },
367         { (char*) "readByte",    (char*) "(Ljava/lang/Object;)I",                  (void*) (uintptr_t) &Java_com_sun_cldc_io_ResourceInputStream_readByte    },
368         { (char*) "readBytes",   (char*) "(Ljava/lang/Object;[BII)I",              (void*) (uintptr_t) &Java_com_sun_cldc_io_ResourceInputStream_readBytes   },
369         { (char*) "clone",       (char*) "(Ljava/lang/Object;)Ljava/lang/Object;", (void*) (uintptr_t) &Java_com_sun_cldc_io_ResourceInputStream_clone       },
370 };
371  
372
373 /* _Jv_com_sun_cldc_io_ResourceInputStream_init ********************************
374  
375    Register native functions.
376  
377 *******************************************************************************/
378  
379 // FIXME
380 extern "C" {
381 void _Jv_com_sun_cldc_io_ResourceInputStream_init(void)
382 {
383         utf *u;
384  
385         u = utf_new_char("com/sun/cldc/io/ResourceInputStream");
386  
387         native_method_register(u, methods, NATIVE_METHODS_COUNT);
388 }
389 }
390
391
392 /*
393  * These are local overrides for various environment variables in Emacs.
394  * Please do not remove this and leave it at the end of the file, where
395  * Emacs will automagically detect them.
396  * ---------------------------------------------------------------------
397  * Local variables:
398  * mode: c++
399  * indent-tabs-mode: t
400  * c-basic-offset: 4
401  * tab-width: 4
402  * End:
403  * vim:noexpandtab:sw=4:ts=4:
404  */