4 #include <msp/core/error.h>
5 #include <msp/core/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>
14 #include "executable.h"
18 #include "objectfile.h"
20 #include "pkgconfig.h"
21 #include "sharedlibrary.h"
22 #include "staticlibrary.h"
23 #include "systemlibrary.h"
25 #include "virtualtarget.h"
30 Builder::Builder(int argc, char **argv):
43 create_makefile(false)
47 bool full_paths=false;
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);
70 if(!analyze_mode.empty())
72 analyzer=new Analyzer(*this);
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);
83 throw UsageError("Invalid analyze mode");
85 analyzer->set_max_depth(max_depth);
86 analyzer->set_full_paths(full_paths);
88 else if(!clean && !create_makefile)
91 const list<string> &args=getopt.get_args();
92 for(list<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
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)));
98 cmdline_targets.push_back(*i);
101 if(cmdline_targets.empty())
102 cmdline_targets.push_back("default");
104 if(!work_dir.empty())
105 chdir(work_dir.c_str());
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"));
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"));
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"));
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"));
128 for(StringMap::iterator i=archs.begin(); i!=archs.end(); ++i)
130 if(i->first=="native")
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"));
141 Gets a package with the specified name, possibly creating it.
143 @param n Package name
145 @return Pointer to the package, or 0 if the package could not be located
147 Package *Builder::get_package(const string &n)
149 PackageMap::iterator i=packages.find(n);
150 if(i!=packages.end())
153 // Try to get source directory with pkgconfig
155 argv.push_back("pkg-config");
156 argv.push_back("--variable=source");
158 string srcdir=strip(run_command(argv));
162 dirs.push_back(srcdir);
164 // Make some other guesses about the source directory
166 if(!dirname.compare(0, 3, "msp"))
168 dirs.push_back(cwd/dirname);
169 dirs.push_back(cwd/".."/dirname);
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"))
176 if(i!=packages.end())
181 // Package source not found - create a binary package
182 Package *pkg=Package::create(*this, n);
183 packages.insert(PackageMap::value_type(n, pkg));
185 new_pkgs.push_back(pkg);
191 Returns the target with the given name, or 0 if no such target exists.
193 Target *Builder::get_target(const string &n)
195 TargetMap::iterator i=targets.find(n);
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
207 Target *Builder::get_header(const string &include, const string &, const string &from, const list<string> &path)
210 update_hash(hash, from);
211 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
212 update_hash(hash, *i);
214 string id=hash+include;
215 TargetMap::iterator i=includes.find(id);
216 if(i!=includes.end())
219 string fn=include.substr(1);
221 if(include[0]=='"' && (tgt=get_header(Path::Path(from)/fn)))
223 else if((tgt=get_header(Path::Path("/usr/include")/fn)))
225 //XXX Determine the C++ header location dynamically
226 else if((tgt=get_header(Path::Path("/usr/include/c++/4.1.2")/fn)))
230 for(list<string>::const_iterator j=path.begin(); (j!=path.end() && !tgt); ++j)
231 tgt=get_header(cwd/ *j/fn);
234 includes.insert(TargetMap::value_type(id, tgt));
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.
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
248 @return Some kind of library target, if a match was found
250 Target *Builder::get_library(const string &lib, const string &arch, const list<string> &path, LibMode mode)
253 for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
254 update_hash(hash, *i);
256 //XXX Incorporate mode into id
258 TargetMap::iterator i=libraries.find(id);
259 if(i!=libraries.end())
265 syspath.push_back("/lib");
266 syspath.push_back("/usr/lib");
269 syspath.push_back("/usr/"+get_arch_prefix(arch)+"/lib");
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);
277 libraries.insert(TargetMap::value_type(id, tgt));
282 const string &Builder::get_arch_prefix(const string &arch) const
284 StringMap::const_iterator i=archs.find(arch);
286 throw InvalidParameterValue("Unknown architecture");
291 string Builder::get_tool(const std::string &tool, const std::string &arch)
293 ToolMap::iterator i=tools.find(arch);
296 StringMap::iterator j=i->second.find(tool);
297 if(j!=i->second.end())
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");
307 return get_arch_prefix(arch)+"-"+j->second;
310 void Builder::apply_profile_template(Config &config, const string &pt) const
312 vector<string> parts=split(pt, '-');
314 for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
316 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
317 if(j==profile_tmpl.end())
320 config.update(j->second);
326 if(load_build_file(cwd/build_file))
328 cerr<<"No build info here.\n";
332 default_pkg=packages.begin()->second;
334 while(!new_pkgs.empty())
336 Package *pkg=new_pkgs.front();
337 new_pkgs.erase(new_pkgs.begin());
341 default_pkg->configure(cmdline_options, conf_all?2:1);
345 usage(0, "builder", false);
352 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
357 else if(i->second->get_buildable() && i->second->get_arch()!=default_pkg->get_arch())
358 prob="wrong architecture ("+i->second->get_arch()+")";
360 problems.insert(StringMap::value_type(i->first, prob));
363 if(!problems.empty())
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";
378 cout<<packages.size()<<" packages, "<<targets.size()<<" targets\n";
381 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
383 cout<<' '<<i->second->get_name();
384 if(i->second->get_buildable())
387 unsigned ood_count=0;
388 for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
389 if(j->second->get_package()==i->second)
392 if(j->second->get_rebuild())
397 cout<<" ("<<count<<" targets";
399 cout<<", "<<ood_count<<" out-of-date";
412 exit_code=do_clean();
414 exit_code=do_build();
421 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
423 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
428 void Builder::usage(const char *reason, const char *argv0, bool 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> ...]";
438 "Usage: "<<argv0<<" [options] [<target> ...]\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";
462 Loads the given build file.
464 @param fn Path to the file
466 @return 0 on success, -1 if the file could not be opened
468 int Builder::load_build_file(const Path::Path &fn)
470 ifstream in(fn.str().c_str());
474 Parser::Parser parser(in, fn.str());
475 Loader loader(*this, fn.subpath(0, fn.size()-1));
482 Creates targets for all packages and prepares them for building.
484 @return 0 if everything went ok, -1 if something bad happened and a build
485 shouldn't be attempted
487 int Builder::create_targets()
489 Target *world=new VirtualTarget(*this, "world");
492 Target *def_tgt=new VirtualTarget(*this, "default");
494 world->add_depend(def_tgt);
496 Target *install=new VirtualTarget(*this, "install");
498 world->add_depend(install);
500 for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
504 if(!i->second->get_buildable())
507 Path::Path inst_base;
508 if(i->second->get_buildable() && i->second->get_install_flags())
509 inst_base=i->second->get_prefix();
511 const ComponentList &components=i->second->get_components();
512 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
514 // Collect all files belonging to the component
516 const PathList &sources=j->get_sources();
517 for(PathList::const_iterator k=sources.begin(); k!=sources.end(); ++k)
521 if(S_ISDIR(st.st_mode))
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);
531 bool build_exe=j->get_type()!=Component::HEADERS;
533 list<ObjectFile *> objs;
534 for(PathList::iterator k=files.begin(); k!=files.end(); ++k)
536 string basename=(*k)[-1];
537 string ext=Path::splitext(basename).ext;
538 if((ext==".cpp" || ext==".c") && build_exe)
540 SourceFile *src=new SourceFile(*this, &*j, k->str());
544 ObjectFile *obj=new ObjectFile(*this, *j, *src);
550 Target *hdr=get_target(k->str());
553 hdr=new Header(*this, &*j, k->str());
557 // Install headers if requested
558 if(!j->get_install_headers().empty())
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());
563 install->add_depend(inst);
571 StaticLibrary *slib=0;
572 if(j->get_type()==Component::LIBRARY)
574 exe=new SharedLibrary(*this, *j, objs);
575 slib=new StaticLibrary(*this, *j, objs);
579 exe=new Executable(*this, *j, objs);
582 if(i->second==default_pkg && j->get_default())
584 def_tgt->add_depend(exe);
585 if(slib) def_tgt->add_depend(slib);
589 world->add_depend(exe);
590 if(slib) world->add_depend(slib);
596 if(j->get_type()==Component::PROGRAM)
598 else if(j->get_type()==Component::LIBRARY)
600 if(!inst_dir.empty())
602 Install *inst=new Install(*this, *i->second, *exe, (inst_base/inst_dir/Path::basename(exe->get_name())).str());
604 install->add_depend(inst);
608 inst=new Install(*this, *i->second, *slib, (inst_base/inst_dir/Path::basename(slib->get_name())).str());
610 install->add_depend(inst);
617 if(i->second->get_install_flags()&(Package::LIB|Package::INCLUDE))
619 PkgConfig *pc=new PkgConfig(*this, *i->second);
621 Install *inst=new Install(*this, *i->second, *pc, (inst_base/"lib"/"pkgconfig"/Path::basename(pc->get_name())).str());
623 install->add_depend(inst);
627 // Find dependencies until no new targets are created
628 while(!new_tgts.empty())
630 Target *tgt=new_tgts.front();
631 new_tgts.erase(new_tgts.begin());
633 if(!tgt->get_depends_ready())
634 new_tgts.push_back(tgt);
638 for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
640 Target *tgt=get_target((cwd/ *i).str());
643 cerr<<"Unknown what-if target "<<*i<<'\n';
649 // Make the cmdline target depend on all targets mentioned on the command line
650 Target *cmdline=new VirtualTarget(*this, "cmdline");
652 bool build_world=false;
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 cerr<<"I don't know anything about "<<*i<<'\n';
665 cmdline->add_depend(tgt);
668 /* If world is to be built, prepare cmdline. If not, add cmdline to world
669 and prepare world. I don't really like this, but it keeps the graph
675 world->add_depend(cmdline);
683 Check if a header exists, either as a target or a file. Either an existing
684 target or a new SystemHeader target will be returned.
686 Target *Builder::get_header(const Msp::Path::Path &fn)
688 Target *tgt=get_target(fn.str());
693 add_target(tgt=new SystemHeader(*this, fn.str()));
699 Target *Builder::get_library(const string &lib, const string &arch, const Path::Path &path, LibMode mode)
701 // Populate a list of candidate filenames
702 StringList candidates;
707 candidates.push_back("lib"+lib+".dll");
709 candidates.push_back("lib"+lib+".so");
712 /* Static libraries are always considered, since sometimes shared versions
713 may not be available */
714 candidates.push_back("lib"+lib+".a");
716 candidates.push_back("lib"+lib+".dll.a");
718 for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
720 string full=(path/ *i).str();
721 Target *tgt=get_target(full);
725 Target *real_tgt=tgt;
726 if(dynamic_cast<Install *>(tgt))
727 real_tgt=real_tgt->get_depends().front();
729 /* Ignore dynamic libraries from local packages unless library mode is
731 if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
736 else if(Path::exists(full))
738 tgt=new SystemLibrary(*this, full);
748 Adds a target to both the target map and the new target queue.
750 void Builder::add_target(Target *t)
752 targets.insert(TargetMap::value_type(t->get_name(), t));
753 new_tgts.push_back(t);
757 Updates a hash with a string. This is used from get_header and get_library.
759 void Builder::update_hash(string &hash, const string &value)
761 for(unsigned i=0; i<value.size(); ++i)
762 hash[i%hash.size()]^=value[i];
766 This function supervises the build process, starting new actions when slots
769 int Builder::do_build()
771 Target *cmdline=get_target("cmdline");
773 unsigned total=cmdline->count_rebuild();
776 cout<<"Already up to date\n";
779 cout<<"Will build "<<total<<" target(s)\n";
781 vector<Action *> actions;
784 cout<<"0 targets built\n";
792 if(actions.size()<jobs && !fail)
794 Target *tgt=cmdline->get_buildable_target();
797 Action *action=tgt->build();
799 actions.push_back(action);
801 else if(actions.empty())
805 Time::sleep(10*Time::msec);
807 for(unsigned i=0; i<actions.size();)
809 int status=actions[i]->check();
815 cout<<"\e["<<actions.size()+1<<'A';
816 cout<<count<<" targets built\n";
820 if(i<actions.size()-1)
821 cout<<"\e["<<actions.size()-i-1<<"B";
825 actions.erase(actions.begin()+i);
828 if(actions.empty() && fail)
837 cout<<"Build failed\n";
843 Cleans buildable targets. If clean is 1, cleans only this package. If
844 clean is 2 or greater, cleans all buildable packages.
846 int Builder::do_clean()
848 // Cleaning doesn't care about ordering, so a simpler method can be used
850 set<Target *> clean_tgts;
852 queue.push_back(get_target("cmdline"));
854 while(!queue.empty())
856 Target *tgt=queue.front();
857 queue.erase(queue.begin());
859 if(tgt->get_buildable() && (tgt->get_package()==default_pkg || clean>=2))
860 clean_tgts.insert(tgt);
862 const TargetList &deps=tgt->get_depends();
863 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
864 if(!clean_tgts.count(*i))
868 for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
870 Action *action=new Unlink(*this, **i);
871 while(action->check()<0);
879 Prints out information about the default package.
881 void Builder::package_help()
883 const Config &config=default_pkg->get_config();
884 const Config::OptionMap &options=config.get_options();
886 cout<<"Required packages:\n ";
887 const PkgRefList &requires=default_pkg->get_requires();
888 for(PkgRefList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
890 if(i!=requires.begin())
895 cout<<"Package configuration:\n";
896 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
898 const Config::Option &opt=i->second;
899 cout<<" "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
903 Application::RegApp<Builder> Builder::reg;
905 Builder::Loader::Loader(Builder &b, const Path::Path &s):
909 add("package", &Loader::package);
912 void Builder::Loader::package(const string &n)
914 Package *pkg=new Package(bld, n, src);
916 bld.packages.insert(PackageMap::value_type(n, pkg));
917 bld.new_pkgs.push_back(pkg);