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