elfcpp/:
[external/binutils.git] / gold / incremental.cc
1 // inremental.cc -- incremental linking support for gold
2
3 // Copyright 2009 Free Software Foundation, Inc.
4 // Written by Mikolaj Zalewski <mikolajz@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 <cstdarg>
26
27 #include "elfcpp.h"
28 #include "output.h"
29 #include "incremental.h"
30 #include "archive.h"
31 #include "output.h"
32 #include "target-select.h"
33
34 using elfcpp::Convert;
35
36 namespace gold {
37
38 // Version information. Will change frequently during the development, later
39 // we could think about backward (and forward?) compatibility.
40 const int INCREMENTAL_LINK_VERSION = 1;
41
42 namespace internal {
43
44 // Header of the .gnu_incremental_input section.
45 struct Incremental_inputs_header_data
46 {
47   // Incremental linker version.
48   elfcpp::Elf_Word version;
49
50   // Numer of input files in the link.
51   elfcpp::Elf_Word input_file_count;
52
53   // Offset of command line options in .gnu_incremental_strtab.
54   elfcpp::Elf_Word command_line_offset;
55
56   // Padding.
57   elfcpp::Elf_Word reserved;
58 };
59
60 // Data stored in .gnu_incremental_input after the header for each of the
61 // Incremental_input_header_data::input_file_count input entries.
62 struct Incremental_inputs_entry_data
63 {
64   // Offset of file name in .gnu_incremental_strtab section.
65   elfcpp::Elf_Word filename_offset;
66
67   // Offset of data in .gnu_incremental_input.
68   elfcpp::Elf_Word data_offset;
69
70   // Timestamp (in seconds).
71   elfcpp::Elf_Xword timestamp_sec;
72
73   // Nano-second part of timestamp (if supported).
74   elfcpp::Elf_Word timestamp_nsec;
75
76   // Type of the input entry.
77   elfcpp::Elf_Half input_type;
78
79   // Padding.
80   elfcpp::Elf_Half reserved;
81 };
82
83 }
84
85 // Accessors.
86
87 // See internal::Incremental_input_header for fields descriptions.
88 template<int size, bool big_endian>
89 class Incremental_inputs_header_write
90 {
91  public:
92   Incremental_inputs_header_write(unsigned char *p)
93     : p_(reinterpret_cast<internal::Incremental_inputs_header_data*>(p))
94   { }
95
96   static const int data_size = sizeof(internal::Incremental_inputs_header_data);
97
98   void
99   put_version(elfcpp::Elf_Word v)
100   { this->p_->version = Convert<32, big_endian>::convert_host(v); }
101
102   void
103   put_input_file_count(elfcpp::Elf_Word v)
104   { this->p_->input_file_count = Convert<32, big_endian>::convert_host(v); }
105
106   void
107   put_command_line_offset(elfcpp::Elf_Word v)
108   { this->p_->command_line_offset = Convert<32, big_endian>::convert_host(v); }
109
110   void
111   put_reserved(elfcpp::Elf_Word v)
112   { this->p_->reserved = Convert<32, big_endian>::convert_host(v); }
113
114  private:
115   internal::Incremental_inputs_header_data* p_;
116 };
117
118 // See internal::Incremental_input_entry for fields descriptions.
119 template<int size, bool big_endian>
120 class Incremental_inputs_entry_write
121 {
122  public:
123   Incremental_inputs_entry_write(unsigned char *p)
124     : p_(reinterpret_cast<internal::Incremental_inputs_entry_data*>(p))
125   { }
126
127   static const int data_size = sizeof(internal::Incremental_inputs_entry_data);
128
129   void
130   put_filename_offset(elfcpp::Elf_Word v)
131   { this->p_->filename_offset = Convert<32, big_endian>::convert_host(v); }
132
133   void
134   put_data_offset(elfcpp::Elf_Word v)
135   { this->p_->data_offset = Convert<32, big_endian>::convert_host(v); }
136
137   void
138   put_timestamp_sec(elfcpp::Elf_Xword v)
139   { this->p_->timestamp_sec = Convert<64, big_endian>::convert_host(v); }
140
141   void
142   put_timestamp_nsec(elfcpp::Elf_Word v)
143   { this->p_->timestamp_nsec = Convert<32, big_endian>::convert_host(v); }
144
145   void
146   put_input_type(elfcpp::Elf_Word v)
147   { this->p_->input_type = Convert<32, big_endian>::convert_host(v); }
148
149   void
150   put_reserved(elfcpp::Elf_Word v)
151   { this->p_->reserved = Convert<32, big_endian>::convert_host(v); }
152
153  private:
154   internal::Incremental_inputs_entry_data* p_;
155 };
156
157 // Inform the user why we don't do an incremental link.  Not called in
158 // the obvious case of missing output file.  TODO: Is this helpful?
159
160 void
161 vexplain_no_incremental(const char* format, va_list args)
162 {
163   char* buf = NULL;
164   if (vasprintf(&buf, format, args) < 0)
165     gold_nomem();
166   gold_info(_("the link might take longer: "
167               "cannot perform incremental link: %s"), buf);
168   free(buf);
169 }
170
171 void
172 explain_no_incremental(const char* format, ...)
173 {
174   va_list args;
175   va_start(args, format);
176   vexplain_no_incremental(format, args);
177   va_end(args);
178 }
179
180 // Report an error.
181
182 void
183 Incremental_binary::error(const char* format, ...) const
184 {
185   va_list args;
186   va_start(args, format);
187   // Current code only checks if the file can be used for incremental linking,
188   // so errors shouldn't fail the build, but only result in a fallback to a
189   // full build.
190   // TODO: when we implement incremental editing of the file, we may need a
191   // flag that will cause errors to be treated seriously.
192   vexplain_no_incremental(format, args);
193   va_end(args);
194 }
195
196 template<int size, bool big_endian>
197 bool
198 Sized_incremental_binary<size, big_endian>::do_find_incremental_inputs_section(
199     Location* location)
200 {
201   unsigned int shndx = this->elf_file_.find_section_by_type(
202       elfcpp::SHT_GNU_INCREMENTAL_INPUTS);
203   if (shndx == elfcpp::SHN_UNDEF)  // Not found.
204     return false;
205   *location = this->elf_file_.section_contents(shndx);
206   return true;
207 }
208
209 namespace
210 {
211
212 // Create a Sized_incremental_binary object of the specified size and
213 // endianness. Fails if the target architecture is not supported.
214
215 template<int size, bool big_endian>
216 Incremental_binary*
217 make_sized_incremental_binary(Output_file* file,
218                               const elfcpp::Ehdr<size, big_endian>& ehdr)
219 {
220   Target* target = select_target(ehdr.get_e_machine(), size, big_endian,
221                                  ehdr.get_e_ident()[elfcpp::EI_OSABI],
222                                  ehdr.get_e_ident()[elfcpp::EI_ABIVERSION]);
223   if (target == NULL)
224     {
225       explain_no_incremental(_("unsupported ELF machine number %d"),
226                ehdr.get_e_machine());
227       return NULL;
228     }
229
230   return new Sized_incremental_binary<size, big_endian>(file, ehdr, target);
231 }
232
233 }  // End of anonymous namespace.
234
235 // Create an Incremental_binary object for FILE. Returns NULL is this is not
236 // possible, e.g. FILE is not an ELF file or has an unsupported target. FILE
237 // should be opened.
238
239 Incremental_binary*
240 open_incremental_binary(Output_file* file)
241 {
242   off_t filesize = file->filesize();
243   int want = elfcpp::Elf_recognizer::max_header_size;
244   if (filesize < want)
245     want = filesize;
246
247   const unsigned char* p = file->get_input_view(0, want);
248   if (!elfcpp::Elf_recognizer::is_elf_file(p, want))
249     {
250       explain_no_incremental(_("output is not an ELF file."));
251       return NULL;
252     }
253
254   int size;
255   bool big_endian;
256   std::string error;
257   if (!elfcpp::Elf_recognizer::is_valid_header(p, want, &size, &big_endian,
258                                                &error))
259     {
260       explain_no_incremental(error.c_str());
261       return NULL;
262     }
263
264   Incremental_binary* result = NULL;
265   if (size == 32)
266     {
267       if (big_endian)
268         {
269 #ifdef HAVE_TARGET_32_BIG
270           result = make_sized_incremental_binary<32, true>(
271               file, elfcpp::Ehdr<32, true>(p));
272 #else
273           explain_no_incremental(_("unsupported file: 32-bit, big-endian"));
274 #endif
275         }
276       else
277         {
278 #ifdef HAVE_TARGET_32_LITTLE
279           result = make_sized_incremental_binary<32, false>(
280               file, elfcpp::Ehdr<32, false>(p));
281 #else
282           explain_no_incremental(_("unsupported file: 32-bit, little-endian"));
283 #endif
284         }
285     }
286   else if (size == 64)
287     {
288       if (big_endian)
289         {
290 #ifdef HAVE_TARGET_64_BIG
291           result = make_sized_incremental_binary<64, true>(
292               file, elfcpp::Ehdr<64, true>(p));
293 #else
294           explain_no_incremental(_("unsupported file: 64-bit, big-endian"));
295 #endif
296         }
297       else
298         {
299 #ifdef HAVE_TARGET_64_LITTLE
300           result = make_sized_incremental_binary<64, false>(
301               file, elfcpp::Ehdr<64, false>(p));
302 #else
303           explain_no_incremental(_("unsupported file: 64-bit, little-endian"));
304 #endif
305         }
306     }
307   else
308     gold_unreachable();
309
310   return result;
311 }
312
313 // Analyzes the output file to check if incremental linking is possible and
314 // (to be done) what files need to be relinked.
315
316 bool
317 Incremental_checker::can_incrementally_link_output_file()
318 {
319   Output_file output(this->output_name_);
320   if (!output.open_for_modification())
321     return false;
322   Incremental_binary* binary = open_incremental_binary(&output);
323   if (binary == NULL)
324     return false;
325   Incremental_binary::Location inputs_location;
326   if (!binary->find_incremental_inputs_section(&inputs_location))
327     {
328       explain_no_incremental("no incremental data from previous build");
329       delete binary;
330       return false;
331     }
332   return true;
333 }
334
335 // Add the command line to the string table, setting
336 // command_line_key_.  In incremental builds, the command line is
337 // stored in .gnu_incremental_inputs so that the next linker run can
338 // check if the command line options didn't change.
339
340 void
341 Incremental_inputs::report_command_line(int argc, const char* const* argv)
342 {
343   // Always store 'gold' as argv[0] to avoid a full relink if the user used a
344   // different path to the linker.
345   std::string args("gold");
346   // Copied from collect_argv in main.cc.
347   for (int i = 1; i < argc; ++i)
348     {
349       // Adding/removing these options should result in a full relink.
350       if (strcmp(argv[i], "--incremental-changed") == 0
351           || strcmp(argv[i], "--incremental-unchanged") == 0
352           || strcmp(argv[i], "--incremental-unknown") == 0)
353         continue;
354
355       args.append(" '");
356       // Now append argv[i], but with all single-quotes escaped
357       const char* argpos = argv[i];
358       while (1)
359         {
360           const int len = strcspn(argpos, "'");
361           args.append(argpos, len);
362           if (argpos[len] == '\0')
363             break;
364           args.append("'\"'\"'");
365           argpos += len + 1;
366         }
367       args.append("'");
368     }
369   this->strtab_->add(args.c_str(), true, &this->command_line_key_);
370 }
371
372 // Record that the input argument INPUT is an achive ARCHIVE.  This is
373 // called by Read_symbols after finding out the type of the file.
374
375 void
376 Incremental_inputs::report_archive(const Input_argument* input,
377                                    Archive* archive)
378 {
379   Hold_lock hl(*this->lock_);
380
381   Input_info info;
382   info.type = INCREMENTAL_INPUT_ARCHIVE;
383   info.archive = archive;
384   info.mtime = archive->file().get_mtime();
385   this->inputs_map_.insert(std::make_pair(input, info));
386 }
387
388 // Record that the input argument INPUT is an object OBJ.  This is
389 // called by Read_symbols after finding out the type of the file.
390
391 void
392 Incremental_inputs::report_object(const Input_argument* input,
393                                   Object* obj)
394 {
395   Hold_lock hl(*this->lock_);
396
397   Input_info info;
398   info.type = (obj->is_dynamic()
399                ? INCREMENTAL_INPUT_SHARED_LIBRARY
400                : INCREMENTAL_INPUT_OBJECT);
401   info.object = obj;
402   info.mtime = obj->input_file()->file().get_mtime();
403   this->inputs_map_.insert(std::make_pair(input, info));
404 }
405
406 // Record that the input argument INPUT is an script SCRIPT.  This is
407 // called by read_script after parsing the script and reading the list
408 // of inputs added by this script.
409
410 void
411 Incremental_inputs::report_script(const Input_argument* input,
412                                   Timespec mtime,
413                                   Script_info* script)
414 {
415   Hold_lock hl(*this->lock_);
416
417   Input_info info;
418   info.type = INCREMENTAL_INPUT_SCRIPT;
419   info.script = script;
420   info.mtime = mtime;
421   this->inputs_map_.insert(std::make_pair(input, info));
422 }
423
424 // Compute indexes in the order in which the inputs should appear in
425 // .gnu_incremental_inputs.  This needs to be done after all the
426 // scripts are parsed.  The function is first called for the command
427 // line inputs arguments and may call itself recursively for e.g. a
428 // list of elements of a group or a list of inputs added by a script.
429 // The [BEGIN; END) interval to analyze and *INDEX is the current
430 // value of the index (that will be updated).
431
432 void
433 Incremental_inputs::finalize_inputs(
434     Input_argument_list::const_iterator begin,
435     Input_argument_list::const_iterator end,
436     unsigned int* index)
437 {
438   for (Input_argument_list::const_iterator p = begin; p != end; ++p)
439     {
440       if (p->is_group())
441         {
442           finalize_inputs(p->group()->begin(), p->group()->end(), index);
443           continue;
444         }
445
446       Inputs_info_map::iterator it = this->inputs_map_.find(&(*p));
447       // TODO: turn it into an assert when the code will be more stable.
448       if (it == this->inputs_map_.end())
449         {
450           gold_error("internal error: %s: incremental build info not provided",
451                      (p->is_file() ? p->file().name() : "[group]"));
452           continue;
453         }
454       Input_info* info = &it->second;
455       info->index = *index;
456       (*index)++;
457       this->strtab_->add(p->file().name(), false, &info->filename_key);
458       if (info->type == INCREMENTAL_INPUT_SCRIPT)
459         {
460           finalize_inputs(info->script->inputs()->begin(),
461                           info->script->inputs()->end(),
462                           index);
463         }
464     }
465 }
466
467 // Finalize the incremental link information.  Called from
468 // Layout::finalize.
469
470 void
471 Incremental_inputs::finalize()
472 {
473   unsigned int index = 0;
474   finalize_inputs(this->inputs_->begin(), this->inputs_->end(), &index);
475
476   // Sanity check.
477   for (Inputs_info_map::const_iterator p = this->inputs_map_.begin();
478        p != this->inputs_map_.end();
479        ++p)
480     {
481       gold_assert(p->second.filename_key != 0);
482     }
483
484   this->strtab_->set_string_offsets();
485 }
486
487 // Create the content of the .gnu_incremental_inputs section.
488
489 Output_section_data*
490 Incremental_inputs::create_incremental_inputs_section_data()
491 {
492   switch (parameters->size_and_endianness())
493     {
494 #ifdef HAVE_TARGET_32_LITTLE
495     case Parameters::TARGET_32_LITTLE:
496       return this->sized_create_inputs_section_data<32, false>();
497 #endif
498 #ifdef HAVE_TARGET_32_BIG
499     case Parameters::TARGET_32_BIG:
500       return this->sized_create_inputs_section_data<32, true>();
501 #endif
502 #ifdef HAVE_TARGET_64_LITTLE
503     case Parameters::TARGET_64_LITTLE:
504       return this->sized_create_inputs_section_data<64, false>();
505 #endif
506 #ifdef HAVE_TARGET_64_BIG
507     case Parameters::TARGET_64_BIG:
508       return this->sized_create_inputs_section_data<64, true>();
509 #endif
510     default:
511       gold_unreachable();
512     }
513 }
514
515 // Sized creation of .gnu_incremental_inputs section.
516
517 template<int size, bool big_endian>
518 Output_section_data*
519 Incremental_inputs::sized_create_inputs_section_data()
520 {
521   const int entry_size =
522       Incremental_inputs_entry_write<size, big_endian>::data_size;
523   const int header_size =
524       Incremental_inputs_header_write<size, big_endian>::data_size;
525
526   unsigned int sz = header_size + entry_size * this->inputs_map_.size();
527   unsigned char* buffer = new unsigned char[sz];
528   unsigned char* inputs_base = buffer + header_size;
529
530   Incremental_inputs_header_write<size, big_endian> header_writer(buffer);
531   gold_assert(this->command_line_key_ > 0);
532   int cmd_offset = this->strtab_->get_offset_from_key(this->command_line_key_);
533
534   header_writer.put_version(INCREMENTAL_LINK_VERSION);
535   header_writer.put_input_file_count(this->inputs_map_.size());
536   header_writer.put_command_line_offset(cmd_offset);
537   header_writer.put_reserved(0);
538
539   for (Inputs_info_map::const_iterator it = this->inputs_map_.begin();
540        it != this->inputs_map_.end();
541        ++it)
542     {
543       gold_assert(it->second.index < this->inputs_map_.size());
544
545       unsigned char* entry_buffer =
546           inputs_base + it->second.index * entry_size;
547       Incremental_inputs_entry_write<size, big_endian> entry(entry_buffer);
548       int filename_offset =
549           this->strtab_->get_offset_from_key(it->second.filename_key);
550       entry.put_filename_offset(filename_offset);
551       // TODO: add per input data and timestamp.  Currently we store
552       // an out-of-bounds offset for future version of gold to reject
553       // such an incremental_inputs section.
554       entry.put_data_offset(0xffffffff);
555       entry.put_timestamp_sec(it->second.mtime.seconds);
556       entry.put_timestamp_nsec(it->second.mtime.nanoseconds);
557       entry.put_input_type(it->second.type);
558       entry.put_reserved(0);
559     }
560
561   return new Output_data_const_buffer(buffer, sz, 8,
562                                       "** incremental link inputs list");
563 }
564
565 // Instantiate the templates we need.
566
567 #ifdef HAVE_TARGET_32_LITTLE
568 template
569 class Sized_incremental_binary<32, false>;
570 #endif
571
572 #ifdef HAVE_TARGET_32_BIG
573 template
574 class Sized_incremental_binary<32, true>;
575 #endif
576
577 #ifdef HAVE_TARGET_64_LITTLE
578 template
579 class Sized_incremental_binary<64, false>;
580 #endif
581
582 #ifdef HAVE_TARGET_64_BIG
583 template
584 class Sized_incremental_binary<64, true>;
585 #endif
586
587 } // End namespace gold.