List of usage examples for com.google.common.collect ImmutableBiMap.Builder put
@Override @Nullable V put(@Nullable K key, @Nullable V value);
From source file:com.facebook.buck.apple.toolchain.impl.AppleCxxPlatforms.java
@VisibleForTesting public static AppleCxxPlatform buildWithXcodeToolFinder(ProjectFilesystem filesystem, AppleSdk targetSdk, String minVersion, String targetArchitecture, AppleSdkPaths sdkPaths, BuckConfig buckConfig, XcodeToolFinder xcodeToolFinder, XcodeBuildVersionCache xcodeBuildVersionCache) { AppleCxxPlatform.Builder platformBuilder = AppleCxxPlatform.builder(); ImmutableList.Builder<Path> toolSearchPathsBuilder = ImmutableList.builder(); // Search for tools from most specific to least specific. toolSearchPathsBuilder.add(sdkPaths.getSdkPath().resolve(USR_BIN)) .add(sdkPaths.getSdkPath().resolve("Developer").resolve(USR_BIN)) .add(sdkPaths.getPlatformPath().resolve("Developer").resolve(USR_BIN)); for (Path toolchainPath : sdkPaths.getToolchainPaths()) { toolSearchPathsBuilder.add(toolchainPath.resolve(USR_BIN)); }/*from ww w .j ava 2s . com*/ if (sdkPaths.getDeveloperPath().isPresent()) { toolSearchPathsBuilder.add(sdkPaths.getDeveloperPath().get().resolve(USR_BIN)); toolSearchPathsBuilder.add(sdkPaths.getDeveloperPath().get().resolve("Tools")); } // TODO(beng): Add more and better cflags. ImmutableList.Builder<String> cflagsBuilder = ImmutableList.builder(); cflagsBuilder.add("-isysroot", sdkPaths.getSdkPath().toString()); cflagsBuilder.add("-arch", targetArchitecture); cflagsBuilder.add(targetSdk.getApplePlatform().getMinVersionFlagPrefix() + minVersion); if (targetSdk.getApplePlatform().equals(ApplePlatform.WATCHOS)) { cflagsBuilder.add("-fembed-bitcode"); } AppleConfig appleConfig = buckConfig.getView(AppleConfig.class); ImmutableList.Builder<String> ldflagsBuilder = ImmutableList.builder(); ldflagsBuilder.addAll(Linkers.iXlinker("-sdk_version", targetSdk.getVersion())); if (appleConfig.linkAllObjC()) { ldflagsBuilder.addAll(Linkers.iXlinker("-ObjC")); } if (targetSdk.getApplePlatform().equals(ApplePlatform.WATCHOS)) { ldflagsBuilder.addAll(Linkers.iXlinker("-bitcode_verify")); } // Populate Xcode version keys from Xcode's own Info.plist if available. Optional<String> xcodeBuildVersion = Optional.empty(); Optional<Path> developerPath = sdkPaths.getDeveloperPath(); if (developerPath.isPresent()) { Path xcodeBundlePath = developerPath.get().getParent(); if (xcodeBundlePath != null) { Path xcodeInfoPlistPath = xcodeBundlePath.resolve("Info.plist"); try (InputStream stream = Files.newInputStream(xcodeInfoPlistPath)) { NSDictionary parsedXcodeInfoPlist = (NSDictionary) PropertyListParser.parse(stream); NSObject xcodeVersionObject = parsedXcodeInfoPlist.objectForKey("DTXcode"); if (xcodeVersionObject != null) { Optional<String> xcodeVersion = Optional.of(xcodeVersionObject.toString()); platformBuilder.setXcodeVersion(xcodeVersion); } } catch (IOException e) { LOG.warn("Error reading Xcode's info plist %s; ignoring Xcode versions", xcodeInfoPlistPath); } catch (PropertyListFormatException | ParseException | ParserConfigurationException | SAXException e) { LOG.warn("Error in parsing %s; ignoring Xcode versions", xcodeInfoPlistPath); } } xcodeBuildVersion = xcodeBuildVersionCache.lookup(developerPath.get()); platformBuilder.setXcodeBuildVersion(xcodeBuildVersion); LOG.debug("Xcode build version is: " + xcodeBuildVersion.orElse("<absent>")); } ImmutableList.Builder<String> versions = ImmutableList.builder(); versions.add(targetSdk.getVersion()); ImmutableList<String> toolchainVersions = targetSdk.getToolchains().stream().map(AppleToolchain::getVersion) .flatMap(Optionals::toStream).collect(ImmutableList.toImmutableList()); if (toolchainVersions.isEmpty()) { if (!xcodeBuildVersion.isPresent()) { throw new HumanReadableException("Failed to read toolchain versions and Xcode version."); } versions.add(xcodeBuildVersion.get()); } else { versions.addAll(toolchainVersions); } String version = Joiner.on(':').join(versions.build()); ImmutableList<Path> toolSearchPaths = toolSearchPathsBuilder.build(); Tool clangPath = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "clang", version); Tool clangXxPath = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "clang++", version); Tool ar = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "ar", version); Tool ranlib = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "ranlib", version); Tool strip = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "strip", version); Tool nm = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "nm", version); Tool actool = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "actool", version); Tool ibtool = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "ibtool", version); Tool momc = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "momc", version); Tool xctest = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "xctest", version); Tool dsymutil = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "dsymutil", version); Tool lipo = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "lipo", version); Tool lldb = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "lldb", version); Optional<Path> stubBinaryPath = targetSdk.getApplePlatform().getStubBinaryPath() .map(input -> sdkPaths.getSdkPath().resolve(input)); UserFlavor targetFlavor = UserFlavor.of( Flavor.replaceInvalidCharacters(targetSdk.getName() + "-" + targetArchitecture), String.format("SDK: %s, architecture: %s", targetSdk.getName(), targetArchitecture)); CxxBuckConfig config = appleConfig.useFlavoredCxxSections() ? new CxxBuckConfig(buckConfig, targetFlavor) : new CxxBuckConfig(buckConfig); ImmutableBiMap.Builder<Path, String> sanitizerPaths = ImmutableBiMap.builder(); sanitizerPaths.put(sdkPaths.getSdkPath(), "APPLE_SDKROOT"); sanitizerPaths.put(sdkPaths.getPlatformPath(), "APPLE_PLATFORM_DIR"); if (sdkPaths.getDeveloperPath().isPresent()) { sanitizerPaths.put(sdkPaths.getDeveloperPath().get(), "APPLE_DEVELOPER_DIR"); } // https://github.com/facebook/buck/pull/1168: add the root cell's absolute path to the quote // include path, and also force it to be sanitized by all user rule keys. sanitizerPaths.put(filesystem.getRootPath(), "."); cflagsBuilder.add("-iquote", filesystem.getRootPath().toString()); DebugPathSanitizer compilerDebugPathSanitizer = new PrefixMapDebugPathSanitizer( DebugPathSanitizer.getPaddedDir(".", config.getDebugPathSanitizerLimit(), File.separatorChar), sanitizerPaths.build()); DebugPathSanitizer assemblerDebugPathSanitizer = new MungingDebugPathSanitizer( config.getDebugPathSanitizerLimit(), File.separatorChar, Paths.get("."), sanitizerPaths.build()); ImmutableList<String> cflags = cflagsBuilder.build(); ImmutableMap.Builder<String, String> macrosBuilder = ImmutableMap.builder(); macrosBuilder.put("SDKROOT", sdkPaths.getSdkPath().toString()); macrosBuilder.put("PLATFORM_DIR", sdkPaths.getPlatformPath().toString()); macrosBuilder.put("CURRENT_ARCH", targetArchitecture); if (sdkPaths.getDeveloperPath().isPresent()) { macrosBuilder.put("DEVELOPER_DIR", sdkPaths.getDeveloperPath().get().toString()); } ImmutableMap<String, String> macros = macrosBuilder.build(); Optional<String> buildVersion = Optional.empty(); Path platformVersionPlistPath = sdkPaths.getPlatformPath().resolve("version.plist"); try (InputStream versionPlist = Files.newInputStream(platformVersionPlistPath)) { NSDictionary versionInfo = (NSDictionary) PropertyListParser.parse(versionPlist); if (versionInfo != null) { NSObject productBuildVersion = versionInfo.objectForKey("ProductBuildVersion"); if (productBuildVersion != null) { buildVersion = Optional.of(productBuildVersion.toString()); } else { LOG.warn("In %s, missing ProductBuildVersion. Build version will be unset for this platform.", platformVersionPlistPath); } } else { LOG.warn("Empty version plist in %s. Build version will be unset for this platform.", platformVersionPlistPath); } } catch (NoSuchFileException e) { LOG.warn("%s does not exist. Build version will be unset for this platform.", platformVersionPlistPath); } catch (PropertyListFormatException | SAXException | ParserConfigurationException | ParseException | IOException e) { // Some other error occurred, print the exception since it may contain error details. LOG.warn(e, "Failed to parse %s. Build version will be unset for this platform.", platformVersionPlistPath); } PreprocessorProvider aspp = new PreprocessorProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG); CompilerProvider as = new CompilerProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG, config.getUseDetailedUntrackedHeaderMessages()); PreprocessorProvider cpp = new PreprocessorProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG); CompilerProvider cc = new CompilerProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG, config.getUseDetailedUntrackedHeaderMessages()); PreprocessorProvider cxxpp = new PreprocessorProvider(new ConstantToolProvider(clangXxPath), CxxToolProvider.Type.CLANG); CompilerProvider cxx = new CompilerProvider(new ConstantToolProvider(clangXxPath), CxxToolProvider.Type.CLANG, config.getUseDetailedUntrackedHeaderMessages()); ImmutableList.Builder<String> whitelistBuilder = ImmutableList.builder(); whitelistBuilder.add("^" + Pattern.quote(sdkPaths.getSdkPath().toString()) + "\\/.*"); whitelistBuilder .add("^" + Pattern.quote(sdkPaths.getPlatformPath() + "/Developer/Library/Frameworks") + "\\/.*"); for (Path toolchainPath : sdkPaths.getToolchainPaths()) { LOG.debug("Apple toolchain path: %s", toolchainPath); try { whitelistBuilder.add("^" + Pattern.quote(toolchainPath.toRealPath().toString()) + "\\/.*"); } catch (IOException e) { LOG.warn(e, "Apple toolchain path could not be resolved: %s", toolchainPath); } } HeaderVerification headerVerification = config.getHeaderVerificationOrIgnore() .withPlatformWhitelist(whitelistBuilder.build()); LOG.debug("Headers verification platform whitelist: %s", headerVerification.getPlatformWhitelist()); CxxPlatform cxxPlatform = CxxPlatforms.build(targetFlavor, Platform.MACOS, config, as, aspp, cc, cxx, cpp, cxxpp, new DefaultLinkerProvider(LinkerProvider.Type.DARWIN, new ConstantToolProvider(clangXxPath), config.shouldCacheLinks()), ImmutableList.<String>builder().addAll(cflags).addAll(ldflagsBuilder.build()).build(), ImmutableMultimap.of(), strip, ArchiverProvider.from(new BsdArchiver(ar)), ArchiveContents.NORMAL, Optional.of(new ConstantToolProvider(ranlib)), new PosixNmSymbolNameTool(nm), cflagsBuilder.build(), ImmutableList.of(), cflags, ImmutableList.of(), cflags, ImmutableList.of(), "dylib", "%s.dylib", "a", "o", compilerDebugPathSanitizer, assemblerDebugPathSanitizer, macros, Optional.empty(), headerVerification, PicType.PIC); ApplePlatform applePlatform = targetSdk.getApplePlatform(); ImmutableList.Builder<Path> swiftOverrideSearchPathBuilder = ImmutableList.builder(); AppleSdkPaths.Builder swiftSdkPathsBuilder = AppleSdkPaths.builder().from(sdkPaths); Optional<SwiftPlatform> swiftPlatform = getSwiftPlatform(applePlatform.getName(), targetArchitecture + "-apple-" + applePlatform.getSwiftName().orElse(applePlatform.getName()) + minVersion, version, swiftSdkPathsBuilder.build(), swiftOverrideSearchPathBuilder.addAll(toolSearchPaths).build(), xcodeToolFinder, filesystem); platformBuilder.setCxxPlatform(cxxPlatform).setSwiftPlatform(swiftPlatform).setAppleSdk(targetSdk) .setAppleSdkPaths(sdkPaths).setMinVersion(minVersion).setBuildVersion(buildVersion) .setActool(actool).setIbtool(ibtool).setMomc(momc) .setCopySceneKitAssets(getOptionalTool("copySceneKitAssets", toolSearchPaths, xcodeToolFinder, version, filesystem)) .setXctest(xctest).setDsymutil(dsymutil).setLipo(lipo).setStubBinary(stubBinaryPath).setLldb(lldb) .setCodesignAllocate( getOptionalTool("codesign_allocate", toolSearchPaths, xcodeToolFinder, version, filesystem)) .setCodesignProvider(appleConfig.getCodesignProvider()); return platformBuilder.build(); }
From source file:io.horizondb.model.schema.DefaultRecordSetDefinition.java
/** * Builds the mapping between the record type names and indices. * //from w ww . j ava 2 s.c om * @param recordTypes the record types * @return the mapping between the record type names and indices. */ private static BiMap<String, Integer> buildRecordTypeIndices(Serializables<RecordTypeDefinition> recordTypes) { ImmutableBiMap.Builder<String, Integer> builder = ImmutableBiMap.builder(); for (int i = 0, m = recordTypes.size(); i < m; i++) { RecordTypeDefinition recordType = recordTypes.get(i); builder.put(recordType.getName(), Integer.valueOf(i)); } return builder.build(); }
From source file:com.github.rinde.rinsim.central.arrays.ArraysSolverValidator.java
/** * Validates the inputs for the {@link MultiVehicleArraysSolver}. This method * checks all properties as defined in//from ww w . j a va 2s . c o m * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . If the inputs are not correct an {@link IllegalArgumentException} is * thrown. * @param travelTime Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param releaseDates Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param dueDates Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param servicePairs Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param serviceTimes Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param vehicleTravelTimes Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param inventories Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param remainingServiceTimes Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param currentDestinations Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param currentSolutions Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . */ public static void validateInputs(int[][] travelTime, int[] releaseDates, int[] dueDates, int[][] servicePairs, int[] serviceTimes, int[][] vehicleTravelTimes, int[][] inventories, int[] remainingServiceTimes, int[] currentDestinations, @Nullable SolutionObject[] currentSolutions) { validateInputs(travelTime, releaseDates, dueDates, servicePairs, serviceTimes); // number of vehicles v final int v = vehicleTravelTimes.length; final int n = travelTime.length; checkArgument(v > 0, "At least one vehicle is required."); checkArgument(v == remainingServiceTimes.length, "Expected a remainingServiceTimes array of size %s, but found one with " + "size %s.", v, remainingServiceTimes.length); checkArgument(currentDestinations.length == v, "The currentDestinations array should be of length v=%s, it is %s.", v, currentDestinations.length); validateVehicleTravelTimes(v, n, vehicleTravelTimes, currentDestinations); final ImmutableSet.Builder<Integer> b = ImmutableSet.builder(); for (int i = 0; i < servicePairs.length; i++) { b.add(servicePairs[i][0]); b.add(servicePairs[i][1]); } final Set<Integer> availLocs = b.build(); final int m = n - 2 - servicePairs.length * 2; checkArgument(inventories.length == m, "Invalid number of inventory entries, must be equal to number of " + "delivery locations: %s, found: %s.", m, servicePairs.length); final Multimap<Integer, Integer> inventoriesMap = HashMultimap.create(); final Set<Integer> parcelsInInventory = newHashSet(); for (int i = 0; i < m; i++) { checkArgument(2 == inventories[i].length, "We expected inventories matrix of size m x 2, but we found m x %s " + "at index %s.", inventories[i].length, i); checkArgument(inventories[i][0] >= 0 && inventories[i][0] < v, "Found a reference to a non-existing vehicle (%s) in inventories at " + "row %s.", inventories[i][0], i); checkArgument(inventories[i][1] >= 1 && inventories[i][1] < n - 1, "Found a reference to a non-existing location (%s) in inventories at" + " row %s.", inventories[i][1], i); checkArgument(!availLocs.contains(inventories[i][1]), "Found a reference to a location (%s) in inventories at row %s which " + "is available, as such, it can not be in the inventory.", inventories[i][1], i); checkArgument(!parcelsInInventory.contains(inventories[i][1]), "Found a duplicate inventory entry, first duplicate at row %s.", i); parcelsInInventory.add(inventories[i][1]); inventoriesMap.put(inventories[i][0], inventories[i][1]); } for (int i = 0; i < v; i++) { checkArgument(remainingServiceTimes[i] >= 0, "Remaining service time must be >= 0, found %s.", remainingServiceTimes[i]); } final ImmutableBiMap.Builder<Integer, Integer> servicePairsBuilder = ImmutableBiMap.builder(); for (int i = 0; i < servicePairs.length; i++) { servicePairsBuilder.put(servicePairs[i][0], servicePairs[i][1]); } final ImmutableBiMap<Integer, Integer> servicePairsMap = servicePairsBuilder.build(); for (int i = 0; i < v; i++) { if (remainingServiceTimes[i] != 0) { checkArgument(currentDestinations[i] != 0); } if (currentDestinations[i] != 0) { final int dest = currentDestinations[i]; checkArgument(dest >= 1 && dest < n - 1, "The destination must be a valid location, it can not be the " + "depot. It is %s.", dest); final boolean isAvailablePickupLoc = servicePairsMap.keySet().contains(dest); final boolean isInInventory = inventoriesMap.containsValue(dest); checkArgument(isAvailablePickupLoc != isInInventory, "The destination location %s must be an available pickup location " + "OR a delivery location which is in the inventory, available " + "pickup loc: %s, in inventory: %s.", dest, isAvailablePickupLoc, isInInventory); if (parcelsInInventory.contains(dest)) { checkArgument(inventoriesMap.get(i).contains(dest), "When a vehicle is moving towards a destination which is a " + "delivery location, it must contain this parcel in its " + "cargo. Vehicle %s, destination %s.", i, dest); } } } if (currentSolutions != null) { validateCurrentSolutions(v, n, currentSolutions, currentDestinations, inventoriesMap, servicePairsMap); } }
From source file:net.minecrell.quartz.mappings.loader.Mappings.java
public static Mapper createMapper(Map<String, MappedClass> mappings) { ImmutableBiMap.Builder<String, String> classes = ImmutableBiMap.builder(); ImmutableTable.Builder<String, String, String> methods = ImmutableTable.builder(); ImmutableTable.Builder<String, String, String> fields = ImmutableTable.builder(); ImmutableTable.Builder<String, String, AccessTransform> accessTransforms = ImmutableTable.builder(); ImmutableMultimap.Builder<String, MethodNode> constructors = ImmutableMultimap.builder(); for (Map.Entry<String, MappedClass> entry : mappings.entrySet()) { String internalName = entry.getKey(); String className = internalName.replace('/', '.'); MappedClass mapping = entry.getValue(); String mappedName = mapping.getName(); classes.put(mappedName, internalName); if (mapping.hasMethods()) { fillTable(methods, mappedName, mapping.getMethods()); }/*from w w w .j a va 2 s .c o m*/ if (mapping.hasFields()) { fillTable(fields, mappedName, mapping.getFields()); } if (mapping.hasAccess()) { fillTable(accessTransforms, className, mapping.getAccess()); } } return new Mapper(classes.build(), methods.build(), fields.build(), accessTransforms.build()); }
From source file:com.facebook.buck.android.NdkCxxPlatforms.java
@VisibleForTesting static NdkCxxPlatform build(CxxBuckConfig config, ProjectFilesystem filesystem, Flavor flavor, Platform platform, Path ndkRoot, NdkCxxPlatformTargetConfiguration targetConfiguration, CxxRuntime cxxRuntime, ExecutableFinder executableFinder, boolean strictToolchainPaths) { // Create a version string to use when generating rule keys via the NDK tools we'll generate // below. This will be used in lieu of hashing the contents of the tools, so that builds from // different host platforms (which produce identical output) will share the cache with one // another./*www . j av a2 s. co m*/ NdkCxxPlatformCompiler.Type compilerType = targetConfiguration.getCompiler().getType(); String version = Joiner.on('-') .join(ImmutableList.of(readVersion(ndkRoot), targetConfiguration.getToolchain(), targetConfiguration.getTargetAppPlatform(), compilerType, targetConfiguration.getCompiler().getVersion(), targetConfiguration.getCompiler().getGccVersion(), cxxRuntime)); Host host = Preconditions.checkNotNull(BUILD_PLATFORMS.get(platform)); NdkCxxToolchainPaths toolchainPaths = new NdkCxxToolchainPaths(filesystem, ndkRoot, targetConfiguration, host.toString(), cxxRuntime, strictToolchainPaths); // Sanitized paths will have magic placeholders for parts of the paths that // are machine/host-specific. See comments on ANDROID_NDK_ROOT and // BUILD_HOST_SUBST above. NdkCxxToolchainPaths sanitizedPaths = toolchainPaths.getSanitizedPaths(); // Build up the map of paths that must be sanitized. ImmutableBiMap.Builder<Path, Path> sanitizePathsBuilder = ImmutableBiMap.builder(); sanitizePathsBuilder.put(toolchainPaths.getNdkToolRoot(), sanitizedPaths.getNdkToolRoot()); if (compilerType != NdkCxxPlatformCompiler.Type.GCC) { sanitizePathsBuilder.put(toolchainPaths.getNdkGccToolRoot(), sanitizedPaths.getNdkGccToolRoot()); } sanitizePathsBuilder.put(ndkRoot, Paths.get(ANDROID_NDK_ROOT)); CxxToolProvider.Type type = compilerType == NdkCxxPlatformCompiler.Type.CLANG ? CxxToolProvider.Type.CLANG : CxxToolProvider.Type.GCC; ToolProvider ccTool = new ConstantToolProvider( getCTool(toolchainPaths, compilerType.getCc(), version, executableFinder)); ToolProvider cxxTool = new ConstantToolProvider( getCTool(toolchainPaths, compilerType.getCxx(), version, executableFinder)); CompilerProvider cc = new CompilerProvider(ccTool, type); PreprocessorProvider cpp = new PreprocessorProvider(ccTool, type); CompilerProvider cxx = new CompilerProvider(cxxTool, type); PreprocessorProvider cxxpp = new PreprocessorProvider(cxxTool, type); CxxPlatform.Builder cxxPlatformBuilder = CxxPlatform.builder(); ImmutableBiMap<Path, Path> sanitizePaths = sanitizePathsBuilder.build(); PrefixMapDebugPathSanitizer compilerDebugPathSanitizer = new PrefixMapDebugPathSanitizer( config.getDebugPathSanitizerLimit(), File.separatorChar, Paths.get("."), sanitizePaths, filesystem.getRootPath().toAbsolutePath(), type); MungingDebugPathSanitizer assemblerDebugPathSanitizer = new MungingDebugPathSanitizer( config.getDebugPathSanitizerLimit(), File.separatorChar, Paths.get("."), sanitizePaths); cxxPlatformBuilder.setFlavor(flavor).setAs(cc) .addAllAsflags(getAsflags(targetConfiguration, toolchainPaths)).setAspp(cpp).setCc(cc) .addAllCflags(getCflagsInternal(targetConfiguration, toolchainPaths)).setCpp(cpp) .addAllCppflags(getCppflags(targetConfiguration, toolchainPaths)).setCxx(cxx) .addAllCxxflags(getCxxflagsInternal(targetConfiguration, toolchainPaths)).setCxxpp(cxxpp) .addAllCxxppflags(getCxxppflags(targetConfiguration, toolchainPaths)) .setLd(new DefaultLinkerProvider(LinkerProvider.Type.GNU, new ConstantToolProvider(getCcLinkTool(targetConfiguration, toolchainPaths, compilerType.getCxx(), version, executableFinder)))) .addAllLdflags(targetConfiguration.getLinkerFlags(compilerType)) // Default linker flags added by the NDK .addLdflags( // Add a deterministic build ID to Android builds. // We use it to find symbols from arbitrary binaries. "-Wl,--build-id", // Enforce the NX (no execute) security feature "-Wl,-z,noexecstack", // Strip unused code "-Wl,--gc-sections", // Refuse to produce dynamic objects with undefined symbols "-Wl,-z,defs", // Forbid dangerous copy "relocations" "-Wl,-z,nocopyreloc", // We always pass the runtime library on the command line, so setting this flag // means the resulting link will only use it if it was actually needed it. "-Wl,--as-needed") .setStrip(getGccTool(toolchainPaths, "strip", version, executableFinder)) .setSymbolNameTool( new PosixNmSymbolNameTool(getGccTool(toolchainPaths, "nm", version, executableFinder))) .setAr(new GnuArchiver(getGccTool(toolchainPaths, "ar", version, executableFinder))) .setRanlib(getGccTool(toolchainPaths, "ranlib", version, executableFinder)) // NDK builds are cross compiled, so the header is the same regardless of the host platform. .setCompilerDebugPathSanitizer(compilerDebugPathSanitizer) .setAssemblerDebugPathSanitizer(assemblerDebugPathSanitizer).setSharedLibraryExtension("so") .setSharedLibraryVersionedExtensionFormat("so.%s").setStaticLibraryExtension("a") .setObjectFileExtension("o") .setSharedLibraryInterfaceFactory(config.shouldUseSharedLibraryInterfaces() ? Optional.of(ElfSharedLibraryInterfaceFactory.of(new ConstantToolProvider( getGccTool(toolchainPaths, "objcopy", version, executableFinder)))) : Optional.empty()) .setHeaderVerification(config.getHeaderVerification()); if (cxxRuntime != CxxRuntime.SYSTEM) { cxxPlatformBuilder.putRuntimeLdflags(Linker.LinkableDepType.SHARED, "-l" + cxxRuntime.getSharedName()); cxxPlatformBuilder.putRuntimeLdflags(Linker.LinkableDepType.STATIC, "-l" + cxxRuntime.getStaticName()); } CxxPlatform cxxPlatform = cxxPlatformBuilder.build(); return NdkCxxPlatform.builder().setCxxPlatform(cxxPlatform).setCxxRuntime(cxxRuntime) .setCxxSharedRuntimePath( toolchainPaths.getCxxRuntimeLibsDirectory().resolve(cxxRuntime.getSoname())) .setObjdump(getGccTool(toolchainPaths, "objdump", version, executableFinder)).build(); }
From source file:com.facebook.buck.android.toolchain.ndk.impl.NdkCxxPlatforms.java
@VisibleForTesting static UnresolvedNdkCxxPlatform build(CxxBuckConfig config, AndroidBuckConfig androidConfig, ProjectFilesystem filesystem, Flavor flavor, Platform platform, Path ndkRoot, NdkCxxPlatformTargetConfiguration targetConfiguration, NdkCxxRuntime cxxRuntime, NdkCxxRuntimeType runtimeType, ExecutableFinder executableFinder, boolean strictToolchainPaths) { String ndkVersion = readVersion(ndkRoot); if (getNdkMajorVersion(ndkVersion) > 17 && cxxRuntime != NdkCxxRuntime.LIBCXX && cxxRuntime != NdkCxxRuntime.SYSTEM) { throw new HumanReadableException( "C++ runtime %s was removed in Android NDK 18.\n" + "Detected Android NDK version is %s.\n" + "Configuration needs to be changed in order to build with the current Android NDK", cxxRuntime.toString(), ndkVersion); }//w ww.j a v a 2 s . c o m // Create a version string to use when generating rule keys via the NDK tools we'll generate // below. This will be used in lieu of hashing the contents of the tools, so that builds from // different host platforms (which produce identical output) will share the cache with one // another. NdkCompilerType compilerType = targetConfiguration.getCompiler().getType(); String version = Joiner.on('-') .join(ImmutableList.of(readVersion(ndkRoot), targetConfiguration.getToolchain(), targetConfiguration.getTargetAppPlatform(), compilerType, targetConfiguration.getCompiler().getVersion(), targetConfiguration.getCompiler().getGccVersion(), cxxRuntime)); Host host = getHost(platform); NdkCxxToolchainPaths toolchainPaths = new NdkCxxToolchainPaths(filesystem, ndkRoot, targetConfiguration, host.toString(), cxxRuntime, strictToolchainPaths, getUseUnifiedHeaders(androidConfig, ndkVersion)); // Sanitized paths will have magic placeholders for parts of the paths that // are machine/host-specific. See comments on ANDROID_NDK_ROOT and // BUILD_HOST_SUBST above. NdkCxxToolchainPaths sanitizedPaths = toolchainPaths.getSanitizedPaths(); // Build up the map of paths that must be sanitized. ImmutableBiMap.Builder<Path, String> sanitizePathsBuilder = ImmutableBiMap.builder(); sanitizePathsBuilder.put(toolchainPaths.getNdkToolRoot(), MorePaths.pathWithUnixSeparators(sanitizedPaths.getNdkToolRoot())); if (compilerType != NdkCompilerType.GCC) { sanitizePathsBuilder.put(toolchainPaths.getNdkGccToolRoot(), MorePaths.pathWithUnixSeparators(sanitizedPaths.getNdkGccToolRoot())); } sanitizePathsBuilder.put(ndkRoot, AndroidNdkConstants.ANDROID_NDK_ROOT); CxxToolProvider.Type type = compilerType == NdkCompilerType.CLANG ? CxxToolProvider.Type.CLANG : CxxToolProvider.Type.GCC; ToolProvider ccTool = new ConstantToolProvider( getCTool(toolchainPaths, compilerType.cc, version, executableFinder)); ToolProvider cxxTool = new ConstantToolProvider( getCTool(toolchainPaths, compilerType.cxx, version, executableFinder)); CompilerProvider cc = new CompilerProvider(ccTool, () -> type, config.getUseDetailedUntrackedHeaderMessages(), true); PreprocessorProvider cpp = new PreprocessorProvider(ccTool, type, true); CompilerProvider cxx = new CompilerProvider(cxxTool, () -> type, config.getUseDetailedUntrackedHeaderMessages(), true); PreprocessorProvider cxxpp = new PreprocessorProvider(cxxTool, type, true); CxxPlatform.Builder cxxPlatformBuilder = CxxPlatform.builder(); ImmutableBiMap<Path, String> sanitizePaths = sanitizePathsBuilder.build(); PrefixMapDebugPathSanitizer compilerDebugPathSanitizer = new PrefixMapDebugPathSanitizer(".", sanitizePaths, true); DebugPathSanitizer assemblerDebugPathSanitizer = new MungingDebugPathSanitizer( config.getDebugPathSanitizerLimit(), File.separatorChar, Paths.get("."), sanitizePaths); cxxPlatformBuilder.setFlavor(flavor).setAs(cc) .addAllAsflags(getAsflags(targetConfiguration, toolchainPaths)).setAspp(cpp).setCc(cc) .addAllCflags(getCCompilationFlags(targetConfiguration, toolchainPaths, androidConfig)).setCpp(cpp) .addAllCppflags(getCPreprocessorFlags(targetConfiguration, toolchainPaths, androidConfig)) .setCxx(cxx) .addAllCxxflags(getCxxCompilationFlags(targetConfiguration, toolchainPaths, androidConfig)) .setCxxpp(cxxpp) .addAllCxxppflags(getCxxPreprocessorFlags(targetConfiguration, toolchainPaths, androidConfig)) .setLd(new DefaultLinkerProvider(LinkerProvider.Type.GNU, new ConstantToolProvider(getCcLinkTool(targetConfiguration, toolchainPaths, compilerType.cxx, version, cxxRuntime, executableFinder)), config.shouldCacheLinks())) .addAllLdflags(getLdFlags(targetConfiguration, androidConfig)) .setStrip(getGccTool(toolchainPaths, "strip", version, executableFinder)) .setSymbolNameTool( new PosixNmSymbolNameTool(getGccTool(toolchainPaths, "nm", version, executableFinder))) .setAr(ArchiverProvider .from(new GnuArchiver(getGccTool(toolchainPaths, "ar", version, executableFinder)))) .setArchiveContents(config.getArchiveContents().orElse(ArchiveContents.NORMAL)) .setRanlib( new ConstantToolProvider(getGccTool(toolchainPaths, "ranlib", version, executableFinder))) // NDK builds are cross compiled, so the header is the same regardless of the host platform. .setCompilerDebugPathSanitizer(compilerDebugPathSanitizer) .setAssemblerDebugPathSanitizer(assemblerDebugPathSanitizer).setSharedLibraryExtension("so") .setSharedLibraryVersionedExtensionFormat("so.%s").setStaticLibraryExtension("a") .setObjectFileExtension("o") .setSharedLibraryInterfaceParams( config.getSharedLibraryInterfaces() != SharedLibraryInterfaceParams.Type.DISABLED ? Optional.of(ElfSharedLibraryInterfaceParams.of( new ConstantToolProvider( getGccTool(toolchainPaths, "objcopy", version, executableFinder)), ImmutableList.of(), config.getSharedLibraryInterfaces() == SharedLibraryInterfaceParams.Type.DEFINED_ONLY)) : Optional.empty()) .setPublicHeadersSymlinksEnabled(config.getPublicHeadersSymlinksEnabled()) .setPrivateHeadersSymlinksEnabled(config.getPrivateHeadersSymlinksEnabled()) .setFilepathLengthLimited(config.getFilepathLengthLimited()); // Add the NDK root path to the white-list so that headers from the NDK won't trigger the // verification warnings. Ideally, long-term, we'd model NDK libs/headers via automatically // generated nodes/descriptions so that they wouldn't need to special case it here. HeaderVerification headerVerification = config.getHeaderVerificationOrIgnore(); try { headerVerification = headerVerification.withPlatformWhitelist(ImmutableList .of("^" + Pattern.quote(ndkRoot.toRealPath().toString() + File.separatorChar) + ".*")); } catch (IOException e) { LOG.warn(e, "NDK path could not be resolved: %s", ndkRoot); } cxxPlatformBuilder.setHeaderVerification(headerVerification); LOG.debug("NDK root: %s", ndkRoot.toString()); LOG.debug("Headers verification platform whitelist: %s", headerVerification.getPlatformWhitelist()); if (cxxRuntime != NdkCxxRuntime.SYSTEM) { cxxPlatformBuilder.putRuntimeLdflags(Linker.LinkableDepType.SHARED, "-l" + cxxRuntime.sharedName); cxxPlatformBuilder.putRuntimeLdflags(Linker.LinkableDepType.STATIC, "-l" + cxxRuntime.staticName); if (getNdkMajorVersion(ndkVersion) >= 12 && cxxRuntime == NdkCxxRuntime.LIBCXX) { if (getNdkMajorVersion(ndkVersion) < 17 || targetConfiguration.getTargetArchAbi() == NdkTargetArchAbi.ARMEABI_V7A || targetConfiguration.getTargetArchAbi() == NdkTargetArchAbi.X86) { cxxPlatformBuilder.putRuntimeLdflags(Linker.LinkableDepType.STATIC, "-landroid_support"); } cxxPlatformBuilder.putRuntimeLdflags(Linker.LinkableDepType.STATIC, "-lc++abi"); if (targetConfiguration.getTargetArchAbi() == NdkTargetArchAbi.ARMEABI) { cxxPlatformBuilder.putRuntimeLdflags(Linker.LinkableDepType.STATIC, "-latomic"); } } } CxxPlatform cxxPlatform = cxxPlatformBuilder.build(); NdkCxxPlatform.Builder builder = NdkCxxPlatform.builder(); builder.setCxxPlatform(cxxPlatform).setCxxRuntime(cxxRuntime) .setObjdump(getGccTool(toolchainPaths, "objdump", version, executableFinder)); if ((cxxRuntime != NdkCxxRuntime.SYSTEM) && (runtimeType != NdkCxxRuntimeType.STATIC)) { builder.setCxxSharedRuntimePath(PathSourcePath.of(filesystem, toolchainPaths.getCxxRuntimeLibsDirectory().resolve(cxxRuntime.getSoname()))); } return StaticUnresolvedNdkCxxPlatform.of(builder.build()); }
From source file:com.publictransitanalytics.scoregenerator.Main.java
private static <S extends ScoreCard> BiMap<OperationDescription, Calculation<S>> runComparison( final OperationDescription baseDescription, final ScoreCardFactory scoreCardFactory, final Set<Center> centers, final Duration samplingInterval, final Duration span, final boolean backward, final TimeTracker timeTracker, final Grid grid, final Map<String, ServiceDataDirectory> serviceDirectoriesMap, final Duration longestDuration, final OperationDescription comparisonDescription, final NetworkConsoleFactory consoleFactory) throws InterruptedException, IOException, ExecutionException { final ImmutableBiMap.Builder<OperationDescription, Calculation<S>> resultBuilder = ImmutableBiMap.builder(); final Calculation<S> calculation = buildCalculation(baseDescription, serviceDirectoriesMap, grid, centers, longestDuration, backward, span, samplingInterval, timeTracker, scoreCardFactory); final NetworkConsole console = consoleFactory.getConsole(calculation.getTransitNetwork(), calculation.getStopIdMap()); console.enterConsole();/*from w ww . j a va 2 s . co m*/ resultBuilder.put(baseDescription, calculation); final Environment environment = new Environment(grid, longestDuration); if (comparisonDescription != null) { final Calculation trialCalculation = buildCalculation(comparisonDescription, serviceDirectoriesMap, grid, centers, longestDuration, backward, span, samplingInterval, timeTracker, scoreCardFactory); final NetworkConsole trialConsole = consoleFactory.getConsole(trialCalculation.getTransitNetwork(), trialCalculation.getStopIdMap()); trialConsole.enterConsole(); log.info("Trial in service time = {}; original in service time = {}.", trialCalculation.getTransitNetwork().getInServiceTime(), calculation.getTransitNetwork().getInServiceTime()); resultBuilder.put(comparisonDescription, trialCalculation); } final BiMap<OperationDescription, Calculation<S>> calculations = resultBuilder.build(); final Workflow workflow = new ParallelTaskExecutor( new ProgressiveRangeExecutor(new DynamicProgrammingAlgorithm(), environment)); workflow.calculate(calculations.values()); return calculations; }
From source file:org.neatrchlab.StatefulP4Interpreter.java
@Override public ImmutableBiMap<Criterion.Type, String> criterionTypeMap() { ImmutableBiMap.Builder<Criterion.Type, String> builder = ImmutableBiMap.builder(); builder.put(Criterion.Type.IN_PORT, "standard_metadata.ingress_port"); builder.put(Criterion.Type.ETH_DST, "ethernet.dstAddr"); builder.put(Criterion.Type.ETH_SRC, "ethernet.srcAddr"); builder.put(Criterion.Type.ETH_TYPE, "ethernet.etherType"); return builder.build(); }
From source file:com.facebook.buck.cxx.MungingDebugPathSanitizer.java
private ImmutableBiMap<Path, Path> getAllPathsWork(Path workingDir) { ImmutableBiMap.Builder<Path, Path> builder = ImmutableBiMap.builder(); builder.put(workingDir, compilationDirectory); builder.putAll(other);/*from w w w .j a va 2 s . c o m*/ return builder.build(); }
From source file:com.google.devtools.build.lib.skyframe.ToolchainUtil.java
@Nullable private static ImmutableBiMap<Label, Label> resolveToolchainLabels(Environment env, Set<Label> requiredToolchains, BuildConfiguration configuration) throws InterruptedException, ToolchainContextException { // If there are no required toolchains, bail out early. if (requiredToolchains.isEmpty()) { return ImmutableBiMap.of(); }/*ww w . ja v a2 s . c o m*/ // Load the execution and target platforms for the current configuration. PlatformDescriptors platforms = loadPlatformDescriptors(env, configuration); if (platforms == null) { return null; } // Find the toolchains for the required toolchain types. List<SkyKey> registeredToolchainKeys = new ArrayList<>(); for (Label toolchainType : requiredToolchains) { registeredToolchainKeys.add(ToolchainResolutionValue.key(configuration, toolchainType, platforms.targetPlatform(), platforms.execPlatform())); } Map<SkyKey, ValueOrException4<NoToolchainFoundException, ConfiguredValueCreationException, InvalidToolchainLabelException, EvalException>> results = env .getValuesOrThrow(registeredToolchainKeys, NoToolchainFoundException.class, ConfiguredValueCreationException.class, InvalidToolchainLabelException.class, EvalException.class); boolean valuesMissing = false; // Load the toolchains. ImmutableBiMap.Builder<Label, Label> builder = new ImmutableBiMap.Builder<>(); List<Label> missingToolchains = new ArrayList<>(); for (Map.Entry<SkyKey, ValueOrException4<NoToolchainFoundException, ConfiguredValueCreationException, InvalidToolchainLabelException, EvalException>> entry : results .entrySet()) { try { Label requiredToolchainType = ((ToolchainResolutionKey) entry.getKey().argument()).toolchainType(); ValueOrException4<NoToolchainFoundException, ConfiguredValueCreationException, InvalidToolchainLabelException, EvalException> valueOrException = entry .getValue(); if (valueOrException.get() == null) { valuesMissing = true; } else { Label toolchainLabel = ((ToolchainResolutionValue) valueOrException.get()).toolchainLabel(); builder.put(requiredToolchainType, toolchainLabel); } } catch (NoToolchainFoundException e) { // Save the missing type and continue looping to check for more. missingToolchains.add(e.missingToolchainType()); } catch (ConfiguredValueCreationException e) { throw new ToolchainContextException(e); } catch (InvalidToolchainLabelException e) { throw new ToolchainContextException(e); } catch (EvalException e) { throw new ToolchainContextException(e); } } if (!missingToolchains.isEmpty()) { throw new ToolchainContextException(new UnresolvedToolchainsException(missingToolchains)); } if (valuesMissing) { return null; } return builder.build(); }