3 This file is part of builder
4 Copyright © 2006-2010 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
10 #include <msp/core/except.h>
11 #include <msp/core/getopt.h>
12 #include <msp/datafile/parser.h>
13 #include <msp/fs/dir.h>
14 #include <msp/fs/stat.h>
15 #include <msp/fs/utils.h>
16 #include <msp/io/buffered.h>
17 #include <msp/io/except.h>
18 #include <msp/io/file.h>
19 #include <msp/io/print.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>
27 #include "binarypackage.h"
33 #include "pkgconfig.h"
34 #include "sharedlibrary.h"
35 #include "sourcepackage.h"
36 #include "systemlibrary.h"
38 #include "virtualtarget.h"
45 void update_hash(string &hash, const string &value)
47 for(unsigned i=0; i<value.size(); ++i)
48 hash[i%hash.size()] ^= value[i];
54 Builder::Builder(int argc, char **argv):
56 native_arch(*this, string()),
69 create_makefile(false)
73 bool full_paths = false;
74 unsigned max_depth = 5;
75 StringList cmdline_warn;
80 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG).set_help("Perform analysis. MODE can be deps, alldeps or rebuild.", "MODE");
81 getopt.add_option('b', "build", build, GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
82 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG).set_help("Clean buildable targets.");
83 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG).set_help("Read info from FILE instead of Build.", "FILE");
84 getopt.add_option('h', "help", help, GetOpt::NO_ARG).set_help("Print this message.");
85 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG).set_help("Run NUM commands at once, whenever possible.", "NUM");
86 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
87 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG).set_help("Print more information about what's going on.");
88 getopt.add_option('x', "no-externals", no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
89 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
90 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
91 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
92 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
93 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
94 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG).set_help("Architecture to build for.", "ARCH");
95 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG).set_help("Stop after configuring packages.");
96 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG).set_help("Output full paths in analysis.");
97 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG).set_help("Maximum depth to show in analysis.", "NUM");
98 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
99 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
100 usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
101 helpmsg = getopt.generate_help();
104 if(!analyze_mode.empty())
106 analyzer = new Analyzer(*this);
108 if(analyze_mode=="deps")
109 analyzer->set_mode(Analyzer::DEPS);
110 else if(analyze_mode=="alldeps")
111 analyzer->set_mode(Analyzer::ALLDEPS);
112 else if(analyze_mode=="rebuild")
113 analyzer->set_mode(Analyzer::REBUILD);
114 else if(analyze_mode=="rdeps")
115 analyzer->set_mode(Analyzer::RDEPS);
117 throw UsageError("Invalid analyze mode");
119 analyzer->set_max_depth(max_depth);
120 analyzer->set_full_paths(full_paths);
122 else if(!clean && !create_makefile)
125 const vector<string> &args = getopt.get_args();
126 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
128 string::size_type equal = i->find('=');
129 if(equal!=string::npos)
130 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
132 cmdline_targets.push_back(*i);
135 if(cmdline_targets.empty())
136 cmdline_targets.push_back("default");
138 if(!work_dir.empty())
143 native_arch.set_tool("CC", "gcc");
144 native_arch.set_tool("CXX", "g++");
145 native_arch.set_tool("LD", "gcc");
146 native_arch.set_tool("LXX", "g++");
147 native_arch.set_tool("AR", "ar");
149 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
150 load_build_file((FS::get_user_data_dir("builder")/"rc").str());
153 current_arch = &native_arch;
155 current_arch = new Architecture(*this, arch);
157 if(!current_arch->is_native())
159 for(StringMap::const_iterator i=cross_prefixes.begin(); i!=cross_prefixes.end(); ++i)
160 if(current_arch->match_name(i->first))
162 current_arch->set_cross_prefix(i->second);
169 if(current_arch->is_native())
170 prefix = (FS::get_home_dir()/"local").str();
172 prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
175 prefix = FS::getcwd()/prfx;
177 warnings.push_back("all");
178 warnings.push_back("extra");
179 warnings.push_back("shadow");
180 warnings.push_back("pointer-arith");
181 warnings.push_back("error");
182 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
184 vector<string> warns = split(*i, ',');
185 warnings.insert(warnings.end(), warns.begin(), warns.end());
188 pkg_path.push_back(cwd/".");
189 pkg_path.push_back(cwd/"..");
194 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
196 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
203 if(prefix.str()!="/usr")
205 FS::Path pcdir = prefix/"lib"/"pkgconfig";
206 if(const char *pcp = getenv("PKG_CONFIG_PATH"))
208 vector<string> path = split(pcp, ':');
210 for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
211 found = (*i==pcdir.str());
214 path.push_back(pcdir.str());
215 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
219 setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
222 if(load_build_file(cwd/build_file))
226 usage(0, "builder", false);
231 IO::print(IO::cerr, "No build info here.\n");
236 main_pkg->configure(cmdline_options, conf_all?2:1);
240 usage(0, "builder", false);
254 IO::print("Building on %s, for %s%s\n", native_arch.get_name(),
255 current_arch->get_name(), (current_arch->is_native() ? " (native)" : ""));
256 IO::print("Prefix is %s\n", prefix);
261 unsigned n_packages = 0;
262 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
263 if(i->second->is_configured())
265 IO::print("%d active packages, %d targets\n", n_packages, targets.size());
270 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
272 if(!i->second->is_configured())
275 IO::print(" %s", i->second->get_name());
276 if(dynamic_cast<SourcePackage *>(i->second))
279 unsigned to_be_built = 0;
280 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
281 if(j->second->get_package()==i->second)
284 if(j->second->get_rebuild())
289 IO::print(" (%d targets", count);
291 IO::print(", %d to be built", to_be_built);
301 if(!problems.empty())
303 IO::print(IO::cerr, "The following problems were detected:\n");
304 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
305 IO::print(IO::cerr, " %s: %s\n", i->package, i->descr);
307 IO::print(IO::cerr, "Please fix them and try again.\n");
312 exit_code = do_clean();
314 exit_code = do_build();
319 string Builder::run_pkgconfig(const string &pkg, const string &what)
322 argv.push_back("pkg-config");
323 if(what=="cflags" || what=="libs")
324 argv.push_back("--"+what);
325 else if(what=="flags")
327 argv.push_back("--cflags");
328 argv.push_back("--libs");
331 argv.push_back("--variable="+what);
335 IO::print("Running %s\n", join(argv.begin(), argv.end()));
338 string res = run_command(argv, &status);
340 throw Exception(format("pkg-config for package %s failed", pkg));
345 Package *Builder::get_package(const string &name)
347 PackageMap::iterator i = packages.find(format("%s/%s", name, current_arch->get_system()));
348 if(i==packages.end())
349 i = packages.find(name);
350 if(i!=packages.end())
355 FS::Path path = get_package_location(name);
356 if(!path.empty() && !load_build_file(path/"Build"))
358 i = packages.find(name);
359 if(i!=packages.end())
367 // Package source not found - create a binary package
368 pkg = BinaryPackage::from_pkgconfig(*this, name);
372 problem(name, "not found");
375 packages.insert(PackageMap::value_type(name, pkg));
380 Target *Builder::get_target(const string &n) const
382 // XXX Used for getting targets by path. get_target(const FS::Path &)?
383 TargetMap::const_iterator i = targets.find(n);
389 Target *Builder::get_header(const string &include, const FS::Path &from, const list<string> &path)
393 update_hash(hash, from.str());
394 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
395 update_hash(hash, *i);
397 string id = hash+include;
398 TargetMap::iterator i = includes.find(id);
399 if(i!=includes.end())
402 static string cxx_ver;
406 argv.push_back(current_arch->get_tool("CXX"));
407 argv.push_back("--version");
408 if(RegMatch m = Regex("[0-9]\\.[0-9.]+").match(run_command(argv)))
411 while(!cxx_ver.empty() && !FS::is_dir(FS::Path("/usr/include/c++")/cxx_ver))
413 string::size_type dot = cxx_ver.rfind('.');
414 if(dot==string::npos)
419 IO::print("C++ version is %s\n", cxx_ver);
425 string fn = include.substr(1);
427 IO::print("Looking for include %s from %s with path %s\n", fn, from, join(path.begin(), path.end()));
430 if(current_arch->is_native())
431 syspath.push_back("/usr/include");
433 syspath.push_back("/usr/"+current_arch->get_cross_prefix()+"/include");
435 syspath.push_back((FS::Path("/usr/include/c++/")/cxx_ver).str());
439 tgt = get_header(FS::Path(from)/fn);
440 for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
441 tgt = get_header(cwd/ *j/fn);
442 for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
443 tgt = get_header(FS::Path(*j)/fn);
445 includes.insert(TargetMap::value_type(id, tgt));
450 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
453 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
454 update_hash(hash, *i);
456 string id = hash+string(1, mode)+lib;
457 TargetMap::iterator i = libraries.find(id);
458 if(i!=libraries.end())
462 if(current_arch->is_native())
464 syspath.push_back("/lib");
465 syspath.push_back("/usr/lib");
468 syspath.push_back("/usr/"+current_arch->get_cross_prefix()+"/lib");
471 IO::print("Looking for library %s with path %s\n", lib, join(path.begin(), path.end()));
474 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
475 tgt = get_library(lib, cwd/ *j, mode);
476 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
477 tgt = get_library(lib, *j, mode);
479 libraries.insert(TargetMap::value_type(id, tgt));
484 void Builder::apply_profile_template(Config &config, const string &pt) const
486 vector<string> parts = split(pt, '-');
488 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
490 ProfileTemplateMap::const_iterator j = profile_tmpl.find(*i);
491 if(j==profile_tmpl.end())
494 config.update(j->second);
498 void Builder::problem(const string &p, const string &d)
500 problems.push_back(Problem(p, d));
503 void Builder::add_target(FileTarget *t)
505 targets.insert(TargetMap::value_type(t->get_path().str(), t));
506 new_tgts.push_back(t);
509 void Builder::add_target(VirtualTarget *t)
511 targets.insert(TargetMap::value_type(t->get_name(), t));
512 new_tgts.push_back(t);
515 void Builder::usage(const char *reason, const char *argv0, bool brief)
518 IO::print(IO::cerr, "%s\n", reason);
521 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
524 IO::print(IO::cerr, "Builder 1.0\n\n");
525 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
526 IO::print(IO::cerr, "Options:\n");
527 IO::print(IO::cerr, helpmsg);
531 FS::Path Builder::get_package_location(const string &name)
534 IO::print("Looking for package %s\n", name);
538 // Try to get source directory with pkgconfig
539 string srcdir = strip(run_pkgconfig(name, "source"));
548 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
550 list<string> files = list_files(*i);
551 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
553 FS::Path full = *i / *j;
554 if(FS::exists(full/"Build"))
555 pkg_dirs.push_back(full);
559 IO::print("%d packages found in path\n", pkg_dirs.size());
562 bool msp = !name.compare(0, 3, "msp");
563 for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
565 string base = basename(*i);
566 unsigned dash = base.rfind('-');
568 if(!base.compare(0, dash, name))
570 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
577 int Builder::load_build_file(const FS::Path &fn)
581 IO::BufferedFile in(fn.str());
584 IO::print("Reading %s\n", fn);
586 DataFile::Parser parser(in, fn.str());
587 Loader loader(*this, fn.subpath(0, fn.size()-1));
590 catch(const IO::FileNotFound &)
598 int Builder::create_targets()
600 Target *world = new VirtualTarget(*this, "world");
602 Target *def_tgt = new VirtualTarget(*this, "default");
603 world->add_depend(def_tgt);
605 Target *install = new VirtualTarget(*this, "install");
606 world->add_depend(install);
608 Target *tarballs = new VirtualTarget(*this, "tarballs");
609 world->add_depend(tarballs);
611 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
613 if(!i->second->is_configured())
616 SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second);
620 const ComponentList &components = spkg->get_components();
621 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
624 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
626 PkgConfig *pc = new PkgConfig(*this, *spkg);
627 install->add_depend(new Install(*this, *spkg, *pc));
631 // Find dependencies until no new targets are created
632 while(!new_tgts.empty())
634 Target *tgt = new_tgts.front();
635 new_tgts.erase(new_tgts.begin());
637 if(!tgt->get_depends_ready())
638 new_tgts.push_back(tgt);
642 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
644 FileTarget *tgt = dynamic_cast<FileTarget *>(get_target((cwd/ *i).str()));
647 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
653 // Make the cmdline target depend on all targets mentioned on the command line
654 Target *cmdline = new VirtualTarget(*this, "cmdline");
655 bool build_world = false;
656 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
658 Target *tgt = get_target(*i);
660 tgt = get_target((cwd/ *i).str());
663 IO::print("I don't know anything about %s\n", *i);
668 cmdline->add_depend(tgt);
673 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
674 if(SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second))
675 spkg->get_deps_cache().save();
680 Target *Builder::get_header(const FS::Path &fn)
682 Target *tgt = get_target(fn.str());
687 tgt = new SystemHeader(*this, fn.str());
693 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
695 // Populate a list of candidate filenames
696 StringList candidates;
700 // XXX Should probably let the Architecture populate the list
701 if(current_arch->get_system()=="windows")
703 candidates.push_back("lib"+lib+".dll");
704 candidates.push_back(lib+".dll");
707 candidates.push_back("lib"+lib+".so");
710 /* Static libraries are always considered, since sometimes shared versions
711 may not be available */
712 candidates.push_back("lib"+lib+".a");
713 if(current_arch->get_system()=="windows")
714 candidates.push_back("lib"+lib+".dll.a");
716 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
718 string full = (path/ *i).str();
719 Target *tgt = get_target(full);
723 Target *real_tgt = tgt->get_real_target();
725 /* Ignore dynamic libraries from local packages unless library mode is
727 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
732 else if(FS::is_reg(full))
734 tgt = new SystemLibrary(*this, full);
742 int Builder::do_build()
744 Target *cmdline = get_target("cmdline");
747 for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
748 if(i->second->is_buildable() && i->second->get_rebuild())
753 IO::print("Already up to date\n");
757 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
759 vector<Action *> actions;
768 if(actions.size()<jobs && !fail)
770 Target *tgt = cmdline->get_buildable_target();
773 Action *action = tgt->build();
775 actions.push_back(action);
778 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
780 else if(actions.empty())
784 Time::sleep(10*Time::msec);
786 for(unsigned i=0; i<actions.size();)
788 int status = actions[i]->check();
794 actions.erase(actions.begin()+i);
797 if(actions.empty() && fail)
808 IO::print("Build failed\n");
809 else if(show_progress)
810 IO::print("Build complete\n");
815 int Builder::do_clean()
817 // Cleaning doesn't care about ordering, so a simpler method can be used
819 set<Target *> clean_tgts;
821 queue.push_back(get_target("cmdline"));
823 while(!queue.empty())
825 Target *tgt = queue.front();
826 queue.erase(queue.begin());
828 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
829 clean_tgts.insert(tgt);
831 const TargetList &deps = tgt->get_depends();
832 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
833 if(!clean_tgts.count(*i))
837 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
838 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
840 Action *action = new Unlink(*this, *ft);
841 while(action->check()<0) ;
848 void Builder::package_help()
850 const Config &config = main_pkg->get_config();
851 const Config::OptionMap &options = config.get_options();
853 IO::print("Required packages:\n ");
854 const PackageList &requires = main_pkg->get_requires();
855 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
857 if(i!=requires.begin())
859 IO::print((*i)->get_name());
861 IO::print("\n\nPackage configuration:\n");
862 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
864 const Config::Option &opt = i->second;
865 IO::print(" %s: %s (%s)", opt.name, opt.descr, opt.value);
866 if(opt.value!=opt.defv)
867 IO::print(" [%s]", opt.defv);
872 Application::RegApp<Builder> Builder::reg;
873 string Builder::usagemsg;
874 string Builder::helpmsg;
877 Builder::Loader::Loader(Builder &b, const FS::Path &s):
881 add("binary_package", &Loader::binpkg);
882 add("cross_prefix", &Loader::cross_prefix);
883 add("profile", &Loader::profile);
884 add("package", &Loader::package);
887 void Builder::Loader::binpkg(const string &n)
889 BinaryPackage *pkg = new BinaryPackage(bld, n);
891 bld.packages.insert(PackageMap::value_type(n, pkg));
894 void Builder::Loader::cross_prefix(const string &a, const string &p)
896 bld.cross_prefixes[a] = p;
899 void Builder::Loader::profile(const string &n)
902 ProfileLoader ldr(prf);
904 bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
907 void Builder::Loader::package(const string &n)
909 SourcePackage *pkg = new SourcePackage(bld, n, src);
914 bld.packages.insert(PackageMap::value_type(n, pkg));
918 Builder::ProfileLoader::ProfileLoader(StringMap &p):
921 add("option", &ProfileLoader::option);
924 void Builder::ProfileLoader::option(const string &o, const string &v)
926 profile.insert(StringMap::value_type(o, v));