1 /*
   2  * Copyright (c) 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.
   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 package com.sun.tools.jextract;
  24 
  25 import jdk.internal.joptsimple.OptionException;
  26 import jdk.internal.joptsimple.OptionParser;
  27 import jdk.internal.joptsimple.OptionSet;
  28 import jdk.internal.joptsimple.util.KeyValuePair;
  29 
  30 import java.io.File;
  31 import java.io.IOException;
  32 import java.io.PrintWriter;
  33 import java.nio.file.Files;
  34 import java.nio.file.Path;
  35 import java.nio.file.Paths;
  36 import java.text.MessageFormat;
  37 import java.util.List;
  38 import java.util.Locale;
  39 import java.util.ResourceBundle;
  40 import java.util.logging.ConsoleHandler;
  41 import java.util.logging.Level;
  42 import java.util.logging.Logger;
  43 import java.util.logging.SimpleFormatter;
  44 import java.util.regex.PatternSyntaxException;
  45 import java.util.spi.ToolProvider;
  46 
  47 public final class Main {
  48     public static final boolean DEBUG = Boolean.getBoolean("jextract.debug");
  49 
  50     // FIXME: Remove this if/when the macros support is deemed stable
  51     public static boolean INCLUDE_MACROS = Boolean.parseBoolean(System.getProperty("jextract.INCLUDE_MACROS", "true"));
  52 
  53     private static final String MESSAGES_RESOURCE = "com.sun.tools.jextract.resources.Messages";
  54 
  55     private static final ResourceBundle MESSAGES_BUNDLE;
  56     static {
  57         MESSAGES_BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, Locale.getDefault());
  58     }
  59 
  60     public static String format(String msgId, Object... args) {
  61         return new MessageFormat(MESSAGES_BUNDLE.getString(msgId)).format(args);
  62     }
  63 
  64     private final Context ctx;
  65     private String targetPackage;
  66 
  67     public Main(Context ctx) {
  68         this.ctx = ctx;
  69     }
  70 
  71     private void processPackageMapping(Object arg) {
  72         String str = (String) arg;
  73         Path p = null;
  74         String pkgName;
  75         if (str.indexOf('=') == -1) {
  76             pkgName = str;
  77         } else {
  78             KeyValuePair kv = KeyValuePair.valueOf(str);
  79             p = Paths.get(kv.key);
  80             pkgName = kv.value;
  81 
  82             if (!Files.isDirectory(p)) {
  83                 throw new IllegalArgumentException(format("not.a.directory", kv.key));
  84             }
  85         }
  86 
  87         Utils.validPackageName(pkgName);
  88         ctx.usePackageForFolder(p, pkgName);
  89     }
  90 
  91     private void processHeader(Object header) {
  92         Path p = Paths.get((String) header);
  93         if (!Files.isReadable(p)) {
  94             throw new IllegalArgumentException(format("cannot.read.header.file", header));
  95         }
  96         p = p.toAbsolutePath();
  97         ctx.usePackageForFolder(p.getParent(), targetPackage);
  98         ctx.addSource(p);
  99     }
 100 
 101     private void setupLogging(Level level) {
 102         Logger logger = ctx.logger;
 103         logger.setUseParentHandlers(false);
 104         ConsoleHandler log = new ConsoleHandler();
 105         System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s: %5$s%n");
 106         log.setFormatter(new SimpleFormatter());
 107         logger.setLevel(level);
 108         log.setLevel(level);
 109         logger.addHandler(log);
 110     }
 111 
 112     private void printHelp(OptionParser parser) {
 113         try {
 114             parser.printHelpOn(ctx.err);
 115         } catch (IOException ex) {
 116             if (Main.DEBUG) {
 117                 ex.printStackTrace(ctx.err);
 118             }
 119         }
 120     }
 121 
 122     public int run(String[] args) {
 123         OptionParser parser = new OptionParser();
 124         parser.accepts("dry-run", format("help.dry_run"));
 125         parser.accepts("I", format("help.I")).withRequiredArg();
 126         // option is expected to specify paths to load shared libraries
 127         // to check & warn missing symbols during jextract session.
 128         parser.accepts("L", format("help.L")).withRequiredArg();
 129         parser.accepts("l", format("help.l")).withRequiredArg();
 130         parser.accepts("d", format("help.d")).withRequiredArg();
 131         parser.acceptsAll(List.of("o", "jar"), format("help.o")).withRequiredArg();
 132         parser.acceptsAll(List.of("t", "target-package"), format("help.t")).withRequiredArg();
 133         parser.acceptsAll(List.of("m", "package-map"), format("help.m")).withRequiredArg();
 134         parser.acceptsAll(List.of("?", "h", "help"), format("help.h")).forHelp();
 135         parser.accepts("C", format("help.C")).withRequiredArg();
 136         parser.accepts("include-symbols", format("help.include_symbols")).withRequiredArg();
 137         parser.accepts("log", format("help.log")).withRequiredArg();
 138         parser.accepts("no-locations", format("help.no.locations"));
 139         parser.accepts("exclude-symbols", format("help.exclude_symbols")).withRequiredArg();
 140         parser.accepts("rpath", format("help.rpath")).withRequiredArg();
 141         parser.accepts("infer-rpath", format("help.infer.rpath"));
 142         parser.accepts("static-forwarder", format("help.static.forwarder")).
 143             withRequiredArg().ofType(boolean.class);
 144         parser.nonOptions(format("help.non.option"));
 145 
 146         OptionSet options = null;
 147         try {
 148              options = parser.parse(args);
 149         } catch (OptionException oe) {
 150              ctx.err.println(oe.getMessage());
 151              if (Main.DEBUG) {
 152                  oe.printStackTrace(ctx.err);
 153              }
 154              printHelp(parser);
 155              return 1;
 156         }
 157 
 158         if (args.length == 0 || options.has("h")) {
 159              printHelp(parser);
 160              return args.length == 0? 1 : 0;
 161         }
 162 
 163         if (options.nonOptionArguments().isEmpty()) {
 164             ctx.err.println(format("err.no.input.files"));
 165             return 2;
 166         }
 167 
 168         if (options.has("log")) {
 169             setupLogging(Level.parse((String) options.valueOf("log")));
 170         } else {
 171             setupLogging(Level.WARNING);
 172         }
 173 
 174         if (options.has("I")) {
 175             options.valuesOf("I").forEach(p -> ctx.addClangArg("-I" + p));
 176         }
 177 
 178         // append the built-in headers directory
 179         ctx.addClangArg("-I" + getBuiltinHeadersDir());
 180 
 181         if (options.has("C")) {
 182             options.valuesOf("C").forEach(p -> ctx.addClangArg((String) p));
 183         }
 184 
 185         if (options.has("l")) {
 186             for (Object arg : options.valuesOf("l")) {
 187                 String lib = (String)arg;
 188                 if (lib.indexOf(File.separatorChar) != -1) {
 189                     ctx.err.println(format("l.name.should.not.be.path", lib));
 190                     return 1;
 191                 }
 192                 ctx.addLibraryName(lib);
 193             }
 194         }
 195 
 196         if (options.has("no-locations")) {
 197             ctx.setNoNativeLocations();
 198         }
 199 
 200         boolean infer_rpath = options.has("infer-rpath");
 201         if (options.has("rpath")) {
 202             if (infer_rpath) {
 203                 //conflicting rpaths options
 204                 ctx.err.println(format("warn.rpath.auto.conflict"));
 205                 infer_rpath = false;
 206             }
 207 
 208             // "rpath" with no "l" option!
 209             if (options.has("l")) {
 210                 options.valuesOf("rpath").forEach(p -> ctx.addLibraryPath((String) p));
 211             } else {
 212                 ctx.err.println(format("warn.rpath.without.l"));
 213             }
 214         }
 215 
 216         // generate static forwarder class if user specified -l option
 217         boolean staticForwarder = true;
 218         if (options.has("static-forwarder")) {
 219             staticForwarder = (boolean)options.valueOf("static-forwarder");
 220         }
 221         ctx.setGenStaticForwarder(staticForwarder && options.has("l"));
 222 
 223         if (options.has("include-symbols")) {
 224             try {
 225                 options.valuesOf("include-symbols").forEach(sym -> ctx.addIncludeSymbols((String) sym));
 226             } catch (PatternSyntaxException pse) {
 227                 ctx.err.println(format("include.symbols.pattern.error", pse.getMessage()));
 228             }
 229         }
 230 
 231         if (options.has("exclude-symbols")) {
 232             try {
 233                 options.valuesOf("exclude-symbols").forEach(sym -> ctx.addExcludeSymbols((String) sym));
 234             } catch (PatternSyntaxException pse) {
 235                 ctx.err.println(format("exclude.symbols.pattern.error", pse.getMessage()));
 236             }
 237         }
 238 
 239         if (options.has("L")) {
 240             List<?> libpaths = options.valuesOf("L");
 241             // "L" with no "l" option!
 242             if (options.has("l")) {
 243                 libpaths.forEach(p -> ctx.addLinkCheckPath((String) p));
 244                 if (infer_rpath) {
 245                     libpaths.forEach(p -> ctx.addLibraryPath((String) p));
 246                 }
 247             } else {
 248                 ctx.err.println(format("warn.L.without.l"));
 249             }
 250         } else if (infer_rpath) {
 251             ctx.err.println(format("warn.rpath.auto.without.L"));
 252         }
 253 
 254         targetPackage = options.has("t") ? (String) options.valueOf("t") : "";
 255         if (!targetPackage.isEmpty()) {
 256             Utils.validPackageName(targetPackage);
 257         }
 258 
 259         if (options.has("m")) {
 260             options.valuesOf("m").forEach(this::processPackageMapping);
 261         }
 262 
 263         try {
 264             options.nonOptionArguments().stream().forEach(this::processHeader);
 265             ctx.parse();
 266         } catch (RuntimeException re) {
 267             ctx.err.println(re.getMessage());
 268             if (Main.DEBUG) {
 269                 re.printStackTrace(ctx.err);
 270             }
 271             return 2;
 272         }
 273 
 274         if (options.has("dry-run")) {
 275             return 0;
 276         }
 277 
 278         boolean hasOutput = false;
 279 
 280         if (options.has("d")) {
 281             hasOutput = true;
 282             Path dest = Paths.get((String) options.valueOf("d"));
 283             dest = dest.toAbsolutePath();
 284             try {
 285                 if (!Files.exists(dest)) {
 286                     Files.createDirectories(dest);
 287                 } else if (!Files.isDirectory(dest)) {
 288                     ctx.err.println(format("not.a.directory", dest));
 289                     return 4;
 290                 }
 291                 ctx.collectClassFiles(dest, args, targetPackage);
 292             } catch (IOException ex) {
 293                 ctx.err.println(format("cannot.write.class.file", dest, ex));
 294                 if (Main.DEBUG) {
 295                     ex.printStackTrace(ctx.err);
 296                 }
 297                 return 5;
 298             }
 299         }
 300 
 301         String outputName;
 302         if (options.has("o")) {
 303             outputName = (String) options.valueOf("o");
 304         } else if (hasOutput) {
 305             return 0;
 306         } else {
 307             outputName =  Paths.get((String)options.nonOptionArguments().get(0)).getFileName() + ".jar";
 308         }
 309 
 310         try {
 311             ctx.collectJarFile(Paths.get(outputName), args, targetPackage);
 312         } catch (IOException ex) {
 313             ctx.err.println(format("cannot.write.jar.file", outputName, ex));
 314             if (Main.DEBUG) {
 315                 ex.printStackTrace(ctx.err);
 316             }
 317             return 3;
 318         }
 319 
 320         return 0;
 321     }
 322 
 323     private static Path getBuiltinHeadersDir() {
 324         return Paths.get(System.getProperty("java.home"), "conf", "jextract");
 325     }
 326 
 327     public static void main(String... args) {
 328         Main instance = new Main(new Context());
 329 
 330         System.exit(instance.run(args));
 331     }
 332 
 333     public static class JextractToolProvider implements ToolProvider {
 334         @Override
 335         public String name() {
 336             return "jextract";
 337         }
 338 
 339         @Override
 340         public int run(PrintWriter out, PrintWriter err, String... args) {
 341             // defensive check to throw security exception early.
 342             // Note that the successful run of jextract under security
 343             // manager would require far more permissions like loading
 344             // library (clang), file system access etc.
 345             if (System.getSecurityManager() != null) {
 346                 System.getSecurityManager().
 347                     checkPermission(new RuntimePermission("jextract"));
 348             }
 349 
 350             Main instance = new Main(new Context(out, err));
 351             return instance.run(args);
 352         }
 353     }
 354 }