]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Load builderrc from sys_data_dir to avoid the need of copying it to $HOME
[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));
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(get_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/"+get_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::File inf(fn.str());
551                 IO::Buffered in(inf);
552
553                 if(verbose>=3)
554                         cout<<"Reading "<<fn<<'\n';
555
556                 DataFile::Parser parser(in, fn.str());
557                 Loader loader(*this, fn.subpath(0, fn.size()-1));
558                 loader.load(parser);
559         }
560         catch(const IO::FileNotFound &)
561         {
562                 return -1;
563         }
564
565         return 0;
566 }
567
568 /**
569 Creates targets for all packages and prepares them for building.
570
571 @return  0 if everything went ok, -1 if something bad happened and a build
572          shouldn't be attempted
573 */
574 int Builder::create_targets()
575 {
576         Target *world=new VirtualTarget(*this, "world");
577
578         Target *def_tgt=new VirtualTarget(*this, "default");
579         world->add_depend(def_tgt);
580
581         Target *install=new VirtualTarget(*this, "install");
582         world->add_depend(install);
583
584         Target *tarballs=new VirtualTarget(*this, "tarballs");
585         world->add_depend(tarballs);
586
587         PackageList all_reqs=main_pkg->collect_requires();
588         for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
589         {
590                 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
591                 if(!spkg)
592                         continue;
593
594                 const ComponentList &components=spkg->get_components();
595                 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
596                         j->create_targets();
597
598                 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
599                 {
600                         PkgConfig *pc=new PkgConfig(*this, *spkg);
601                         install->add_depend(new Install(*this, *spkg, *pc));
602                 }
603
604                 tarballs->add_depend(new TarBall(*this, *spkg));
605         }
606
607         // Find dependencies until no new targets are created
608         while(!new_tgts.empty())
609         {
610                 Target *tgt=new_tgts.front();
611                 new_tgts.erase(new_tgts.begin());
612                 tgt->find_depends();
613                 if(!tgt->get_depends_ready())
614                         new_tgts.push_back(tgt);
615         }
616
617         // Apply what-ifs
618         for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
619         {
620                 Target *tgt=get_target((cwd/ *i).str());
621                 if(!tgt)
622                 {
623                         cerr<<"Unknown what-if target "<<*i<<'\n';
624                         return -1;
625                 }
626                 tgt->touch();
627         }
628
629         // Make the cmdline target depend on all targets mentioned on the command line
630         Target *cmdline=new VirtualTarget(*this, "cmdline");
631         bool build_world=false;
632         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
633         {
634                 Target *tgt=get_target(*i);
635                 if(!tgt)
636                         tgt=get_target((cwd/ *i).str());
637                 if(!tgt)
638                 {
639                         cerr<<"I don't know anything about "<<*i<<'\n';
640                         return -1;
641                 }
642                 if(tgt==world)
643                         build_world=true;
644                 cmdline->add_depend(tgt);
645         }
646
647         /* If world is to be built, prepare cmdline.  If not, add cmdline to world
648            and prepare world.  I don't really like this, but it keeps the graph
649            acyclic. */
650         if(build_world)
651                 cmdline->prepare();
652         else
653         {
654                 world->add_depend(cmdline);
655                 world->prepare();
656         }
657
658         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
659                 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
660                         spkg->get_deps_cache().save();
661
662         return 0;
663 }
664
665 /**
666 Check if a header exists, either as a target or a file.  Either an existing
667 target or a new SystemHeader target will be returned.
668 */
669 Target *Builder::get_header(const Msp::FS::Path &fn)
670 {
671         Target *tgt=get_target(fn.str());
672         if(tgt) return tgt;
673
674         if(FS::is_reg(fn))
675         {
676                 tgt=new SystemHeader(*this, fn.str());
677                 return tgt;
678         }
679         return 0;
680 }
681
682 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
683 {
684         // Populate a list of candidate filenames
685         StringList candidates;
686
687         if(mode!=ALL_STATIC)
688         {
689                 if(current_arch->get_name()=="win32")
690                 {
691                         candidates.push_back("lib"+lib+".dll");
692                         candidates.push_back(lib+".dll");
693                 }
694                 else
695                         candidates.push_back("lib"+lib+".so");
696         }
697
698         /* Static libraries are always considered, since sometimes shared versions
699         may not be available */
700         candidates.push_back("lib"+lib+".a");
701         if(current_arch->get_name()=="win32")
702                 candidates.push_back("lib"+lib+".dll.a");
703
704         for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
705         {
706                 string full=(path/ *i).str();
707                 Target *tgt=get_target(full);
708
709                 if(tgt)
710                 {
711                         Target *real_tgt=tgt;
712                         if(dynamic_cast<Install *>(tgt))
713                                 real_tgt=real_tgt->get_depends().front();
714
715                         /* Ignore dynamic libraries from local packages unless library mode is
716                         DYNAMIC */
717                         if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
718                                 continue;
719                         else if(tgt)
720                                 return tgt;
721                 }
722                 else if(FS::is_reg(full))
723                 {
724                         tgt=new SystemLibrary(*this, full);
725                         return tgt;
726                 }
727         }
728
729         return 0;
730 }
731
732 /**
733 Updates a hash with a string.  This is used from get_header and get_library.
734 */
735 void Builder::update_hash(string &hash, const string &value)
736 {
737         for(unsigned i=0; i<value.size(); ++i)
738                 hash[i%hash.size()]^=value[i];
739 }
740
741 /**
742 This function supervises the build process, starting new actions when slots
743 become available.
744 */
745 int Builder::do_build()
746 {
747         Target *cmdline=get_target("cmdline");
748
749         unsigned total=cmdline->count_rebuild();
750         if(!total)
751         {
752                 cout<<"Already up to date\n";
753                 return 0;
754         }
755         if(verbose>=1)
756                 cout<<"Will build "<<total<<" target(s)\n";
757
758         vector<Action *> actions;
759
760         unsigned count=0;
761
762         bool fail=false;
763         bool finish=false;
764
765         while(!finish)
766         {
767                 if(actions.size()<jobs && !fail)
768                 {
769                         Target *tgt=cmdline->get_buildable_target();
770                         if(tgt)
771                         {
772                                 Action *action=tgt->build();
773                                 if(action)
774                                         actions.push_back(action);
775
776                                 if(show_progress)
777                                 {
778                                         cout<<count<<" of "<<total<<" targets built\033[1G";
779                                         cout.flush();
780                                 }
781                         }
782                         else if(actions.empty())
783                                 finish=true;
784                 }
785                 else
786                         Time::sleep(10*Time::msec);
787
788                 for(unsigned i=0; i<actions.size();)
789                 {
790                         int status=actions[i]->check();
791                         if(status>=0)
792                         {
793                                 ++count;
794
795                                 delete actions[i];
796                                 actions.erase(actions.begin()+i);
797                                 if(status>0)
798                                         fail=true;
799                                 if(actions.empty() && fail)
800                                         finish=true;
801                         }
802                         else
803                                 ++i;
804                 }
805         }
806
807         if(show_progress)
808                 cout<<"\033[K";
809         if(fail)
810                 cout<<"Build failed\n";
811         else if(show_progress)
812                 cout<<"Build complete\n";
813
814         return fail?1:0;
815 }
816
817 /**
818 Cleans buildable targets.  If clean is 1, cleans only this package.  If
819 clean is 2 or greater, cleans all buildable packages.
820 */
821 int Builder::do_clean()
822 {
823         // Cleaning doesn't care about ordering, so a simpler method can be used
824
825         set<Target *> clean_tgts;
826         TargetList queue;
827         queue.push_back(get_target("cmdline"));
828
829         while(!queue.empty())
830         {
831                 Target *tgt=queue.front();
832                 queue.erase(queue.begin());
833
834                 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
835                         clean_tgts.insert(tgt);
836
837                 const TargetList &deps=tgt->get_depends();
838                 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
839                         if(!clean_tgts.count(*i))
840                                 queue.push_back(*i);
841         }
842
843         for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
844         {
845                 Action *action=new Unlink(*this, **i);
846                 while(action->check()<0) ;
847                 delete action;
848         }
849
850         return 0;
851 }
852
853 /**
854 Prints out information about the default package.
855 */
856 void Builder::package_help()
857 {
858         const Config &config=main_pkg->get_config();
859         const Config::OptionMap &options=config.get_options();
860
861         cout<<"Required packages:\n  ";
862         const PackageList &requires=main_pkg->get_requires();
863         for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
864         {
865                 if(i!=requires.begin())
866                         cout<<", ";
867                 cout<<(*i)->get_name();
868         }
869         cout<<"\n\n";
870         cout<<"Package configuration:\n";
871         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
872         {
873                 const Config::Option &opt=i->second;
874                 cout<<"  "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
875         }
876 }
877
878 Application::RegApp<Builder> Builder::reg;
879
880
881 Builder::Loader::Loader(Builder &b, const FS::Path &s):
882         bld(b),
883         src(s)
884 {
885         add("architecture", &Loader::architecture);
886         add("binary_package", &Loader::binpkg);
887         add("profile", &Loader::profile);
888         add("package", &Loader::package);
889 }
890
891 void Builder::Loader::architecture(const string &n)
892 {
893         Architecture arch(bld, n);
894         load_sub(arch);
895         bld.archs.insert(ArchMap::value_type(n, arch));
896 }
897
898 void Builder::Loader::binpkg(const string &n)
899 {
900         BinaryPackage *pkg=new BinaryPackage(bld, n);
901         load_sub(*pkg);
902         bld.packages.insert(PackageMap::value_type(n, pkg));
903 }
904
905 void Builder::Loader::profile(const string &n)
906 {
907         StringMap prf;
908         ProfileLoader ldr(prf);
909         load_sub_with(ldr);
910         bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
911 }
912
913 void Builder::Loader::package(const string &n)
914 {
915         SourcePackage *pkg=new SourcePackage(bld, n, src);
916         if(!bld.main_pkg)
917                 bld.main_pkg=pkg;
918
919         load_sub(*pkg);
920         bld.packages.insert(PackageMap::value_type(n, pkg));
921 }
922
923
924 Builder::ProfileLoader::ProfileLoader(StringMap &p):
925         profile(p)
926 {
927         add("option", &ProfileLoader::option);
928 }
929
930 void Builder::ProfileLoader::option(const string &o, const string &v)
931 {
932         profile.insert(StringMap::value_type(o, v));
933 }