From Craig Silverstein: rename option functions for future option
[external/binutils.git] / gold / fileread.cc
1 // fileread.cc -- read files for gold
2
3 // Copyright 2006, 2007 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 <cstring>
26 #include <cerrno>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <sys/mman.h>
30 #include <sys/uio.h>
31 #include "filenames.h"
32
33 #include "parameters.h"
34 #include "options.h"
35 #include "dirsearch.h"
36 #include "target.h"
37 #include "binary.h"
38 #include "fileread.h"
39
40 namespace gold
41 {
42
43 // Class File_read::View.
44
45 File_read::View::~View()
46 {
47   gold_assert(!this->is_locked());
48   if (!this->mapped_)
49     delete[] this->data_;
50   else
51     {
52       if (::munmap(const_cast<unsigned char*>(this->data_), this->size_) != 0)
53         gold_warning(_("munmap failed: %s"), strerror(errno));
54
55       File_read::current_mapped_bytes -= this->size_;
56     }
57 }
58
59 void
60 File_read::View::lock()
61 {
62   ++this->lock_count_;
63 }
64
65 void
66 File_read::View::unlock()
67 {
68   gold_assert(this->lock_count_ > 0);
69   --this->lock_count_;
70 }
71
72 bool
73 File_read::View::is_locked()
74 {
75   return this->lock_count_ > 0;
76 }
77
78 // Class File_read.
79
80 // The File_read static variables.
81 unsigned long long File_read::total_mapped_bytes;
82 unsigned long long File_read::current_mapped_bytes;
83 unsigned long long File_read::maximum_mapped_bytes;
84
85 // The File_read class is designed to support file descriptor caching,
86 // but this is not currently implemented.
87
88 File_read::~File_read()
89 {
90   gold_assert(this->token_.is_writable());
91   if (this->descriptor_ >= 0)
92     {
93       if (close(this->descriptor_) < 0)
94         gold_warning(_("close of %s failed: %s"),
95                      this->name_.c_str(), strerror(errno));
96       this->descriptor_ = -1;
97     }
98   this->name_.clear();
99   this->clear_views(true);
100 }
101
102 // Open the file.
103
104 bool
105 File_read::open(const Task* task, const std::string& name)
106 {
107   gold_assert(this->token_.is_writable()
108               && this->descriptor_ < 0
109               && this->name_.empty());
110   this->name_ = name;
111
112   this->descriptor_ = ::open(this->name_.c_str(), O_RDONLY);
113
114   if (this->descriptor_ >= 0)
115     {
116       struct stat s;
117       if (::fstat(this->descriptor_, &s) < 0)
118         gold_error(_("%s: fstat failed: %s"),
119                    this->name_.c_str(), strerror(errno));
120       this->size_ = s.st_size;
121     }
122
123   this->token_.add_writer(task);
124
125   return this->descriptor_ >= 0;
126 }
127
128 // Open the file with the contents in memory.
129
130 bool
131 File_read::open(const Task* task, const std::string& name,
132                 const unsigned char* contents, off_t size)
133 {
134   gold_assert(this->token_.is_writable()
135               && this->descriptor_ < 0
136               && this->name_.empty());
137   this->name_ = name;
138   this->contents_ = contents;
139   this->size_ = size;
140   this->token_.add_writer(task);
141   return true;
142 }
143
144 // Release the file.  This is called when we are done with the file in
145 // a Task.
146
147 void
148 File_read::release()
149 {
150   gold_assert(this->is_locked());
151
152   File_read::total_mapped_bytes += this->mapped_bytes_;
153   File_read::current_mapped_bytes += this->mapped_bytes_;
154   this->mapped_bytes_ = 0;
155   if (File_read::current_mapped_bytes > File_read::maximum_mapped_bytes)
156     File_read::maximum_mapped_bytes = File_read::current_mapped_bytes;
157
158   this->clear_views(false);
159
160   this->released_ = true;
161 }
162
163 // Lock the file.
164
165 void
166 File_read::lock(const Task* task)
167 {
168   gold_assert(this->released_);
169   this->token_.add_writer(task);
170   this->released_ = false;
171 }
172
173 // Unlock the file.
174
175 void
176 File_read::unlock(const Task* task)
177 {
178   this->release();
179   this->token_.remove_writer(task);
180 }
181
182 // Return whether the file is locked.
183
184 bool
185 File_read::is_locked() const
186 {
187   if (!this->token_.is_writable())
188     return true;
189   // The file is not locked, so it should have been released.
190   gold_assert(this->released_);
191   return false;
192 }
193
194 // See if we have a view which covers the file starting at START for
195 // SIZE bytes.  Return a pointer to the View if found, NULL if not.
196
197 inline File_read::View*
198 File_read::find_view(off_t start, section_size_type size) const
199 {
200   off_t page = File_read::page_offset(start);
201
202   Views::const_iterator p = this->views_.lower_bound(page);
203   if (p == this->views_.end() || p->first > page)
204     {
205       if (p == this->views_.begin())
206         return NULL;
207       --p;
208     }
209
210   if (p->second->start() + static_cast<off_t>(p->second->size())
211       < start + static_cast<off_t>(size))
212     return NULL;
213
214   p->second->set_accessed();
215
216   return p->second;
217 }
218
219 // Read SIZE bytes from the file starting at offset START.  Read into
220 // the buffer at P.
221
222 void
223 File_read::do_read(off_t start, section_size_type size, void* p) const
224 {
225   ssize_t bytes;
226   if (this->contents_ != NULL)
227     {
228       bytes = this->size_ - start;
229       if (static_cast<section_size_type>(bytes) >= size)
230         {
231           memcpy(p, this->contents_ + start, size);
232           return;
233         }
234     }
235   else
236     {
237       bytes = ::pread(this->descriptor_, p, size, start);
238       if (static_cast<section_size_type>(bytes) == size)
239         return;
240
241       if (bytes < 0)
242         {
243           gold_fatal(_("%s: pread failed: %s"),
244                      this->filename().c_str(), strerror(errno));
245           return;
246         }
247     }
248
249   gold_fatal(_("%s: file too short: read only %lld of %lld bytes at %lld"),
250              this->filename().c_str(),
251              static_cast<long long>(bytes),
252              static_cast<long long>(size),
253              static_cast<long long>(start));
254 }
255
256 // Read data from the file.
257
258 void
259 File_read::read(off_t start, section_size_type size, void* p) const
260 {
261   const File_read::View* pv = this->find_view(start, size);
262   if (pv != NULL)
263     {
264       memcpy(p, pv->data() + (start - pv->start()), size);
265       return;
266     }
267
268   this->do_read(start, size, p);
269 }
270
271 // Find an existing view or make a new one.
272
273 File_read::View*
274 File_read::find_or_make_view(off_t start, section_size_type size, bool cache)
275 {
276   gold_assert(!this->token_.is_writable());
277   this->released_ = false;
278
279   File_read::View* v = this->find_view(start, size);
280   if (v != NULL)
281     {
282       if (cache)
283         v->set_cache();
284       return v;
285     }
286
287   off_t poff = File_read::page_offset(start);
288
289   File_read::View* const vnull = NULL;
290   std::pair<Views::iterator, bool> ins =
291     this->views_.insert(std::make_pair(poff, vnull));
292
293   if (!ins.second)
294     {
295       // There was an existing view at this offset.  It must not be
296       // large enough.  We can't delete it here, since something might
297       // be using it; put it on a list to be deleted when the file is
298       // unlocked.
299       v = ins.first->second;
300       gold_assert(v->size() - (start - v->start()) < size);
301       if (v->should_cache())
302         cache = true;
303       v->clear_cache();
304       this->saved_views_.push_back(v);
305     }
306
307   // We need to map data from the file.
308
309   section_size_type psize = File_read::pages(size + (start - poff));
310
311   if (poff + static_cast<off_t>(psize) >= this->size_)
312     {
313       psize = this->size_ - poff;
314       gold_assert(psize >= size);
315     }
316
317   if (this->contents_ != NULL)
318     {
319       unsigned char* p = new unsigned char[psize];
320       this->do_read(poff, psize, p);
321       v = new File_read::View(poff, psize, p, cache, false);
322     }
323   else
324     {
325       void* p = ::mmap(NULL, psize, PROT_READ, MAP_PRIVATE,
326                        this->descriptor_, poff);
327       if (p == MAP_FAILED)
328         gold_fatal(_("%s: mmap offset %lld size %lld failed: %s"),
329                    this->filename().c_str(),
330                    static_cast<long long>(poff),
331                    static_cast<long long>(psize),
332                    strerror(errno));
333
334       this->mapped_bytes_ += psize;
335
336       const unsigned char* pbytes = static_cast<const unsigned char*>(p);
337       v = new File_read::View(poff, psize, pbytes, cache, true);
338     }
339
340   ins.first->second = v;
341   return v;
342 }
343
344 // Get a view into the file.
345
346 const unsigned char*
347 File_read::get_view(off_t start, section_size_type size, bool cache)
348 {
349   File_read::View* pv = this->find_or_make_view(start, size, cache);
350   return pv->data() + (start - pv->start());
351 }
352
353 File_view*
354 File_read::get_lasting_view(off_t start, section_size_type size, bool cache)
355 {
356   File_read::View* pv = this->find_or_make_view(start, size, cache);
357   pv->lock();
358   return new File_view(*this, pv, pv->data() + (start - pv->start()));
359 }
360
361 // Use readv to read COUNT entries from RM starting at START.  BASE
362 // must be added to all file offsets in RM.
363
364 void
365 File_read::do_readv(off_t base, const Read_multiple& rm, size_t start,
366                     size_t count)
367 {
368   unsigned char discard[File_read::page_size];
369   iovec iov[File_read::max_readv_entries * 2];
370   size_t iov_index = 0;
371
372   off_t first_offset = rm[start].file_offset;
373   off_t last_offset = first_offset;
374   ssize_t want = 0;
375   for (size_t i = 0; i < count; ++i)
376     {
377       const Read_multiple_entry& i_entry(rm[start + i]);
378
379       if (i_entry.file_offset > last_offset)
380         {
381           size_t skip = i_entry.file_offset - last_offset;
382           gold_assert(skip <= sizeof discard);
383
384           iov[iov_index].iov_base = discard;
385           iov[iov_index].iov_len = skip;
386           ++iov_index;
387
388           want += skip;
389         }
390
391       iov[iov_index].iov_base = i_entry.buffer;
392       iov[iov_index].iov_len = i_entry.size;
393       ++iov_index;
394
395       want += i_entry.size;
396
397       last_offset = i_entry.file_offset + i_entry.size;
398     }
399
400   gold_assert(iov_index < sizeof iov / sizeof iov[0]);
401
402   if (::lseek(this->descriptor_, base + first_offset, SEEK_SET) < 0)
403     gold_fatal(_("%s: lseek failed: %s"),
404                this->filename().c_str(), strerror(errno));
405
406   ssize_t got = ::readv(this->descriptor_, iov, iov_index);
407
408   if (got < 0)
409     gold_fatal(_("%s: readv failed: %s"),
410                this->filename().c_str(), strerror(errno));
411   if (got != want)
412     gold_fatal(_("%s: file too short: read only %zd of %zd bytes at %lld"),
413                this->filename().c_str(),
414                got, want, static_cast<long long>(base + first_offset));
415 }
416
417 // Read several pieces of data from the file.
418
419 void
420 File_read::read_multiple(off_t base, const Read_multiple& rm)
421 {
422   size_t count = rm.size();
423   size_t i = 0;
424   while (i < count)
425     {
426       // Find up to MAX_READV_ENTRIES consecutive entries which are
427       // less than one page apart.
428       const Read_multiple_entry& i_entry(rm[i]);
429       off_t i_off = i_entry.file_offset;
430       off_t end_off = i_off + i_entry.size;
431       size_t j;
432       for (j = i + 1; j < count; ++j)
433         {
434           if (j - i >= File_read::max_readv_entries)
435             break;
436           const Read_multiple_entry& j_entry(rm[j]);
437           off_t j_off = j_entry.file_offset;
438           gold_assert(j_off >= end_off);
439           off_t j_end_off = j_off + j_entry.size;
440           if (j_end_off - end_off >= File_read::page_size)
441             break;
442           end_off = j_end_off;
443         }
444
445       if (j == i + 1)
446         this->read(base + i_off, i_entry.size, i_entry.buffer);
447       else
448         {
449           File_read::View* view = this->find_view(base + i_off,
450                                                   end_off - i_off);
451           if (view == NULL)
452             this->do_readv(base, rm, i, j - i);
453           else
454             {
455               const unsigned char* v = (view->data()
456                                         + (base + i_off - view->start()));
457               for (size_t k = i; k < j; ++k)
458                 {
459                   const Read_multiple_entry& k_entry(rm[k]);
460                   gold_assert((convert_to_section_size_type(k_entry.file_offset
461                                                            - i_off)
462                                + k_entry.size)
463                               <= convert_to_section_size_type(end_off
464                                                               - i_off));
465                   memcpy(k_entry.buffer,
466                          v + (k_entry.file_offset - i_off),
467                          k_entry.size);
468                 }
469             }
470         }
471
472       i = j;
473     }
474 }
475
476 // Mark all views as no longer cached.
477
478 void
479 File_read::clear_view_cache_marks()
480 {
481   // Just ignore this if there are multiple objects associated with
482   // the file.  Otherwise we will wind up uncaching and freeing some
483   // views for other objects.
484   if (this->object_count_ > 1)
485     return;
486
487   for (Views::iterator p = this->views_.begin();
488        p != this->views_.end();
489        ++p)
490     p->second->clear_cache();
491   for (Saved_views::iterator p = this->saved_views_.begin();
492        p != this->saved_views_.end();
493        ++p)
494     (*p)->clear_cache();
495 }
496
497 // Remove all the file views.  For a file which has multiple
498 // associated objects (i.e., an archive), we keep accessed views
499 // around until next time, in the hopes that they will be useful for
500 // the next object.
501
502 void
503 File_read::clear_views(bool destroying)
504 {
505   Views::iterator p = this->views_.begin();
506   while (p != this->views_.end())
507     {
508       bool should_delete;
509       if (p->second->is_locked())
510         should_delete = false;
511       else if (destroying)
512         should_delete = true;
513       else if (p->second->should_cache())
514         should_delete = false;
515       else if (this->object_count_ > 1 && p->second->accessed())
516         should_delete = false;
517       else
518         should_delete = true;
519
520       if (should_delete)
521         {
522           delete p->second;
523
524           // map::erase invalidates only the iterator to the deleted
525           // element.
526           Views::iterator pe = p;
527           ++p;
528           this->views_.erase(pe);
529         }
530       else
531         {
532           gold_assert(!destroying);
533           p->second->clear_accessed();
534           ++p;
535         }
536     }
537
538   Saved_views::iterator q = this->saved_views_.begin();
539   while (q != this->saved_views_.end())
540     {
541       if (!(*q)->is_locked())
542         {
543           delete *q;
544           q = this->saved_views_.erase(q);
545         }
546       else
547         {
548           gold_assert(!destroying);
549           ++q;
550         }
551     }
552 }
553
554 // Print statistical information to stderr.  This is used for --stats.
555
556 void
557 File_read::print_stats()
558 {
559   fprintf(stderr, _("%s: total bytes mapped for read: %llu\n"),
560           program_name, File_read::total_mapped_bytes);
561   fprintf(stderr, _("%s: maximum bytes mapped for read at one time: %llu\n"),
562           program_name, File_read::maximum_mapped_bytes);
563 }
564
565 // Class File_view.
566
567 File_view::~File_view()
568 {
569   gold_assert(this->file_.is_locked());
570   this->view_->unlock();
571 }
572
573 // Class Input_file.
574
575 // Create a file for testing.
576
577 Input_file::Input_file(const Task* task, const char* name,
578                        const unsigned char* contents, off_t size)
579   : file_()
580 {
581   this->input_argument_ =
582     new Input_file_argument(name, false, "", false,
583                             Position_dependent_options());
584   bool ok = file_.open(task, name, contents, size);
585   gold_assert(ok);
586 }
587
588 // Return the position dependent options in force for this file.
589
590 const Position_dependent_options&
591 Input_file::options() const
592 {
593   return this->input_argument_->options();
594 }
595
596 // Return the name given by the user.  For -lc this will return "c".
597
598 const char*
599 Input_file::name() const
600 {
601   return this->input_argument_->name();
602 }
603
604 // Return whether we are only reading symbols.
605
606 bool
607 Input_file::just_symbols() const
608 {
609   return this->input_argument_->just_symbols();
610 }
611
612 // Open the file.
613
614 // If the filename is not absolute, we assume it is in the current
615 // directory *except* when:
616 //    A) input_argument_->is_lib() is true; or
617 //    B) input_argument_->extra_search_path() is not empty.
618 // In both cases, we look in extra_search_path + library_path to find
619 // the file location, rather than the current directory.
620
621 bool
622 Input_file::open(const General_options& options, const Dirsearch& dirpath,
623                  const Task* task)
624 {
625   std::string name;
626
627   // Case 1: name is an absolute file, just try to open it
628   // Case 2: name is relative but is_lib is false and extra_search_path
629   //         is empty
630   if (IS_ABSOLUTE_PATH (this->input_argument_->name())
631       || (!this->input_argument_->is_lib()
632           && this->input_argument_->extra_search_path() == NULL))
633     {
634       name = this->input_argument_->name();
635       this->found_name_ = name;
636     }
637   // Case 3: is_lib is true
638   else if (this->input_argument_->is_lib())
639     {
640       // We don't yet support extra_search_path with -l.
641       gold_assert(this->input_argument_->extra_search_path() == NULL);
642       std::string n1("lib");
643       n1 += this->input_argument_->name();
644       std::string n2;
645       if (options.is_static()
646           || this->input_argument_->options().Bstatic())
647         n1 += ".a";
648       else
649         {
650           n2 = n1 + ".a";
651           n1 += ".so";
652         }
653       name = dirpath.find(n1, n2, &this->is_in_sysroot_);
654       if (name.empty())
655         {
656           gold_error(_("cannot find -l%s"),
657                      this->input_argument_->name());
658           return false;
659         }
660       if (n2.empty() || name[name.length() - 1] == 'o')
661         this->found_name_ = n1;
662       else
663         this->found_name_ = n2;
664     }
665   // Case 4: extra_search_path is not empty
666   else
667     {
668       gold_assert(this->input_argument_->extra_search_path() != NULL);
669
670       // First, check extra_search_path.
671       name = this->input_argument_->extra_search_path();
672       if (!IS_DIR_SEPARATOR (name[name.length() - 1]))
673         name += '/';
674       name += this->input_argument_->name();
675       struct stat dummy_stat;
676       if (::stat(name.c_str(), &dummy_stat) < 0)
677         {
678           // extra_search_path failed, so check the normal search-path.
679           name = dirpath.find(this->input_argument_->name(), "",
680                               &this->is_in_sysroot_);
681           if (name.empty())
682             {
683               gold_error(_("cannot find %s"),
684                          this->input_argument_->name());
685               return false;
686             }
687         }
688       this->found_name_ = this->input_argument_->name();
689     }
690
691   // Now that we've figured out where the file lives, try to open it.
692
693   General_options::Object_format format =
694     this->input_argument_->options().format();
695   bool ok;
696   if (format == General_options::OBJECT_FORMAT_ELF)
697     ok = this->file_.open(task, name);
698   else
699     {
700       gold_assert(format == General_options::OBJECT_FORMAT_BINARY);
701       ok = this->open_binary(options, task, name);
702     }
703
704   if (!ok)
705     {
706       gold_error(_("cannot open %s: %s"),
707                  name.c_str(), strerror(errno));
708       return false;
709     }
710
711   return true;
712 }
713
714 // Open a file for --format binary.
715
716 bool
717 Input_file::open_binary(const General_options& options,
718                         const Task* task, const std::string& name)
719 {
720   // In order to open a binary file, we need machine code, size, and
721   // endianness.  We may not have a valid target at this point, in
722   // which case we use the default target.
723   Target* target;
724   if (parameters->is_target_valid())
725     target = parameters->target();
726   else
727     target = options.default_target();
728
729   Binary_to_elf binary_to_elf(target->machine_code(),
730                               target->get_size(),
731                               target->is_big_endian(),
732                               name);
733   if (!binary_to_elf.convert(task))
734     return false;
735   return this->file_.open(task, name, binary_to_elf.converted_data_leak(),
736                           binary_to_elf.converted_size());
737 }
738
739 } // End namespace gold.