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