]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Fix rebuild graph walking over symlinks
[builder.git] / source / builder.cpp
1 /* $Id$
2
3 This file is part of builder
4 Copyright © 2006-2010  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <set>
9 #include <cstdlib>
10 #include <msp/core/except.h>
11 #include <msp/core/getopt.h>
12 #include <msp/datafile/parser.h>
13 #include <msp/fs/dir.h>
14 #include <msp/fs/stat.h>
15 #include <msp/fs/utils.h>
16 #include <msp/io/buffered.h>
17 #include <msp/io/except.h>
18 #include <msp/io/file.h>
19 #include <msp/io/print.h>
20 #include <msp/strings/formatter.h>
21 #include <msp/strings/regex.h>
22 #include <msp/strings/utils.h>
23 #include <msp/time/units.h>
24 #include <msp/time/utils.h>
25 #include "action.h"
26 #include "analyzer.h"
27 #include "binarypackage.h"
28 #include "builder.h"
29 #include "header.h"
30 #include "install.h"
31 #include "misc.h"
32 #include "package.h"
33 #include "pkgconfig.h"
34 #include "sharedlibrary.h"
35 #include "sourcepackage.h"
36 #include "systemlibrary.h"
37 #include "unlink.h"
38 #include "virtualtarget.h"
39
40 using namespace std;
41 using namespace Msp;
42
43 namespace {
44
45 void update_hash(string &hash, const string &value)
46 {
47         for(unsigned i=0; i<value.size(); ++i)
48                 hash[i%hash.size()] ^= value[i];
49 }
50
51 }
52
53
54 Builder::Builder(int argc, char **argv):
55         main_pkg(0),
56         native_arch(*this, string()),
57         analyzer(0),
58         build(false),
59         clean(0),
60         dry_run(false),
61         help(false),
62         verbose(1),
63         show_progress(false),
64         build_file("Build"),
65         jobs(1),
66         conf_all(false),
67         conf_only(false),
68         build_all(false),
69         create_makefile(false)
70 {
71         string analyze_mode;
72         string work_dir;
73         bool full_paths = false;
74         unsigned max_depth = 5;
75         StringList cmdline_warn;
76         string prfx;
77         string arch;
78
79         GetOpt getopt;
80         getopt.add_option('a', "analyze",    analyze_mode,  GetOpt::REQUIRED_ARG).set_help("Perform analysis.  MODE can be deps, alldeps or rebuild.", "MODE");
81         getopt.add_option('b', "build",      build,         GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
82         getopt.add_option('c', "clean",      clean,         GetOpt::NO_ARG).set_help("Clean buildable targets.");
83         getopt.add_option('f', "file",       build_file,    GetOpt::REQUIRED_ARG).set_help("Read info from FILE instead of Build.", "FILE");
84         getopt.add_option('h', "help",       help,          GetOpt::NO_ARG).set_help("Print this message.");
85         getopt.add_option('j', "jobs",       jobs,          GetOpt::REQUIRED_ARG).set_help("Run NUM commands at once, whenever possible.", "NUM");
86         getopt.add_option('n', "dry-run",    dry_run,       GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
87         getopt.add_option('v', "verbose",    verbose,       GetOpt::NO_ARG).set_help("Print more information about what's going on.");
88         getopt.add_option('x', "no-externals",  no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
89         getopt.add_option('A', "conf-all",   conf_all,      GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
90         getopt.add_option('B', "build-all",  build_all,     GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
91         getopt.add_option('C', "chdir",      work_dir,      GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
92         getopt.add_option('P', "progress",   show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
93         getopt.add_option('W', "what-if",    what_if,       GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
94         getopt.add_option(     "arch",       arch,          GetOpt::REQUIRED_ARG).set_help("Architecture to build for.", "ARCH");
95         getopt.add_option(     "conf-only",  conf_only,     GetOpt::NO_ARG).set_help("Stop after configuring packages.");
96         getopt.add_option(     "full-paths", full_paths,    GetOpt::NO_ARG).set_help("Output full paths in analysis.");
97         getopt.add_option(     "max-depth",  max_depth,     GetOpt::REQUIRED_ARG).set_help("Maximum depth to show in analysis.", "NUM");
98         getopt.add_option(     "prefix",     prfx,          GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
99         getopt.add_option(     "warnings",   cmdline_warn,  GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
100         usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
101         helpmsg = getopt.generate_help();
102         getopt(argc, argv);
103
104         if(!analyze_mode.empty())
105         {
106                 analyzer = new Analyzer(*this);
107
108                 if(analyze_mode=="deps")
109                         analyzer->set_mode(Analyzer::DEPS);
110                 else if(analyze_mode=="alldeps")
111                         analyzer->set_mode(Analyzer::ALLDEPS);
112                 else if(analyze_mode=="rebuild")
113                         analyzer->set_mode(Analyzer::REBUILD);
114                 else if(analyze_mode=="rdeps")
115                         analyzer->set_mode(Analyzer::RDEPS);
116                 else
117                         throw UsageError("Invalid analyze mode");
118
119                 analyzer->set_max_depth(max_depth);
120                 analyzer->set_full_paths(full_paths);
121         }
122         else if(!clean && !create_makefile)
123                 build = true;
124
125         const vector<string> &args = getopt.get_args();
126         for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
127         {
128                 string::size_type equal = i->find('=');
129                 if(equal!=string::npos)
130                         cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
131                 else
132                         cmdline_targets.push_back(*i);
133         }
134
135         if(cmdline_targets.empty())
136                 cmdline_targets.push_back("default");
137
138         if(!work_dir.empty())
139                 FS::chdir(work_dir);
140
141         cwd = FS::getcwd();
142
143         native_arch.set_tool("CC",  "gcc");
144         native_arch.set_tool("CXX", "g++");
145         native_arch.set_tool("LD",  "gcc");
146         native_arch.set_tool("LXX", "g++");
147         native_arch.set_tool("AR",  "ar");
148
149         load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
150         load_build_file((FS::get_user_data_dir("builder")/"rc").str());
151
152         if(arch.empty())
153                 current_arch = &native_arch;
154         else
155                 current_arch = new Architecture(*this, arch);
156
157         if(!current_arch->is_native())
158         {
159                 for(StringMap::const_iterator i=cross_prefixes.begin(); i!=cross_prefixes.end(); ++i)
160                         if(current_arch->match_name(i->first))
161                         {
162                                 current_arch->set_cross_prefix(i->second);
163                                 break;
164                         }
165         }
166
167         if(prfx.empty())
168         {
169                 if(current_arch->is_native())
170                         prefix = (FS::get_home_dir()/"local").str();
171                 else
172                         prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
173         }
174         else
175                 prefix = FS::getcwd()/prfx;
176
177         warnings.push_back("all");
178         warnings.push_back("extra");
179         warnings.push_back("shadow");
180         warnings.push_back("pointer-arith");
181         warnings.push_back("error");
182         for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
183         {
184                 vector<string> warns = split(*i, ',');
185                 warnings.insert(warnings.end(), warns.begin(), warns.end());
186         }
187
188         pkg_path.push_back(cwd/".");
189         pkg_path.push_back(cwd/"..");
190 }
191
192 Builder::~Builder()
193 {
194         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
195                 delete i->second;
196         for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
197                 delete i->second;
198         delete analyzer;
199 }
200
201 int Builder::main()
202 {
203         if(prefix.str()!="/usr")
204         {
205                 FS::Path pcdir = prefix/"lib"/"pkgconfig";
206                 if(const char *pcp = getenv("PKG_CONFIG_PATH"))
207                 {
208                         vector<string> path = split(pcp, ':');
209                         bool found = false;
210                         for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
211                                 found = (*i==pcdir.str());
212                         if(!found)
213                         {
214                                 path.push_back(pcdir.str());
215                                 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
216                         }
217                 }
218                 else
219                         setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
220         }
221
222         if(load_build_file(cwd/build_file))
223         {
224                 if(help)
225                 {
226                         usage(0, "builder", false);
227                         return 0;
228                 }
229                 else
230                 {
231                         IO::print(IO::cerr, "No build info here.\n");
232                         return 1;
233                 }
234         }
235
236         main_pkg->configure(cmdline_options, conf_all?2:1);
237
238         if(help)
239         {
240                 usage(0, "builder", false);
241                 IO::print("\n");
242                 package_help();
243                 return 0;
244         }
245
246         if(conf_only)
247                 return 0;
248
249         if(create_targets())
250                 return 1;
251
252         if(verbose>=2)
253         {
254                 IO::print("Building on %s, for %s%s\n", native_arch.get_name(),
255                         current_arch->get_name(), (current_arch->is_native() ? " (native)" : ""));
256                 IO::print("Prefix is %s\n", prefix);
257         }
258
259         if(verbose>=1)
260         {
261                 unsigned n_packages = 0;
262                 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
263                         if(i->second && i->second->is_configured())
264                                 ++n_packages;
265                 IO::print("%d active packages, %d targets\n", n_packages, targets.size());
266         }
267
268         if(verbose>=2)
269         {
270                 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
271                 {
272                         if(!i->second->is_configured())
273                                 continue;
274
275                         IO::print(" %s", i->second->get_name());
276                         if(dynamic_cast<SourcePackage *>(i->second))
277                                 IO::print("*");
278                         unsigned count = 0;
279                         unsigned to_be_built = 0;
280                         for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
281                                 if(j->second->get_package()==i->second)
282                                 {
283                                         ++count;
284                                         if(j->second->get_rebuild())
285                                                 ++to_be_built;
286                                 }
287                         if(count)
288                         {
289                                 IO::print(" (%d targets", count);
290                                 if(to_be_built)
291                                         IO::print(", %d to be built", to_be_built);
292                                 IO::print(")");
293                         }
294                         IO::print("\n");
295                 }
296         }
297
298         if(analyzer)
299                 analyzer->analyze();
300
301         if(!problems.empty())
302         {
303                 IO::print(IO::cerr, "The following problems were detected:\n");
304                 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
305                         IO::print(IO::cerr, "  %s: %s\n", i->package, i->descr);
306                 if(!analyzer)
307                         IO::print(IO::cerr, "Please fix them and try again.\n");
308                 return 1;
309         }
310
311         if(clean)
312                 exit_code = do_clean();
313         else if(build)
314                 exit_code = do_build();
315
316         return exit_code;
317 }
318
319 string Builder::run_pkgconfig(const string &pkg, const string &what)
320 {
321         list<string> argv;
322         argv.push_back("pkg-config");
323         if(what=="cflags" || what=="libs")
324                 argv.push_back("--"+what);
325         else if(what=="flags")
326         {
327                 argv.push_back("--cflags");
328                 argv.push_back("--libs");
329         }
330         else
331                 argv.push_back("--variable="+what);
332         argv.push_back(pkg);
333
334         if(verbose>=4)
335                 IO::print("Running %s\n", join(argv.begin(), argv.end()));
336
337         int status;
338         string res = run_command(argv, &status);
339         if(status)
340                 throw Exception(format("pkg-config for package %s failed", pkg));
341
342         return res;
343 }
344
345 Package *Builder::get_package(const string &name)
346 {
347         PackageMap::iterator i = packages.find(format("%s/%s", name, current_arch->get_system()));
348         if(i==packages.end())
349                 i = packages.find(name);
350         if(i!=packages.end())
351                 return i->second;
352
353         if(!no_externals)
354         {
355                 FS::Path path = get_package_location(name);
356                 if(!path.empty() && !load_build_file(path/"Build"))
357                 {
358                         i = packages.find(name);
359                         if(i!=packages.end())
360                                 return i->second;
361                 }
362         }
363
364         Package *pkg = 0;
365         try
366         {
367                 // Package source not found - create a binary package
368                 pkg = BinaryPackage::from_pkgconfig(*this, name);
369         }
370         catch(...)
371         {
372                 problem(name, "not found");
373         }
374
375         packages.insert(PackageMap::value_type(name, pkg));
376
377         return pkg;
378 }
379
380 Target *Builder::get_target(const string &n) const
381 {
382         // XXX Used for getting targets by path.  get_target(const FS::Path &)?
383         TargetMap::const_iterator i = targets.find(n);
384         if(i!=targets.end())
385                 return i->second;
386         return 0;
387 }
388
389 Target *Builder::get_header(const string &include, const FS::Path &from, const list<string> &path)
390 {
391         string hash(8, 0);
392         if(include[0]=='\"')
393                 update_hash(hash, from.str());
394         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
395                 update_hash(hash, *i);
396
397         string id = hash+include;
398         TargetMap::iterator i = includes.find(id);
399         if(i!=includes.end())
400                 return i->second;
401
402         static string cxx_ver;
403         if(cxx_ver.empty())
404         {
405                 StringList argv;
406                 argv.push_back(current_arch->get_tool("CXX"));
407                 argv.push_back("--version");
408                 if(RegMatch m = Regex("[0-9]\\.[0-9.]+").match(run_command(argv)))
409                 {
410                         cxx_ver = m[0].str;
411                         while(!cxx_ver.empty() && !FS::is_dir(FS::Path("/usr/include/c++")/cxx_ver))
412                         {
413                                 string::size_type dot = cxx_ver.rfind('.');
414                                 if(dot==string::npos)
415                                         break;
416                                 cxx_ver.erase(dot);
417                         }
418                         if(verbose>=5)
419                                 IO::print("C++ version is %s\n", cxx_ver);
420                 }
421                 else
422                         cxx_ver = "-";
423         }
424
425         string fn = include.substr(1);
426         if(verbose>=5)
427                 IO::print("Looking for include %s from %s with path %s\n", fn, from, join(path.begin(), path.end()));
428
429         StringList syspath;
430         if(current_arch->is_native())
431                 syspath.push_back("/usr/include");
432         else
433                 syspath.push_back("/usr/"+current_arch->get_cross_prefix()+"/include");
434         if(cxx_ver!="-")
435                 syspath.push_back((FS::Path("/usr/include/c++/")/cxx_ver).str());
436
437         Target *tgt = 0;
438         if(include[0]=='\"')
439                 tgt = get_header(FS::Path(from)/fn);
440         for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
441                 tgt = get_header(cwd/ *j/fn);
442         for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
443                 tgt = get_header(FS::Path(*j)/fn);
444
445         includes.insert(TargetMap::value_type(id, tgt));
446
447         return tgt;
448 }
449
450 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
451 {
452         string hash(8, 0);
453         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
454                 update_hash(hash, *i);
455
456         string id = hash+string(1, mode)+lib;
457         TargetMap::iterator i = libraries.find(id);
458         if(i!=libraries.end())
459                 return i->second;
460
461         StringList syspath;
462         if(current_arch->is_native())
463         {
464                 syspath.push_back("/lib");
465                 syspath.push_back("/usr/lib");
466         }
467         else
468                 syspath.push_back("/usr/"+current_arch->get_cross_prefix()+"/lib");
469
470         if(verbose>=5)
471                 IO::print("Looking for library %s with path %s\n", lib, join(path.begin(), path.end()));
472
473         Target *tgt = 0;
474         for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
475                 tgt = get_library(lib, cwd/ *j, mode);
476         for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
477                 tgt = get_library(lib, *j, mode);
478
479         libraries.insert(TargetMap::value_type(id, tgt));
480
481         return tgt;
482 }
483
484 void Builder::apply_profile_template(Config &config, const string &pt) const
485 {
486         vector<string> parts = split(pt, '-');
487
488         for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
489         {
490                 ProfileTemplateMap::const_iterator j = profile_tmpl.find(*i);
491                 if(j==profile_tmpl.end())
492                         continue;
493
494                 config.update(j->second);
495         }
496 }
497
498 void Builder::problem(const string &p, const string &d)
499 {
500         problems.push_back(Problem(p, d));
501 }
502
503 void Builder::add_target(FileTarget *t)
504 {
505         targets.insert(TargetMap::value_type(t->get_path().str(), t));
506         new_tgts.push_back(t);
507 }
508
509 void Builder::add_target(VirtualTarget *t)
510 {
511         targets.insert(TargetMap::value_type(t->get_name(), t));
512         new_tgts.push_back(t);
513 }
514
515 void Builder::usage(const char *reason, const char *argv0, bool brief)
516 {
517         if(reason)
518                 IO::print(IO::cerr, "%s\n", reason);
519
520         if(brief)
521                 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
522         else
523         {
524                 IO::print(IO::cerr, "Builder 1.0\n\n");
525                 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
526                 IO::print(IO::cerr, "Options:\n");
527                 IO::print(IO::cerr, helpmsg);
528         }
529 }
530
531 FS::Path Builder::get_package_location(const string &name)
532 {
533         if(verbose>=3)
534                 IO::print("Looking for package %s\n", name);
535
536         try
537         {
538                 // Try to get source directory with pkgconfig
539                 string srcdir = strip(run_pkgconfig(name, "source"));
540                 if(!srcdir.empty())
541                         return srcdir;
542         }
543         catch(...)
544         { }
545
546         if(pkg_dirs.empty())
547         {
548                 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
549                 {
550                         list<string> files = list_files(*i);
551                         for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
552                         {
553                                 FS::Path full = *i / *j;
554                                 if(FS::exists(full/"Build"))
555                                         pkg_dirs.push_back(full);
556                         }
557                 }
558                 if(verbose>=3)
559                         IO::print("%d packages found in path\n", pkg_dirs.size());
560         }
561
562         bool msp = !name.compare(0, 3, "msp");
563         for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
564         {
565                 string base = basename(*i);
566                 unsigned dash = base.rfind('-');
567
568                 if(!base.compare(0, dash, name))
569                         return *i;
570                 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
571                         return *i;
572         }
573
574         return FS::Path();
575 }
576
577 int Builder::load_build_file(const FS::Path &fn)
578 {
579         try
580         {
581                 IO::BufferedFile in(fn.str());
582
583                 if(verbose>=3)
584                         IO::print("Reading %s\n", fn);
585
586                 DataFile::Parser parser(in, fn.str());
587                 Loader loader(*this, fn.subpath(0, fn.size()-1));
588                 loader.load(parser);
589         }
590         catch(const IO::FileNotFound &)
591         {
592                 return -1;
593         }
594
595         return 0;
596 }
597
598 int Builder::create_targets()
599 {
600         Target *world = new VirtualTarget(*this, "world");
601
602         Target *def_tgt = new VirtualTarget(*this, "default");
603         world->add_depend(def_tgt);
604
605         Target *install = new VirtualTarget(*this, "install");
606         world->add_depend(install);
607
608         Target *tarballs = new VirtualTarget(*this, "tarballs");
609         world->add_depend(tarballs);
610
611         for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
612         {
613                 if(!i->second || !i->second->is_configured())
614                         continue;
615
616                 SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second);
617                 if(!spkg)
618                         continue;
619
620                 const ComponentList &components = spkg->get_components();
621                 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
622                         j->create_targets();
623
624                 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
625                 {
626                         PkgConfig *pc = new PkgConfig(*this, *spkg);
627                         install->add_depend(new Install(*this, *spkg, *pc));
628                 }
629         }
630
631         // Find dependencies until no new targets are created
632         while(!new_tgts.empty())
633         {
634                 Target *tgt = new_tgts.front();
635                 new_tgts.erase(new_tgts.begin());
636                 tgt->find_depends();
637                 if(!tgt->get_depends_ready())
638                         new_tgts.push_back(tgt);
639         }
640
641         // Apply what-ifs
642         for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
643         {
644                 FileTarget *tgt = dynamic_cast<FileTarget *>(get_target((cwd/ *i).str()));
645                 if(!tgt)
646                 {
647                         IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
648                         return -1;
649                 }
650                 tgt->touch();
651         }
652
653         // Make the cmdline target depend on all targets mentioned on the command line
654         Target *cmdline = new VirtualTarget(*this, "cmdline");
655         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
656         {
657                 Target *tgt = get_target(*i);
658                 if(!tgt)
659                         tgt = get_target((cwd/ *i).str());
660                 if(!tgt)
661                 {
662                         IO::print("I don't know anything about %s\n", *i);
663                         return -1;
664                 }
665
666                 cmdline->add_depend(tgt);
667         }
668
669         cmdline->prepare();
670
671         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
672                 if(SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second))
673                         spkg->get_deps_cache().save();
674
675         return 0;
676 }
677
678 Target *Builder::get_header(const FS::Path &fn)
679 {
680         Target *tgt = get_target(fn.str());
681         if(tgt) return tgt;
682
683         if(FS::is_reg(fn))
684         {
685                 tgt = new SystemHeader(*this, fn.str());
686                 return tgt;
687         }
688         return 0;
689 }
690
691 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
692 {
693         // Populate a list of candidate filenames
694         StringList candidates;
695
696         if(mode!=ALL_STATIC)
697         {
698                 // XXX Should probably let the Architecture populate the list
699                 if(current_arch->get_system()=="windows")
700                 {
701                         candidates.push_back("lib"+lib+".dll");
702                         candidates.push_back(lib+".dll");
703                 }
704                 else
705                         candidates.push_back("lib"+lib+".so");
706         }
707
708         /* Static libraries are always considered, since sometimes shared versions
709         may not be available */
710         candidates.push_back("lib"+lib+".a");
711         if(current_arch->get_system()=="windows")
712                 candidates.push_back("lib"+lib+".dll.a");
713
714         for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
715         {
716                 string full = (path/ *i).str();
717                 Target *tgt = get_target(full);
718
719                 if(tgt)
720                 {
721                         Target *real_tgt = tgt->get_real_target();
722
723                         /* Ignore dynamic libraries from local packages unless library mode is
724                         DYNAMIC */
725                         if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
726                                 continue;
727                         else if(tgt)
728                                 return tgt;
729                 }
730                 else if(FS::is_reg(full))
731                 {
732                         tgt = new SystemLibrary(*this, full);
733                         return tgt;
734                 }
735         }
736
737         return 0;
738 }
739
740 int Builder::do_build()
741 {
742         Target *cmdline = get_target("cmdline");
743
744         unsigned total = 0;
745         for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
746                 if(i->second->is_buildable() && i->second->get_rebuild())
747                         ++total;
748
749         if(!total)
750         {
751                 IO::print("Already up to date\n");
752                 return 0;
753         }
754         if(verbose>=1)
755                 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
756
757         vector<Action *> actions;
758
759         unsigned count = 0;
760
761         bool fail = false;
762         bool finish = false;
763
764         while(!finish)
765         {
766                 if(actions.size()<jobs && !fail)
767                 {
768                         Target *tgt = cmdline->get_buildable_target();
769                         if(tgt)
770                         {
771                                 Action *action = tgt->build();
772                                 if(action)
773                                         actions.push_back(action);
774
775                                 if(show_progress)
776                                         IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
777                         }
778                         else if(actions.empty())
779                                 finish = true;
780                 }
781                 else
782                         Time::sleep(10*Time::msec);
783
784                 for(unsigned i=0; i<actions.size();)
785                 {
786                         int status = actions[i]->check();
787                         if(status>=0)
788                         {
789                                 ++count;
790
791                                 delete actions[i];
792                                 actions.erase(actions.begin()+i);
793                                 if(status>0)
794                                         fail = true;
795                                 if(actions.empty() && fail)
796                                         finish = true;
797                         }
798                         else
799                                 ++i;
800                 }
801         }
802
803         if(show_progress)
804                 IO::print("\033[K");
805         if(fail)
806                 IO::print("Build failed\n");
807         else if(show_progress)
808                 IO::print("Build complete\n");
809
810         return fail;
811 }
812
813 int Builder::do_clean()
814 {
815         // Cleaning doesn't care about ordering, so a simpler method can be used
816
817         set<Target *> clean_tgts;
818         TargetList queue;
819         queue.push_back(get_target("cmdline"));
820
821         while(!queue.empty())
822         {
823                 Target *tgt = queue.front();
824                 queue.erase(queue.begin());
825
826                 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
827                         clean_tgts.insert(tgt);
828
829                 const TargetList &deps = tgt->get_depends();
830                 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
831                         if(!clean_tgts.count(*i))
832                                 queue.push_back(*i);
833         }
834
835         for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
836                 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
837                 {
838                         Action *action = new Unlink(*this, *ft);
839                         while(action->check()<0) ;
840                         delete action;
841                 }
842
843         return 0;
844 }
845
846 void Builder::package_help()
847 {
848         const Config &config = main_pkg->get_config();
849         const Config::OptionMap &options = config.get_options();
850
851         IO::print("Required packages:\n  ");
852         const PackageList &requires = main_pkg->get_requires();
853         for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
854         {
855                 if(i!=requires.begin())
856                         IO::print(", ");
857                 IO::print((*i)->get_name());
858         }
859         IO::print("\n\nPackage configuration:\n");
860         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
861         {
862                 const Config::Option &opt = i->second;
863                 IO::print("  %s: %s (%s)", opt.name, opt.descr, opt.value);
864                 if(opt.value!=opt.defv)
865                         IO::print(" [%s]", opt.defv);
866                 IO::print("\n");
867         }
868 }
869
870 Application::RegApp<Builder> Builder::reg;
871 string Builder::usagemsg;
872 string Builder::helpmsg;
873
874
875 Builder::Loader::Loader(Builder &b, const FS::Path &s):
876         bld(b),
877         src(s)
878 {
879         add("binary_package", &Loader::binpkg);
880         add("cross_prefix", &Loader::cross_prefix);
881         add("profile", &Loader::profile);
882         add("package", &Loader::package);
883 }
884
885 void Builder::Loader::binpkg(const string &n)
886 {
887         BinaryPackage *pkg = new BinaryPackage(bld, n);
888         load_sub(*pkg);
889         bld.packages.insert(PackageMap::value_type(n, pkg));
890 }
891
892 void Builder::Loader::cross_prefix(const string &a, const string &p)
893 {
894         bld.cross_prefixes[a] = p;
895 }
896
897 void Builder::Loader::profile(const string &n)
898 {
899         StringMap prf;
900         ProfileLoader ldr(prf);
901         load_sub_with(ldr);
902         bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
903 }
904
905 void Builder::Loader::package(const string &n)
906 {
907         SourcePackage *pkg = new SourcePackage(bld, n, src);
908         if(!bld.main_pkg)
909                 bld.main_pkg = pkg;
910
911         load_sub(*pkg);
912         bld.packages.insert(PackageMap::value_type(n, pkg));
913 }
914
915
916 Builder::ProfileLoader::ProfileLoader(StringMap &p):
917         profile(p)
918 {
919         add("option", &ProfileLoader::option);
920 }
921
922 void Builder::ProfileLoader::option(const string &o, const string &v)
923 {
924         profile.insert(StringMap::value_type(o, v));
925 }