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