3 This file is part of builder
4 Copyright © 2006-2010 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
10 #include <msp/core/getopt.h>
11 #include <msp/datafile/parser.h>
12 #include <msp/fs/dir.h>
13 #include <msp/fs/stat.h>
14 #include <msp/fs/utils.h>
15 #include <msp/io/buffered.h>
16 #include <msp/io/file.h>
17 #include <msp/io/print.h>
18 #include <msp/strings/format.h>
19 #include <msp/strings/regex.h>
20 #include <msp/strings/utils.h>
21 #include <msp/time/units.h>
22 #include <msp/time/utils.h>
25 #include "binarypackage.h"
31 #include "pkgconfig.h"
32 #include "sharedlibrary.h"
33 #include "sourcepackage.h"
34 #include "systemlibrary.h"
36 #include "virtualtarget.h"
43 void update_hash(string &hash, const string &value)
45 for(unsigned i=0; i<value.size(); ++i)
46 hash[i%hash.size()] ^= value[i];
52 Builder::Builder(int argc, char **argv):
54 native_arch(*this, string()),
67 create_makefile(false)
71 bool full_paths = false;
72 unsigned max_depth = 5;
73 StringList cmdline_warn;
78 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG).set_help("Perform analysis. MODE can be deps, alldeps or rebuild.", "MODE");
79 getopt.add_option('b', "build", build, GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
80 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG).set_help("Clean buildable targets.");
81 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG).set_help("Read info from FILE instead of Build.", "FILE");
82 getopt.add_option('h', "help", help, GetOpt::NO_ARG).set_help("Print this message.");
83 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG).set_help("Run NUM commands at once, whenever possible.", "NUM");
84 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
85 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG).set_help("Print more information about what's going on.");
86 getopt.add_option('x', "no-externals", no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
87 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
88 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
89 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
90 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
91 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
92 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG).set_help("Architecture to build for.", "ARCH");
93 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG).set_help("Stop after configuring packages.");
94 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG).set_help("Output full paths in analysis.");
95 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG).set_help("Maximum depth to show in analysis.", "NUM");
96 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
97 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
98 usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
99 helpmsg = getopt.generate_help();
102 if(!analyze_mode.empty())
104 analyzer = new Analyzer(*this);
106 if(analyze_mode=="deps")
107 analyzer->set_mode(Analyzer::DEPS);
108 else if(analyze_mode=="alldeps")
109 analyzer->set_mode(Analyzer::ALLDEPS);
110 else if(analyze_mode=="rebuild")
111 analyzer->set_mode(Analyzer::REBUILD);
112 else if(analyze_mode=="rdeps")
113 analyzer->set_mode(Analyzer::RDEPS);
115 throw usage_error("Invalid analyze mode");
117 analyzer->set_max_depth(max_depth);
118 analyzer->set_full_paths(full_paths);
120 else if(!clean && !create_makefile)
123 const vector<string> &args = getopt.get_args();
124 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
126 string::size_type equal = i->find('=');
127 if(equal!=string::npos)
128 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
130 cmdline_targets.push_back(*i);
133 if(cmdline_targets.empty())
134 cmdline_targets.push_back("default");
136 if(!work_dir.empty())
141 native_arch.set_tool("CC", "gcc");
142 native_arch.set_tool("CXX", "g++");
143 native_arch.set_tool("LD", "gcc");
144 native_arch.set_tool("LXX", "g++");
145 native_arch.set_tool("AR", "ar");
147 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
148 load_build_file((FS::get_user_data_dir("builder")/"rc").str());
151 current_arch = &native_arch;
153 current_arch = new Architecture(*this, arch);
155 if(!current_arch->is_native())
157 for(StringMap::const_iterator i=cross_prefixes.begin(); i!=cross_prefixes.end(); ++i)
158 if(current_arch->match_name(i->first))
160 current_arch->set_cross_prefix(i->second);
167 if(current_arch->is_native())
168 prefix = (FS::get_home_dir()/"local").str();
170 prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
173 prefix = FS::getcwd()/prfx;
175 warnings.push_back("all");
176 warnings.push_back("extra");
177 warnings.push_back("shadow");
178 warnings.push_back("pointer-arith");
179 warnings.push_back("error");
180 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
182 vector<string> warns = split(*i, ',');
183 warnings.insert(warnings.end(), warns.begin(), warns.end());
186 pkg_path.push_back(cwd/".");
187 pkg_path.push_back(cwd/"..");
192 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
194 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
201 if(prefix.str()!="/usr")
203 FS::Path pcdir = prefix/"lib"/"pkgconfig";
204 if(const char *pcp = getenv("PKG_CONFIG_PATH"))
206 vector<string> path = split(pcp, ':');
208 for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
209 found = (*i==pcdir.str());
212 path.push_back(pcdir.str());
213 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
217 setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
220 if(load_build_file(cwd/build_file))
224 usage(0, "builder", false);
229 IO::print(IO::cerr, "No build info here.\n");
234 main_pkg->configure(cmdline_options, conf_all?2:1);
238 usage(0, "builder", false);
252 IO::print("Building on %s, for %s%s\n", native_arch.get_name(),
253 current_arch->get_name(), (current_arch->is_native() ? " (native)" : ""));
254 IO::print("Prefix is %s\n", prefix);
259 unsigned n_packages = 0;
260 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
261 if(i->second && i->second->is_configured())
263 IO::print("%d active packages, %d targets\n", n_packages, targets.size());
268 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
270 if(!i->second->is_configured())
273 IO::print(" %s", i->second->get_name());
274 if(dynamic_cast<SourcePackage *>(i->second))
277 unsigned to_be_built = 0;
278 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
279 if(j->second->get_package()==i->second)
282 if(j->second->get_rebuild())
287 IO::print(" (%d targets", count);
289 IO::print(", %d to be built", to_be_built);
299 if(!problems.empty())
301 IO::print(IO::cerr, "The following problems were detected:\n");
302 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
303 IO::print(IO::cerr, " %s: %s\n", i->package, i->descr);
305 IO::print(IO::cerr, "Please fix them and try again.\n");
310 exit_code = do_clean();
312 exit_code = do_build();
317 string Builder::run_pkgconfig(const string &pkg, const string &what)
320 argv.push_back("pkg-config");
321 if(what=="cflags" || what=="libs")
322 argv.push_back("--"+what);
323 else if(what=="flags")
325 argv.push_back("--cflags");
326 argv.push_back("--libs");
329 argv.push_back("--variable="+what);
333 IO::print("Running %s\n", join(argv.begin(), argv.end()));
336 string res = run_command(argv, &status);
338 throw runtime_error(format("pkg-config for package %s failed", pkg));
343 Package *Builder::get_package(const string &name)
345 PackageMap::iterator i = packages.find(format("%s/%s", name, current_arch->get_system()));
346 if(i==packages.end())
347 i = packages.find(name);
348 if(i!=packages.end())
353 FS::Path path = get_package_location(name);
354 if(!path.empty() && !load_build_file(path/"Build"))
356 i = packages.find(name);
357 if(i!=packages.end())
365 // Package source not found - create a binary package
366 pkg = BinaryPackage::from_pkgconfig(*this, name);
370 problem(name, "not found");
373 packages.insert(PackageMap::value_type(name, pkg));
378 Target *Builder::get_target(const string &n) const
380 // XXX Used for getting targets by path. get_target(const FS::Path &)?
381 TargetMap::const_iterator i = targets.find(n);
387 Target *Builder::get_header(const string &include, const FS::Path &from, const list<string> &path)
391 update_hash(hash, from.str());
392 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
393 update_hash(hash, *i);
395 string id = hash+include;
396 TargetMap::iterator i = includes.find(id);
397 if(i!=includes.end())
400 static string cxx_ver;
404 argv.push_back(current_arch->get_tool("CXX"));
405 argv.push_back("--version");
406 if(RegMatch m = Regex("[0-9]\\.[0-9.]+").match(run_command(argv)))
409 while(!cxx_ver.empty() && !FS::is_dir(FS::Path("/usr/include/c++")/cxx_ver))
411 string::size_type dot = cxx_ver.rfind('.');
412 if(dot==string::npos)
417 IO::print("C++ version is %s\n", cxx_ver);
423 string fn = include.substr(1);
425 IO::print("Looking for include %s from %s with path %s\n", fn, from, join(path.begin(), path.end()));
428 if(current_arch->is_native())
429 syspath.push_back("/usr/include");
431 syspath.push_back("/usr/"+current_arch->get_cross_prefix()+"/include");
433 syspath.push_back((FS::Path("/usr/include/c++/")/cxx_ver).str());
437 tgt = get_header(FS::Path(from)/fn);
438 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
439 tgt = get_header(cwd/ *j/fn);
440 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
441 tgt = get_header(FS::Path(*j)/fn);
443 includes.insert(TargetMap::value_type(id, tgt));
448 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
451 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
452 update_hash(hash, *i);
454 string id = hash+string(1, mode)+lib;
455 TargetMap::iterator i = libraries.find(id);
456 if(i!=libraries.end())
460 if(current_arch->is_native())
462 syspath.push_back("/lib");
463 syspath.push_back("/usr/lib");
466 syspath.push_back("/usr/"+current_arch->get_cross_prefix()+"/lib");
469 IO::print("Looking for library %s with path %s\n", lib, join(path.begin(), path.end()));
472 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
473 tgt = get_library(lib, cwd/ *j, mode);
474 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
475 tgt = get_library(lib, *j, mode);
477 libraries.insert(TargetMap::value_type(id, tgt));
482 void Builder::apply_profile_template(Config &config, const string &pt) const
484 vector<string> parts = split(pt, '-');
486 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
488 ProfileTemplateMap::const_iterator j = profile_tmpl.find(*i);
489 if(j==profile_tmpl.end())
492 config.update(j->second);
496 void Builder::problem(const string &p, const string &d)
498 problems.push_back(Problem(p, d));
501 void Builder::add_target(FileTarget *t)
503 targets.insert(TargetMap::value_type(t->get_path().str(), t));
504 new_tgts.push_back(t);
507 void Builder::add_target(VirtualTarget *t)
509 targets.insert(TargetMap::value_type(t->get_name(), t));
510 new_tgts.push_back(t);
513 void Builder::usage(const char *reason, const char *argv0, bool brief)
516 IO::print(IO::cerr, "%s\n", reason);
519 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
522 IO::print(IO::cerr, "Builder 1.0\n\n");
523 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
524 IO::print(IO::cerr, "Options:\n");
525 IO::print(IO::cerr, helpmsg);
529 FS::Path Builder::get_package_location(const string &name)
532 IO::print("Looking for package %s\n", name);
536 // Try to get source directory with pkgconfig
537 string srcdir = strip(run_pkgconfig(name, "source"));
546 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
548 list<string> files = list_files(*i);
549 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
551 FS::Path full = *i / *j;
552 if(FS::exists(full/"Build"))
553 pkg_dirs.push_back(full);
557 IO::print("%d packages found in path\n", pkg_dirs.size());
560 bool msp = !name.compare(0, 3, "msp");
561 for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
563 string base = basename(*i);
564 unsigned dash = base.rfind('-');
566 if(!base.compare(0, dash, name))
568 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
575 int Builder::load_build_file(const FS::Path &fn)
579 IO::BufferedFile in(fn.str());
582 IO::print("Reading %s\n", fn);
584 DataFile::Parser parser(in, fn.str());
585 Loader loader(*this, fn.subpath(0, fn.size()-1));
588 catch(const IO::file_not_found &)
596 int Builder::create_targets()
598 Target *world = new VirtualTarget(*this, "world");
600 Target *def_tgt = new VirtualTarget(*this, "default");
601 world->add_depend(def_tgt);
603 Target *install = new VirtualTarget(*this, "install");
604 world->add_depend(install);
606 Target *tarballs = new VirtualTarget(*this, "tarballs");
607 world->add_depend(tarballs);
609 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
611 if(!i->second || !i->second->is_configured())
614 SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second);
618 const ComponentList &components = spkg->get_components();
619 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
622 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
624 PkgConfig *pc = new PkgConfig(*this, *spkg);
625 install->add_depend(new Install(*this, *spkg, *pc));
629 // Find dependencies until no new targets are created
630 while(!new_tgts.empty())
632 Target *tgt = new_tgts.front();
633 new_tgts.erase(new_tgts.begin());
635 if(!tgt->get_depends_ready())
636 new_tgts.push_back(tgt);
640 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
642 FileTarget *tgt = dynamic_cast<FileTarget *>(get_target((cwd/ *i).str()));
645 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
651 // Make the cmdline target depend on all targets mentioned on the command line
652 Target *cmdline = new VirtualTarget(*this, "cmdline");
653 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
655 Target *tgt = get_target(*i);
657 tgt = get_target((cwd/ *i).str());
660 IO::print("I don't know anything about %s\n", *i);
664 cmdline->add_depend(tgt);
669 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
670 if(SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second))
671 spkg->get_deps_cache().save();
676 Target *Builder::get_header(const FS::Path &fn)
678 Target *tgt = get_target(fn.str());
683 tgt = new SystemHeader(*this, fn.str());
689 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
691 // Populate a list of candidate filenames
692 StringList candidates;
696 // XXX Should probably let the Architecture populate the list
697 if(current_arch->get_system()=="windows")
699 candidates.push_back("lib"+lib+".dll");
700 candidates.push_back(lib+".dll");
703 candidates.push_back("lib"+lib+".so");
706 /* Static libraries are always considered, since sometimes shared versions
707 may not be available */
708 candidates.push_back("lib"+lib+".a");
709 if(current_arch->get_system()=="windows")
710 candidates.push_back("lib"+lib+".dll.a");
712 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
714 string full = (path/ *i).str();
715 Target *tgt = get_target(full);
719 Target *real_tgt = tgt->get_real_target();
721 /* Ignore dynamic libraries from local packages unless library mode is
723 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
728 else if(FS::is_reg(full))
730 tgt = new SystemLibrary(*this, full);
738 int Builder::do_build()
740 Target *cmdline = get_target("cmdline");
743 for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
744 if(i->second->is_buildable() && i->second->get_rebuild())
749 IO::print("Already up to date\n");
753 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
755 vector<Action *> actions;
764 if(actions.size()<jobs && !fail)
766 Target *tgt = cmdline->get_buildable_target();
769 Action *action = tgt->build();
771 actions.push_back(action);
774 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
776 else if(actions.empty())
780 Time::sleep(10*Time::msec);
782 for(unsigned i=0; i<actions.size();)
784 int status = actions[i]->check();
790 actions.erase(actions.begin()+i);
793 if(actions.empty() && fail)
804 IO::print("Build failed\n");
805 else if(show_progress)
806 IO::print("Build complete\n");
811 int Builder::do_clean()
813 // Cleaning doesn't care about ordering, so a simpler method can be used
815 set<Target *> clean_tgts;
817 queue.push_back(get_target("cmdline"));
819 while(!queue.empty())
821 Target *tgt = queue.front();
822 queue.erase(queue.begin());
824 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
825 clean_tgts.insert(tgt);
827 const TargetList &deps = tgt->get_depends();
828 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
829 if(!clean_tgts.count(*i))
833 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
834 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
836 Action *action = new Unlink(*this, *ft);
837 while(action->check()<0) ;
844 void Builder::package_help()
846 const Config &config = main_pkg->get_config();
847 const Config::OptionMap &options = config.get_options();
849 IO::print("Required packages:\n ");
850 const PackageList &requires = main_pkg->get_requires();
851 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
853 if(i!=requires.begin())
855 IO::print((*i)->get_name());
857 IO::print("\n\nPackage configuration:\n");
858 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
860 const Config::Option &opt = i->second;
861 IO::print(" %s: %s (%s)", opt.name, opt.descr, opt.value);
862 if(opt.value!=opt.defv)
863 IO::print(" [%s]", opt.defv);
868 string Builder::usagemsg;
869 string Builder::helpmsg;
872 Builder::Loader::Loader(Builder &b, const FS::Path &s):
876 add("binary_package", &Loader::binpkg);
877 add("cross_prefix", &Loader::cross_prefix);
878 add("profile", &Loader::profile);
879 add("package", &Loader::package);
882 void Builder::Loader::binpkg(const string &n)
884 BinaryPackage *pkg = new BinaryPackage(bld, n);
886 bld.packages.insert(PackageMap::value_type(n, pkg));
889 void Builder::Loader::cross_prefix(const string &a, const string &p)
891 bld.cross_prefixes[a] = p;
894 void Builder::Loader::profile(const string &n)
897 ProfileLoader ldr(prf);
899 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
902 void Builder::Loader::package(const string &n)
904 SourcePackage *pkg = new SourcePackage(bld, n, src);
909 bld.packages.insert(PackageMap::value_type(n, pkg));
913 Builder::ProfileLoader::ProfileLoader(StringMap &p):
916 add("option", &ProfileLoader::option);
919 void Builder::ProfileLoader::option(const string &o, const string &v)
921 profile.insert(StringMap::value_type(o, v));