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