Path: blob/aarch64-shenandoah-jdk8u272-b10/langtools/src/share/classes/com/sun/tools/sjavac/JavacState.java
38899 views
/*1* Copyright (c) 2012, 2013, 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.*;28import java.util.Collections;29import java.util.Date;30import java.util.Set;31import java.util.HashSet;32import java.util.List;33import java.util.Map;34import java.util.HashMap;35import java.text.SimpleDateFormat;36import java.net.URI;37import java.util.*;3839/**40* The javac state class maintains the previous (prev) and the current (now)41* build states and everything else that goes into the javac_state file.42*43* <p><b>This is NOT part of any supported API.44* If you write code that depends on this, you do so at your own45* risk. This code and its internal interfaces are subject to change46* or deletion without notice.</b></p>47*/48public class JavacState49{50// The arguments to the compile. If not identical, then it cannot51// be an incremental build!52String theArgs;53// The number of cores limits how many threads are used for heavy concurrent work.54int numCores;5556// The bin_dir/javac_state57private String javacStateFilename;58private File javacState;5960// The previous build state is loaded from javac_state61private BuildState prev;62// The current build state is constructed during the build,63// then saved as the new javac_state.64private BuildState now;6566// Something has changed in the javac_state. It needs to be saved!67private boolean needsSaving;68// If this is a new javac_state file, then do not print unnecessary messages.69private boolean newJavacState;7071// These are packages where something has changed and the package72// needs to be recompiled. Actions that trigger recompilation:73// * source belonging to the package has changed74// * artifact belonging to the package is lost, or its timestamp has been changed.75// * an unknown artifact has appeared, we simply delete it, but we also trigger a recompilation.76// * a package that is tainted, taints all packages that depend on it.77private Set<String> taintedPackages;78// After a compile, the pubapis are compared with the pubapis stored in the javac state file.79// Any packages where the pubapi differ are added to this set.80// Later we use this set and the dependency information to taint dependent packages.81private Set<String> packagesWithChangedPublicApis;82// When a module-info.java file is changed, taint the module,83// then taint all modules that depend on that that module.84// A module dependency can occur directly through a require, or85// indirectly through a module that does a public export for the first tainted module.86// When all modules are tainted, then taint all packages belonging to these modules.87// Then rebuild. It is perhaps possible (and valuable?) to do a more finegrained examination of the88// change in module-info.java, but that will have to wait.89private Set<String> taintedModules;90// The set of all packages that has been recompiled.91// Copy over the javac_state for the packages that did not need recompilation,92// verbatim from the previous (prev) to the new (now) build state.93private Set<String> recompiledPackages;9495// The output directories filled with tasty artifacts.96private File binDir, gensrcDir, headerDir;9798// The current status of the file system.99private Set<File> binArtifacts;100private Set<File> gensrcArtifacts;101private Set<File> headerArtifacts;102103// The status of the sources.104Set<Source> removedSources = null;105Set<Source> addedSources = null;106Set<Source> modifiedSources = null;107108// Visible sources for linking. These are the only109// ones that -sourcepath is allowed to see.110Set<URI> visibleSrcs;111112// Visible classes for linking. These are the only113// ones that -classpath is allowed to see.114// It maps from a classpath root to the set of visible classes for that root.115// If the set is empty, then all classes are visible for that root.116// It can also map from a jar file to the set of visible classes for that jar file.117Map<URI,Set<String>> visibleClasses;118119// Setup two transforms that always exist.120private CopyFile copyFiles = new CopyFile();121private CompileJavaPackages compileJavaPackages = new CompileJavaPackages();122123// Where to send stdout and stderr.124private PrintStream out, err;125126JavacState(String[] args, File bd, File gd, File hd, boolean permitUnidentifiedArtifacts, boolean removeJavacState,127PrintStream o, PrintStream e) {128out = o;129err = e;130numCores = Main.findNumberOption(args, "-j");131theArgs = "";132for (String a : removeArgsNotAffectingState(args)) {133theArgs = theArgs+a+" ";134}135binDir = bd;136gensrcDir = gd;137headerDir = hd;138javacStateFilename = binDir.getPath()+File.separator+"javac_state";139javacState = new File(javacStateFilename);140if (removeJavacState && javacState.exists()) {141javacState.delete();142}143newJavacState = false;144if (!javacState.exists()) {145newJavacState = true;146// If there is no javac_state then delete the contents of all the artifact dirs!147// We do not want to risk building a broken incremental build.148// BUT since the makefiles still copy things straight into the bin_dir et al,149// we avoid deleting files here, if the option --permit-unidentified-classes was supplied.150if (!permitUnidentifiedArtifacts) {151deleteContents(binDir);152deleteContents(gensrcDir);153deleteContents(headerDir);154}155needsSaving = true;156}157prev = new BuildState();158now = new BuildState();159taintedPackages = new HashSet<String>();160recompiledPackages = new HashSet<String>();161packagesWithChangedPublicApis = new HashSet<String>();162}163164public BuildState prev() { return prev; }165public BuildState now() { return now; }166167/**168* Remove args not affecting the state.169*/170static String[] removeArgsNotAffectingState(String[] args) {171String[] out = new String[args.length];172int j = 0;173for (int i = 0; i<args.length; ++i) {174if (args[i].equals("-j")) {175// Just skip it and skip following value176i++;177} else if (args[i].startsWith("--server:")) {178// Just skip it.179} else if (args[i].startsWith("--log=")) {180// Just skip it.181} else if (args[i].equals("--compare-found-sources")) {182// Just skip it and skip verify file name183i++;184} else {185// Copy argument.186out[j] = args[i];187j++;188}189}190String[] ret = new String[j];191System.arraycopy(out, 0, ret, 0, j);192return ret;193}194195/**196* Specify which sources are visible to the compiler through -sourcepath.197*/198public void setVisibleSources(Map<String,Source> vs) {199visibleSrcs = new HashSet<URI>();200for (String s : vs.keySet()) {201Source src = vs.get(s);202visibleSrcs.add(src.file().toURI());203}204}205206/**207* Specify which classes are visible to the compiler through -classpath.208*/209public void setVisibleClasses(Map<String,Source> vs) {210visibleSrcs = new HashSet<URI>();211for (String s : vs.keySet()) {212Source src = vs.get(s);213visibleSrcs.add(src.file().toURI());214}215}216/**217* Returns true if this is an incremental build.218*/219public boolean isIncremental() {220return !prev.sources().isEmpty();221}222223/**224* Find all artifacts that exists on disk.225*/226public void findAllArtifacts() {227binArtifacts = findAllFiles(binDir);228gensrcArtifacts = findAllFiles(gensrcDir);229headerArtifacts = findAllFiles(headerDir);230}231232/**233* Lookup the artifacts generated for this package in the previous build.234*/235private Map<String,File> fetchPrevArtifacts(String pkg) {236Package p = prev.packages().get(pkg);237if (p != null) {238return p.artifacts();239}240return new HashMap<String,File>();241}242243/**244* Delete all prev artifacts in the currently tainted packages.245*/246public void deleteClassArtifactsInTaintedPackages() {247for (String pkg : taintedPackages) {248Map<String,File> arts = fetchPrevArtifacts(pkg);249for (File f : arts.values()) {250if (f.exists() && f.getName().endsWith(".class")) {251f.delete();252}253}254}255}256257/**258* Mark the javac_state file to be in need of saving and as a side effect,259* it gets a new timestamp.260*/261private void needsSaving() {262needsSaving = true;263}264265/**266* Save the javac_state file.267*/268public void save() throws IOException {269if (!needsSaving) return;270try (FileWriter out = new FileWriter(javacStateFilename)) {271StringBuilder b = new StringBuilder();272long millisNow = System.currentTimeMillis();273Date d = new Date(millisNow);274SimpleDateFormat df =275new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");276b.append("# javac_state ver 0.3 generated "+millisNow+" "+df.format(d)+"\n");277b.append("# This format might change at any time. Please do not depend on it.\n");278b.append("# M module\n");279b.append("# P package\n");280b.append("# S C source_tobe_compiled timestamp\n");281b.append("# S L link_only_source timestamp\n");282b.append("# G C generated_source timestamp\n");283b.append("# A artifact timestamp\n");284b.append("# D dependency\n");285b.append("# I pubapi\n");286b.append("# R arguments\n");287b.append("R ").append(theArgs).append("\n");288289// Copy over the javac_state for the packages that did not need recompilation.290now.copyPackagesExcept(prev, recompiledPackages, new HashSet<String>());291// Save the packages, ie package names, dependencies, pubapis and artifacts!292// I.e. the lot.293Module.saveModules(now.modules(), b);294295String s = b.toString();296out.write(s, 0, s.length());297}298}299300/**301* Load a javac_state file.302*/303public static JavacState load(String[] args, File binDir, File gensrcDir, File headerDir,304boolean permitUnidentifiedArtifacts, PrintStream out, PrintStream err) {305JavacState db = new JavacState(args, binDir, gensrcDir, headerDir, permitUnidentifiedArtifacts, false, out, err);306Module lastModule = null;307Package lastPackage = null;308Source lastSource = null;309boolean noFileFound = false;310boolean foundCorrectVerNr = false;311boolean newCommandLine = false;312boolean syntaxError = false;313314try (BufferedReader in = new BufferedReader(new FileReader(db.javacStateFilename))) {315for (;;) {316String l = in.readLine();317if (l==null) break;318if (l.length()>=3 && l.charAt(1) == ' ') {319char c = l.charAt(0);320if (c == 'M') {321lastModule = db.prev.loadModule(l);322} else323if (c == 'P') {324if (lastModule == null) { syntaxError = true; break; }325lastPackage = db.prev.loadPackage(lastModule, l);326} else327if (c == 'D') {328if (lastModule == null || lastPackage == null) { syntaxError = true; break; }329lastPackage.loadDependency(l);330} else331if (c == 'I') {332if (lastModule == null || lastPackage == null) { syntaxError = true; break; }333lastPackage.loadPubapi(l);334} else335if (c == 'A') {336if (lastModule == null || lastPackage == null) { syntaxError = true; break; }337lastPackage.loadArtifact(l);338} else339if (c == 'S') {340if (lastModule == null || lastPackage == null) { syntaxError = true; break; }341lastSource = db.prev.loadSource(lastPackage, l, false);342} else343if (c == 'G') {344if (lastModule == null || lastPackage == null) { syntaxError = true; break; }345lastSource = db.prev.loadSource(lastPackage, l, true);346} else347if (c == 'R') {348String ncmdl = "R "+db.theArgs;349if (!l.equals(ncmdl)) {350newCommandLine = true;351}352} else353if (c == '#') {354if (l.startsWith("# javac_state ver ")) {355int sp = l.indexOf(" ", 18);356if (sp != -1) {357String ver = l.substring(18,sp);358if (!ver.equals("0.3")) {359break;360}361foundCorrectVerNr = true;362}363}364}365}366}367} catch (FileNotFoundException e) {368// Silently create a new javac_state file.369noFileFound = true;370} catch (IOException e) {371Log.info("Dropping old javac_state because of errors when reading it.");372db = new JavacState(args, binDir, gensrcDir, headerDir, permitUnidentifiedArtifacts, true, out, err);373foundCorrectVerNr = true;374newCommandLine = false;375syntaxError = false;376}377if (foundCorrectVerNr == false && !noFileFound) {378Log.info("Dropping old javac_state since it is of an old version.");379db = new JavacState(args, binDir, gensrcDir, headerDir, permitUnidentifiedArtifacts, true, out, err);380} else381if (newCommandLine == true && !noFileFound) {382Log.info("Dropping old javac_state since a new command line is used!");383db = new JavacState(args, binDir, gensrcDir, headerDir, permitUnidentifiedArtifacts, true, out, err);384} else385if (syntaxError == true) {386Log.info("Dropping old javac_state since it contains syntax errors.");387db = new JavacState(args, binDir, gensrcDir, headerDir, permitUnidentifiedArtifacts, true, out, err);388}389db.prev.calculateDependents();390return db;391}392393/**394* Mark a java package as tainted, ie it needs recompilation.395*/396public void taintPackage(String name, String because) {397if (!taintedPackages.contains(name)) {398if (because != null) Log.debug("Tainting "+Util.justPackageName(name)+" because "+because);399// It has not been tainted before.400taintedPackages.add(name);401needsSaving();402Package nowp = now.packages().get(name);403if (nowp != null) {404for (String d : nowp.dependents()) {405taintPackage(d, because);406}407}408}409}410411/**412* This packages need recompilation.413*/414public Set<String> taintedPackages() {415return taintedPackages;416}417418/**419* Clean out the tainted package set, used after the first round of compiles,420* prior to propagating dependencies.421*/422public void clearTaintedPackages() {423taintedPackages = new HashSet<String>();424}425426/**427* Go through all sources and check which have been removed, added or modified428* and taint the corresponding packages.429*/430public void checkSourceStatus(boolean check_gensrc) {431removedSources = calculateRemovedSources();432for (Source s : removedSources) {433if (!s.isGenerated() || check_gensrc) {434taintPackage(s.pkg().name(), "source "+s.name()+" was removed");435}436}437438addedSources = calculateAddedSources();439for (Source s : addedSources) {440String msg = null;441if (isIncremental()) {442// When building from scratch, there is no point443// printing "was added" for every file since all files are added.444// However for an incremental build it makes sense.445msg = "source "+s.name()+" was added";446}447if (!s.isGenerated() || check_gensrc) {448taintPackage(s.pkg().name(), msg);449}450}451452modifiedSources = calculateModifiedSources();453for (Source s : modifiedSources) {454if (!s.isGenerated() || check_gensrc) {455taintPackage(s.pkg().name(), "source "+s.name()+" was modified");456}457}458}459460/**461* Acquire the compile_java_packages suffix rule for .java files.462*/463public Map<String,Transformer> getJavaSuffixRule() {464Map<String,Transformer> sr = new HashMap<String,Transformer>();465sr.put(".java", compileJavaPackages);466return sr;467}468469/**470* Acquire the copying transform.471*/472public Transformer getCopier() {473return copyFiles;474}475476/**477* If artifacts have gone missing, force a recompile of the packages478* they belong to.479*/480public void taintPackagesThatMissArtifacts() {481for (Package pkg : prev.packages().values()) {482for (File f : pkg.artifacts().values()) {483if (!f.exists()) {484// Hmm, the artifact on disk does not exist! Someone has removed it....485// Lets rebuild the package.486taintPackage(pkg.name(), ""+f+" is missing.");487}488}489}490}491492/**493* Propagate recompilation through the dependency chains.494* Avoid re-tainting packages that have already been compiled.495*/496public void taintPackagesDependingOnChangedPackages(Set<String> pkgs, Set<String> recentlyCompiled) {497for (Package pkg : prev.packages().values()) {498for (String dep : pkg.dependencies()) {499if (pkgs.contains(dep) && !recentlyCompiled.contains(pkg.name())) {500taintPackage(pkg.name(), " its depending on "+dep);501}502}503}504}505506/**507* Scan all output dirs for artifacts and remove those files (artifacts?)508* that are not recognized as such, in the javac_state file.509*/510public void removeUnidentifiedArtifacts() {511Set<File> allKnownArtifacts = new HashSet<File>();512for (Package pkg : prev.packages().values()) {513for (File f : pkg.artifacts().values()) {514allKnownArtifacts.add(f);515}516}517// Do not forget about javac_state....518allKnownArtifacts.add(javacState);519520for (File f : binArtifacts) {521if (!allKnownArtifacts.contains(f)) {522Log.debug("Removing "+f.getPath()+" since it is unknown to the javac_state.");523f.delete();524}525}526for (File f : headerArtifacts) {527if (!allKnownArtifacts.contains(f)) {528Log.debug("Removing "+f.getPath()+" since it is unknown to the javac_state.");529f.delete();530}531}532for (File f : gensrcArtifacts) {533if (!allKnownArtifacts.contains(f)) {534Log.debug("Removing "+f.getPath()+" since it is unknown to the javac_state.");535f.delete();536}537}538}539540/**541* Remove artifacts that are no longer produced when compiling!542*/543public void removeSuperfluousArtifacts(Set<String> recentlyCompiled) {544// Nothing to do, if nothing was recompiled.545if (recentlyCompiled.size() == 0) return;546547for (String pkg : now.packages().keySet()) {548// If this package has not been recompiled, skip the check.549if (!recentlyCompiled.contains(pkg)) continue;550Collection<File> arts = now.artifacts().values();551for (File f : fetchPrevArtifacts(pkg).values()) {552if (!arts.contains(f)) {553Log.debug("Removing "+f.getPath()+" since it is now superfluous!");554if (f.exists()) f.delete();555}556}557}558}559560/**561* Return those files belonging to prev, but not now.562*/563private Set<Source> calculateRemovedSources() {564Set<Source> removed = new HashSet<Source>();565for (String src : prev.sources().keySet()) {566if (now.sources().get(src) == null) {567removed.add(prev.sources().get(src));568}569}570return removed;571}572573/**574* Return those files belonging to now, but not prev.575*/576private Set<Source> calculateAddedSources() {577Set<Source> added = new HashSet<Source>();578for (String src : now.sources().keySet()) {579if (prev.sources().get(src) == null) {580added.add(now.sources().get(src));581}582}583return added;584}585586/**587* Return those files where the timestamp is newer.588* If a source file timestamp suddenly is older than what is known589* about it in javac_state, then consider it modified, but print590* a warning!591*/592private Set<Source> calculateModifiedSources() {593Set<Source> modified = new HashSet<Source>();594for (String src : now.sources().keySet()) {595Source n = now.sources().get(src);596Source t = prev.sources().get(src);597if (prev.sources().get(src) != null) {598if (t != null) {599if (n.lastModified() > t.lastModified()) {600modified.add(n);601} else if (n.lastModified() < t.lastModified()) {602modified.add(n);603Log.warn("The source file "+n.name()+" timestamp has moved backwards in time.");604}605}606}607}608return modified;609}610611/**612* Recursively delete a directory and all its contents.613*/614private static void deleteContents(File dir) {615if (dir != null && dir.exists()) {616for (File f : dir.listFiles()) {617if (f.isDirectory()) {618deleteContents(f);619}620f.delete();621}622}623}624625/**626* Run the copy translator only.627*/628public void performCopying(File binDir, Map<String,Transformer> suffixRules) {629Map<String,Transformer> sr = new HashMap<String,Transformer>();630for (Map.Entry<String,Transformer> e : suffixRules.entrySet()) {631if (e.getValue() == copyFiles) {632sr.put(e.getKey(), e.getValue());633}634}635perform(binDir, sr);636}637638/**639* Run all the translators that translate into java source code.640* I.e. all translators that are not copy nor compile_java_source.641*/642public void performTranslation(File gensrcDir, Map<String,Transformer> suffixRules) {643Map<String,Transformer> sr = new HashMap<String,Transformer>();644for (Map.Entry<String,Transformer> e : suffixRules.entrySet()) {645if (e.getValue() != copyFiles &&646e.getValue() != compileJavaPackages) {647sr.put(e.getKey(), e.getValue());648}649}650perform(gensrcDir, sr);651}652653/**654* Compile all the java sources. Return true, if it needs to be called again!655*/656public boolean performJavaCompilations(File binDir,657String serverSettings,658String[] args,659Set<String> recentlyCompiled,660boolean[] rcValue) {661Map<String,Transformer> suffixRules = new HashMap<String,Transformer>();662suffixRules.put(".java", compileJavaPackages);663compileJavaPackages.setExtra(serverSettings);664compileJavaPackages.setExtra(args);665666rcValue[0] = perform(binDir, suffixRules);667recentlyCompiled.addAll(taintedPackages());668clearTaintedPackages();669boolean again = !packagesWithChangedPublicApis.isEmpty();670taintPackagesDependingOnChangedPackages(packagesWithChangedPublicApis, recentlyCompiled);671packagesWithChangedPublicApis = new HashSet<String>();672return again && rcValue[0];673}674675/**676* Store the source into the set of sources belonging to the given transform.677*/678private void addFileToTransform(Map<Transformer,Map<String,Set<URI>>> gs, Transformer t, Source s) {679Map<String,Set<URI>> fs = gs.get(t);680if (fs == null) {681fs = new HashMap<String,Set<URI>>();682gs.put(t, fs);683}684Set<URI> ss = fs.get(s.pkg().name());685if (ss == null) {686ss = new HashSet<URI>();687fs.put(s.pkg().name(), ss);688}689ss.add(s.file().toURI());690}691692/**693* For all packages, find all sources belonging to the package, group the sources694* based on their transformers and apply the transformers on each source code group.695*/696private boolean perform(File outputDir, Map<String,Transformer> suffixRules)697{698boolean rc = true;699// Group sources based on transforms. A source file can only belong to a single transform.700Map<Transformer,Map<String,Set<URI>>> groupedSources = new HashMap<Transformer,Map<String,Set<URI>>>();701for (Source src : now.sources().values()) {702Transformer t = suffixRules.get(src.suffix());703if (t != null) {704if (taintedPackages.contains(src.pkg().name()) && !src.isLinkedOnly()) {705addFileToTransform(groupedSources, t, src);706}707}708}709// Go through the transforms and transform them.710for (Map.Entry<Transformer,Map<String,Set<URI>>> e : groupedSources.entrySet()) {711Transformer t = e.getKey();712Map<String,Set<URI>> srcs = e.getValue();713// These maps need to be synchronized since multiple threads will be writing results into them.714Map<String,Set<URI>> packageArtifacts = Collections.synchronizedMap(new HashMap<String,Set<URI>>());715Map<String,Set<String>> packageDependencies = Collections.synchronizedMap(new HashMap<String,Set<String>>());716Map<String,String> packagePublicApis = Collections.synchronizedMap(new HashMap<String,String>());717718boolean r = t.transform(srcs,719visibleSrcs,720visibleClasses,721prev.dependents(),722outputDir.toURI(),723packageArtifacts,724packageDependencies,725packagePublicApis,7260,727isIncremental(),728numCores,729out,730err);731if (!r) rc = false;732733for (String p : srcs.keySet()) {734recompiledPackages.add(p);735}736// The transform is done! Extract all the artifacts and store the info into the Package objects.737for (Map.Entry<String,Set<URI>> a : packageArtifacts.entrySet()) {738Module mnow = now.findModuleFromPackageName(a.getKey());739mnow.addArtifacts(a.getKey(), a.getValue());740}741// Extract all the dependencies and store the info into the Package objects.742for (Map.Entry<String,Set<String>> a : packageDependencies.entrySet()) {743Set<String> deps = a.getValue();744Module mnow = now.findModuleFromPackageName(a.getKey());745mnow.setDependencies(a.getKey(), deps);746}747// Extract all the pubapis and store the info into the Package objects.748for (Map.Entry<String,String> a : packagePublicApis.entrySet()) {749Module mprev = prev.findModuleFromPackageName(a.getKey());750List<String> pubapi = Package.pubapiToList(a.getValue());751Module mnow = now.findModuleFromPackageName(a.getKey());752mnow.setPubapi(a.getKey(), pubapi);753if (mprev.hasPubapiChanged(a.getKey(), pubapi)) {754// Aha! The pubapi of this package has changed!755// It can also be a new compile from scratch.756if (mprev.lookupPackage(a.getKey()).existsInJavacState()) {757// This is an incremental compile! The pubapi758// did change. Trigger recompilation of dependents.759packagesWithChangedPublicApis.add(a.getKey());760Log.info("The pubapi of "+Util.justPackageName(a.getKey())+" has changed!");761}762}763}764}765return rc;766}767768/**769* Utility method to recursively find all files below a directory.770*/771private static Set<File> findAllFiles(File dir) {772Set<File> foundFiles = new HashSet<File>();773if (dir == null) {774return foundFiles;775}776recurse(dir, foundFiles);777return foundFiles;778}779780private static void recurse(File dir, Set<File> foundFiles) {781for (File f : dir.listFiles()) {782if (f.isFile()) {783foundFiles.add(f);784} else if (f.isDirectory()) {785recurse(f, foundFiles);786}787}788}789790/**791* Compare the calculate source list, with an explicit list, usually supplied from the makefile.792* Used to detect bugs where the makefile and sjavac have different opinions on which files793* should be compiled.794*/795public void compareWithMakefileList(File makefileSourceList)796throws ProblemException797{798// If we are building on win32 using for example cygwin the paths in the makefile source list799// might be /cygdrive/c/.... which does not match c:\....800// We need to adjust our calculated sources to be identical, if necessary.801boolean mightNeedRewriting = File.pathSeparatorChar == ';';802803if (makefileSourceList == null) return;804805Set<String> calculatedSources = new HashSet<String>();806Set<String> listedSources = new HashSet<String>();807808// Create a set of filenames with full paths.809for (Source s : now.sources().values()) {810// Don't include link only sources when comparing sources to compile811if (!s.isLinkedOnly()) {812calculatedSources.add(s.file().getPath());813}814}815// Read in the file and create another set of filenames with full paths.816try {817BufferedReader in = new BufferedReader(new FileReader(makefileSourceList));818for (;;) {819String l = in.readLine();820if (l==null) break;821l = l.trim();822if (mightNeedRewriting) {823if (l.indexOf(":") == 1 && l.indexOf("\\") == 2) {824// Everything a-ok, the format is already C:\foo\bar825} else if (l.indexOf(":") == 1 && l.indexOf("/") == 2) {826// The format is C:/foo/bar, rewrite into the above format.827l = l.replaceAll("/","\\\\");828} else if (l.charAt(0) == '/' && l.indexOf("/",1) != -1) {829// The format might be: /cygdrive/c/foo/bar, rewrite into the above format.830// Do not hardcode the name cygdrive here.831int slash = l.indexOf("/",1);832l = l.replaceAll("/","\\\\");833l = ""+l.charAt(slash+1)+":"+l.substring(slash+2);834}835if (Character.isLowerCase(l.charAt(0))) {836l = Character.toUpperCase(l.charAt(0))+l.substring(1);837}838}839listedSources.add(l);840}841} catch (FileNotFoundException e) {842throw new ProblemException("Could not open "+makefileSourceList.getPath()+" since it does not exist!");843} catch (IOException e) {844throw new ProblemException("Could not read "+makefileSourceList.getPath());845}846847for (String s : listedSources) {848if (!calculatedSources.contains(s)) {849throw new ProblemException("The makefile listed source "+s+" was not calculated by the smart javac wrapper!");850}851}852853for (String s : calculatedSources) {854if (!listedSources.contains(s)) {855throw new ProblemException("The smart javac wrapper calculated source "+s+" was not listed by the makefiles!");856}857}858}859}860861862