]> git.tdb.fi Git - builder.git/blob - source/lib/builder.cpp
Avoid exception if plugins directory is not found
[builder.git] / source / lib / builder.cpp
1 #include <deque>
2 #include <set>
3 #include <msp/core/algorithm.h>
4 #include <msp/core/except.h>
5 #include <msp/core/maputils.h>
6 #include <msp/datafile/parser.h>
7 #include <msp/fs/dir.h>
8 #include <msp/fs/stat.h>
9 #include <msp/fs/utils.h>
10 #include <msp/io/buffered.h>
11 #include <msp/io/file.h>
12 #include <msp/io/print.h>
13 #include <msp/strings/format.h>
14 #include <msp/strings/utils.h>
15 #include <msp/time/timedelta.h>
16 #include <msp/time/utils.h>
17 #include "binarypackage.h"
18 #include "builder.h"
19 #include "installedfile.h"
20 #include "package.h"
21 #include "plugin.h"
22 #include "sharedlibrary.h"
23 #include "task.h"
24 #include "tool.h"
25 #include "virtualtarget.h"
26
27 using namespace std;
28 using namespace Msp;
29
30 Builder::Builder():
31         package_manager(*this),
32         native_arch(*this, string()),
33         vfs(*this),
34         build_graph(*this),
35         logger(&default_logger)
36 {
37         set_architecture(string());
38 }
39
40 Builder::~Builder()
41 {
42         if(current_arch!=&native_arch)
43                 delete current_arch;
44 }
45
46 void Builder::load_plugins()
47 {
48         using CreateFunc = Plugin *(Builder &);
49
50         FS::Path plugins_dir = FS::get_sys_lib_dir();
51         if(!FS::exists(plugins_dir))
52                 return;
53
54         logger->log("files", "Traversing %s", plugins_dir);
55         vector<LoadedPlugin> unordered_plugins;
56         for(const string &f: list_filtered(plugins_dir, "\\.dlm$"))
57         {
58                 LoadedPlugin plugin;
59                 plugin.path = plugins_dir/f;
60
61                 try
62                 {
63                         plugin.module = new Module(plugin.path.str());
64                 }
65                 catch(const exception &exc)
66                 {
67                         logger->log("plugins", "Failed to load plugin %s: %s", f, exc.what());
68                         continue;
69                 }
70
71                 try
72                 {
73                         CreateFunc *create_func = reinterpret_cast<CreateFunc *>(plugin.module->get_symbol("create_plugin"));
74                         plugin.plugin = create_func(*this);
75                         if(plugin.plugin)
76                         {
77                                 logger->log("plugins", "Loaded plugin %s", f);
78                                 unordered_plugins.emplace_back(move(plugin));
79                                 continue;
80                         }
81                         else
82                                 logger->log("plugins", "Plugin %s refused to initialize", f);
83                 }
84                 catch(const exception &exc)
85                 {
86                         logger->log("plugins", "Failed to initialize plugin %s: %s", f, exc.what());
87                 }
88         }
89
90         auto have_plugin = [this](const string &r){
91                 return any_of(plugins.begin(), plugins.end(), [&r](const LoadedPlugin &p){ return FS::basepart(FS::basename(p.path))==r; });
92         };
93
94         while(!unordered_plugins.empty())
95         {
96                 bool any_added = false;
97                 for(auto i=unordered_plugins.begin(); i!=unordered_plugins.end(); )
98                 {
99                         const vector<string> &required = i->plugin->get_required_plugins();
100                         if(all_of(required.begin(), required.end(), have_plugin))
101                         {
102                                 plugins.push_back(move(*i));
103                                 i = unordered_plugins.erase(i);
104                                 any_added = true;
105                         }
106                         else
107                                 ++i;
108                 }
109
110                 if(!any_added)
111                         break;
112         }
113
114         for(const LoadedPlugin &p: unordered_plugins)
115         {
116                 vector<string> missing;
117                 for(const string &r: p.plugin->get_required_plugins())
118                         if(!have_plugin(r))
119                                 missing.push_back(r);
120                 logger->log("plugins", "Missing required plugins for plugin %s: %s",
121                         FS::basename(p.path), join(missing.begin(), missing.end()));
122         }
123 }
124
125 void Builder::set_architecture(const string &name)
126 {
127         if(current_arch!=&native_arch)
128                 delete current_arch;
129
130         if(name.empty())
131                 current_arch = &native_arch;
132         else
133                 current_arch = new Architecture(*this, name);
134
135         if(auto_prefix)
136                 update_auto_prefix();
137 }
138
139 vector<string> Builder::get_build_types() const
140 {
141         vector<string> keys;
142         keys.reserve(build_types.size());
143         for(const auto &kvp: build_types)
144                 keys.push_back(kvp.first);
145         return keys;
146 }
147
148 const BuildType &Builder::get_build_type() const
149 {
150         if(!build_type)
151                 throw invalid_state("no build type");
152         return *build_type;
153 }
154
155 void Builder::set_build_type(const string &name)
156 {
157         build_type = &get_item(build_types, name);
158 }
159
160 void Builder::set_prefix(const FS::Path &p)
161 {
162         auto_prefix = false;
163         prefix = p;
164 }
165
166 void Builder::set_temp_directory(const FS::Path &p)
167 {
168         tempdir = p;
169 }
170
171 void Builder::update_auto_prefix()
172 {
173         if(current_arch->is_native())
174                 prefix = FS::get_home_dir()/"local";
175         else
176                 prefix = FS::get_home_dir()/"local"/current_arch->get_name();
177 }
178
179 void Builder::add_default_tools()
180 {
181         for(const LoadedPlugin &p: plugins)
182                 p.plugin->add_tools(toolchain, *current_arch);
183
184         auto i = find_if(toolchain.get_toolchains(), [](const Toolchain *tc){ return (tc->has_tool("CC") || tc->has_tool("CXX")); });
185         if(i!=toolchain.get_toolchains().end())
186         {
187                 current_arch->refine((*i)->get_name());
188                 if(auto_prefix)
189                         update_auto_prefix();
190         }
191 }
192
193 void Builder::set_logger(const Logger *l)
194 {
195         logger = (l ? l : &default_logger);
196 }
197
198 vector<string> Builder::collect_problems() const
199 {
200         vector<string> target_problems;
201         vector<string> problems;
202         vector<const Package *> broken_packages;
203         vector<const Component *> broken_components;
204         vector<const Tool *> broken_tools;
205
206         for(const auto &kvp: build_graph.get_targets())
207                 if(kvp.second->is_broken())
208                 {
209                         const Package *package = kvp.second->get_package();
210                         if(package && package->is_broken())
211                                 collect_broken_packages(*package, broken_packages);
212
213                         const Component *component = kvp.second->get_component();
214                         if(component && component->is_broken() && !any_equals(broken_components, component))
215                         {
216                                 broken_components.push_back(component);
217                                 collect_broken_packages(component->get_package(), broken_packages);
218                                 for(const Package *r: component->get_required_packages())
219                                         if(r->is_broken())
220                                                 collect_broken_packages(*r, broken_packages);
221                         }
222
223                         const Tool *tool = kvp.second->get_tool();
224                         if(tool && tool->is_broken() && !any_equals(broken_tools, tool))
225                         {
226                                 broken_tools.push_back(tool);
227                                 for(const string &p: tool->get_problems())
228                                         problems.push_back(format("%s: %s", tool->get_tag(), p));
229                         }
230
231                         for(const string &p: kvp.second->get_problems())
232                                 target_problems.push_back(format("%s: %s", kvp.second->get_name(), p));
233                 }
234
235         for(const Package *p: broken_packages)
236         {
237                 for(const string &b: p->get_problems())
238                         problems.push_back(format("%s: %s", p->get_name(), b));
239
240                 for(const Component *c: broken_components)
241                         if(&c->get_package()==p)
242                         {
243                                 for(const string &b: c->get_problems())
244                                         problems.push_back(format("%s/%s: %s", p->get_name(), c->get_name(), b));
245                         }
246         }
247
248         problems.insert(problems.end(), make_move_iterator(target_problems.begin()), make_move_iterator(target_problems.end()));
249
250         return problems;
251 }
252
253 void Builder::collect_broken_packages(const Package &pkg, vector<const Package *> &broken) const
254 {
255         if(any_equals(broken, &pkg))
256                 return;
257
258         broken.push_back(&pkg);
259
260         for(const Package *r: pkg.get_required_packages())
261                 if(r->is_broken())
262                         collect_broken_packages(*r, broken);
263 }
264
265 void Builder::load_build_file(const FS::Path &fn, const Config::InputOptions *opts, bool all)
266 {
267         IO::BufferedFile in(fn.str());
268
269         get_logger().log("files", "Reading %s", fn);
270
271         DataFile::Parser parser(in, fn.str());
272         Loader loader(*this, opts, all);
273         loader.load(parser);
274 }
275
276 void Builder::save_caches()
277 {
278         for(const auto &kvp: package_manager.get_packages())
279                 kvp.second->save_caches();
280 }
281
282 int Builder::build(unsigned jobs, bool dry_run, bool show_progress)
283 {
284         unsigned total = build_graph.count_rebuild_targets();
285
286         if(!total)
287         {
288                 get_logger().log("summary", "Already up to date");
289                 return 0;
290         }
291         get_logger().log("summary", "Will build %d target%s", total, (total!=1 ? "s" : ""));
292
293         vector<Task *> tasks;
294
295         unsigned count = 0;
296
297         bool fail = false;
298         bool finish = false;
299         bool starved = false;
300
301         while(!finish)
302         {
303                 if(tasks.size()<jobs && !fail && !starved)
304                 {
305                         Target *tgt = build_graph.get_buildable_target();
306                         if(tgt)
307                         {
308                                 if(tgt->get_tool())
309                                 {
310                                         if(show_progress)
311                                                 IO::print("\033[K");
312                                         get_logger().log("tasks", "%-4s  %s", tgt->get_tool()->get_tag(), tgt->get_name());
313                                 }
314                                 Task *task = tgt->build();
315                                 if(task)
316                                 {
317                                         get_logger().log("commands", "%s", task->get_command());
318                                         if(dry_run)
319                                         {
320                                                 task->signal_finished.emit(true);
321                                                 delete task;
322                                         }
323                                         else
324                                         {
325                                                 task->start();
326                                                 tasks.push_back(task);
327                                         }
328                                 }
329
330                                 if(show_progress)
331                                         IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
332                         }
333                         else if(tasks.empty())
334                                 finish = true;
335                         else
336                                 starved = true;
337                 }
338                 else
339                         Time::sleep(10*Time::msec);
340
341                 for(unsigned i=0; i<tasks.size();)
342                 {
343                         Task::Status status;
344                         if(jobs==1 || (tasks.size()==1 && starved))
345                                 status = tasks[i]->wait();
346                         else
347                                 status = tasks[i]->check();
348
349                         if(status!=Task::RUNNING)
350                         {
351                                 ++count;
352
353                                 delete tasks[i];
354                                 tasks.erase(tasks.begin()+i);
355                                 if(status==Task::ERROR)
356                                         fail = true;
357                                 if(tasks.empty() && fail)
358                                         finish = true;
359                                 starved = false;
360                         }
361                         else
362                                 ++i;
363                 }
364         }
365
366         if(show_progress)
367                 IO::print("\033[K");
368         if(fail)
369                 get_logger().log("summary", "Build failed");
370         else if(show_progress)
371                 get_logger().log("summary", "Build complete");
372
373         return fail;
374 }
375
376 int Builder::clean(bool all, bool dry_run)
377 {
378         // Cleaning doesn't care about ordering, so a simpler method can be used
379
380         set<Target *> clean_tgts;
381         deque<Target *> queue;
382         queue.push_back(&build_graph.get_goals());
383
384         while(!queue.empty())
385         {
386                 Target *tgt = queue.front();
387                 queue.pop_front();
388
389                 if(tgt->is_buildable() && (tgt->get_package()==&package_manager.get_main_package() || all))
390                         clean_tgts.insert(tgt);
391
392                 for(Target *t: tgt->get_dependencies())
393                         if(!clean_tgts.count(t))
394                                 queue.push_back(t);
395         }
396
397         for(Target *t: clean_tgts)
398         {
399                 get_logger().log("tasks", "RM    %s", t->get_name());
400                 if(!dry_run)
401                         t->clean();
402         }
403
404         return 0;
405 }
406
407
408 Builder::LoadedPlugin::LoadedPlugin(LoadedPlugin &&other):
409         path(move(other.path)),
410         module(other.module),
411         plugin(other.plugin)
412 {
413         other.module = 0;
414         other.plugin = 0;
415 }
416
417 Builder::LoadedPlugin &Builder::LoadedPlugin::operator=(LoadedPlugin &&other)
418 {
419         delete plugin;
420         delete module;
421         path = move(other.path);
422         module = other.module;
423         plugin = other.plugin;
424         other.module = 0;
425         other.plugin = 0;
426         return *this;
427 }
428
429 Builder::LoadedPlugin::~LoadedPlugin()
430 {
431         delete plugin;
432         delete module;
433 }
434
435
436 Builder::Loader::Loader(Builder &b, const Config::InputOptions *o, bool a):
437         DataFile::ObjectLoader<Builder>(b),
438         options(o),
439         conf_all(a)
440 {
441         add("architecture", &Loader::architecture);
442         add("binary_package", &Loader::binpkg);
443         add("build_type", &Loader::build_type);
444         add("package", &Loader::package);
445
446         if(!obj.top_loader)
447                 obj.top_loader = this;
448         else if(!options && obj.top_loader!=this && obj.top_loader->conf_all)
449                 options = obj.top_loader->options;
450 }
451
452 Builder::Loader::~Loader()
453 {
454         if(obj.top_loader==this)
455                 obj.top_loader = 0;
456 }
457
458 void Builder::Loader::architecture(const string &n)
459 {
460         if(obj.current_arch->match_name(n))
461                 load_sub(*obj.current_arch);
462 }
463
464 void Builder::Loader::binpkg(const string &n)
465 {
466         BinaryPackage *pkg = new BinaryPackage(obj, n);
467         load_sub(*pkg);
468 }
469
470 void Builder::Loader::build_type(const string &n)
471 {
472         BuildType btype(n);
473         load_sub(btype);
474         auto i = obj.build_types.insert({ n, btype }).first;
475         if(!obj.build_type)
476                 obj.build_type = &i->second;
477 }
478
479 void Builder::Loader::package(const string &n)
480 {
481         SourcePackage *pkg = new SourcePackage(obj, n, get_source());
482
483         load_sub(*pkg, options);
484
485         if(obj.build_type)
486                 pkg->set_build_type(*obj.build_type);
487 }