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