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