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