1 /* 2 * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 /* 26 * @test 27 * @summary SharedArchiveConsistency 28 * @requires vm.cds 29 * @library /test/lib 30 * @modules java.base/jdk.internal.misc 31 * java.compiler 32 * java.management 33 * jdk.jartool/sun.tools.jar 34 * jdk.internal.jvmstat/sun.jvmstat.monitor 35 * @build sun.hotspot.WhiteBox 36 * @compile test-classes/Hello.java 37 * @run driver ClassFileInstaller sun.hotspot.WhiteBox 38 * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI SharedArchiveConsistency 39 */ 40 import jdk.test.lib.process.OutputAnalyzer; 41 import jdk.test.lib.Utils; 42 import java.io.File; 43 import java.io.FileInputStream; 44 import java.io.FileOutputStream; 45 import java.io.IOException; 46 import java.nio.ByteBuffer; 47 import java.nio.ByteOrder; 48 import java.nio.channels.FileChannel; 49 import java.nio.file.Files; 50 import java.nio.file.Path; 51 import java.nio.file.Paths; 52 import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; 53 import java.nio.file.StandardOpenOption; 54 import static java.nio.file.StandardOpenOption.READ; 55 import static java.nio.file.StandardOpenOption.WRITE; 56 import java.util.ArrayList; 57 import java.util.HashSet; 58 import java.util.List; 59 import java.util.Random; 60 import sun.hotspot.WhiteBox; 61 62 public class SharedArchiveConsistency { 63 public static WhiteBox wb; 64 public static int offset_magic; // FileMapHeader::_magic 65 public static int sp_offset_crc; // CDSFileMapRegion::_crc 66 public static int file_header_size = -1;// total size of header, variant, need calculation 67 public static int CDSFileMapRegion_size; // size of CDSFileMapRegion 68 public static int sp_offset; // offset of CDSFileMapRegion 69 public static int sp_used_offset; // offset of CDSFileMapRegion::_used 70 public static int size_t_size; // size of size_t 71 72 public static File jsa; // will be updated during test 73 public static File orgJsaFile; // kept the original file not touched. 74 // The following should be consistent with the enum in the C++ MetaspaceShared class 75 public static String[] shared_region_name = { 76 "mc", // MiscCode 77 "rw", // ReadWrite 78 "ro", // ReadOnly 79 "md", // MiscData 80 "first_closed_archive", 81 "last_closed_archive", 82 "first_open_archive", 83 "last_open_archive" 84 }; 85 86 public static int num_regions = shared_region_name.length; 87 public static String[] matchMessages = { 88 "Unable to use shared archive", 89 "An error has occurred while processing the shared archive file.", 90 "Checksum verification failed.", 91 "The shared archive file has been truncated." 92 }; 93 94 public static void getFileOffsetInfo() throws Exception { 95 wb = WhiteBox.getWhiteBox(); 96 offset_magic = wb.getOffsetForName("FileMapHeader::_magic"); 97 sp_offset_crc = wb.getOffsetForName("CDSFileMapRegion::_crc"); 98 try { 99 int nonExistOffset = wb.getOffsetForName("FileMapHeader::_non_exist_offset"); 100 System.exit(-1); // should fail 101 } catch (Exception e) { 102 // success 103 } 104 105 sp_offset = wb.getOffsetForName("FileMapHeader::_space[0]") - offset_magic; 106 sp_used_offset = wb.getOffsetForName("CDSFileMapRegion::_used") - sp_offset_crc; 107 size_t_size = wb.getOffsetForName("size_t_size"); 108 CDSFileMapRegion_size = wb.getOffsetForName("CDSFileMapRegion_size"); 109 } 110 111 public static int getFileHeaderSize(FileChannel fc) throws Exception { 112 if (file_header_size != -1) { 113 return file_header_size; 114 } 115 // this is not real header size, it is struct size 116 int int_size = wb.getOffsetForName("int_size"); 117 file_header_size = wb.getOffsetForName("file_header_size"); 118 int offset_path_misc_info = wb.getOffsetForName("FileMapHeader::_paths_misc_info_size") - 119 offset_magic; 120 int path_misc_info_size = (int)readInt(fc, offset_path_misc_info, int_size); 121 file_header_size += path_misc_info_size; //readInt(fc, offset_path_misc_info, size_t_size); 122 System.out.println("offset_path_misc_info = " + offset_path_misc_info); 123 System.out.println("path_misc_info_size = " + path_misc_info_size); 124 System.out.println("file_header_size = " + file_header_size); 125 file_header_size = (int)align_up_page(file_header_size); 126 System.out.println("file_header_size (aligned to page) = " + file_header_size); 127 return file_header_size; 128 } 129 130 public static long align_up_page(long l) throws Exception { 131 // wb is obtained in getFileOffsetInfo() which is called first in main() else we should call 132 // WhiteBox.getWhiteBox() here first. 133 int pageSize = wb.getVMPageSize(); 134 return (l + pageSize -1) & (~ (pageSize - 1)); 135 } 136 137 private static long getRandomBetween(long start, long end) throws Exception { 138 if (start > end) { 139 throw new IllegalArgumentException("start must be less than end"); 140 } 141 Random aRandom = Utils.getRandomInstance(); 142 int d = aRandom.nextInt((int)(end - start)); 143 if (d < 1) { 144 d = 1; 145 } 146 return start + d; 147 } 148 149 public static long readInt(FileChannel fc, long offset, int nbytes) throws Exception { 150 ByteBuffer bb = ByteBuffer.allocate(nbytes); 151 bb.order(ByteOrder.nativeOrder()); 152 fc.position(offset); 153 fc.read(bb); 154 return (nbytes > 4 ? bb.getLong(0) : bb.getInt(0)); 155 } 156 157 public static void writeData(FileChannel fc, long offset, ByteBuffer bb) throws Exception { 158 fc.position(offset); 159 fc.write(bb); 160 fc.force(true); 161 } 162 163 public static FileChannel getFileChannel() throws Exception { 164 List<StandardOpenOption> arry = new ArrayList<StandardOpenOption>(); 165 arry.add(READ); 166 arry.add(WRITE); 167 return FileChannel.open(jsa.toPath(), new HashSet<StandardOpenOption>(arry)); 168 } 169 170 public static void modifyJsaContentRandomly() throws Exception { 171 FileChannel fc = getFileChannel(); 172 // corrupt random area in the data areas 173 long[] used = new long[num_regions]; // record used bytes 174 long start0, start, end, off; 175 int used_offset, path_info_size; 176 177 int bufSize; 178 System.out.printf("%-24s%12s%12s%16s\n", "Space Name", "Used bytes", "Reg Start", "Random Offset"); 179 start0 = getFileHeaderSize(fc); 180 for (int i = 0; i < num_regions; i++) { 181 used[i] = get_region_used_size_aligned(fc, i); 182 start = start0; 183 for (int j = 0; j < i; j++) { 184 start += align_up_page(used[j]); 185 } 186 end = start + used[i]; 187 if (start == end) { 188 continue; // Ignore empty regions 189 } 190 off = getRandomBetween(start, end); 191 System.out.printf("%-24s%12d%12d%16d\n", shared_region_name[i], used[i], start, off); 192 if (end - off < 1024) { 193 bufSize = (int)(end - off + 1); 194 } else { 195 bufSize = 1024; 196 } 197 ByteBuffer bbuf = ByteBuffer.wrap(new byte[bufSize]); 198 writeData(fc, off, bbuf); 199 } 200 if (fc.isOpen()) { 201 fc.close(); 202 } 203 } 204 205 static long get_region_used_size_aligned(FileChannel fc, int region) throws Exception { 206 long n = sp_offset + CDSFileMapRegion_size * region + sp_used_offset; 207 long alignment = WhiteBox.getWhiteBox().metaspaceReserveAlignment(); 208 long used = readInt(fc, n, size_t_size); 209 used = (used + alignment - 1) & ~(alignment - 1); 210 return used; 211 } 212 213 public static boolean modifyJsaContent(int region) throws Exception { 214 FileChannel fc = getFileChannel(); 215 byte[] buf = new byte[4096]; 216 ByteBuffer bbuf = ByteBuffer.wrap(buf); 217 218 long total = 0L; 219 long[] used = new long[num_regions]; 220 System.out.printf("%-24s%12s\n", "Space name", "Used bytes"); 221 for (int i = 0; i < num_regions; i++) { 222 used[i] = get_region_used_size_aligned(fc, i); 223 System.out.printf("%-24s%12d\n", shared_region_name[i], used[i]); 224 total += used[i]; 225 } 226 System.out.printf("%-24s%12d\n", "Total: ", total); 227 long header_size = getFileHeaderSize(fc); 228 long region_start_offset = header_size; 229 for (int i=0; i<region; i++) { 230 region_start_offset += used[i]; 231 } 232 if (used[region] == 0) { 233 System.out.println("Region " + shared_region_name[region] + " is empty. Nothing to corrupt."); 234 return false; 235 } 236 System.out.println("Corrupt " + shared_region_name[region] + " section, start = " + region_start_offset 237 + " (header_size + 0x" + Long.toHexString(region_start_offset-header_size) + ")"); 238 long bytes_written = 0L; 239 while (bytes_written < used[region]) { 240 writeData(fc, region_start_offset + bytes_written, bbuf); 241 bbuf.clear(); 242 bytes_written += 4096; 243 } 244 fc.force(true); 245 if (fc.isOpen()) { 246 fc.close(); 247 } 248 return true; 249 } 250 251 public static void modifyJsaHeader() throws Exception { 252 FileChannel fc = getFileChannel(); 253 // screw up header info 254 byte[] buf = new byte[getFileHeaderSize(fc)]; 255 ByteBuffer bbuf = ByteBuffer.wrap(buf); 256 writeData(fc, 0L, bbuf); 257 if (fc.isOpen()) { 258 fc.close(); 259 } 260 } 261 262 public static void copyFile(File from, File to) throws Exception { 263 if (to.exists()) { 264 if(!to.delete()) { 265 throw new IOException("Could not delete file " + to); 266 } 267 } 268 to.createNewFile(); 269 setReadWritePermission(to); 270 Files.copy(from.toPath(), to.toPath(), REPLACE_EXISTING); 271 } 272 273 // Copy file with bytes deleted or inserted 274 // del -- true, deleted, false, inserted 275 public static void copyFile(File from, File to, boolean del) throws Exception { 276 try ( 277 FileChannel inputChannel = new FileInputStream(from).getChannel(); 278 FileChannel outputChannel = new FileOutputStream(to).getChannel() 279 ) { 280 long size = inputChannel.size(); 281 int init_size = getFileHeaderSize(inputChannel); 282 outputChannel.transferFrom(inputChannel, 0, init_size); 283 int n = (int)getRandomBetween(0, 1024); 284 if (del) { 285 System.out.println("Delete " + n + " bytes at data start section"); 286 inputChannel.position(init_size + n); 287 outputChannel.transferFrom(inputChannel, init_size, size - init_size - n); 288 } else { 289 System.out.println("Insert " + n + " bytes at data start section"); 290 outputChannel.position(init_size); 291 outputChannel.write(ByteBuffer.wrap(new byte[n])); 292 outputChannel.transferFrom(inputChannel, init_size + n , size - init_size); 293 } 294 } 295 } 296 297 public static void restoreJsaFile() throws Exception { 298 Files.copy(orgJsaFile.toPath(), jsa.toPath(), REPLACE_EXISTING); 299 } 300 301 public static void setReadWritePermission(File file) throws Exception { 302 if (!file.canRead()) { 303 if (!file.setReadable(true)) { 304 throw new IOException("Cannot modify file " + file + " as readable"); 305 } 306 } 307 if (!file.canWrite()) { 308 if (!file.setWritable(true)) { 309 throw new IOException("Cannot modify file " + file + " as writable"); 310 } 311 } 312 } 313 314 public static void testAndCheck(String[] execArgs) throws Exception { 315 OutputAnalyzer output = TestCommon.execCommon(execArgs); 316 String stdtxt = output.getOutput(); 317 System.out.println("Note: this test may fail in very rare occasions due to CRC32 checksum collision"); 318 for (String message : matchMessages) { 319 if (stdtxt.contains(message)) { 320 // match any to return 321 return; 322 } 323 } 324 TestCommon.checkExec(output); 325 } 326 327 // dump with hello.jsa, then 328 // read the jsa file 329 // 1) run normal 330 // 2) modify header 331 // 3) keep header correct but modify content in each region specified by shared_region_name[] 332 // 4) update both header and content, test 333 // 5) delete bytes in data begining 334 // 6) insert bytes in data begining 335 // 7) randomly corrupt data in each region specified by shared_region_name[] 336 public static void main(String... args) throws Exception { 337 // must call to get offset info first!!! 338 getFileOffsetInfo(); 339 Path currentRelativePath = Paths.get(""); 340 String currentDir = currentRelativePath.toAbsolutePath().toString(); 341 System.out.println("Current relative path is: " + currentDir); 342 // get jar file 343 String jarFile = JarBuilder.getOrCreateHelloJar(); 344 345 // dump (appcds.jsa created) 346 TestCommon.testDump(jarFile, null); 347 348 // test, should pass 349 System.out.println("1. Normal, should pass but may fail\n"); 350 351 String[] execArgs = {"-cp", jarFile, "Hello"}; 352 // tests that corrupt contents of the archive need to run with 353 // VerifySharedSpaces enabled to detect inconsistencies 354 String[] verifyExecArgs = {"-XX:+VerifySharedSpaces", "-cp", jarFile, "Hello"}; 355 356 OutputAnalyzer output = TestCommon.execCommon(execArgs); 357 358 try { 359 TestCommon.checkExecReturn(output, 0, true, "Hello World"); 360 } catch (Exception e) { 361 TestCommon.checkExecReturn(output, 1, true, matchMessages[0]); 362 } 363 364 // get current archive name 365 jsa = new File(TestCommon.getCurrentArchiveName()); 366 if (!jsa.exists()) { 367 throw new IOException(jsa + " does not exist!"); 368 } 369 370 setReadWritePermission(jsa); 371 372 // save as original untouched 373 orgJsaFile = new File(new File(currentDir), "appcds.jsa.bak"); 374 copyFile(jsa, orgJsaFile); 375 376 377 // modify jsa header, test should fail 378 System.out.println("\n2. Corrupt header, should fail\n"); 379 modifyJsaHeader(); 380 output = TestCommon.execCommon(execArgs); 381 output.shouldContain("The shared archive file has the wrong version"); 382 output.shouldNotContain("Checksum verification failed"); 383 384 File newJsaFile = null; 385 // modify content 386 System.out.println("\n3. Corrupt Content, should fail\n"); 387 for (int i=0; i<num_regions; i++) { 388 newJsaFile = new File(TestCommon.getNewArchiveName(shared_region_name[i])); 389 copyFile(orgJsaFile, newJsaFile); 390 if (modifyJsaContent(i)) { 391 testAndCheck(execArgs); 392 } 393 } 394 395 // modify both header and content, test should fail 396 System.out.println("\n4. Corrupt Header and Content, should fail\n"); 397 newJsaFile = new File(TestCommon.getNewArchiveName("header-and-content")); 398 copyFile(orgJsaFile, newJsaFile); 399 modifyJsaHeader(); 400 modifyJsaContent(0); // this will not be reached since failed on header change first 401 output = TestCommon.execCommon(execArgs); 402 output.shouldContain("The shared archive file has the wrong version"); 403 output.shouldNotContain("Checksum verification failed"); 404 405 // delete bytes in data section 406 System.out.println("\n5. Delete bytes at beginning of data section, should fail\n"); 407 copyFile(orgJsaFile, jsa, true); 408 testAndCheck(verifyExecArgs); 409 410 // insert bytes in data section forward 411 System.out.println("\n6. Insert bytes at beginning of data section, should fail\n"); 412 copyFile(orgJsaFile, jsa, false); 413 testAndCheck(verifyExecArgs); 414 415 System.out.println("\n7. modify Content in random areas, should fail\n"); 416 newJsaFile = new File(TestCommon.getNewArchiveName("random-areas")); 417 copyFile(orgJsaFile, newJsaFile); 418 modifyJsaContentRandomly(); 419 testAndCheck(verifyExecArgs); 420 } 421 }