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 
114     // TBD:   assert(module_name_len > 0, "module name must be non-empty");
115     assert(name_len > 0 && "resource name must be non-empty");
116 
117     // Do not attempt to lookup anything of the form /modules/... or /packages/...
118     if (strncmp(module_name, str_modules, sizeof(str_modules)) == 0
119             || strncmp(module_name, str_packages, sizeof(str_packages)) == 0) {
120         return 0L;
121     }
122     // If the preview mode version of the path string is too long for the buffer,
123     // return not found (even when not in preview mode).
124     if (1 + module_name_len + preview_infix_len + 1 + name_len + 1 > IMAGE_MAX_PATH) {
125         return 0L;
126     }
127 
128     // Concatenate to get full path
129     char name_buffer[IMAGE_MAX_PATH];
130     char* path;
131     {   // Write the buffer with room to prepend the preview mode infix
132         // at the start (saves copying the trailing name part twice).
133         size_t index = preview_infix_len;
134         name_buffer[index++] = '/';
135         memcpy(&name_buffer[index], module_name, module_name_len);
136         index += module_name_len;
137         name_buffer[index++] = '/';
138         memcpy(&name_buffer[index], name, name_len);
139         index += name_len;
140         name_buffer[index++] = '\0';
141         // Path begins at the leading '/' (not the start of the buffer).
142         path = &name_buffer[preview_infix_len];
143     }
144 
145     // find_location_index() returns the data "offset", not an index.
146     const ImageFileReader* image_file = (ImageFileReader*) image;
147     u4 locOffset = image_file->find_location_index(path, (u8*) size);
148     if (locOffset != 0) {
149         ImageLocation loc;
150         loc.set_data(image_file->get_location_offset_data(locOffset));
151 
152         u4 flags = loc.get_preview_flags();
153         // No preview flags means "a normal resource, without a preview version".
154         // This is the overwhelmingly common case, with or without preview mode.
155         if (flags == 0) {
156             return locOffset;
157         }
158         // Regardless of preview mode, don't return resources requested directly
159         // via their preview path.
160         if ((flags & ImageLocation::FLAGS_IS_PREVIEW_VERSION) != 0) {
161             return 0L;
162         }
163         // Even if there is a preview version, we might not want to return it.
164         if (!is_preview_mode || (flags & ImageLocation::FLAGS_HAS_PREVIEW_VERSION) == 0) {
165             return locOffset;
166         }
167     } else if (!is_preview_mode) {
168         // No normal resource found, and not in preview mode.
169         return 0L;
170     }
171 
172     // We are in preview mode, and the preview version of the resource is needed.
173     // This is either because:
174     // 1. The normal resource was flagged as having a preview version (rare)
175     // 2. This is a preview-only resource (there was no normal resource, very rare)
176     // 3. The requested resource doesn't exist (this should typically not happen)
177     //
178     // Since we only expect requests for resources which exist in jimage files, we
179     // expect this 2nd lookup to succeed (this is contrary to the expectations for
180     // the JRT file system, where non-existent resource lookups are common).
181 
182     {   // Rewrite the front of the name buffer to make it a preview path.
183         size_t index = 0;
184         name_buffer[index++] = '/';
185         memcpy(&name_buffer[index], module_name, module_name_len);
186         index += module_name_len;
187         memcpy(&name_buffer[index], preview_infix, preview_infix_len);
188         index += preview_infix_len;
189         // Check we copied up to the expected '/' separator.
190         assert(name_buffer[index] == '/' && "bad string concatenation");
191         // The preview path now begins at the start of the buffer.
192         path = &name_buffer[0];
193     }
194     return image_file->find_location_index(path, (u8*) size);
195 }
196 
197 /*
198  * JImageGetResource - Given an open image file (see JImageOpen), a resource's
199  * location information (see JImageFindResource), a buffer of appropriate
200  * size and the size, retrieve the bytes associated with the
201  * resource. If the size is less than the resource size then the read is truncated.
202  * If the size is greater than the resource size then the remainder of the buffer
203  * is zero filled.  The function will return the actual size of the resource.
204  *
205  * Ex.
206  *  jlong size;
207  *   JImageLocationRef location = (*JImageFindResource)(image,
208  *                                 "java.base", "9.0", "java/lang/String.class", &size);
209  *  char* buffer = new char[size];
210  *  (*JImageGetResource)(image, location, buffer, size);
211  */
212 extern "C" JNIEXPORT jlong
213 JIMAGE_GetResource(JImageFile* image, JImageLocationRef location,
214         char* buffer, jlong size) {
215     ((ImageFileReader*) image)->get_resource((u4) location, (u1*) buffer);
216     return size;
217 }
218 
219 /*
220  * JImageResourceIterator - Given an open image file (see JImageOpen), a visitor
221  * function and a visitor argument, iterator through each of the image's resources.
222  * The visitor function is called with the image file, the module name, the
223  * package name, the base name, the extension and the visitor argument. The return
224  * value of the visitor function should be true, unless an early iteration exit is
225  * required. All strings are utf-8, zero byte terminated.file.
226  *
227  * Ex.
228  *   bool ctw_visitor(JImageFile* jimage, const char* module_name, const char* version,
229  *                  const char* package, const char* name, const char* extension, void* arg) {
230  *     if (strcmp(extension, "class") == 0) {
231  *       char path[JIMAGE_MAX_PATH];
232  *       Thread* THREAD = Thread::current();
233  *       jio_snprintf(path, JIMAGE_MAX_PATH - 1, "/%s/%s", package, name);
234  *       ClassLoader::compile_the_world_in(path, (Handle)arg, THREAD);
235  *       return !HAS_PENDING_EXCEPTION;
236  *     }
237  *     return true;
238  *   }
239  *   (*JImageResourceIterator)(image, ctw_visitor, loader);
240  */
241 extern "C" JNIEXPORT void
242 JIMAGE_ResourceIterator(JImageFile* image,
243         JImageResourceVisitor_t visitor, void* arg) {
244     ImageFileReader* imageFile = (ImageFileReader*) image;
245     u4 nEntries = imageFile->table_length();
246     const ImageStrings strings = imageFile->get_strings();
247     for (u4 i = 0; i < nEntries; i++) {
248         ImageLocation location(imageFile->get_location_data(i));
249 
250         u4 moduleOffset = (u4) location.get_attribute(ImageLocation::ATTRIBUTE_MODULE);
251         if (moduleOffset == 0) {
252             continue; // skip non-modules
253         }
254         const char *module = strings.get(moduleOffset);
255         if (strcmp(module, "modules") == 0
256             || strcmp(module, "packages") == 0) {
257             continue; // always skip
258         }
259 
260         u4 parentOffset = (u4) location.get_attribute(ImageLocation::ATTRIBUTE_PARENT);
261         const char *parent = strings.get(parentOffset);
262         u4 baseOffset = (u4) location.get_attribute(ImageLocation::ATTRIBUTE_BASE);
263         const char *base = strings.get(baseOffset);
264         u4 extOffset = (u4) location.get_attribute(ImageLocation::ATTRIBUTE_EXTENSION);
265         const char *extension = strings.get(extOffset);
266 
267         if (!(*visitor)(image, module, "9", parent, base, extension, arg)) {
268             break;
269         }
270     }
271 }