]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Make sure to use absolute paths when looking for headers/libraries
[builder.git] / source / builder.cpp
1 #include <fstream>
2 #include <iostream>
3 #include <msp/progress.h>
4 #include <msp/strconv.h>
5 #include <msp/strutils.h>
6 #include <msp/core/error.h>
7 #include <msp/getopt++/getopt++.h>
8 #include <msp/parser/parser.h>
9 #include <msp/path/utils.h>
10 #include <msp/time/units.h>
11 #include <msp/time/utils.h>
12 #include "action.h"
13 #include "analyzer.h"
14 #include "builder.h"
15 #include "executable.h"
16 #include "header.h"
17 #include "install.h"
18 #include "misc.h"
19 #include "objectfile.h"
20 #include "package.h"
21 #include "systemlibrary.h"
22 #include "virtualtarget.h"
23
24 using namespace std;
25 using namespace Msp;
26
27 Builder::Builder(int argc, char **argv):
28         verbose(1),
29         cwd(Path::getcwd()),
30         build_file("Build"),
31         do_build(true),
32         analyzer(0),
33         jobs(1),
34         chrome(false)
35 {
36         GetOpt getopt;
37         getopt.add_option(GetOpt::Option('v', "verbose", GetOpt::NONE));
38         getopt.add_option(GetOpt::Option('a', "analyze", GetOpt::REQUIRED));
39         getopt.add_option(GetOpt::Option('b', "build", GetOpt::NONE));
40         getopt.add_option(GetOpt::Option("max-depth", GetOpt::REQUIRED));
41         getopt.add_option(GetOpt::Option('n', "dry-run", GetOpt::NONE));
42         getopt.add_option(GetOpt::Option('W', "what-if", GetOpt::REQUIRED));
43         getopt.add_option(GetOpt::Option('B', "build-all", GetOpt::NONE));
44         getopt.add_option(GetOpt::Option('C', "chdir", GetOpt::REQUIRED));
45         getopt.add_option(GetOpt::Option('j', "jobs", GetOpt::REQUIRED, "1"));
46         getopt.add_option(GetOpt::Option('h', "help", GetOpt::NONE));
47         getopt.add_option(GetOpt::Option('c', "clean", GetOpt::NONE));
48         getopt.add_option(GetOpt::Option('f', "file", GetOpt::REQUIRED, "Build"));
49         getopt.add_option(GetOpt::Option("chrome", GetOpt::NONE));
50         getopt.add_option(GetOpt::Option("full-paths", GetOpt::NONE));
51         getopt.add_option(GetOpt::Option('A', "conf-all", GetOpt::NONE));
52         int index=getopt(argc, argv);
53
54         verbose+=getopt['v'].count();
55
56         if(getopt['a'])
57         {
58                 analyzer=new Analyzer(*this);
59
60                 string mode=getopt['a'].arg();
61                 if(mode=="deps")
62                         analyzer->set_mode(Analyzer::DEPS);
63                 else if(mode=="alldeps")
64                         analyzer->set_mode(Analyzer::ALLDEPS);
65                 else if(mode=="rebuild")
66                         analyzer->set_mode(Analyzer::REBUILD);
67                 else if(mode=="rdeps")
68                         analyzer->set_mode(Analyzer::RDEPS);
69                 else
70                         throw UsageError("Invalid analysis mode");
71
72                 if(getopt["max-depth"])
73                         analyzer->set_max_depth(strtol(getopt["max-depth"].arg()));
74                 analyzer->set_full_paths(getopt["full-paths"]);
75
76                 if(!getopt['b'])
77                         do_build=false;
78         }
79
80         dry_run=getopt['n'];
81         jobs=max(strtol(getopt['j'].arg()), 1L);
82         chrome=getopt["chrome"];
83         conf_all=getopt['A'];
84         build_file=getopt['f'].arg();
85         build_all=getopt['B'];
86
87         if(getopt['C'])
88                 chdir(getopt['C'].arg().c_str());
89
90         for(int i=index; i<argc; ++i)
91         {
92                 string v(argv[i]);
93                 unsigned equal=v.find('=');
94                 if(equal!=string::npos)
95                         cmdline_options.insert(RawOptionMap::value_type(v.substr(0, equal), v.substr(equal+1)));
96                 else
97                         cmdline_targets.push_back(argv[i]);
98         }
99
100         if(cmdline_targets.empty())
101                 cmdline_targets.push_back("default");
102
103         if(getopt['W'])
104                 what_if.push_back(getopt['W'].arg());
105 }
106
107 /**
108 Gets a package with the specified name, possibly creating it.
109
110 @param   n  Package name
111
112 @return  Pointer to the package, or 0 if the package could not be located
113 */
114 Package *Builder::get_package(const string &n)
115 {
116         PackageMap::iterator i=packages.find(n);
117         if(i!=packages.end())
118                 return i->second;
119
120         // Try to get source directory with pkgconfig
121         list<string> argv;
122         argv.push_back("pkg-config");
123         argv.push_back("--variable=source");
124         argv.push_back(n);
125         string srcdir=strip(run_command(argv));
126         
127         PathList dirs;
128         if(!srcdir.empty())
129                 dirs.push_back(srcdir);
130
131         // Make some other guesses about the source directory
132         string dirname=n;
133         if(!dirname.compare(0, 3, "msp"))
134                 dirname.erase(0, 3);
135         dirs.push_back(cwd/dirname);
136         dirs.push_back(cwd/".."/dirname);
137
138         // Go through the candidate directories and look for a Build file
139         for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
140                 if(!load_build_file(*j/"Build"))
141                 {
142                         i=packages.find(n);
143                         if(i!=packages.end())
144                                 return i->second;
145                         break;
146                 }
147
148         // Package source not found - create a binary package
149         Package *pkg=Package::create(*this, n);
150         packages.insert(PackageMap::value_type(n, pkg));
151         if(pkg)
152                 new_pkgs.push_back(pkg);
153
154         return pkg;
155 }
156
157 /**
158 Returns the target with the given name, or 0 if no such target exists.
159 */
160 Target *Builder::get_target(const string &n)
161 {
162         TargetMap::iterator i=targets.find(n);
163         if(i!=targets.end())
164                 return i->second;
165         return 0;
166 }
167
168 /**
169 Tries to locate a header included from a given location and with a given include
170 path.  Considers known targets as well as existing files.
171 */
172 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
173 {
174         string hash(8, 0);
175         update_hash(hash, from);
176         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
177                 update_hash(hash, *i);
178
179         string id=hash+include;
180         TargetMap::iterator i=includes.find(id);
181         if(i!=includes.end())
182                 return i->second;
183
184         string fn=include.substr(1);
185         Target *tgt=0;
186         if(include[0]=='"' && (tgt=check_header(Path::Path(from)/fn)))
187                 return tgt;
188         if((tgt=check_header(Path::Path("/usr/include")/fn)))
189                 return tgt;
190         //XXX Determine the C++ header location dynamically
191         if((tgt=check_header(Path::Path("/usr/include/c++/4.1.2")/fn)))
192                 return tgt;
193         for(list<string>::const_iterator j=path.begin(); j!=path.end(); ++j)
194                 if((tgt=check_header(Path::getcwd()/ *j/fn)))
195                         return tgt;
196         
197         return 0;
198 }
199
200 Target *Builder::get_library(const string &lib, const list<string> &path)
201 {
202         string hash(8, 0);
203         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
204                 update_hash(hash, *i);
205
206         string id=hash+lib;
207         TargetMap::iterator i=libraries.find(id);
208         if(i!=libraries.end())
209                 return i->second;
210
211         string basename="lib"+lib+".so";
212         for(list<string>::const_iterator j=path.begin(); j!=path.end(); ++j)
213         {
214                 string full=(Path::getcwd()/ *j/basename).str();
215                 Target *tgt=get_target(full);
216                 if(tgt) return tgt;
217                 
218                 if(Path::exists(full))
219                 {
220                         add_target(tgt=new SystemLibrary(*this, full));
221                         return tgt;
222                 }
223         }
224
225         return 0;
226 }
227
228 int Builder::main()
229 {
230         if(load_build_file(cwd/build_file))
231         {
232                 cerr<<"No build info here.\n";
233                 return 1;
234         }
235
236         default_pkg=packages.begin()->second;
237
238         while(!new_pkgs.empty())
239         {
240                 Package *pkg=new_pkgs.front();
241                 if(pkg==default_pkg || conf_all)
242                         pkg->process_options(cmdline_options);
243                 new_pkgs.erase(new_pkgs.begin());
244                 pkg->resolve_refs();
245         }
246
247         std::list<std::string> missing;
248         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
249                 if(!i->second)
250                         missing.push_back(i->first);
251
252         if(!missing.empty())
253         {
254                 missing.sort();
255                 cerr<<"The following packages were not found on the system:\n";
256                 for(list<string>::iterator i=missing.begin(); i!=missing.end(); ++i)
257                         cerr<<"  "<<*i<<'\n';
258                 cerr<<"Please install them and try again.\n";
259                 return 1;
260         }
261
262         default_pkg->create_build_info();
263
264         if(create_targets())
265                 return 1;
266
267         cout<<packages.size()<<" packages, "<<targets.size()<<" targets\n";
268         if(verbose>=2)
269         {
270                 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
271                 {
272                         cout<<' '<<i->second->get_name();
273                         if(i->second->get_buildable())
274                                 cout<<'*';
275                         unsigned count=0;
276                         unsigned ood_count=0;
277                         for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
278                                 if(j->second->get_package()==i->second)
279                                 {
280                                         ++count;
281                                         if(j->second->get_rebuild())
282                                                 ++ood_count;
283                                 }
284                         if(count)
285                         {
286                                 cout<<" ("<<count<<" targets";
287                                 if(ood_count)
288                                         cout<<", "<<ood_count<<" out-of-date";
289                                 cout<<")\n";
290                         }
291                 }
292         }
293
294         if(analyzer)
295                 analyzer->analyze();
296
297         if(do_build)
298                 build();
299
300         return exit_code;
301 }
302
303 Builder::~Builder()
304 {
305         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
306                 delete i->second;
307         for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
308                 delete i->second;
309         delete analyzer;
310 }
311
312 int Builder::load_build_file(const Path::Path &fn)
313 {
314         ifstream in(fn.str().c_str());
315         if(!in)
316                 return -1;
317
318         Parser::Parser parser(in, fn.str());
319         Loader loader(*this, fn.subpath(0, fn.size()-1));
320         loader.load(parser);
321
322         return 0;
323 }
324
325 int Builder::create_targets()
326 {
327         Target *world=new VirtualTarget(*this, "world");
328         add_target(world);
329
330         Target *def_tgt=new VirtualTarget(*this, "default");
331         add_target(def_tgt);
332         world->add_depend(def_tgt);
333
334         Target *install=new VirtualTarget(*this, "install");
335         add_target(install);
336         world->add_depend(install);
337
338         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
339         {
340                 if(!i->second)
341                         continue;
342                 if(!i->second->get_buildable())
343                         continue;
344
345                 Path::Path inst_base;
346                 if(i->second->get_config().is_option("prefix"))
347                         inst_base=i->second->get_config().get_option("prefix").value;
348
349                 const ComponentList &components=i->second->get_components();
350                 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
351                 {
352                         PathList files;
353                         const PathList &sources=j->get_sources();
354                         for(PathList::const_iterator k=sources.begin(); k!=sources.end(); ++k)
355                         {
356                                 struct stat st;
357                                 stat(*k, st);
358                                 if(S_ISDIR(st.st_mode))
359                                 {
360                                         list<string> sfiles=list_files(*k);
361                                         for(list<string>::iterator l=sfiles.begin(); l!=sfiles.end(); ++l)
362                                                 files.push_back(*k / *l);
363                                 }
364                                 else
365                                         files.push_back(*k);
366                         }
367
368                         bool build_exe=j->get_type()!=Component::HEADERS;
369                         
370                         list<ObjectFile *> objs;
371                         for(PathList::iterator k=files.begin(); k!=files.end(); ++k)
372                         {
373                                 string basename=(*k)[-1];
374                                 string ext=Path::splitext(basename).ext;
375                                 if(ext==".cpp" || ext==".c")
376                                 {
377                                         if(build_exe)
378                                         {
379                                                 SourceFile *src=new SourceFile(*this, &*j, k->str());
380                                                 add_target(src);
381                                                 
382                                                 ObjectFile *obj=new ObjectFile(*this, *j, *src);
383                                                 add_target(obj);
384                                                 objs.push_back(obj);
385                                         }
386                                 }
387                                 else if(ext==".h")
388                                 {
389                                         Target *hdr=get_target(k->str());
390                                         if(!hdr)
391                                         {
392                                                 hdr=new Header(*this, &*j, k->str());
393                                                 add_target(hdr);
394                                         }
395                                         if(!j->get_install_headers().empty())
396                                         {
397                                                 Path::Path inst_path=inst_base/"include"/j->get_install_headers()/basename;
398                                                 Install *inst=new Install(*this, *i->second, *hdr, inst_path.str());
399                                                 add_target(inst);
400                                                 install->add_depend(inst);
401                                         }
402                                 }
403                         }
404
405                         if(build_exe)
406                         {
407                                 Executable *exe=new Executable(*this, *j, objs);
408                                 add_target(exe);
409                                 if(i->second==default_pkg)
410                                         def_tgt->add_depend(exe);
411                                 else
412                                         world->add_depend(exe);
413
414                                 if(j->get_install())
415                                 {
416                                         string inst_dir;
417                                         if(j->get_type()==Component::PROGRAM)
418                                                 inst_dir="bin";
419                                         else if(j->get_type()==Component::LIBRARY)
420                                                 inst_dir="lib";
421                                         if(!inst_dir.empty())
422                                         {
423                                                 Install *inst=new Install(*this, *i->second, *exe, (inst_base/inst_dir/Path::basename(exe->get_name())).str());
424                                                 add_target(inst);
425                                                 install->add_depend(inst);
426                                         }
427                                 }
428                         }
429                 }
430         }
431
432         while(!new_tgts.empty())
433         {
434                 Target *tgt=new_tgts.front();
435                 new_tgts.erase(new_tgts.begin());
436                 tgt->find_depends();
437                 if(!tgt->get_depends_ready())
438                         new_tgts.push_back(tgt);
439         }
440
441         for(list<string>::iterator i=what_if.begin(); i!=what_if.end(); ++i)
442         {
443                 Target *tgt=get_target((cwd/ *i).str());
444                 if(!tgt)
445                 {
446                         cerr<<"Unknown what-if target "<<*i<<'\n';
447                         return -1;
448                 }
449                 tgt->touch();
450         }
451
452         Target *cmdline=new VirtualTarget(*this, "cmdline");
453         add_target(cmdline);
454         world->add_depend(cmdline);
455         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
456         {
457                 Target *tgt=get_target(*i);
458                 if(!tgt)
459                         tgt=get_target((cwd/ *i).str());
460                 if(!tgt)
461                 {
462                         cerr<<"I don't know anything about "<<*i<<'\n';
463                         return -1;
464                 }
465                 cmdline->add_depend(tgt);
466         }
467
468         world->prepare();
469
470         return 0;
471 }
472
473 Target *Builder::check_header(const Msp::Path::Path &fn)
474 {
475         Target *tgt=get_target(fn.str());
476         if(tgt) return tgt;
477
478         if(Path::exists(fn))
479         {
480                 add_target(tgt=new SystemHeader(*this, fn.str()));
481                 return tgt;
482         }
483         return 0;
484 }
485
486 void Builder::add_target(Target *t)
487 {
488         targets.insert(TargetMap::value_type(t->get_name(), t));
489         new_tgts.push_back(t);
490 }
491
492 void Builder::update_hash(string &hash, const string &value)
493 {
494         for(unsigned i=0; i<value.size(); ++i)
495                 hash[i%hash.size()]^=value[i];
496 }
497
498 /**
499 This function supervises the build process, starting new actions when slots
500 become available.
501 */
502 int Builder::build()
503 {
504         Target *cmdline=get_target("cmdline");
505
506         unsigned total=cmdline->count_rebuild();
507         if(!total)
508         {
509                 cout<<"Already up to date\n";
510                 return 0;
511         }
512         cout<<"Will build "<<total<<" target(s)\n";
513
514         vector<Action *> actions;
515
516         if(chrome)
517                 cout<<"0 targets built\n";
518         unsigned count=0;
519
520         bool fail=false;
521         bool finish=false;
522
523         while(!finish)
524         {
525                 if(actions.size()<jobs && !fail)
526                 {
527                         Target *tgt=cmdline->get_buildable_target();
528                         if(tgt)
529                         {
530                                 Action *action=tgt->build();
531                                 if(action)
532                                         actions.push_back(action);
533                         }
534                         else if(actions.empty())
535                                 finish=true;
536                 }
537                 else
538                         Time::sleep(10*Time::msec);
539
540                 for(unsigned i=0; i<actions.size();)
541                 {
542                         int status=actions[i]->check();
543                         if(status>=0)
544                         {
545                                 ++count;
546                                 if(chrome)
547                                 {
548                                         cout<<"\e["<<actions.size()+1<<'A';
549                                         cout<<count<<" targets built\n";
550                                         if(i)
551                                                 cout<<"\e["<<i<<"B";
552                                         cout<<"\e[M";
553                                         if(i<actions.size()-1)
554                                                 cout<<"\e["<<actions.size()-i-1<<"B";
555                                         cout.flush();
556                                 }
557                                 delete actions[i];
558                                 actions.erase(actions.begin()+i);
559                                 if(status>0)
560                                         fail=true;
561                                 if(actions.empty() && fail)
562                                         finish=true;
563                         }
564                         else
565                                 ++i;
566                 }
567         }
568
569         return fail?-1:0;
570 }
571
572 Application::RegApp<Builder> Builder::reg;
573
574 Builder::Loader::Loader(Builder &b, const Path::Path &s):
575         bld(b),
576         src(s)
577 {
578         add("package", &Loader::package);
579 }
580
581 void Builder::Loader::package(const string &n)
582 {
583         Package *pkg=new Package(bld, n, src);
584         load_sub(*pkg);
585         bld.packages.insert(PackageMap::value_type(n, pkg));
586         bld.new_pkgs.push_back(pkg);
587 }
588