1 /*
   2  * Copyright (c) 2014, 2015, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.tools.jimage;
  27 
  28 import java.io.File;
  29 import java.io.IOException;
  30 import java.io.PrintWriter;
  31 import java.nio.ByteBuffer;
  32 import java.nio.ByteOrder;
  33 import java.nio.channels.FileChannel;
  34 import java.nio.file.Files;
  35 import java.nio.file.Path;
  36 import static java.nio.file.StandardOpenOption.READ;
  37 import static java.nio.file.StandardOpenOption.WRITE;
  38 import java.util.LinkedList;
  39 import java.util.List;
  40 import jdk.internal.jimage.BasicImageReader;
  41 import jdk.internal.jimage.ImageHeader;
  42 import static jdk.internal.jimage.ImageHeader.MAGIC;
  43 import static jdk.internal.jimage.ImageHeader.MAJOR_VERSION;
  44 import static jdk.internal.jimage.ImageHeader.MINOR_VERSION;
  45 import jdk.internal.jimage.ImageLocation;
  46 import jdk.internal.jimage.ImageModuleData;
  47 import jdk.internal.jimage.ImageResourcesTree;
  48 import jdk.tools.jimage.TaskHelper.BadArgs;
  49 import jdk.tools.jimage.TaskHelper.HiddenOption;
  50 import jdk.tools.jimage.TaskHelper.Option;
  51 import jdk.tools.jimage.TaskHelper.OptionsHelper;
  52 
  53 class JImageTask {
  54 
  55     static final Option<?>[] recognizedOptions = {
  56         new Option<JImageTask>(true, "--dir") {
  57             @Override
  58             protected void process(JImageTask task, String opt, String arg) throws BadArgs {
  59                  task.options.directory = arg;
  60             }
  61         },
  62         new HiddenOption<JImageTask>(false, "--fullversion") {
  63             @Override
  64             protected void process(JImageTask task, String opt, String arg) {
  65                 task.options.fullVersion = true;
  66             }
  67         },
  68         new Option<JImageTask>(false, "--help") {
  69             @Override
  70             protected void process(JImageTask task, String opt, String arg) {
  71                 task.options.help = true;
  72             }
  73         },
  74 
  75         new Option<JImageTask>(true, "--flags") {
  76             @Override
  77             protected void process(JImageTask task, String opt, String arg) {
  78                 task.options.flags = arg;
  79             }
  80         },
  81 
  82         new Option<JImageTask>(false, "--verbose") {
  83             @Override
  84             protected void process(JImageTask task, String opt, String arg) throws BadArgs {
  85                  task.options.verbose = true;
  86             }
  87         },
  88         new Option<JImageTask>(false, "--version") {
  89             @Override
  90             protected void process(JImageTask task, String opt, String arg) {
  91                 task.options.version = true;
  92             }
  93         },
  94     };
  95     private static final TaskHelper taskHelper
  96             = new TaskHelper("jdk.tools.jimage.resources.jimage");
  97     private static final OptionsHelper<JImageTask> optionsHelper
  98             = taskHelper.newOptionsHelper(JImageTask.class, recognizedOptions);
  99 
 100     static class OptionsValues {
 101         Task task = Task.LIST;
 102         String directory = ".";
 103         boolean fullVersion;
 104         boolean help;
 105         String flags;
 106         boolean verbose;
 107         boolean version;
 108         List<File> jimages = new LinkedList<>();
 109     }
 110 
 111     private static final String PROGNAME = "jimage";
 112     private final OptionsValues options = new OptionsValues();
 113 
 114     enum Task {
 115         EXTRACT,
 116         INFO,
 117         LIST,
 118         RECREATE,
 119         SET,
 120         VERIFY
 121     };
 122 
 123     private String pad(String string, int width, boolean justifyRight) {
 124         int length = string.length();
 125 
 126         if (length == width) {
 127             return string;
 128         }
 129 
 130         if (length > width) {
 131             return string.substring(0, width);
 132         }
 133 
 134         int padding = width - length;
 135 
 136         StringBuilder sb = new StringBuilder(width);
 137         if (justifyRight) {
 138             for (int i = 0; i < padding; i++) {
 139                 sb.append(' ');
 140             }
 141         }
 142 
 143         sb.append(string);
 144 
 145         if (!justifyRight) {
 146             for (int i = 0; i < padding; i++) {
 147                 sb.append(' ');
 148             }
 149         }
 150 
 151         return sb.toString();
 152     }
 153 
 154     private String pad(String string, int width) {
 155         return pad(string, width, false);
 156     }
 157 
 158     private String pad(long value, int width) {
 159         return pad(Long.toString(value), width, true);
 160     }
 161 
 162     private static final int EXIT_OK = 0;        // No errors.
 163     private static final int EXIT_ERROR = 1;     // Completed but reported errors.
 164     private static final int EXIT_CMDERR = 2;    // Bad command-line arguments and/or switches.
 165     private static final int EXIT_SYSERR = 3;    // System error or resource exhaustion.
 166     private static final int EXIT_ABNORMAL = 4;  // Terminated abnormally.
 167 
 168     int run(String[] args) {
 169         if (log == null) {
 170             setLog(new PrintWriter(System.out));
 171         }
 172 
 173         try {
 174             List<String> unhandled = optionsHelper.handleOptions(this, args);
 175             if(!unhandled.isEmpty()) {
 176                 options.task = Enum.valueOf(Task.class, unhandled.get(0).toUpperCase());
 177                 for(int i = 1; i < unhandled.size(); i++) {
 178                     options.jimages.add(new File(unhandled.get(i)));
 179                 }
 180             }
 181             if (options.help) {
 182                 optionsHelper.showHelp(PROGNAME, "recreate only options:");
 183             }
 184             if (options.version || options.fullVersion) {
 185                 taskHelper.showVersion(options.fullVersion);
 186             }
 187             boolean ok = run();
 188             return ok ? EXIT_OK : EXIT_ERROR;
 189         } catch (BadArgs e) {
 190             taskHelper.reportError(e.key, e.args);
 191             if (e.showUsage) {
 192                 log.println(taskHelper.getMessage("main.usage.summary", PROGNAME));
 193             }
 194             return EXIT_CMDERR;
 195         } catch (Exception x) {
 196             x.printStackTrace();
 197             return EXIT_ABNORMAL;
 198         } finally {
 199             log.flush();
 200         }
 201     }
 202 
 203     private void recreate() throws IOException, BadArgs {
 204         File directory = new File(options.directory);
 205         if (!directory.isDirectory()) {
 206             throw taskHelper.newBadArgs("err.not.a.dir", directory.getAbsolutePath());
 207         }
 208         Path dirPath = directory.toPath();
 209         if (options.jimages.isEmpty()) {
 210             throw taskHelper.newBadArgs("err.jimage.not.specified");
 211         } else if (options.jimages.size() != 1) {
 212             throw taskHelper.newBadArgs("err.only.one.jimage");
 213         }
 214 
 215         Path jimage = options.jimages.get(0).toPath();
 216 
 217         if (jimage.toFile().createNewFile()) {
 218             ExtractedImage img = new ExtractedImage(dirPath, log, options.verbose);
 219             img.recreateJImage(jimage);
 220         } else {
 221             throw taskHelper.newBadArgs("err.jimage.already.exists", jimage.getFileName());
 222         }
 223     }
 224 
 225     private void title(File file, BasicImageReader reader) {
 226         log.println("jimage: " + file.getName());
 227     }
 228 
 229     private void listTitle(File file, BasicImageReader reader) {
 230         title(file, reader);
 231 
 232         if (options.verbose) {
 233             log.print(pad("Offset", OFFSET_WIDTH + 1));
 234             log.print(pad("Size", SIZE_WIDTH + 1));
 235             log.print(pad("Compressed", COMPRESSEDSIZE_WIDTH + 1));
 236             log.println(" Entry");
 237         }
 238     }
 239 
 240     private interface JImageAction {
 241         public void apply(File file, BasicImageReader reader) throws IOException, BadArgs;
 242     }
 243 
 244     private interface ResourceAction {
 245         public void apply(BasicImageReader reader, String name,
 246                 ImageLocation location) throws IOException, BadArgs;
 247     }
 248 
 249     private void extract(BasicImageReader reader, String name,
 250             ImageLocation location) throws IOException, BadArgs {
 251         File directory = new File(options.directory);
 252         byte[] bytes = reader.getResource(location);
 253         File resource =  new File(directory, name);
 254         File parent = resource.getParentFile();
 255 
 256         if (parent.exists()) {
 257             if (!parent.isDirectory()) {
 258                 throw taskHelper.newBadArgs("err.cannot.create.dir", parent.getAbsolutePath());
 259             }
 260         } else if (!parent.mkdirs()) {
 261             throw taskHelper.newBadArgs("err.cannot.create.dir", parent.getAbsolutePath());
 262         }
 263 
 264         if (name.endsWith(ImageModuleData.META_DATA_EXTENSION)) {
 265             ImageModuleData imageModuleData = new ImageModuleData(reader, bytes);
 266             List<String> lines = imageModuleData.fromModulePackages();
 267             Files.write(resource.toPath(), lines);
 268         } else {
 269             if (!ImageResourcesTree.isTreeInfoResource(name)) {
 270                 Files.write(resource.toPath(), bytes);
 271             }
 272         }
 273     }
 274 
 275     private static final int NUMBER_WIDTH = 12;
 276     private static final int OFFSET_WIDTH = NUMBER_WIDTH;
 277     private static final int SIZE_WIDTH = NUMBER_WIDTH;
 278     private static final int COMPRESSEDSIZE_WIDTH = NUMBER_WIDTH;
 279 
 280     private void print(String entry, ImageLocation location) {
 281         log.print(pad(location.getContentOffset(), OFFSET_WIDTH) + " ");
 282         log.print(pad(location.getUncompressedSize(), SIZE_WIDTH) + " ");
 283         log.print(pad(location.getCompressedSize(), COMPRESSEDSIZE_WIDTH) + " ");
 284         log.println(entry);
 285     }
 286 
 287     private void print(BasicImageReader reader, String entry) {
 288         if (options.verbose) {
 289             print(entry, reader.findLocation(entry));
 290         } else {
 291             log.println(entry);
 292         }
 293     }
 294 
 295     private void info(File file, BasicImageReader reader) throws IOException {
 296         ImageHeader header = reader.getHeader();
 297 
 298         log.println(" Major Version:  " + header.getMajorVersion());
 299         log.println(" Minor Version:  " + header.getMinorVersion());
 300         log.println(" Flags:          " + Integer.toHexString(header.getMinorVersion()));
 301         log.println(" Resource Count: " + header.getResourceCount());
 302         log.println(" Table Length:   " + header.getTableLength());
 303         log.println(" Offsets Size:   " + header.getOffsetsSize());
 304         log.println(" Redirects Size: " + header.getRedirectSize());
 305         log.println(" Locations Size: " + header.getLocationsSize());
 306         log.println(" Strings Size:   " + header.getStringsSize());
 307         log.println(" Index Size:     " + header.getIndexSize());
 308     }
 309 
 310     private void list(BasicImageReader reader, String name, ImageLocation location) {
 311         print(reader, name);
 312     }
 313 
 314     void set(File file, BasicImageReader reader) throws BadArgs {
 315         try {
 316             ImageHeader oldHeader = reader.getHeader();
 317 
 318             int value = 0;
 319             try {
 320                 value = Integer.valueOf(options.flags);
 321             } catch (NumberFormatException ex) {
 322                 throw taskHelper.newBadArgs("err.flags.not.int", options.flags);
 323             }
 324 
 325             ImageHeader newHeader = new ImageHeader(MAGIC, MAJOR_VERSION, MINOR_VERSION,
 326                     value,
 327                     oldHeader.getResourceCount(), oldHeader.getTableLength(),
 328                     oldHeader.getLocationsSize(), oldHeader.getStringsSize());
 329 
 330             ByteBuffer buffer = ByteBuffer.allocate(ImageHeader.getHeaderSize());
 331             buffer.order(ByteOrder.nativeOrder());
 332             newHeader.writeTo(buffer);
 333             buffer.rewind();
 334 
 335             try (FileChannel channel = FileChannel.open(file.toPath(), READ, WRITE)) {
 336                 channel.write(buffer, 0);
 337             }
 338         } catch (IOException ex) {
 339             throw taskHelper.newBadArgs("err.cannot.update.file", file.getName());
 340         }
 341     }
 342 
 343      void verify(BasicImageReader reader, String name, ImageLocation location) {
 344         if (name.endsWith(".class")) {
 345             byte[] bytes = reader.getResource(location);
 346 
 347             if (bytes == null || bytes.length <= 4 ||
 348                 (bytes[0] & 0xFF) != 0xCA ||
 349                 (bytes[1] & 0xFF) != 0xFE ||
 350                 (bytes[2] & 0xFF) != 0xBA ||
 351                 (bytes[3] & 0xFF) != 0xBE) {
 352                 log.print(" NOT A CLASS: ");
 353                 print(reader, name);
 354             }
 355         }
 356     }
 357 
 358     private void iterate(JImageAction jimageAction,
 359             ResourceAction resourceAction) throws IOException, BadArgs {
 360         for (File file : options.jimages) {
 361             if (!file.exists() || !file.isFile()) {
 362                 throw taskHelper.newBadArgs("err.not.a.jimage", file.getName());
 363             }
 364 
 365             String path = file.getCanonicalPath();
 366             BasicImageReader reader = BasicImageReader.open(path);
 367 
 368             if (jimageAction != null) {
 369                 jimageAction.apply(file, reader);
 370             }
 371 
 372             if (resourceAction != null) {
 373                 String[] entryNames = reader.getEntryNames();
 374 
 375                 for (String name : entryNames) {
 376                     if (!ImageResourcesTree.isTreeInfoResource(name)) {
 377                         ImageLocation location = reader.findLocation(name);
 378                         resourceAction.apply(reader, name, location);
 379                     }
 380                 }
 381             }
 382        }
 383     }
 384 
 385     private boolean run() throws IOException, BadArgs {
 386         switch (options.task) {
 387             case EXTRACT:
 388                 iterate(null, this::extract);
 389                 break;
 390             case INFO:
 391                 iterate(this::info, null);
 392                 break;
 393             case LIST:
 394                 iterate(this::listTitle, this::list);
 395                 break;
 396             case RECREATE:
 397                 recreate();
 398                 break;
 399             case SET:
 400                 iterate(this::set, null);
 401                 break;
 402             case VERIFY:
 403                 iterate(this::title, this::verify);
 404                 break;
 405             default:
 406                 throw taskHelper.newBadArgs("err.invalid.task", options.task.name()).showUsage(true);
 407         }
 408         return true;
 409     }
 410 
 411     private PrintWriter log;
 412     void setLog(PrintWriter out) {
 413         log = out;
 414         taskHelper.setLog(log);
 415     }
 416 }