3 #include <msp/core/getopt.h>
4 #include <msp/datafile/parser.h>
5 #include <msp/fs/dir.h>
6 #include <msp/fs/stat.h>
7 #include <msp/fs/utils.h>
8 #include <msp/io/buffered.h>
9 #include <msp/io/file.h>
10 #include <msp/io/print.h>
11 #include <msp/strings/format.h>
12 #include <msp/strings/regex.h>
13 #include <msp/strings/utils.h>
14 #include <msp/time/units.h>
15 #include <msp/time/utils.h>
18 #include "binarypackage.h"
24 #include "pkgconfig.h"
25 #include "sharedlibrary.h"
26 #include "sourcepackage.h"
27 #include "systemlibrary.h"
29 #include "virtualtarget.h"
36 void update_hash(string &hash, const string &value)
38 for(unsigned i=0; i<value.size(); ++i)
39 hash[i%hash.size()] ^= value[i];
45 Builder::Builder(int argc, char **argv):
47 native_arch(*this, string()),
60 create_makefile(false)
64 bool full_paths = false;
65 unsigned max_depth = 5;
66 StringList cmdline_warn;
71 getopt.add_option('a', "analyze", analyze_mode, GetOpt::REQUIRED_ARG).set_help("Perform analysis. MODE can be deps, alldeps or rebuild.", "MODE");
72 getopt.add_option('b', "build", build, GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
73 getopt.add_option('c', "clean", clean, GetOpt::NO_ARG).set_help("Clean buildable targets.");
74 getopt.add_option('f', "file", build_file, GetOpt::REQUIRED_ARG).set_help("Read info from FILE instead of Build.", "FILE");
75 getopt.add_option('h', "help", help, GetOpt::NO_ARG).set_help("Print this message.");
76 getopt.add_option('j', "jobs", jobs, GetOpt::REQUIRED_ARG).set_help("Run NUM commands at once, whenever possible.", "NUM");
77 getopt.add_option('n', "dry-run", dry_run, GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
78 getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG).set_help("Print more information about what's going on.");
79 getopt.add_option('x', "no-externals", no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
80 getopt.add_option('A', "conf-all", conf_all, GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
81 getopt.add_option('B', "build-all", build_all, GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
82 getopt.add_option('C', "chdir", work_dir, GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
83 getopt.add_option('P', "progress", show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
84 getopt.add_option('W', "what-if", what_if, GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
85 getopt.add_option( "arch", arch, GetOpt::REQUIRED_ARG).set_help("Architecture to build for.", "ARCH");
86 getopt.add_option( "conf-only", conf_only, GetOpt::NO_ARG).set_help("Stop after configuring packages.");
87 getopt.add_option( "full-paths", full_paths, GetOpt::NO_ARG).set_help("Output full paths in analysis.");
88 getopt.add_option( "max-depth", max_depth, GetOpt::REQUIRED_ARG).set_help("Maximum depth to show in analysis.", "NUM");
89 getopt.add_option( "prefix", prfx, GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
90 getopt.add_option( "warnings", cmdline_warn, GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
91 usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
92 helpmsg = getopt.generate_help();
95 if(!analyze_mode.empty())
97 analyzer = new Analyzer(*this);
99 if(analyze_mode=="deps")
100 analyzer->set_mode(Analyzer::DEPS);
101 else if(analyze_mode=="alldeps")
102 analyzer->set_mode(Analyzer::ALLDEPS);
103 else if(analyze_mode=="rebuild")
104 analyzer->set_mode(Analyzer::REBUILD);
105 else if(analyze_mode=="rdeps")
106 analyzer->set_mode(Analyzer::RDEPS);
108 throw usage_error("Invalid analyze mode");
110 analyzer->set_max_depth(max_depth);
111 analyzer->set_full_paths(full_paths);
113 else if(!clean && !create_makefile)
116 const vector<string> &args = getopt.get_args();
117 for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
119 string::size_type equal = i->find('=');
120 if(equal!=string::npos)
121 cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
123 cmdline_targets.push_back(*i);
126 if(cmdline_targets.empty())
127 cmdline_targets.push_back("default");
129 if(!work_dir.empty())
134 native_arch.set_tool("CC", "gcc");
135 native_arch.set_tool("CXX", "g++");
136 native_arch.set_tool("LD", "gcc");
137 native_arch.set_tool("LXX", "g++");
138 native_arch.set_tool("AR", "ar");
140 load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
141 load_build_file((FS::get_user_data_dir("builder")/"rc").str());
144 current_arch = &native_arch;
146 current_arch = new Architecture(*this, arch);
148 if(!current_arch->is_native())
150 for(StringMap::const_iterator i=cross_prefixes.begin(); i!=cross_prefixes.end(); ++i)
151 if(current_arch->match_name(i->first))
153 current_arch->set_cross_prefix(i->second);
160 if(current_arch->is_native())
161 prefix = (FS::get_home_dir()/"local").str();
163 prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
166 prefix = FS::getcwd()/prfx;
168 warnings.push_back("all");
169 warnings.push_back("extra");
170 warnings.push_back("shadow");
171 warnings.push_back("pointer-arith");
172 warnings.push_back("error");
173 for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
175 vector<string> warns = split(*i, ',');
176 warnings.insert(warnings.end(), warns.begin(), warns.end());
179 pkg_path.push_back(cwd/".");
180 pkg_path.push_back(cwd/"..");
185 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
187 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
194 if(prefix.str()!="/usr")
196 FS::Path pcdir = prefix/"lib"/"pkgconfig";
197 if(const char *pcp = getenv("PKG_CONFIG_PATH"))
199 vector<string> path = split(pcp, ':');
201 for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
202 found = (*i==pcdir.str());
205 path.push_back(pcdir.str());
206 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
210 setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
213 if(load_build_file(cwd/build_file))
217 usage(0, "builder", false);
222 IO::print(IO::cerr, "No build info here.\n");
227 main_pkg->configure(cmdline_options, conf_all?2:1);
231 usage(0, "builder", false);
245 IO::print("Building on %s, for %s%s\n", native_arch.get_name(),
246 current_arch->get_name(), (current_arch->is_native() ? " (native)" : ""));
247 IO::print("Prefix is %s\n", prefix);
252 unsigned n_packages = 0;
253 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
254 if(i->second && i->second->is_configured())
256 IO::print("%d active packages, %d targets\n", n_packages, targets.size());
261 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
263 if(!i->second->is_configured())
266 IO::print(" %s", i->second->get_name());
267 if(dynamic_cast<SourcePackage *>(i->second))
270 unsigned to_be_built = 0;
271 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
272 if(j->second->get_package()==i->second)
275 if(j->second->get_rebuild())
280 IO::print(" (%d targets", count);
282 IO::print(", %d to be built", to_be_built);
292 if(!problems.empty())
294 IO::print(IO::cerr, "The following problems were detected:\n");
295 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
296 IO::print(IO::cerr, " %s: %s\n", i->package, i->descr);
298 IO::print(IO::cerr, "Please fix them and try again.\n");
303 exit_code = do_clean();
305 exit_code = do_build();
310 string Builder::run_pkgconfig(const string &pkg, const string &what)
313 argv.push_back("pkg-config");
314 if(what=="cflags" || what=="libs")
315 argv.push_back("--"+what);
316 else if(what=="flags")
318 argv.push_back("--cflags");
319 argv.push_back("--libs");
322 argv.push_back("--variable="+what);
326 IO::print("Running %s\n", join(argv.begin(), argv.end()));
329 string res = run_command(argv, &status);
331 throw runtime_error(format("pkg-config for package %s failed", pkg));
336 Package *Builder::get_package(const string &name)
338 PackageMap::iterator i = packages.find(format("%s/%s", name, current_arch->get_system()));
339 if(i==packages.end())
340 i = packages.find(name);
341 if(i!=packages.end())
346 FS::Path path = get_package_location(name);
347 if(!path.empty() && !load_build_file(path/"Build"))
349 i = packages.find(name);
350 if(i!=packages.end())
358 // Package source not found - create a binary package
359 pkg = BinaryPackage::from_pkgconfig(*this, name);
363 problem(name, "not found");
366 packages.insert(PackageMap::value_type(name, pkg));
371 Target *Builder::get_target(const string &n) const
373 TargetMap::const_iterator i = targets.find(n);
379 FileTarget *Builder::get_target_by_path(const FS::Path &p) const
381 TargetMap::const_iterator i = targets_by_path.find(p.str());
382 if(i!=targets_by_path.end())
383 return static_cast<FileTarget *>(i->second);
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");
464 if(current_arch->match_name("pc-32-linux"))
465 syspath.push_back("/usr/lib/i386-linux-gnu");
466 else if(current_arch->match_name("pc-64-linux"))
467 syspath.push_back("/usr/lib/x86_64-linux-gnu");
470 syspath.push_back("/usr/"+current_arch->get_cross_prefix()+"/lib");
473 IO::print("Looking for library %s with path %s\n", lib, join(path.begin(), path.end()));
476 for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
477 tgt = get_library(lib, cwd/ *j, mode);
478 for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
479 tgt = get_library(lib, *j, mode);
481 libraries.insert(TargetMap::value_type(id, tgt));
486 void Builder::apply_profile_template(Config &config, const string &pt) const
488 vector<string> parts = split(pt, '-');
490 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
492 ProfileTemplateMap::const_iterator j = profile_tmpl.find(*i);
493 if(j==profile_tmpl.end())
496 config.update(j->second);
500 void Builder::problem(const string &p, const string &d)
502 problems.push_back(Problem(p, d));
505 void Builder::add_target(Target *t)
507 targets.insert(TargetMap::value_type(t->get_name(), t));
508 new_tgts.push_back(t);
511 void Builder::register_path(const FS::Path &path, FileTarget *t)
513 targets_by_path.insert(TargetMap::value_type(path.str(), t));
516 void Builder::usage(const char *reason, const char *argv0, bool brief)
519 IO::print(IO::cerr, "%s\n", reason);
522 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
525 IO::print(IO::cerr, "Builder 1.0\n\n");
526 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
527 IO::print(IO::cerr, "Options:\n");
528 IO::print(IO::cerr, helpmsg);
532 FS::Path Builder::get_package_location(const string &name)
535 IO::print("Looking for package %s\n", name);
539 // Try to get source directory with pkgconfig
540 string srcdir = strip(run_pkgconfig(name, "source"));
549 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
551 list<string> files = list_files(*i);
552 for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
554 FS::Path full = *i / *j;
555 if(FS::exists(full/"Build"))
556 pkg_dirs.push_back(full);
560 IO::print("%d packages found in path\n", pkg_dirs.size());
563 bool msp = !name.compare(0, 3, "msp");
564 for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
566 string base = basename(*i);
567 unsigned dash = base.rfind('-');
569 if(!base.compare(0, dash, name))
571 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
578 int Builder::load_build_file(const FS::Path &fn)
582 IO::BufferedFile in(fn.str());
585 IO::print("Reading %s\n", fn);
587 DataFile::Parser parser(in, fn.str());
588 Loader loader(*this, fn.subpath(0, fn.size()-1));
591 catch(const IO::file_not_found &)
599 int Builder::create_targets()
601 Target *world = new VirtualTarget(*this, "world");
603 Target *def_tgt = new VirtualTarget(*this, "default");
604 world->add_depend(def_tgt);
606 Target *install = new VirtualTarget(*this, "install");
607 world->add_depend(install);
609 Target *tarballs = new VirtualTarget(*this, "tarballs");
610 world->add_depend(tarballs);
612 for(PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
614 if(!i->second || !i->second->is_configured())
617 SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second);
621 const ComponentList &components = spkg->get_components();
622 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
625 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
627 PkgConfig *pc = new PkgConfig(*this, *spkg);
628 install->add_depend(new Install(*this, *spkg, *pc));
632 // Find dependencies until no new targets are created
633 while(!new_tgts.empty())
635 Target *tgt = new_tgts.front();
636 new_tgts.erase(new_tgts.begin());
638 if(!tgt->get_depends_ready())
639 new_tgts.push_back(tgt);
643 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
645 FileTarget *tgt = get_target_by_path(cwd/ *i);
648 IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
654 // Make the cmdline target depend on all targets mentioned on the command line
655 Target *cmdline = new VirtualTarget(*this, "cmdline");
656 for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
658 Target *tgt = get_target(*i);
660 tgt = get_target_by_path(*i);
662 tgt = get_target_by_path(cwd/ *i);
665 IO::print("I don't know anything about %s\n", *i);
669 cmdline->add_depend(tgt);
674 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
675 if(SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second))
676 spkg->get_deps_cache().save();
681 Target *Builder::get_header(const FS::Path &fn)
683 Target *tgt = get_target_by_path(fn);
688 tgt = new SystemHeader(*this, fn.str());
694 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
696 // Populate a list of candidate filenames
697 StringList candidates;
701 // XXX Should probably let the Architecture populate the list
702 if(current_arch->get_system()=="windows")
704 candidates.push_back("lib"+lib+".dll");
705 candidates.push_back(lib+".dll");
708 candidates.push_back("lib"+lib+".so");
711 /* Static libraries are always considered, since sometimes shared versions
712 may not be available */
713 candidates.push_back("lib"+lib+".a");
714 if(current_arch->get_system()=="windows")
715 candidates.push_back("lib"+lib+".dll.a");
717 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
719 FS::Path full = path/ *i;
720 Target *tgt = get_target_by_path(full);
724 Target *real_tgt = tgt->get_real_target();
726 /* Ignore dynamic libraries from local packages unless library mode is
728 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
733 else if(FS::is_reg(full))
735 tgt = new SystemLibrary(*this, full.str());
743 int Builder::do_build()
745 Target *cmdline = get_target("cmdline");
748 for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
749 if(i->second->is_buildable() && i->second->get_rebuild())
754 IO::print("Already up to date\n");
758 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
760 vector<Action *> actions;
769 if(actions.size()<jobs && !fail)
771 Target *tgt = cmdline->get_buildable_target();
774 Action *action = tgt->build();
776 actions.push_back(action);
779 IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
781 else if(actions.empty())
785 Time::sleep(10*Time::msec);
787 for(unsigned i=0; i<actions.size();)
789 int status = actions[i]->check();
795 actions.erase(actions.begin()+i);
798 if(actions.empty() && fail)
809 IO::print("Build failed\n");
810 else if(show_progress)
811 IO::print("Build complete\n");
816 int Builder::do_clean()
818 // Cleaning doesn't care about ordering, so a simpler method can be used
820 set<Target *> clean_tgts;
822 queue.push_back(get_target("cmdline"));
824 while(!queue.empty())
826 Target *tgt = queue.front();
827 queue.erase(queue.begin());
829 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
830 clean_tgts.insert(tgt);
832 const TargetList &deps = tgt->get_depends();
833 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
834 if(!clean_tgts.count(*i))
838 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
839 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
841 Action *action = new Unlink(*this, *ft);
842 while(action->check()<0) ;
849 void Builder::package_help()
851 const Config &config = main_pkg->get_config();
852 const Config::OptionMap &options = config.get_options();
854 IO::print("Required packages:\n ");
855 const PackageList &requires = main_pkg->get_requires();
856 for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
858 if(i!=requires.begin())
860 IO::print((*i)->get_name());
862 IO::print("\n\nPackage configuration:\n");
863 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
865 const Config::Option &opt = i->second;
866 IO::print(" %s: %s (%s)", opt.name, opt.descr, opt.value);
867 if(opt.value!=opt.defv)
868 IO::print(" [%s]", opt.defv);
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));