1 /*
2 * Copyright (c) 2015, 2025, 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 <string.h>
33
34 #include "jimage.hpp"
35
36 #include "imageFile.hpp"
37
38 #include "jni_util.h"
39
40 /*
41 * Declare jimage library specific JNI_Onload entry for static build.
42 */
43 extern "C" {
44 DEF_STATIC_JNI_OnLoad
45 }
46
47 /*
48 * JImageOpen - Given the supplied full path file name, open an image file. This
49 * function will also initialize tables and retrieve meta-data necessary to
50 * satisfy other functions in the API. If the image file has been previously
51 * open, a new open request will share memory and resources used by the previous
52 * open. A call to JImageOpen should be balanced by a call to JImageClose, to
53 * release memory and resources used. If the image file is not found or cannot
54 * be open, then NULL is returned and error will contain a reason for the
55 * failure; a positive value for a system error number, negative for a jimage
56 * specific error (see JImage Error Codes.)
57 *
58 * Ex.
59 * jint error;
60 * JImageFile* jimage = (*JImageOpen)(JAVA_HOME "lib/modules", &error);
61 * if (image == NULL) {
62 * tty->print_cr("JImage failed to open: %d", error);
63 * ...
64 * }
65 * ...
66 */
67 extern "C" JNIEXPORT JImageFile*
68 JIMAGE_Open(const char *name, jint* error) {
69 // TODO - return a meaningful error code
70 *error = 0;
71 ImageFileReader* jfile = ImageFileReader::open(name);
72 return (JImageFile*) jfile;
73 }
74
75 /*
76 * JImageClose - Given the supplied open image file (see JImageOpen), release
77 * memory and resources used by the open file and close the file. If the image
78 * file is shared by other uses, release and close is deferred until the last use
79 * is also closed.
80 *
81 * Ex.
82 * (*JImageClose)(image);
83 */
84 extern "C" JNIEXPORT void
85 JIMAGE_Close(JImageFile* image) {
86 ImageFileReader::close((ImageFileReader*) image);
87 }
88
89 /*
90 * JImageFindResource - Given an open image file (see JImageOpen), a module
91 * name, a version string and the name of a class/resource, return location
92 * information describing the resource and its size. If no resource is found, the
93 * function returns JIMAGE_NOT_FOUND and the value of size is undefined.
94 * The resulting location does/should not have to be released.
95 * All strings are utf-8, zero byte terminated.
96 *
97 * Ex.
98 * jlong size;
99 * JImageLocationRef location = (*JImageFindResource)(image,
100 * "java.base", "java/lang/String.class", is_preview_mode, &size);
101 */
102 extern "C" JNIEXPORT JImageLocationRef
103 JIMAGE_FindResource(JImageFile* image,
104 const char* module_name, const char* name, bool is_preview_mode,
105 jlong* size) {
106 static const char str_modules[] = "modules";
107 static const char str_packages[] = "packages";
108 static const char preview_infix[] = "/META-INF/preview";
109
110 size_t module_name_len = strlen(module_name);
111 size_t name_len = strlen(name);
112 size_t preview_infix_len = strlen(preview_infix);
113 assert(module_name_len > 0 && "module name must be non-empty");
114 assert(name_len > 0 && "name must non-empty");
115
116 // Do not attempt to lookup anything of the form /modules/... or /packages/...
117 if (strncmp(module_name, str_modules, sizeof(str_modules)) == 0
118 || strncmp(module_name, str_packages, sizeof(str_packages)) == 0) {
119 return 0L;
120 }
121 // If the preview mode version of the path string is too long for the buffer,
122 // return not found (even when not in preview mode).
123 if (1 + module_name_len + preview_infix_len + 1 + name_len + 1 > IMAGE_MAX_PATH) {
124 return 0L;
125 }
126
127 // Concatenate to get full path
128 char name_buffer[IMAGE_MAX_PATH];
129 char* path;
130 { // Write the buffer with room to prepend the preview mode infix
131 // at the start (saves copying the trailing name part twice).
132 size_t index = preview_infix_len;
133 name_buffer[index++] = '/';
134 memcpy(&name_buffer[index], module_name, module_name_len);
135 index += module_name_len;
136 name_buffer[index++] = '/';
137 memcpy(&name_buffer[index], name, name_len);
138 index += name_len;
139 name_buffer[index++] = '\0';
140 // Path begins at the leading '/' (not the start of the buffer).
141 path = &name_buffer[preview_infix_len];
142 }
143
144 // find_location_index() returns the data "offset", not an index.
145 const ImageFileReader* image_file = (ImageFileReader*) image;
146 u4 locOffset = image_file->find_location_index(path, (u8*) size);
147 if (locOffset != 0) {
148 ImageLocation loc;
149 loc.set_data(image_file->get_location_offset_data(locOffset));
150
151 u4 flags = loc.get_preview_flags();
152 // No preview flags means "a normal resource, without a preview version".
153 // This is the overwhelmingly common case, with or without preview mode.
154 if (flags == 0) {
155 return locOffset;
156 }
157 // Regardless of preview mode, don't return resources requested directly
158 // via their preview path.
159 if ((flags & ImageLocation::FLAGS_IS_PREVIEW_VERSION) != 0) {
160 return 0L;
161 }
162 // Even if there is a preview version, we might not want to return it.
163 if (!is_preview_mode || (flags & ImageLocation::FLAGS_HAS_PREVIEW_VERSION) == 0) {
164 return locOffset;
165 }
166 } else if (!is_preview_mode) {
167 // No normal resource found, and not in preview mode.
168 return 0L;
169 }
170
171 // We are in preview mode, and the preview version of the resource is needed.
172 // This is either because:
173 // 1. The normal resource was flagged as having a preview version (rare)
174 // 2. This is a preview-only resource (there was no normal resource, very rare)
175 // 3. The requested resource doesn't exist (this should typically not happen)
176 //
177 // Since we only expect requests for resources which exist in jimage files, we
178 // expect this 2nd lookup to succeed (this is contrary to the expectations for
179 // the JRT file system, where non-existent resource lookups are common).
180
181 { // Rewrite the front of the name buffer to make it a preview path.
182 size_t index = 0;
183 name_buffer[index++] = '/';
184 memcpy(&name_buffer[index], module_name, module_name_len);
185 index += module_name_len;
186 memcpy(&name_buffer[index], preview_infix, preview_infix_len);
187 index += preview_infix_len;
188 // Check we copied up to the expected '/' separator.
189 assert(name_buffer[index] == '/' && "bad string concatenation");
190 // The preview path now begins at the start of the buffer.
191 path = &name_buffer[0];
192 }
193 return image_file->find_location_index(path, (u8*) size);
194 }
195
196 /*
197 * JImageGetResource - Given an open image file (see JImageOpen), a resource's
198 * location information (see JImageFindResource), a buffer of appropriate
199 * size and the size, retrieve the bytes associated with the
200 * resource. If the size is less than the resource size then the read is truncated.
201 * If the size is greater than the resource size then the remainder of the buffer
202 * is zero filled. The function will return the actual size of the resource.
203 *
204 * Ex.
205 * jlong size;
206 * JImageLocationRef location = (*JImageFindResource)(image,
207 * "java.base", "9.0", "java/lang/String.class", &size);
208 * char* buffer = new char[size];
209 * (*JImageGetResource)(image, location, buffer, size);
210 */
211 extern "C" JNIEXPORT jlong
212 JIMAGE_GetResource(JImageFile* image, JImageLocationRef location,
213 char* buffer, jlong size) {
214 ((ImageFileReader*) image)->get_resource((u4) location, (u1*) buffer);
215 return size;
216 }
217
218 /*
219 * JImageResourceIterator - Given an open image file (see JImageOpen), a visitor
220 * function and a visitor argument, iterator through each of the image's resources.
221 * The visitor function is called with the image file, the module name, the
222 * package name, the base name, the extension and the visitor argument. The return
223 * value of the visitor function should be true, unless an early iteration exit is
224 * required. All strings are utf-8, zero byte terminated.file.
225 *
226 * Ex.
227 * bool ctw_visitor(JImageFile* jimage, const char* module_name, const char* version,
228 * const char* package, const char* name, const char* extension, void* arg) {
229 * if (strcmp(extension, "class") == 0) {
230 * char path[JIMAGE_MAX_PATH];
231 * Thread* THREAD = Thread::current();
232 * jio_snprintf(path, JIMAGE_MAX_PATH - 1, "/%s/%s", package, name);
233 * ClassLoader::compile_the_world_in(path, (Handle)arg, THREAD);
234 * return !HAS_PENDING_EXCEPTION;
235 * }
236 * return true;
237 * }
238 * (*JImageResourceIterator)(image, ctw_visitor, loader);
239 */
240 extern "C" JNIEXPORT void
241 JIMAGE_ResourceIterator(JImageFile* image,
242 JImageResourceVisitor_t visitor, void* arg) {
243 ImageFileReader* imageFile = (ImageFileReader*) image;
244 u4 nEntries = imageFile->table_length();
245 const ImageStrings strings = imageFile->get_strings();
246 for (u4 i = 0; i < nEntries; i++) {
247 ImageLocation location(imageFile->get_location_data(i));
248
249 u4 moduleOffset = (u4) location.get_attribute(ImageLocation::ATTRIBUTE_MODULE);
250 if (moduleOffset == 0) {
251 continue; // skip non-modules
252 }
253 const char *module = strings.get(moduleOffset);
254 if (strcmp(module, "modules") == 0
255 || strcmp(module, "packages") == 0) {
256 continue; // always skip
257 }
258
259 u4 parentOffset = (u4) location.get_attribute(ImageLocation::ATTRIBUTE_PARENT);
260 const char *parent = strings.get(parentOffset);
261 u4 baseOffset = (u4) location.get_attribute(ImageLocation::ATTRIBUTE_BASE);
262 const char *base = strings.get(baseOffset);
263 u4 extOffset = (u4) location.get_attribute(ImageLocation::ATTRIBUTE_EXTENSION);
264 const char *extension = strings.get(extOffset);
265
266 if (!(*visitor)(image, module, "9", parent, base, extension, arg)) {
267 break;
268 }
269 }
270 }