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