Path: blob/master/src/jdk.compiler/share/classes/com/sun/tools/sjavac/JavacState.java
41175 views
/*1* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package com.sun.tools.sjavac;2627import java.io.BufferedReader;28import java.io.File;29import java.io.FileNotFoundException;30import java.io.FileReader;31import java.io.FileWriter;32import java.io.IOException;33import java.io.Writer;34import java.net.URI;35import java.nio.file.NoSuchFileException;36import java.text.SimpleDateFormat;37import java.util.Collection;38import java.util.Collections;39import java.util.Date;40import java.util.HashMap;41import java.util.HashSet;42import java.util.List;43import java.util.Map;44import java.util.Set;45import java.util.stream.Collectors;4647import com.sun.tools.sjavac.comp.CompilationService;48import com.sun.tools.sjavac.options.Options;49import com.sun.tools.sjavac.pubapi.PubApi;5051/**52* The javac state class maintains the previous (prev) and the current (now)53* build states and everything else that goes into the javac_state file.54*55* <p><b>This is NOT part of any supported API.56* If you write code that depends on this, you do so at your own risk.57* This code and its internal interfaces are subject to change or58* deletion without notice.</b>59*/60public class JavacState {61// The arguments to the compile. If not identical, then it cannot62// be an incremental build!63String theArgs;64// The number of cores limits how many threads are used for heavy concurrent work.65int numCores;6667// The bin_dir/javac_state68private File javacState;6970// The previous build state is loaded from javac_state71private BuildState prev;72// The current build state is constructed during the build,73// then saved as the new javac_state.74private BuildState now;7576// Something has changed in the javac_state. It needs to be saved!77private boolean needsSaving;78// If this is a new javac_state file, then do not print unnecessary messages.79private boolean newJavacState;8081// These are packages where something has changed and the package82// needs to be recompiled. Actions that trigger recompilation:83// * source belonging to the package has changed84// * artifact belonging to the package is lost, or its timestamp has been changed.85// * an unknown artifact has appeared, we simply delete it, but we also trigger a recompilation.86// * a package that is tainted, taints all packages that depend on it.87private Set<String> taintedPackages;88// After a compile, the pubapis are compared with the pubapis stored in the javac state file.89// Any packages where the pubapi differ are added to this set.90// Later we use this set and the dependency information to taint dependent packages.91private Set<String> packagesWithChangedPublicApis;92// When a module-info.java file is changed, taint the module,93// then taint all modules that depend on that that module.94// A module dependency can occur directly through a require, or95// indirectly through a module that does a public export for the first tainted module.96// When all modules are tainted, then taint all packages belonging to these modules.97// Then rebuild. It is perhaps possible (and valuable?) to do a more fine-grained examination of the98// change in module-info.java, but that will have to wait.99private Set<String> taintedModules;100// The set of all packages that has been recompiled.101// Copy over the javac_state for the packages that did not need recompilation,102// verbatim from the previous (prev) to the new (now) build state.103private Set<String> recompiledPackages;104105// The output directories filled with tasty artifacts.106private File binDir, gensrcDir, headerDir, stateDir;107108// The current status of the file system.109private Set<File> binArtifacts;110private Set<File> gensrcArtifacts;111private Set<File> headerArtifacts;112113// The status of the sources.114Set<Source> removedSources = null;115Set<Source> addedSources = null;116Set<Source> modifiedSources = null;117118// Visible sources for linking. These are the only119// ones that -sourcepath is allowed to see.120Set<URI> visibleSrcs;121122// Setup transform that always exist.123private CompileJavaPackages compileJavaPackages = new CompileJavaPackages();124125// Command line options.126private Options options;127128JavacState(Options op, boolean removeJavacState) {129options = op;130numCores = options.getNumCores();131theArgs = options.getStateArgsString();132binDir = Util.pathToFile(options.getDestDir());133gensrcDir = Util.pathToFile(options.getGenSrcDir());134headerDir = Util.pathToFile(options.getHeaderDir());135stateDir = Util.pathToFile(options.getStateDir());136javacState = new File(stateDir, "javac_state");137if (removeJavacState && javacState.exists()) {138javacState.delete();139}140newJavacState = false;141if (!javacState.exists()) {142newJavacState = true;143// If there is no javac_state then delete the contents of all the artifact dirs!144// We do not want to risk building a broken incremental build.145// BUT since the makefiles still copy things straight into the bin_dir et al,146// we avoid deleting files here, if the option --permit-unidentified-classes was supplied.147if (!options.areUnidentifiedArtifactsPermitted()) {148deleteContents(binDir);149deleteContents(gensrcDir);150deleteContents(headerDir);151}152needsSaving = true;153}154prev = new BuildState();155now = new BuildState();156taintedPackages = new HashSet<>();157recompiledPackages = new HashSet<>();158packagesWithChangedPublicApis = new HashSet<>();159}160161public BuildState prev() { return prev; }162public BuildState now() { return now; }163164/**165* Remove args not affecting the state.166*/167static String[] removeArgsNotAffectingState(String[] args) {168String[] out = new String[args.length];169int j = 0;170for (int i = 0; i<args.length; ++i) {171if (args[i].equals("-j")) {172// Just skip it and skip following value173i++;174} else if (args[i].startsWith("--server:")) {175// Just skip it.176} else if (args[i].startsWith("--log=")) {177// Just skip it.178} else if (args[i].equals("--compare-found-sources")) {179// Just skip it and skip verify file name180i++;181} else {182// Copy argument.183out[j] = args[i];184j++;185}186}187String[] ret = new String[j];188System.arraycopy(out, 0, ret, 0, j);189return ret;190}191192/**193* Specify which sources are visible to the compiler through -sourcepath.194*/195public void setVisibleSources(Map<String,Source> vs) {196visibleSrcs = new HashSet<>();197for (String s : vs.keySet()) {198Source src = vs.get(s);199visibleSrcs.add(src.file().toURI());200}201}202203/**204* Returns true if this is an incremental build.205*/206public boolean isIncremental() {207return !prev.sources().isEmpty();208}209210/**211* Find all artifacts that exists on disk.212*/213public void findAllArtifacts() {214binArtifacts = findAllFiles(binDir);215gensrcArtifacts = findAllFiles(gensrcDir);216headerArtifacts = findAllFiles(headerDir);217}218219/**220* Lookup the artifacts generated for this package in the previous build.221*/222private Map<String,File> fetchPrevArtifacts(String pkg) {223Package p = prev.packages().get(pkg);224if (p != null) {225return p.artifacts();226}227return new HashMap<>();228}229230/**231* Delete all prev artifacts in the currently tainted packages.232*/233public void deleteClassArtifactsInTaintedPackages() {234for (String pkg : taintedPackages) {235Map<String,File> arts = fetchPrevArtifacts(pkg);236for (File f : arts.values()) {237if (f.exists() && f.getName().endsWith(".class")) {238f.delete();239}240}241}242}243244/**245* Mark the javac_state file to be in need of saving and as a side effect,246* it gets a new timestamp.247*/248private void needsSaving() {249needsSaving = true;250}251252/**253* Save the javac_state file.254*/255public void save() throws IOException {256if (!needsSaving)257return;258try (FileWriter out = new FileWriter(javacState)) {259StringBuilder b = new StringBuilder();260long millisNow = System.currentTimeMillis();261Date d = new Date(millisNow);262SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");263b.append("# javac_state ver 0.4 generated "+millisNow+" "+df.format(d)+"\n");264b.append("# This format might change at any time. Please do not depend on it.\n");265b.append("# R arguments\n");266b.append("# M module\n");267b.append("# P package\n");268b.append("# S C source_tobe_compiled timestamp\n");269b.append("# S L link_only_source timestamp\n");270b.append("# G C generated_source timestamp\n");271b.append("# A artifact timestamp\n");272b.append("# D S dependant -> source dependency\n");273b.append("# D C dependant -> classpath dependency\n");274b.append("# I pubapi\n");275b.append("R ").append(theArgs).append("\n");276277// Copy over the javac_state for the packages that did not need recompilation.278now.copyPackagesExcept(prev, recompiledPackages, new HashSet<String>());279// Save the packages, ie package names, dependencies, pubapis and artifacts!280// I.e. the lot.281Module.saveModules(now.modules(), b);282283String s = b.toString();284out.write(s, 0, s.length());285}286}287288/**289* Load a javac_state file.290*/291public static JavacState load(Options options) {292JavacState db = new JavacState(options, false);293Module lastModule = null;294Package lastPackage = null;295Source lastSource = null;296boolean noFileFound = false;297boolean foundCorrectVerNr = false;298boolean newCommandLine = false;299boolean syntaxError = false;300301Log.debug("Loading javac state file: " + db.javacState);302303try (BufferedReader in = new BufferedReader(new FileReader(db.javacState))) {304for (;;) {305String l = in.readLine();306if (l==null) break;307if (l.length()>=3 && l.charAt(1) == ' ') {308char c = l.charAt(0);309if (c == 'M') {310lastModule = db.prev.loadModule(l);311} else312if (c == 'P') {313if (lastModule == null) { syntaxError = true; break; }314lastPackage = db.prev.loadPackage(lastModule, l);315} else316if (c == 'D') {317if (lastModule == null || lastPackage == null) { syntaxError = true; break; }318char depType = l.charAt(2);319if (depType != 'S' && depType != 'C')320throw new RuntimeException("Bad dependency string: " + l);321lastPackage.parseAndAddDependency(l.substring(4), depType == 'C');322} else323if (c == 'I') {324if (lastModule == null || lastPackage == null) { syntaxError = true; break; }325lastPackage.getPubApi().appendItem(l.substring(2)); // Strip "I "326} else327if (c == 'A') {328if (lastModule == null || lastPackage == null) { syntaxError = true; break; }329lastPackage.loadArtifact(l);330} else331if (c == 'S') {332if (lastModule == null || lastPackage == null) { syntaxError = true; break; }333lastSource = db.prev.loadSource(lastPackage, l, false);334} else335if (c == 'G') {336if (lastModule == null || lastPackage == null) { syntaxError = true; break; }337lastSource = db.prev.loadSource(lastPackage, l, true);338} else339if (c == 'R') {340String ncmdl = "R "+db.theArgs;341if (!l.equals(ncmdl)) {342newCommandLine = true;343}344} else345if (c == '#') {346if (l.startsWith("# javac_state ver ")) {347int sp = l.indexOf(" ", 18);348if (sp != -1) {349String ver = l.substring(18,sp);350if (!ver.equals("0.4")) {351break;352}353foundCorrectVerNr = true;354}355}356}357}358}359} catch (FileNotFoundException | NoSuchFileException e) {360// Silently create a new javac_state file.361noFileFound = true;362} catch (IOException e) {363Log.warn("Dropping old javac_state because of errors when reading it.");364db = new JavacState(options, true);365foundCorrectVerNr = true;366newCommandLine = false;367syntaxError = false;368}369if (foundCorrectVerNr == false && !noFileFound) {370Log.debug("Dropping old javac_state since it is of an old version.");371db = new JavacState(options, true);372} else373if (newCommandLine == true && !noFileFound) {374Log.debug("Dropping old javac_state since a new command line is used!");375db = new JavacState(options, true);376} else377if (syntaxError == true) {378Log.warn("Dropping old javac_state since it contains syntax errors.");379db = new JavacState(options, true);380}381db.prev.calculateDependents();382return db;383}384385/**386* Mark a java package as tainted, ie it needs recompilation.387*/388public void taintPackage(String name, String because) {389if (!taintedPackages.contains(name)) {390if (because != null) Log.debug("Tainting "+Util.justPackageName(name)+" because "+because);391// It has not been tainted before.392taintedPackages.add(name);393needsSaving();394Package nowp = now.packages().get(name);395if (nowp != null) {396for (String d : nowp.dependents()) {397taintPackage(d, because);398}399}400}401}402403/**404* This packages need recompilation.405*/406public Set<String> taintedPackages() {407return taintedPackages;408}409410/**411* Clean out the tainted package set, used after the first round of compiles,412* prior to propagating dependencies.413*/414public void clearTaintedPackages() {415taintedPackages = new HashSet<>();416}417418/**419* Go through all sources and check which have been removed, added or modified420* and taint the corresponding packages.421*/422public void checkSourceStatus(boolean check_gensrc) {423removedSources = calculateRemovedSources();424for (Source s : removedSources) {425if (!s.isGenerated() || check_gensrc) {426taintPackage(s.pkg().name(), "source "+s.name()+" was removed");427}428}429430addedSources = calculateAddedSources();431for (Source s : addedSources) {432String msg = null;433if (isIncremental()) {434// When building from scratch, there is no point435// printing "was added" for every file since all files are added.436// However for an incremental build it makes sense.437msg = "source "+s.name()+" was added";438}439if (!s.isGenerated() || check_gensrc) {440taintPackage(s.pkg().name(), msg);441}442}443444modifiedSources = calculateModifiedSources();445for (Source s : modifiedSources) {446if (!s.isGenerated() || check_gensrc) {447taintPackage(s.pkg().name(), "source "+s.name()+" was modified");448}449}450}451452/**453* Acquire the compile_java_packages suffix rule for .java files.454*/455public Map<String,Transformer> getJavaSuffixRule() {456Map<String,Transformer> sr = new HashMap<>();457sr.put(".java", compileJavaPackages);458return sr;459}460461462/**463* If artifacts have gone missing, force a recompile of the packages464* they belong to.465*/466public void taintPackagesThatMissArtifacts() {467for (Package pkg : prev.packages().values()) {468for (File f : pkg.artifacts().values()) {469if (!f.exists()) {470// Hmm, the artifact on disk does not exist! Someone has removed it....471// Lets rebuild the package.472taintPackage(pkg.name(), ""+f+" is missing.");473}474}475}476}477478/**479* Propagate recompilation through the dependency chains.480* Avoid re-tainting packages that have already been compiled.481*/482public void taintPackagesDependingOnChangedPackages(Set<String> pkgsWithChangedPubApi, Set<String> recentlyCompiled) {483// For each to-be-recompiled-candidates...484for (Package pkg : new HashSet<>(prev.packages().values())) {485// Find out what it depends upon...486Set<String> deps = pkg.typeDependencies()487.values()488.stream()489.flatMap(Collection::stream)490.collect(Collectors.toSet());491for (String dep : deps) {492String depPkg = ":" + dep.substring(0, dep.lastIndexOf('.'));493if (depPkg.equals(pkg.name()))494continue;495// Checking if that dependency has changed496if (pkgsWithChangedPubApi.contains(depPkg) && !recentlyCompiled.contains(pkg.name())) {497taintPackage(pkg.name(), "its depending on " + depPkg);498}499}500}501}502503/**504* Compare the javac_state recorded public apis of packages on the classpath505* with the actual public apis on the classpath.506*/507public void taintPackagesDependingOnChangedClasspathPackages() throws IOException {508509// 1. Collect fully qualified names of all interesting classpath dependencies510Set<String> fqDependencies = new HashSet<>();511for (Package pkg : prev.packages().values()) {512// Check if this package was compiled. If it's presence is recorded513// because it was on the class path and we needed to save it's514// public api, it's not a candidate for tainting.515if (pkg.sources().isEmpty())516continue;517518pkg.typeClasspathDependencies().values().forEach(fqDependencies::addAll);519}520521// 2. Extract the public APIs from the on disk .class files522// (Reason for doing step 1 in a separate phase is to avoid extracting523// public APIs of the same class twice.)524PubApiExtractor pubApiExtractor = new PubApiExtractor(options);525Map<String, PubApi> onDiskPubApi = new HashMap<>();526for (String cpDep : fqDependencies) {527onDiskPubApi.put(cpDep, pubApiExtractor.getPubApi(cpDep));528}529pubApiExtractor.close();530531// 3. Compare them with the public APIs as of last compilation (loaded from javac_state)532nextPkg:533for (Package pkg : prev.packages().values()) {534// Check if this package was compiled. If it's presence is recorded535// because it was on the class path and we needed to save it's536// public api, it's not a candidate for tainting.537if (pkg.sources().isEmpty())538continue;539540Set<String> cpDepsOfThisPkg = new HashSet<>();541for (Set<String> cpDeps : pkg.typeClasspathDependencies().values())542cpDepsOfThisPkg.addAll(cpDeps);543544for (String fqDep : cpDepsOfThisPkg) {545546String depPkg = ":" + fqDep.substring(0, fqDep.lastIndexOf('.'));547PubApi prevPkgApi = prev.packages().get(depPkg).getPubApi();548549// This PubApi directly lists the members of the class,550// i.e. [ MEMBER1, MEMBER2, ... ]551PubApi prevDepApi = prevPkgApi.types.get(fqDep).pubApi;552553// In order to dive *into* the class, we need to add554// .types.get(fqDep).pubApi below.555PubApi currentDepApi = onDiskPubApi.get(fqDep).types.get(fqDep).pubApi;556557if (!currentDepApi.isBackwardCompatibleWith(prevDepApi)) {558List<String> apiDiff = currentDepApi.diff(prevDepApi);559taintPackage(pkg.name(), "depends on classpath "560+ "package which has an updated package api: "561+ String.join("\n", apiDiff));562//Log.debug("========================================");563//Log.debug("------ PREV API ------------------------");564//prevDepApi.asListOfStrings().forEach(Log::debug);565//Log.debug("------ CURRENT API ---------------------");566//currentDepApi.asListOfStrings().forEach(Log::debug);567//Log.debug("========================================");568continue nextPkg;569}570}571}572}573574/**575* Scan all output dirs for artifacts and remove those files (artifacts?)576* that are not recognized as such, in the javac_state file.577*/578public void removeUnidentifiedArtifacts() {579Set<File> allKnownArtifacts = new HashSet<>();580for (Package pkg : prev.packages().values()) {581for (File f : pkg.artifacts().values()) {582allKnownArtifacts.add(f);583}584}585// Do not forget about javac_state....586allKnownArtifacts.add(javacState);587588for (File f : binArtifacts) {589if (!allKnownArtifacts.contains(f) &&590!options.isUnidentifiedArtifactPermitted(f.getAbsolutePath())) {591Log.debug("Removing "+f.getPath()+" since it is unknown to the javac_state.");592f.delete();593}594}595for (File f : headerArtifacts) {596if (!allKnownArtifacts.contains(f)) {597Log.debug("Removing "+f.getPath()+" since it is unknown to the javac_state.");598f.delete();599}600}601for (File f : gensrcArtifacts) {602if (!allKnownArtifacts.contains(f)) {603Log.debug("Removing "+f.getPath()+" since it is unknown to the javac_state.");604f.delete();605}606}607}608609/**610* Remove artifacts that are no longer produced when compiling!611*/612public void removeSuperfluousArtifacts(Set<String> recentlyCompiled) {613// Nothing to do, if nothing was recompiled.614if (recentlyCompiled.size() == 0) return;615616for (String pkg : now.packages().keySet()) {617// If this package has not been recompiled, skip the check.618if (!recentlyCompiled.contains(pkg)) continue;619Collection<File> arts = now.artifacts().values();620for (File f : fetchPrevArtifacts(pkg).values()) {621if (!arts.contains(f)) {622Log.debug("Removing "+f.getPath()+" since it is now superfluous!");623if (f.exists()) f.delete();624}625}626}627}628629/**630* Return those files belonging to prev, but not now.631*/632private Set<Source> calculateRemovedSources() {633Set<Source> removed = new HashSet<>();634for (String src : prev.sources().keySet()) {635if (now.sources().get(src) == null) {636removed.add(prev.sources().get(src));637}638}639return removed;640}641642/**643* Return those files belonging to now, but not prev.644*/645private Set<Source> calculateAddedSources() {646Set<Source> added = new HashSet<>();647for (String src : now.sources().keySet()) {648if (prev.sources().get(src) == null) {649added.add(now.sources().get(src));650}651}652return added;653}654655/**656* Return those files where the timestamp is newer.657* If a source file timestamp suddenly is older than what is known658* about it in javac_state, then consider it modified, but print659* a warning!660*/661private Set<Source> calculateModifiedSources() {662Set<Source> modified = new HashSet<>();663for (String src : now.sources().keySet()) {664Source n = now.sources().get(src);665Source t = prev.sources().get(src);666if (prev.sources().get(src) != null) {667if (t != null) {668if (n.lastModified() > t.lastModified()) {669modified.add(n);670} else if (n.lastModified() < t.lastModified()) {671modified.add(n);672Log.warn("The source file "+n.name()+" timestamp has moved backwards in time.");673}674}675}676}677return modified;678}679680/**681* Recursively delete a directory and all its contents.682*/683private void deleteContents(File dir) {684if (dir != null && dir.exists()) {685for (File f : dir.listFiles()) {686if (f.isDirectory()) {687deleteContents(f);688}689if (!options.isUnidentifiedArtifactPermitted(f.getAbsolutePath())) {690Log.debug("Removing "+f.getAbsolutePath());691f.delete();692}693}694}695}696697/**698* Run the copy translator only.699*/700public void performCopying(File binDir, Map<String,Transformer> suffixRules) {701Map<String,Transformer> sr = new HashMap<>();702for (Map.Entry<String,Transformer> e : suffixRules.entrySet()) {703if (e.getValue().getClass().equals(CopyFile.class)) {704sr.put(e.getKey(), e.getValue());705}706}707perform(null, binDir, sr);708}709710/**711* Run all the translators that translate into java source code.712* I.e. all translators that are not copy nor compile_java_source.713*/714public void performTranslation(File gensrcDir, Map<String,Transformer> suffixRules) {715Map<String,Transformer> sr = new HashMap<>();716for (Map.Entry<String,Transformer> e : suffixRules.entrySet()) {717Class<?> trClass = e.getValue().getClass();718if (trClass == CompileJavaPackages.class || trClass == CopyFile.class)719continue;720721sr.put(e.getKey(), e.getValue());722}723perform(null, gensrcDir, sr);724}725726/**727* Compile all the java sources. Return true, if it needs to be called again!728*/729public boolean performJavaCompilations(CompilationService sjavac,730Options args,731Set<String> recentlyCompiled,732boolean[] rcValue) {733Map<String,Transformer> suffixRules = new HashMap<>();734suffixRules.put(".java", compileJavaPackages);735compileJavaPackages.setExtra(args);736rcValue[0] = perform(sjavac, binDir, suffixRules);737recentlyCompiled.addAll(taintedPackages());738clearTaintedPackages();739boolean again = !packagesWithChangedPublicApis.isEmpty();740taintPackagesDependingOnChangedPackages(packagesWithChangedPublicApis, recentlyCompiled);741packagesWithChangedPublicApis = new HashSet<>();742return again && rcValue[0];743744// TODO: Figure out why 'again' checks packagesWithChangedPublicAPis.745// (It shouldn't matter if packages had changed pub apis as long as no746// one depends on them. Wouldn't it make more sense to let 'again'747// depend on taintedPackages?)748}749750/**751* Store the source into the set of sources belonging to the given transform.752*/753private void addFileToTransform(Map<Transformer,Map<String,Set<URI>>> gs, Transformer t, Source s) {754Map<String,Set<URI>> fs = gs.get(t);755if (fs == null) {756fs = new HashMap<>();757gs.put(t, fs);758}759Set<URI> ss = fs.get(s.pkg().name());760if (ss == null) {761ss = new HashSet<>();762fs.put(s.pkg().name(), ss);763}764ss.add(s.file().toURI());765}766767/**768* For all packages, find all sources belonging to the package, group the sources769* based on their transformers and apply the transformers on each source code group.770*/771private boolean perform(CompilationService sjavac,772File outputDir,773Map<String,Transformer> suffixRules) {774boolean rc = true;775// Group sources based on transforms. A source file can only belong to a single transform.776Map<Transformer,Map<String,Set<URI>>> groupedSources = new HashMap<>();777for (Source src : now.sources().values()) {778Transformer t = suffixRules.get(src.suffix());779if (t != null) {780if (taintedPackages.contains(src.pkg().name()) && !src.isLinkedOnly()) {781addFileToTransform(groupedSources, t, src);782}783}784}785// Go through the transforms and transform them.786for (Map.Entry<Transformer, Map<String, Set<URI>>> e : groupedSources.entrySet()) {787Transformer t = e.getKey();788Map<String, Set<URI>> srcs = e.getValue();789// These maps need to be synchronized since multiple threads will be790// writing results into them.791Map<String, Set<URI>> packageArtifacts = Collections.synchronizedMap(new HashMap<>());792Map<String, Map<String, Set<String>>> packageDependencies = Collections.synchronizedMap(new HashMap<>());793Map<String, Map<String, Set<String>>> packageCpDependencies = Collections.synchronizedMap(new HashMap<>());794Map<String, PubApi> packagePublicApis = Collections.synchronizedMap(new HashMap<>());795Map<String, PubApi> dependencyPublicApis = Collections.synchronizedMap(new HashMap<>());796797boolean r = t.transform(sjavac,798srcs,799visibleSrcs,800prev.dependents(),801outputDir.toURI(),802packageArtifacts,803packageDependencies,804packageCpDependencies,805packagePublicApis,806dependencyPublicApis,8070,808isIncremental(),809numCores);810if (!r)811rc = false;812813for (String p : srcs.keySet()) {814recompiledPackages.add(p);815}816// The transform is done! Extract all the artifacts and store the info into the Package objects.817for (Map.Entry<String, Set<URI>> a : packageArtifacts.entrySet()) {818Module mnow = now.findModuleFromPackageName(a.getKey());819mnow.addArtifacts(a.getKey(), a.getValue());820}821// Extract all the dependencies and store the info into the Package objects.822for (Map.Entry<String, Map<String, Set<String>>> a : packageDependencies.entrySet()) {823Map<String, Set<String>> deps = a.getValue();824Module mnow = now.findModuleFromPackageName(a.getKey());825mnow.setDependencies(a.getKey(), deps, false);826}827for (Map.Entry<String, Map<String, Set<String>>> a : packageCpDependencies.entrySet()) {828Map<String, Set<String>> deps = a.getValue();829Module mnow = now.findModuleFromPackageName(a.getKey());830mnow.setDependencies(a.getKey(), deps, true);831}832833// This map contains the public api of the types that this834// compilation depended upon. This means that it may not contain835// full packages. In other words, we shouldn't remove knowledge of836// public apis but merge these with what we already have.837for (Map.Entry<String, PubApi> a : dependencyPublicApis.entrySet()) {838String pkg = a.getKey();839PubApi packagePartialPubApi = a.getValue();840Package pkgNow = now.findModuleFromPackageName(pkg).lookupPackage(pkg);841PubApi currentPubApi = pkgNow.getPubApi();842PubApi newPubApi = PubApi.mergeTypes(currentPubApi, packagePartialPubApi);843pkgNow.setPubapi(newPubApi);844845// See JDK-8071904846if (now.packages().containsKey(pkg))847now.packages().get(pkg).setPubapi(newPubApi);848else849now.packages().put(pkg, pkgNow);850}851852// The packagePublicApis cover entire packages (since sjavac compiles853// stuff on package level). This means that if a type is missing854// in the public api of a given package, it means that it has been855// removed. In other words, we should *set* the pubapi to whatever856// this map contains, and not merge it with what we already have.857for (Map.Entry<String, PubApi> a : packagePublicApis.entrySet()) {858String pkg = a.getKey();859PubApi newPubApi = a.getValue();860Module mprev = prev.findModuleFromPackageName(pkg);861Module mnow = now.findModuleFromPackageName(pkg);862mnow.setPubapi(pkg, newPubApi);863if (mprev.hasPubapiChanged(pkg, newPubApi)) {864// Aha! The pubapi of this package has changed!865// It can also be a new compile from scratch.866if (mprev.lookupPackage(pkg).existsInJavacState()) {867// This is an incremental compile! The pubapi868// did change. Trigger recompilation of dependents.869packagesWithChangedPublicApis.add(pkg);870Log.debug("The API of " + Util.justPackageName(pkg) + " has changed!");871}872}873}874}875return rc;876}877878/**879* Utility method to recursively find all files below a directory.880*/881private static Set<File> findAllFiles(File dir) {882Set<File> foundFiles = new HashSet<>();883if (dir == null) {884return foundFiles;885}886recurse(dir, foundFiles);887return foundFiles;888}889890private static void recurse(File dir, Set<File> foundFiles) {891for (File f : dir.listFiles()) {892if (f.isFile()) {893foundFiles.add(f);894} else if (f.isDirectory()) {895recurse(f, foundFiles);896}897}898}899900/**901* Compare the calculate source list, with an explicit list, usually902* supplied from the makefile. Used to detect bugs where the makefile and903* sjavac have different opinions on which files should be compiled.904*/905public void compareWithMakefileList(File makefileSourceList)906throws ProblemException {907// If we are building on win32 using for example cygwin the paths in the908// makefile source list909// might be /cygdrive/c/.... which does not match c:\....910// We need to adjust our calculated sources to be identical, if911// necessary.912boolean mightNeedRewriting = File.pathSeparatorChar == ';';913914if (makefileSourceList == null)915return;916917Set<String> calculatedSources = new HashSet<>();918Set<String> listedSources = new HashSet<>();919920// Create a set of filenames with full paths.921for (Source s : now.sources().values()) {922// Don't include link only sources when comparing sources to compile923if (!s.isLinkedOnly()) {924String path = s.file().getPath();925if (mightNeedRewriting)926path = Util.normalizeDriveLetter(path);927calculatedSources.add(path);928}929}930// Read in the file and create another set of filenames with full paths.931try(BufferedReader in = new BufferedReader(new FileReader(makefileSourceList))) {932for (;;) {933String l = in.readLine();934if (l==null) break;935l = l.trim();936if (mightNeedRewriting) {937if (l.indexOf(":") == 1 && l.indexOf("\\") == 2) {938// Everything a-ok, the format is already C:\foo\bar939} else if (l.indexOf(":") == 1 && l.indexOf("/") == 2) {940// The format is C:/foo/bar, rewrite into the above format.941l = l.replaceAll("/","\\\\");942} else if (l.charAt(0) == '/' && l.indexOf("/",1) != -1) {943// The format might be: /cygdrive/c/foo/bar, rewrite into the above format.944// Do not hardcode the name cygdrive here.945int slash = l.indexOf("/",1);946l = l.replaceAll("/","\\\\");947l = ""+l.charAt(slash+1)+":"+l.substring(slash+2);948}949if (Character.isLowerCase(l.charAt(0))) {950l = Character.toUpperCase(l.charAt(0))+l.substring(1);951}952}953listedSources.add(l);954}955} catch (FileNotFoundException | NoSuchFileException e) {956throw new ProblemException("Could not open "+makefileSourceList.getPath()+" since it does not exist!");957} catch (IOException e) {958throw new ProblemException("Could not read "+makefileSourceList.getPath());959}960961for (String s : listedSources) {962if (!calculatedSources.contains(s)) {963throw new ProblemException("The makefile listed source "+s+" was not calculated by the smart javac wrapper!");964}965}966967for (String s : calculatedSources) {968if (!listedSources.contains(s)) {969throw new ProblemException("The smart javac wrapper calculated source "+s+" was not listed by the makefiles!");970}971}972}973}974975976