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