]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Various fixes to package dependency and build info handling
[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->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->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         bool build_world = false;
656         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
657         {
658                 Target *tgt = get_target(*i);
659                 if(!tgt)
660                         tgt = get_target((cwd/ *i).str());
661                 if(!tgt)
662                 {
663                         IO::print("I don't know anything about %s\n", *i);
664                         return -1;
665                 }
666                 if(tgt==world)
667                         build_world = true;
668                 cmdline->add_depend(tgt);
669         }
670
671         cmdline->prepare();
672
673         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
674                 if(SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second))
675                         spkg->get_deps_cache().save();
676
677         return 0;
678 }
679
680 Target *Builder::get_header(const FS::Path &fn)
681 {
682         Target *tgt = get_target(fn.str());
683         if(tgt) return tgt;
684
685         if(FS::is_reg(fn))
686         {
687                 tgt = new SystemHeader(*this, fn.str());
688                 return tgt;
689         }
690         return 0;
691 }
692
693 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
694 {
695         // Populate a list of candidate filenames
696         StringList candidates;
697
698         if(mode!=ALL_STATIC)
699         {
700                 // XXX Should probably let the Architecture populate the list
701                 if(current_arch->get_system()=="windows")
702                 {
703                         candidates.push_back("lib"+lib+".dll");
704                         candidates.push_back(lib+".dll");
705                 }
706                 else
707                         candidates.push_back("lib"+lib+".so");
708         }
709
710         /* Static libraries are always considered, since sometimes shared versions
711         may not be available */
712         candidates.push_back("lib"+lib+".a");
713         if(current_arch->get_system()=="windows")
714                 candidates.push_back("lib"+lib+".dll.a");
715
716         for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
717         {
718                 string full = (path/ *i).str();
719                 Target *tgt = get_target(full);
720
721                 if(tgt)
722                 {
723                         Target *real_tgt = tgt->get_real_target();
724
725                         /* Ignore dynamic libraries from local packages unless library mode is
726                         DYNAMIC */
727                         if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
728                                 continue;
729                         else if(tgt)
730                                 return tgt;
731                 }
732                 else if(FS::is_reg(full))
733                 {
734                         tgt = new SystemLibrary(*this, full);
735                         return tgt;
736                 }
737         }
738
739         return 0;
740 }
741
742 int Builder::do_build()
743 {
744         Target *cmdline = get_target("cmdline");
745
746         unsigned total = 0;
747         for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
748                 if(i->second->is_buildable() && i->second->get_rebuild())
749                         ++total;
750
751         if(!total)
752         {
753                 IO::print("Already up to date\n");
754                 return 0;
755         }
756         if(verbose>=1)
757                 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
758
759         vector<Action *> actions;
760
761         unsigned count = 0;
762
763         bool fail = false;
764         bool finish = false;
765
766         while(!finish)
767         {
768                 if(actions.size()<jobs && !fail)
769                 {
770                         Target *tgt = cmdline->get_buildable_target();
771                         if(tgt)
772                         {
773                                 Action *action = tgt->build();
774                                 if(action)
775                                         actions.push_back(action);
776
777                                 if(show_progress)
778                                         IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
779                         }
780                         else if(actions.empty())
781                                 finish = true;
782                 }
783                 else
784                         Time::sleep(10*Time::msec);
785
786                 for(unsigned i=0; i<actions.size();)
787                 {
788                         int status = actions[i]->check();
789                         if(status>=0)
790                         {
791                                 ++count;
792
793                                 delete actions[i];
794                                 actions.erase(actions.begin()+i);
795                                 if(status>0)
796                                         fail = true;
797                                 if(actions.empty() && fail)
798                                         finish = true;
799                         }
800                         else
801                                 ++i;
802                 }
803         }
804
805         if(show_progress)
806                 IO::print("\033[K");
807         if(fail)
808                 IO::print("Build failed\n");
809         else if(show_progress)
810                 IO::print("Build complete\n");
811
812         return fail;
813 }
814
815 int Builder::do_clean()
816 {
817         // Cleaning doesn't care about ordering, so a simpler method can be used
818
819         set<Target *> clean_tgts;
820         TargetList queue;
821         queue.push_back(get_target("cmdline"));
822
823         while(!queue.empty())
824         {
825                 Target *tgt = queue.front();
826                 queue.erase(queue.begin());
827
828                 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
829                         clean_tgts.insert(tgt);
830
831                 const TargetList &deps = tgt->get_depends();
832                 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
833                         if(!clean_tgts.count(*i))
834                                 queue.push_back(*i);
835         }
836
837         for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
838                 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
839                 {
840                         Action *action = new Unlink(*this, *ft);
841                         while(action->check()<0) ;
842                         delete action;
843                 }
844
845         return 0;
846 }
847
848 void Builder::package_help()
849 {
850         const Config &config = main_pkg->get_config();
851         const Config::OptionMap &options = config.get_options();
852
853         IO::print("Required packages:\n  ");
854         const PackageList &requires = main_pkg->get_requires();
855         for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
856         {
857                 if(i!=requires.begin())
858                         IO::print(", ");
859                 IO::print((*i)->get_name());
860         }
861         IO::print("\n\nPackage configuration:\n");
862         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
863         {
864                 const Config::Option &opt = i->second;
865                 IO::print("  %s: %s (%s)", opt.name, opt.descr, opt.value);
866                 if(opt.value!=opt.defv)
867                         IO::print(" [%s]", opt.defv);
868                 IO::print("\n");
869         }
870 }
871
872 Application::RegApp<Builder> Builder::reg;
873 string Builder::usagemsg;
874 string Builder::helpmsg;
875
876
877 Builder::Loader::Loader(Builder &b, const FS::Path &s):
878         bld(b),
879         src(s)
880 {
881         add("binary_package", &Loader::binpkg);
882         add("cross_prefix", &Loader::cross_prefix);
883         add("profile", &Loader::profile);
884         add("package", &Loader::package);
885 }
886
887 void Builder::Loader::binpkg(const string &n)
888 {
889         BinaryPackage *pkg = new BinaryPackage(bld, n);
890         load_sub(*pkg);
891         bld.packages.insert(PackageMap::value_type(n, pkg));
892 }
893
894 void Builder::Loader::cross_prefix(const string &a, const string &p)
895 {
896         bld.cross_prefixes[a] = p;
897 }
898
899 void Builder::Loader::profile(const string &n)
900 {
901         StringMap prf;
902         ProfileLoader ldr(prf);
903         load_sub_with(ldr);
904         bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
905 }
906
907 void Builder::Loader::package(const string &n)
908 {
909         SourcePackage *pkg = new SourcePackage(bld, n, src);
910         if(!bld.main_pkg)
911                 bld.main_pkg = pkg;
912
913         load_sub(*pkg);
914         bld.packages.insert(PackageMap::value_type(n, pkg));
915 }
916
917
918 Builder::ProfileLoader::ProfileLoader(StringMap &p):
919         profile(p)
920 {
921         add("option", &ProfileLoader::option);
922 }
923
924 void Builder::ProfileLoader::option(const string &o, const string &v)
925 {
926         profile.insert(StringMap::value_type(o, v));
927 }