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