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