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