Add plugin functionality for link-time optimization (LTO).
[external/binutils.git] / gold / gold.cc
1 // gold.cc -- main linker functions
2
3 // Copyright 2006, 2007, 2008 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
5
6 // This file is part of gold.
7
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
12
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
22
23 #include "gold.h"
24
25 #include <cstdlib>
26 #include <cstdio>
27 #include <cstring>
28 #include <unistd.h>
29 #include <algorithm>
30 #include "libiberty.h"
31
32 #include "options.h"
33 #include "debug.h"
34 #include "workqueue.h"
35 #include "dirsearch.h"
36 #include "readsyms.h"
37 #include "symtab.h"
38 #include "common.h"
39 #include "object.h"
40 #include "layout.h"
41 #include "reloc.h"
42 #include "defstd.h"
43 #include "plugin.h"
44
45 namespace gold
46 {
47
48 const char* program_name;
49
50 void
51 gold_exit(bool status)
52 {
53   if (!status && parameters != NULL && parameters->options_valid())
54     unlink_if_ordinary(parameters->options().output_file_name());
55   exit(status ? EXIT_SUCCESS : EXIT_FAILURE);
56 }
57
58 void
59 gold_nomem()
60 {
61   // We are out of memory, so try hard to print a reasonable message.
62   // Note that we don't try to translate this message, since the
63   // translation process itself will require memory.
64
65   // LEN only exists to avoid a pointless warning when write is
66   // declared with warn_use_result, as when compiling with
67   // -D_USE_FORTIFY on GNU/Linux.  Casting to void does not appear to
68   // work, at least not with gcc 4.3.0.
69
70   ssize_t len = write(2, program_name, strlen(program_name));
71   if (len >= 0)
72     {
73       const char* const s = ": out of memory\n";
74       len = write(2, s, strlen(s));
75     }
76   gold_exit(false);
77 }
78
79 // Handle an unreachable case.
80
81 void
82 do_gold_unreachable(const char* filename, int lineno, const char* function)
83 {
84   fprintf(stderr, _("%s: internal error in %s, at %s:%d\n"),
85           program_name, function, filename, lineno);
86   gold_exit(false);
87 }
88
89 // This class arranges to run the functions done in the middle of the
90 // link.  It is just a closure.
91
92 class Middle_runner : public Task_function_runner
93 {
94  public:
95   Middle_runner(const General_options& options,
96                 const Input_objects* input_objects,
97                 Symbol_table* symtab,
98                 Layout* layout, Mapfile* mapfile)
99     : options_(options), input_objects_(input_objects), symtab_(symtab),
100       layout_(layout), mapfile_(mapfile)
101   { }
102
103   void
104   run(Workqueue*, const Task*);
105
106  private:
107   const General_options& options_;
108   const Input_objects* input_objects_;
109   Symbol_table* symtab_;
110   Layout* layout_;
111   Mapfile* mapfile_;
112 };
113
114 void
115 Middle_runner::run(Workqueue* workqueue, const Task* task)
116 {
117   queue_middle_tasks(this->options_, task, this->input_objects_, this->symtab_,
118                      this->layout_, workqueue, this->mapfile_);
119 }
120
121 // Queue up the initial set of tasks for this link job.
122
123 void
124 queue_initial_tasks(const General_options& options,
125                     Dirsearch& search_path,
126                     const Command_line& cmdline,
127                     Workqueue* workqueue, Input_objects* input_objects,
128                     Symbol_table* symtab, Layout* layout, Mapfile* mapfile)
129 {
130   if (cmdline.begin() == cmdline.end())
131     gold_fatal(_("no input files"));
132
133   int thread_count = options.thread_count_initial();
134   if (thread_count == 0)
135     thread_count = cmdline.number_of_input_files();
136   workqueue->set_thread_count(thread_count);
137
138   // Read the input files.  We have to add the symbols to the symbol
139   // table in order.  We do this by creating a separate blocker for
140   // each input file.  We associate the blocker with the following
141   // input file, to give us a convenient place to delete it.
142   Task_token* this_blocker = NULL;
143   for (Command_line::const_iterator p = cmdline.begin();
144        p != cmdline.end();
145        ++p)
146     {
147       Task_token* next_blocker = new Task_token(true);
148       next_blocker->add_blocker();
149       workqueue->queue(new Read_symbols(options, input_objects, symtab, layout,
150                                         &search_path, mapfile, &*p, NULL,
151                                         this_blocker, next_blocker));
152       this_blocker = next_blocker;
153     }
154
155   if (options.has_plugins())
156     {
157       Task_token* next_blocker = new Task_token(true);
158       next_blocker->add_blocker();
159       workqueue->queue(new Plugin_hook(options, input_objects, symtab, layout,
160                                        &search_path, mapfile, this_blocker,
161                                        next_blocker));
162       this_blocker = next_blocker;
163     }
164
165   workqueue->queue(new Task_function(new Middle_runner(options,
166                                                        input_objects,
167                                                        symtab,
168                                                        layout,
169                                                        mapfile),
170                                      this_blocker,
171                                      "Task_function Middle_runner"));
172 }
173
174 // Queue up the middle set of tasks.  These are the tasks which run
175 // after all the input objects have been found and all the symbols
176 // have been read, but before we lay out the output file.
177
178 void
179 queue_middle_tasks(const General_options& options,
180                    const Task* task,
181                    const Input_objects* input_objects,
182                    Symbol_table* symtab,
183                    Layout* layout,
184                    Workqueue* workqueue,
185                    Mapfile* mapfile)
186 {
187   // We have to support the case of not seeing any input objects, and
188   // generate an empty file.  Existing builds depend on being able to
189   // pass an empty archive to the linker and get an empty object file
190   // out.  In order to do this we need to use a default target.
191   if (input_objects->number_of_input_objects() == 0)
192     set_parameters_target(&parameters->default_target());
193
194   int thread_count = options.thread_count_middle();
195   if (thread_count == 0)
196     thread_count = std::max(2, input_objects->number_of_input_objects());
197   workqueue->set_thread_count(thread_count);
198
199   // Now we have seen all the input files.
200   const bool doing_static_link = (!input_objects->any_dynamic()
201                                   && !parameters->options().shared());
202   set_parameters_doing_static_link(doing_static_link);
203   if (!doing_static_link && options.is_static())
204     {
205       // We print out just the first .so we see; there may be others.
206       gold_error(_("cannot mix -static with dynamic object %s"),
207                  (*input_objects->dynobj_begin())->name().c_str());
208     }
209   if (!doing_static_link && parameters->options().relocatable())
210     gold_error(_("cannot mix -r with dynamic object %s"),
211                (*input_objects->dynobj_begin())->name().c_str());
212   if (!doing_static_link
213       && options.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
214     gold_fatal(_("cannot use non-ELF output format with dynamic object %s"),
215                (*input_objects->dynobj_begin())->name().c_str());
216
217   if (is_debugging_enabled(DEBUG_SCRIPT))
218     layout->script_options()->print(stderr);
219
220   // For each dynamic object, record whether we've seen all the
221   // dynamic objects that it depends upon.
222   input_objects->check_dynamic_dependencies();
223
224   // See if any of the input definitions violate the One Definition Rule.
225   // TODO: if this is too slow, do this as a task, rather than inline.
226   symtab->detect_odr_violations(task, options.output_file_name());
227
228   // Create any output sections required by any linker script.
229   layout->create_script_sections();
230
231   // Define some sections and symbols needed for a dynamic link.  This
232   // handles some cases we want to see before we read the relocs.
233   layout->create_initial_dynamic_sections(symtab);
234
235   // Define symbols from any linker scripts.
236   layout->define_script_symbols(symtab);
237
238   // Add any symbols named with -u options to the symbol table.
239   symtab->add_undefined_symbols_from_command_line();
240
241   // Attach sections to segments.
242   layout->attach_sections_to_segments();
243
244   if (!parameters->options().relocatable())
245     {
246       // Predefine standard symbols.
247       define_standard_symbols(symtab, layout);
248
249       // Define __start and __stop symbols for output sections where
250       // appropriate.
251       layout->define_section_symbols(symtab);
252     }
253
254   // Make sure we have symbols for any required group signatures.
255   layout->define_group_signatures(symtab);
256
257   // Read the relocations of the input files.  We do this to find
258   // which symbols are used by relocations which require a GOT and/or
259   // a PLT entry, or a COPY reloc.  When we implement garbage
260   // collection we will do it here by reading the relocations in a
261   // breadth first search by references.
262   //
263   // We could also read the relocations during the first pass, and
264   // mark symbols at that time.  That is how the old GNU linker works.
265   // Doing that is more complex, since we may later decide to discard
266   // some of the sections, and thus change our minds about the types
267   // of references made to the symbols.
268   Task_token* blocker = new Task_token(true);
269   Task_token* symtab_lock = new Task_token(false);
270   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
271        p != input_objects->relobj_end();
272        ++p)
273     {
274       // We can read and process the relocations in any order.  But we
275       // only want one task to write to the symbol table at a time.
276       // So we queue up a task for each object to read the
277       // relocations.  That task will in turn queue a task to wait
278       // until it can write to the symbol table.
279       blocker->add_blocker();
280       workqueue->queue(new Read_relocs(options, symtab, layout, *p,
281                                        symtab_lock, blocker));
282     }
283
284   // Allocate common symbols.  This requires write access to the
285   // symbol table, but is independent of the relocation processing.
286   if (parameters->options().define_common())
287     {
288       blocker->add_blocker();
289       workqueue->queue(new Allocate_commons_task(symtab, layout, mapfile,
290                                                  symtab_lock, blocker));
291     }
292
293   // When all those tasks are complete, we can start laying out the
294   // output file.
295   // TODO(csilvers): figure out a more principled way to get the target
296   Target* target = const_cast<Target*>(&parameters->target());
297   workqueue->queue(new Task_function(new Layout_task_runner(options,
298                                                             input_objects,
299                                                             symtab,
300                                                             target,
301                                                             layout,
302                                                             mapfile),
303                                      blocker,
304                                      "Task_function Layout_task_runner"));
305 }
306
307 // Queue up the final set of tasks.  This is called at the end of
308 // Layout_task.
309
310 void
311 queue_final_tasks(const General_options& options,
312                   const Input_objects* input_objects,
313                   const Symbol_table* symtab,
314                   Layout* layout,
315                   Workqueue* workqueue,
316                   Output_file* of)
317 {
318   int thread_count = options.thread_count_final();
319   if (thread_count == 0)
320     thread_count = std::max(2, input_objects->number_of_input_objects());
321   workqueue->set_thread_count(thread_count);
322
323   bool any_postprocessing_sections = layout->any_postprocessing_sections();
324
325   // Use a blocker to wait until all the input sections have been
326   // written out.
327   Task_token* input_sections_blocker = NULL;
328   if (!any_postprocessing_sections)
329     input_sections_blocker = new Task_token(true);
330
331   // Use a blocker to block any objects which have to wait for the
332   // output sections to complete before they can apply relocations.
333   Task_token* output_sections_blocker = new Task_token(true);
334
335   // Use a blocker to block the final cleanup task.
336   Task_token* final_blocker = new Task_token(true);
337
338   // Queue a task to write out the symbol table.
339   final_blocker->add_blocker();
340   workqueue->queue(new Write_symbols_task(layout,
341                                           symtab,
342                                           input_objects,
343                                           layout->sympool(),
344                                           layout->dynpool(),
345                                           of,
346                                           final_blocker));
347
348   // Queue a task to write out the output sections.
349   output_sections_blocker->add_blocker();
350   final_blocker->add_blocker();
351   workqueue->queue(new Write_sections_task(layout, of, output_sections_blocker,
352                                            final_blocker));
353
354   // Queue a task to write out everything else.
355   final_blocker->add_blocker();
356   workqueue->queue(new Write_data_task(layout, symtab, of, final_blocker));
357
358   // Queue a task for each input object to relocate the sections and
359   // write out the local symbols.
360   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
361        p != input_objects->relobj_end();
362        ++p)
363     {
364       if (input_sections_blocker != NULL)
365         input_sections_blocker->add_blocker();
366       final_blocker->add_blocker();
367       workqueue->queue(new Relocate_task(options, symtab, layout, *p, of,
368                                          input_sections_blocker,
369                                          output_sections_blocker,
370                                          final_blocker));
371     }
372
373   // Queue a task to write out the output sections which depend on
374   // input sections.  If there are any sections which require
375   // postprocessing, then we need to do this last, since it may resize
376   // the output file.
377   if (!any_postprocessing_sections)
378     {
379       final_blocker->add_blocker();
380       Task* t = new Write_after_input_sections_task(layout, of,
381                                                     input_sections_blocker,
382                                                     final_blocker);
383       workqueue->queue(t);
384     }
385   else
386     {
387       Task_token *new_final_blocker = new Task_token(true);
388       new_final_blocker->add_blocker();
389       Task* t = new Write_after_input_sections_task(layout, of,
390                                                     final_blocker,
391                                                     new_final_blocker);
392       workqueue->queue(t);
393       final_blocker = new_final_blocker;
394     }
395
396   // Queue a task to close the output file.  This will be blocked by
397   // FINAL_BLOCKER.
398   workqueue->queue(new Task_function(new Close_task_runner(&options, layout,
399                                                            of),
400                                      final_blocker,
401                                      "Task_function Close_task_runner"));
402 }
403
404 } // End namespace gold.