1 /*
2 * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of Oracle nor the names of its
16 * contributors may be used to endorse or promote products derived
17 * from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #include <assert.h>
33 #include <string.h>
34 #include <stdlib.h>
35
36 #include "endian.hpp"
37 #include "imageDecompressor.hpp"
38 #include "imageFile.hpp"
39 #include "inttypes.hpp"
40 #include "jni.h"
41 #include "osSupport.hpp"
42
43 // Map the full jimage, only with 64 bit addressing.
44 bool ImageFileReader::memory_map_image = sizeof(void *) == 8;
45
46 #ifdef WIN32
47 const char FileSeparator = '\\';
48 #else
49 const char FileSeparator = '/';
50 #endif
51
52 // Image files are an alternate file format for storing classes and resources. The
53 // goal is to supply file access which is faster and smaller than the jar format.
54 //
55 // (More detailed nodes in the header.)
56 //
57
58 // Compute the Perfect Hashing hash code for the supplied UTF-8 string.
hash_code(const char * string,s4 seed)59 s4 ImageStrings::hash_code(const char* string, s4 seed) {
60 assert(seed > 0 && "invariant");
61 // Access bytes as unsigned.
62 u1* bytes = (u1*)string;
63 u4 useed = (u4)seed;
64 // Compute hash code.
65 for (u1 byte = *bytes++; byte; byte = *bytes++) {
66 useed = (useed * HASH_MULTIPLIER) ^ byte;
67 }
68 // Ensure the result is not signed.
69 return (s4)(useed & 0x7FFFFFFF);
70 }
71
72 // Match up a string in a perfect hash table.
73 // Returns the index where the name should be.
74 // Result still needs validation for precise match (false positive.)
find(Endian * endian,const char * name,s4 * redirect,u4 length)75 s4 ImageStrings::find(Endian* endian, const char* name, s4* redirect, u4 length) {
76 // If the table is empty, then short cut.
77 if (!redirect || !length) {
78 return NOT_FOUND;
79 }
80 // Compute the basic perfect hash for name.
81 s4 hash_code = ImageStrings::hash_code(name);
82 // Modulo table size.
83 s4 index = hash_code % length;
84 // Get redirect entry.
85 // value == 0 then not found
86 // value < 0 then -1 - value is true index
87 // value > 0 then value is seed for recomputing hash.
88 s4 value = endian->get(redirect[index]);
89 // if recompute is required.
90 if (value > 0 ) {
91 // Entry collision value, need to recompute hash.
92 hash_code = ImageStrings::hash_code(name, value);
93 // Modulo table size.
94 return hash_code % length;
95 } else if (value < 0) {
96 // Compute direct index.
97 return -1 - value;
98 }
99 // No entry found.
100 return NOT_FOUND;
101 }
102
103 // Test to see if UTF-8 string begins with the start UTF-8 string. If so,
104 // return non-NULL address of remaining portion of string. Otherwise, return
105 // NULL. Used to test sections of a path without copying from image string
106 // table.
starts_with(const char * string,const char * start)107 const char* ImageStrings::starts_with(const char* string, const char* start) {
108 char ch1, ch2;
109 // Match up the strings the best we can.
110 while ((ch1 = *string) && (ch2 = *start)) {
111 if (ch1 != ch2) {
112 // Mismatch, return NULL.
113 return NULL;
114 }
115 // Next characters.
116 string++, start++;
117 }
118 // Return remainder of string.
119 return string;
120 }
121
122 // Inflates the attribute stream into individual values stored in the long
123 // array _attributes. This allows an attribute value to be quickly accessed by
124 // direct indexing. Unspecified values default to zero (from constructor.)
set_data(u1 * data)125 void ImageLocation::set_data(u1* data) {
126 // Deflate the attribute stream into an array of attributes.
127 u1 byte;
128 // Repeat until end header is found.
129 while ((data != NULL) && (byte = *data)) {
130 // Extract kind from header byte.
131 u1 kind = attribute_kind(byte);
132 assert(kind < ATTRIBUTE_COUNT && "invalid image location attribute");
133 // Extract length of data (in bytes).
134 u1 n = attribute_length(byte);
135 // Read value (most significant first.)
136 _attributes[kind] = attribute_value(data + 1, n);
137 // Position to next attribute by skipping attribute header and data bytes.
138 data += n + 1;
139 }
140 }
141
142 // Zero all attribute values.
clear_data()143 void ImageLocation::clear_data() {
144 // Set defaults to zero.
145 memset(_attributes, 0, sizeof(_attributes));
146 }
147
148 // ImageModuleData constructor maps out sub-tables for faster access.
ImageModuleData(const ImageFileReader * image_file)149 ImageModuleData::ImageModuleData(const ImageFileReader* image_file) :
150 _image_file(image_file),
151 _endian(image_file->endian()) {
152 }
153
154 // Release module data resource.
~ImageModuleData()155 ImageModuleData::~ImageModuleData() {
156 }
157
158
159 // Return the module in which a package resides. Returns NULL if not found.
package_to_module(const char * package_name)160 const char* ImageModuleData::package_to_module(const char* package_name) {
161 // replace all '/' by '.'
162 char* replaced = new char[(int) strlen(package_name) + 1];
163 assert(replaced != NULL && "allocation failed");
164 int i;
165 for (i = 0; package_name[i] != '\0'; i++) {
166 replaced[i] = package_name[i] == '/' ? '.' : package_name[i];
167 }
168 replaced[i] = '\0';
169
170 // build path /packages/<package_name>
171 const char* radical = "/packages/";
172 char* path = new char[(int) strlen(radical) + (int) strlen(package_name) + 1];
173 assert(path != NULL && "allocation failed");
174 strcpy(path, radical);
175 strcat(path, replaced);
176 delete[] replaced;
177
178 // retrieve package location
179 ImageLocation location;
180 bool found = _image_file->find_location(path, location);
181 delete[] path;
182 if (!found) {
183 return NULL;
184 }
185
186 // retrieve offsets to module name
187 int size = (int)location.get_attribute(ImageLocation::ATTRIBUTE_UNCOMPRESSED);
188 u1* content = new u1[size];
189 assert(content != NULL && "allocation failed");
190 _image_file->get_resource(location, content);
191 u1* ptr = content;
192 // sequence of sizeof(8) isEmpty|offset. Use the first module that is not empty.
193 u4 offset = 0;
194 for (i = 0; i < size; i+=8) {
195 u4 isEmpty = _endian->get(*((u4*)ptr));
196 ptr += 4;
197 if (!isEmpty) {
198 offset = _endian->get(*((u4*)ptr));
199 break;
200 }
201 ptr += 4;
202 }
203 delete[] content;
204 return _image_file->get_strings().get(offset);
205 }
206
207 // Manage a table of open image files. This table allows multiple access points
208 // to share an open image.
ImageFileReaderTable()209 ImageFileReaderTable::ImageFileReaderTable() : _count(0), _max(_growth) {
210 _table = static_cast<ImageFileReader**>(calloc(_max, sizeof(ImageFileReader*)));
211 assert(_table != NULL && "allocation failed");
212 }
213
214 // Add a new image entry to the table.
add(ImageFileReader * image)215 void ImageFileReaderTable::add(ImageFileReader* image) {
216 if (_count == _max) {
217 _max += _growth;
218 _table = static_cast<ImageFileReader**>(realloc(_table, _max * sizeof(ImageFileReader*)));
219 }
220 _table[_count++] = image;
221 }
222
223 // Remove an image entry from the table.
remove(ImageFileReader * image)224 void ImageFileReaderTable::remove(ImageFileReader* image) {
225 for (u4 i = 0; i < _count; i++) {
226 if (_table[i] == image) {
227 // Swap the last element into the found slot
228 _table[i] = _table[--_count];
229 break;
230 }
231 }
232
233 if (_count != 0 && _count == _max - _growth) {
234 _max -= _growth;
235 _table = static_cast<ImageFileReader**>(realloc(_table, _max * sizeof(ImageFileReader*)));
236 }
237 }
238
239 // Determine if image entry is in table.
contains(ImageFileReader * image)240 bool ImageFileReaderTable::contains(ImageFileReader* image) {
241 for (u4 i = 0; i < _count; i++) {
242 if (_table[i] == image) {
243 return true;
244 }
245 }
246 return false;
247 }
248
249 // Table to manage multiple opens of an image file.
250 ImageFileReaderTable ImageFileReader::_reader_table;
251
252 SimpleCriticalSection _reader_table_lock;
253
254 // Locate an image if file already open.
find_image(const char * name)255 ImageFileReader* ImageFileReader::find_image(const char* name) {
256 // Lock out _reader_table.
257 SimpleCriticalSectionLock cs(&_reader_table_lock);
258 // Search for an exist image file.
259 for (u4 i = 0; i < _reader_table.count(); i++) {
260 // Retrieve table entry.
261 ImageFileReader* reader = _reader_table.get(i);
262 // If name matches, then reuse (bump up use count.)
263 assert(reader->name() != NULL && "reader->name must not be null");
264 if (strcmp(reader->name(), name) == 0) {
265 reader->inc_use();
266 return reader;
267 }
268 }
269
270 return NULL;
271 }
272
273 // Open an image file, reuse structure if file already open.
open(const char * name,bool big_endian)274 ImageFileReader* ImageFileReader::open(const char* name, bool big_endian) {
275 ImageFileReader* reader = find_image(name);
276 if (reader != NULL) {
277 return reader;
278 }
279
280 // Need a new image reader.
281 reader = new ImageFileReader(name, big_endian);
282 if (reader == NULL || !reader->open()) {
283 // Failed to open.
284 delete reader;
285 return NULL;
286 }
287
288 // Lock to update
289 SimpleCriticalSectionLock cs(&_reader_table_lock);
290 // Search for an existing image file.
291 for (u4 i = 0; i < _reader_table.count(); i++) {
292 // Retrieve table entry.
293 ImageFileReader* existing_reader = _reader_table.get(i);
294 // If name matches, then reuse (bump up use count.)
295 assert(reader->name() != NULL && "reader->name still must not be null");
296 if (strcmp(existing_reader->name(), name) == 0) {
297 existing_reader->inc_use();
298 reader->close();
299 delete reader;
300 return existing_reader;
301 }
302 }
303 // Bump use count and add to table.
304 reader->inc_use();
305 _reader_table.add(reader);
306 return reader;
307 }
308
309 // Close an image file if the file is not in use elsewhere.
close(ImageFileReader * reader)310 void ImageFileReader::close(ImageFileReader *reader) {
311 // Lock out _reader_table.
312 SimpleCriticalSectionLock cs(&_reader_table_lock);
313 // If last use then remove from table and then close.
314 if (reader->dec_use()) {
315 _reader_table.remove(reader);
316 delete reader;
317 }
318 }
319
320 // Return an id for the specifed ImageFileReader.
reader_to_ID(ImageFileReader * reader)321 u8 ImageFileReader::reader_to_ID(ImageFileReader *reader) {
322 // ID is just the cloaked reader address.
323 return (u8)reader;
324 }
325
326 // Validate the image id.
id_check(u8 id)327 bool ImageFileReader::id_check(u8 id) {
328 // Make sure the ID is a managed (_reader_table) reader.
329 SimpleCriticalSectionLock cs(&_reader_table_lock);
330 return _reader_table.contains((ImageFileReader*)id);
331 }
332
333 // Return an id for the specifed ImageFileReader.
id_to_reader(u8 id)334 ImageFileReader* ImageFileReader::id_to_reader(u8 id) {
335 assert(id_check(id) && "invalid image id");
336 return (ImageFileReader*)id;
337 }
338
339 // Constructor intializes to a closed state.
ImageFileReader(const char * name,bool big_endian)340 ImageFileReader::ImageFileReader(const char* name, bool big_endian) :
341 _module_data(NULL) {
342 // Copy the image file name.
343 int len = (int) strlen(name) + 1;
344 _name = new char[len];
345 assert(_name != NULL && "allocation failed");
346 strncpy(_name, name, len);
347 // Initialize for a closed file.
348 _fd = -1;
349 _endian = Endian::get_handler(big_endian);
350 _index_data = NULL;
351 }
352
353 // Close image and free up data structures.
~ImageFileReader()354 ImageFileReader::~ImageFileReader() {
355 // Ensure file is closed.
356 close();
357 // Free up name.
358 if (_name) {
359 delete[] _name;
360 _name = NULL;
361 }
362
363 if (_module_data != NULL) {
364 delete _module_data;
365 }
366 }
367
368 // Open image file for read access.
open()369 bool ImageFileReader::open() {
370 // If file exists open for reading.
371 _fd = osSupport::openReadOnly(_name);
372 if (_fd == -1) {
373 return false;
374 }
375 // Retrieve the file size.
376 _file_size = osSupport::size(_name);
377 // Read image file header and verify it has a valid header.
378 size_t header_size = sizeof(ImageHeader);
379 if (_file_size < header_size ||
380 !read_at((u1*)&_header, header_size, 0) ||
381 _header.magic(_endian) != IMAGE_MAGIC ||
382 _header.major_version(_endian) != MAJOR_VERSION ||
383 _header.minor_version(_endian) != MINOR_VERSION) {
384 close();
385 return false;
386 }
387 // Size of image index.
388 _index_size = index_size();
389 // Make sure file is large enough to contain the index.
390 if (_file_size < _index_size) {
391 return false;
392 }
393 // Memory map image (minimally the index.)
394 _index_data = (u1*)osSupport::map_memory(_fd, _name, 0, (size_t)map_size());
395 assert(_index_data && "image file not memory mapped");
396 // Retrieve length of index perfect hash table.
397 u4 length = table_length();
398 // Compute offset of the perfect hash table redirect table.
399 u4 redirect_table_offset = (u4)header_size;
400 // Compute offset of index attribute offsets.
401 u4 offsets_table_offset = redirect_table_offset + length * (u4)sizeof(s4);
402 // Compute offset of index location attribute data.
403 u4 location_bytes_offset = offsets_table_offset + length * (u4)sizeof(u4);
404 // Compute offset of index string table.
405 u4 string_bytes_offset = location_bytes_offset + locations_size();
406 // Compute address of the perfect hash table redirect table.
407 _redirect_table = (s4*)(_index_data + redirect_table_offset);
408 // Compute address of index attribute offsets.
409 _offsets_table = (u4*)(_index_data + offsets_table_offset);
410 // Compute address of index location attribute data.
411 _location_bytes = _index_data + location_bytes_offset;
412 // Compute address of index string table.
413 _string_bytes = _index_data + string_bytes_offset;
414
415 // Initialize the module data
416 _module_data = new ImageModuleData(this);
417 // Successful open (if memory allocation succeeded).
418 return _module_data != NULL;
419 }
420
421 // Close image file.
close()422 void ImageFileReader::close() {
423 // Deallocate the index.
424 if (_index_data) {
425 osSupport::unmap_memory((char*)_index_data, (size_t)map_size());
426 _index_data = NULL;
427 }
428 // Close file.
429 if (_fd != -1) {
430 osSupport::close(_fd);
431 _fd = -1;
432 }
433
434 if (_module_data != NULL) {
435 delete _module_data;
436 _module_data = NULL;
437 }
438 }
439
440 // Read directly from the file.
read_at(u1 * data,u8 size,u8 offset) const441 bool ImageFileReader::read_at(u1* data, u8 size, u8 offset) const {
442 return (u8)osSupport::read(_fd, (char*)data, size, offset) == size;
443 }
444
445 // Find the location attributes associated with the path. Returns true if
446 // the location is found, false otherwise.
find_location(const char * path,ImageLocation & location) const447 bool ImageFileReader::find_location(const char* path, ImageLocation& location) const {
448 // Locate the entry in the index perfect hash table.
449 s4 index = ImageStrings::find(_endian, path, _redirect_table, table_length());
450 // If is found.
451 if (index != ImageStrings::NOT_FOUND) {
452 // Get address of first byte of location attribute stream.
453 u1* data = get_location_data(index);
454 // Expand location attributes.
455 location.set_data(data);
456 // Make sure result is not a false positive.
457 return verify_location(location, path);
458 }
459 return false;
460 }
461
462 // Find the location index and size associated with the path.
463 // Returns the location index and size if the location is found, 0 otherwise.
find_location_index(const char * path,u8 * size) const464 u4 ImageFileReader::find_location_index(const char* path, u8 *size) const {
465 // Locate the entry in the index perfect hash table.
466 s4 index = ImageStrings::find(_endian, path, _redirect_table, table_length());
467 // If found.
468 if (index != ImageStrings::NOT_FOUND) {
469 // Get address of first byte of location attribute stream.
470 u4 offset = get_location_offset(index);
471 u1* data = get_location_offset_data(offset);
472 // Expand location attributes.
473 ImageLocation location(data);
474 // Make sure result is not a false positive.
475 if (verify_location(location, path)) {
476 *size = (jlong)location.get_attribute(ImageLocation::ATTRIBUTE_UNCOMPRESSED);
477 return offset;
478 }
479 }
480 return 0; // not found
481 }
482
483 // Verify that a found location matches the supplied path (without copying.)
verify_location(ImageLocation & location,const char * path) const484 bool ImageFileReader::verify_location(ImageLocation& location, const char* path) const {
485 // Manage the image string table.
486 ImageStrings strings(_string_bytes, _header.strings_size(_endian));
487 // Position to first character of the path string.
488 const char* next = path;
489 // Get module name string.
490 const char* module = location.get_attribute(ImageLocation::ATTRIBUTE_MODULE, strings);
491 // If module string is not empty.
492 if (*module != '\0') {
493 // Compare '/module/' .
494 if (*next++ != '/') return false;
495 if (!(next = ImageStrings::starts_with(next, module))) return false;
496 if (*next++ != '/') return false;
497 }
498 // Get parent (package) string
499 const char* parent = location.get_attribute(ImageLocation::ATTRIBUTE_PARENT, strings);
500 // If parent string is not empty string.
501 if (*parent != '\0') {
502 // Compare 'parent/' .
503 if (!(next = ImageStrings::starts_with(next, parent))) return false;
504 if (*next++ != '/') return false;
505 }
506 // Get base name string.
507 const char* base = location.get_attribute(ImageLocation::ATTRIBUTE_BASE, strings);
508 // Compare with basne name.
509 if (!(next = ImageStrings::starts_with(next, base))) return false;
510 // Get extension string.
511 const char* extension = location.get_attribute(ImageLocation::ATTRIBUTE_EXTENSION, strings);
512 // If extension is not empty.
513 if (*extension != '\0') {
514 // Compare '.extension' .
515 if (*next++ != '.') return false;
516 if (!(next = ImageStrings::starts_with(next, extension))) return false;
517 }
518 // True only if complete match and no more characters.
519 return *next == '\0';
520 }
521
522 // Return the resource for the supplied location offset.
get_resource(u4 offset,u1 * uncompressed_data) const523 void ImageFileReader::get_resource(u4 offset, u1* uncompressed_data) const {
524 // Get address of first byte of location attribute stream.
525 u1* data = get_location_offset_data(offset);
526 // Expand location attributes.
527 ImageLocation location(data);
528 // Read the data
529 get_resource(location, uncompressed_data);
530 }
531
532 // Return the resource for the supplied location.
get_resource(ImageLocation & location,u1 * uncompressed_data) const533 void ImageFileReader::get_resource(ImageLocation& location, u1* uncompressed_data) const {
534 // Retrieve the byte offset and size of the resource.
535 u8 offset = location.get_attribute(ImageLocation::ATTRIBUTE_OFFSET);
536 u8 uncompressed_size = location.get_attribute(ImageLocation::ATTRIBUTE_UNCOMPRESSED);
537 u8 compressed_size = location.get_attribute(ImageLocation::ATTRIBUTE_COMPRESSED);
538 // If the resource is compressed.
539 if (compressed_size != 0) {
540 u1* compressed_data;
541 // If not memory mapped read in bytes.
542 if (!memory_map_image) {
543 // Allocate buffer for compression.
544 compressed_data = new u1[(size_t)compressed_size];
545 assert(compressed_data != NULL && "allocation failed");
546 // Read bytes from offset beyond the image index.
547 bool is_read = read_at(compressed_data, compressed_size, _index_size + offset);
548 assert(is_read && "error reading from image or short read");
549 } else {
550 compressed_data = get_data_address() + offset;
551 }
552 // Get image string table.
553 const ImageStrings strings = get_strings();
554 // Decompress resource.
555 ImageDecompressor::decompress_resource(compressed_data, uncompressed_data, uncompressed_size,
556 &strings, _endian);
557 // If not memory mapped then release temporary buffer.
558 if (!memory_map_image) {
559 delete[] compressed_data;
560 }
561 } else {
562 // Read bytes from offset beyond the image index.
563 bool is_read = read_at(uncompressed_data, uncompressed_size, _index_size + offset);
564 assert(is_read && "error reading from image or short read");
565 }
566 }
567
568 // Return the ImageModuleData for this image
get_image_module_data()569 ImageModuleData * ImageFileReader::get_image_module_data() {
570 return _module_data;
571 }
572