Merge branch 'vendor/TNFTP'
[dragonfly.git] / contrib / binutils-2.24 / gold / fileread.cc
1 // fileread.cc -- read files for gold
2
3 // Copyright 2006, 2007, 2008, 2009, 2010, 2011, 2012
4 // Free Software Foundation, Inc.
5 // Written by Ian Lance Taylor <iant@google.com>.
6
7 // This file is part of gold.
8
9 // This program is free software; you can redistribute it and/or modify
10 // it under the terms of the GNU General Public License as published by
11 // the Free Software Foundation; either version 3 of the License, or
12 // (at your option) any later version.
13
14 // This program is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 // GNU General Public License for more details.
18
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
22 // MA 02110-1301, USA.
23
24 #include "gold.h"
25
26 #include <cstring>
27 #include <cerrno>
28 #include <climits>
29 #include <fcntl.h>
30 #include <unistd.h>
31
32 #ifdef HAVE_SYS_MMAN_H
33 #include <sys/mman.h>
34 #endif
35
36 #ifdef HAVE_READV
37 #include <sys/uio.h>
38 #endif
39
40 #include <sys/stat.h>
41 #include "filenames.h"
42
43 #include "debug.h"
44 #include "parameters.h"
45 #include "options.h"
46 #include "dirsearch.h"
47 #include "target.h"
48 #include "binary.h"
49 #include "descriptors.h"
50 #include "gold-threads.h"
51 #include "fileread.h"
52
53 // For systems without mmap support.
54 #ifndef HAVE_MMAP
55 # define mmap gold_mmap
56 # define munmap gold_munmap
57 # ifndef MAP_FAILED
58 #  define MAP_FAILED (reinterpret_cast<void*>(-1))
59 # endif
60 # ifndef PROT_READ
61 #  define PROT_READ 0
62 # endif
63 # ifndef MAP_PRIVATE
64 #  define MAP_PRIVATE 0
65 # endif
66
67 # ifndef ENOSYS
68 #  define ENOSYS EINVAL
69 # endif
70
71 static void *
72 gold_mmap(void *, size_t, int, int, int, off_t)
73 {
74   errno = ENOSYS;
75   return MAP_FAILED;
76 }
77
78 static int
79 gold_munmap(void *, size_t)
80 {
81   errno = ENOSYS;
82   return -1;
83 }
84
85 #endif
86
87 #ifndef HAVE_READV
88 struct iovec { void* iov_base; size_t iov_len; };
89 ssize_t
90 readv(int, const iovec*, int)
91 {
92   gold_unreachable();
93 }
94 #endif
95
96 namespace gold
97 {
98
99 // Get the last modified time of an unopened file.
100
101 bool
102 get_mtime(const char* filename, Timespec* mtime)
103 {
104   struct stat file_stat;
105
106   if (stat(filename, &file_stat) < 0)
107     return false;
108 #ifdef HAVE_STAT_ST_MTIM
109   mtime->seconds = file_stat.st_mtim.tv_sec;
110   mtime->nanoseconds = file_stat.st_mtim.tv_nsec;
111 #else
112   mtime->seconds = file_stat.st_mtime;
113   mtime->nanoseconds = 0;
114 #endif
115   return true;
116 }
117
118 // Class File_read.
119
120 // A lock for the File_read static variables.
121 static Lock* file_counts_lock = NULL;
122 static Initialize_lock file_counts_initialize_lock(&file_counts_lock);
123
124 // The File_read static variables.
125 unsigned long long File_read::total_mapped_bytes;
126 unsigned long long File_read::current_mapped_bytes;
127 unsigned long long File_read::maximum_mapped_bytes;
128
129 // Class File_read::View.
130
131 File_read::View::~View()
132 {
133   gold_assert(!this->is_locked());
134   switch (this->data_ownership_)
135     {
136     case DATA_ALLOCATED_ARRAY:
137       free(const_cast<unsigned char*>(this->data_));
138       break;
139     case DATA_MMAPPED:
140       if (::munmap(const_cast<unsigned char*>(this->data_), this->size_) != 0)
141         gold_warning(_("munmap failed: %s"), strerror(errno));
142       if (!parameters->options_valid() || parameters->options().stats())
143         {
144           file_counts_initialize_lock.initialize();
145           Hold_optional_lock hl(file_counts_lock);
146           File_read::current_mapped_bytes -= this->size_;
147         }
148       break;
149     case DATA_NOT_OWNED:
150       break;
151     default:
152       gold_unreachable();
153     }
154 }
155
156 void
157 File_read::View::lock()
158 {
159   ++this->lock_count_;
160 }
161
162 void
163 File_read::View::unlock()
164 {
165   gold_assert(this->lock_count_ > 0);
166   --this->lock_count_;
167 }
168
169 bool
170 File_read::View::is_locked()
171 {
172   return this->lock_count_ > 0;
173 }
174
175 // Class File_read.
176
177 File_read::~File_read()
178 {
179   gold_assert(this->token_.is_writable());
180   if (this->is_descriptor_opened_)
181     {
182       release_descriptor(this->descriptor_, true);
183       this->descriptor_ = -1;
184       this->is_descriptor_opened_ = false;
185     }
186   this->name_.clear();
187   this->clear_views(CLEAR_VIEWS_ALL);
188 }
189
190 // Open the file.
191
192 bool
193 File_read::open(const Task* task, const std::string& name)
194 {
195   gold_assert(this->token_.is_writable()
196               && this->descriptor_ < 0
197               && !this->is_descriptor_opened_
198               && this->name_.empty());
199   this->name_ = name;
200
201   this->descriptor_ = open_descriptor(-1, this->name_.c_str(),
202                                       O_RDONLY);
203
204   if (this->descriptor_ >= 0)
205     {
206       this->is_descriptor_opened_ = true;
207       struct stat s;
208       if (::fstat(this->descriptor_, &s) < 0)
209         gold_error(_("%s: fstat failed: %s"),
210                    this->name_.c_str(), strerror(errno));
211       this->size_ = s.st_size;
212       gold_debug(DEBUG_FILES, "Attempt to open %s succeeded",
213                  this->name_.c_str());
214       this->token_.add_writer(task);
215     }
216
217   return this->descriptor_ >= 0;
218 }
219
220 // Open the file with the contents in memory.
221
222 bool
223 File_read::open(const Task* task, const std::string& name,
224                 const unsigned char* contents, off_t size)
225 {
226   gold_assert(this->token_.is_writable()
227               && this->descriptor_ < 0
228               && !this->is_descriptor_opened_
229               && this->name_.empty());
230   this->name_ = name;
231   this->whole_file_view_ = new View(0, size, contents, 0, false,
232                                     View::DATA_NOT_OWNED);
233   this->add_view(this->whole_file_view_);
234   this->size_ = size;
235   this->token_.add_writer(task);
236   return true;
237 }
238
239 // Reopen a descriptor if necessary.
240
241 void
242 File_read::reopen_descriptor()
243 {
244   if (!this->is_descriptor_opened_)
245     {
246       this->descriptor_ = open_descriptor(this->descriptor_,
247                                           this->name_.c_str(),
248                                           O_RDONLY);
249       if (this->descriptor_ < 0)
250         gold_fatal(_("could not reopen file %s"), this->name_.c_str());
251       this->is_descriptor_opened_ = true;
252     }
253 }
254
255 // Release the file.  This is called when we are done with the file in
256 // a Task.
257
258 void
259 File_read::release()
260 {
261   gold_assert(this->is_locked());
262
263   if (!parameters->options_valid() || parameters->options().stats())
264     {
265       file_counts_initialize_lock.initialize();
266       Hold_optional_lock hl(file_counts_lock);
267       File_read::total_mapped_bytes += this->mapped_bytes_;
268       File_read::current_mapped_bytes += this->mapped_bytes_;
269       if (File_read::current_mapped_bytes > File_read::maximum_mapped_bytes)
270         File_read::maximum_mapped_bytes = File_read::current_mapped_bytes;
271     }
272
273   this->mapped_bytes_ = 0;
274
275   // Only clear views if there is only one attached object.  Otherwise
276   // we waste time trying to clear cached archive views.  Similarly
277   // for releasing the descriptor.
278   if (this->object_count_ <= 1)
279     {
280       this->clear_views(CLEAR_VIEWS_NORMAL);
281       if (this->is_descriptor_opened_)
282         {
283           release_descriptor(this->descriptor_, false);
284           this->is_descriptor_opened_ = false;
285         }
286     }
287
288   this->released_ = true;
289 }
290
291 // Lock the file.
292
293 void
294 File_read::lock(const Task* task)
295 {
296   gold_assert(this->released_);
297   this->token_.add_writer(task);
298   this->released_ = false;
299 }
300
301 // Unlock the file.
302
303 void
304 File_read::unlock(const Task* task)
305 {
306   this->release();
307   this->token_.remove_writer(task);
308 }
309
310 // Return whether the file is locked.
311
312 bool
313 File_read::is_locked() const
314 {
315   if (!this->token_.is_writable())
316     return true;
317   // The file is not locked, so it should have been released.
318   gold_assert(this->released_);
319   return false;
320 }
321
322 // See if we have a view which covers the file starting at START for
323 // SIZE bytes.  Return a pointer to the View if found, NULL if not.
324 // If BYTESHIFT is not -1U, the returned View must have the specified
325 // byte shift; otherwise, it may have any byte shift.  If VSHIFTED is
326 // not NULL, this sets *VSHIFTED to a view which would have worked if
327 // not for the requested BYTESHIFT.
328
329 inline File_read::View*
330 File_read::find_view(off_t start, section_size_type size,
331                      unsigned int byteshift, File_read::View** vshifted) const
332 {
333   gold_assert(start <= this->size_
334               && (static_cast<unsigned long long>(size)
335                   <= static_cast<unsigned long long>(this->size_ - start)));
336
337   if (vshifted != NULL)
338     *vshifted = NULL;
339
340   // If we have the whole file mmapped, and the alignment is right,
341   // we can return it.
342   if (this->whole_file_view_)
343     if (byteshift == -1U || byteshift == 0)
344       return this->whole_file_view_;
345
346   off_t page = File_read::page_offset(start);
347
348   unsigned int bszero = 0;
349   Views::const_iterator p = this->views_.upper_bound(std::make_pair(page - 1,
350                                                                     bszero));
351
352   while (p != this->views_.end() && p->first.first <= page)
353     {
354       if (p->second->start() <= start
355           && (p->second->start() + static_cast<off_t>(p->second->size())
356               >= start + static_cast<off_t>(size)))
357         {
358           if (byteshift == -1U || byteshift == p->second->byteshift())
359             {
360               p->second->set_accessed();
361               return p->second;
362             }
363
364           if (vshifted != NULL && *vshifted == NULL)
365             *vshifted = p->second;
366         }
367
368       ++p;
369     }
370
371   return NULL;
372 }
373
374 // Read SIZE bytes from the file starting at offset START.  Read into
375 // the buffer at P.
376
377 void
378 File_read::do_read(off_t start, section_size_type size, void* p)
379 {
380   ssize_t bytes;
381   if (this->whole_file_view_ != NULL)
382     {
383       bytes = this->size_ - start;
384       if (static_cast<section_size_type>(bytes) >= size)
385         {
386           memcpy(p, this->whole_file_view_->data() + start, size);
387           return;
388         }
389     }
390   else
391     {
392       this->reopen_descriptor();
393
394       char *read_ptr = static_cast<char *>(p);
395       off_t read_pos = start;
396       size_t to_read = size;
397       do
398         {
399           bytes = ::pread(this->descriptor_, read_ptr, to_read, read_pos);
400           if (bytes < 0)
401             gold_fatal(_("%s: pread failed: %s"),
402                        this->filename().c_str(), strerror(errno));
403
404           read_pos += bytes;
405           read_ptr += bytes;
406           to_read -= bytes;
407           if (to_read == 0)
408             return;
409         }
410       while (bytes > 0);
411
412       bytes = size - to_read;
413     }
414
415   gold_fatal(_("%s: file too short: read only %lld of %lld bytes at %lld"),
416              this->filename().c_str(),
417              static_cast<long long>(bytes),
418              static_cast<long long>(size),
419              static_cast<long long>(start));
420 }
421
422 // Read data from the file.
423
424 void
425 File_read::read(off_t start, section_size_type size, void* p)
426 {
427   const File_read::View* pv = this->find_view(start, size, -1U, NULL);
428   if (pv != NULL)
429     {
430       memcpy(p, pv->data() + (start - pv->start() + pv->byteshift()), size);
431       return;
432     }
433
434   this->do_read(start, size, p);
435 }
436
437 // Add a new view.  There may already be an existing view at this
438 // offset.  If there is, the new view will be larger, and should
439 // replace the old view.
440
441 void
442 File_read::add_view(File_read::View* v)
443 {
444   std::pair<Views::iterator, bool> ins =
445     this->views_.insert(std::make_pair(std::make_pair(v->start(),
446                                                       v->byteshift()),
447                                        v));
448   if (ins.second)
449     return;
450
451   // There was an existing view at this offset.  It must not be large
452   // enough.  We can't delete it here, since something might be using
453   // it; we put it on a list to be deleted when the file is unlocked.
454   File_read::View* vold = ins.first->second;
455   gold_assert(vold->size() < v->size());
456   if (vold->should_cache())
457     {
458       v->set_cache();
459       vold->clear_cache();
460     }
461   this->saved_views_.push_back(vold);
462
463   ins.first->second = v;
464 }
465
466 // Make a new view with a specified byteshift, reading the data from
467 // the file.
468
469 File_read::View*
470 File_read::make_view(off_t start, section_size_type size,
471                      unsigned int byteshift, bool cache)
472 {
473   gold_assert(size > 0);
474   gold_assert(start <= this->size_
475               && (static_cast<unsigned long long>(size)
476                   <= static_cast<unsigned long long>(this->size_ - start)));
477
478   off_t poff = File_read::page_offset(start);
479
480   section_size_type psize = File_read::pages(size + (start - poff));
481
482   if (poff + static_cast<off_t>(psize) >= this->size_)
483     {
484       psize = this->size_ - poff;
485       gold_assert(psize >= size);
486     }
487
488   void* p;
489   View::Data_ownership ownership;
490   if (byteshift != 0)
491     {
492       p = malloc(psize + byteshift);
493       if (p == NULL)
494         gold_nomem();
495       memset(p, 0, byteshift);
496       this->do_read(poff, psize, static_cast<unsigned char*>(p) + byteshift);
497       ownership = View::DATA_ALLOCATED_ARRAY;
498     }
499   else
500     {
501       this->reopen_descriptor();
502       p = ::mmap(NULL, psize, PROT_READ, MAP_PRIVATE, this->descriptor_, poff);
503       if (p != MAP_FAILED)
504         {
505           ownership = View::DATA_MMAPPED;
506           this->mapped_bytes_ += psize;
507         }
508       else
509         {
510           p = malloc(psize);
511           if (p == NULL)
512             gold_nomem();
513           this->do_read(poff, psize, p);
514           ownership = View::DATA_ALLOCATED_ARRAY;
515         }
516     }
517
518   const unsigned char* pbytes = static_cast<const unsigned char*>(p);
519   File_read::View* v = new File_read::View(poff, psize, pbytes, byteshift,
520                                            cache, ownership);
521
522   this->add_view(v);
523
524   return v;
525 }
526
527 // Find a View or make a new one, shifted as required by the file
528 // offset OFFSET and ALIGNED.
529
530 File_read::View*
531 File_read::find_or_make_view(off_t offset, off_t start,
532                              section_size_type size, bool aligned, bool cache)
533 {
534   // Check that start and end of the view are within the file.
535   if (start > this->size_
536       || (static_cast<unsigned long long>(size)
537           > static_cast<unsigned long long>(this->size_ - start)))
538     gold_fatal(_("%s: attempt to map %lld bytes at offset %lld exceeds "
539                  "size of file; the file may be corrupt"),
540                    this->filename().c_str(),
541                    static_cast<long long>(size),
542                    static_cast<long long>(start));
543
544   unsigned int byteshift;
545   if (offset == 0)
546     byteshift = 0;
547   else
548     {
549       unsigned int target_size = (!parameters->target_valid()
550                                   ? 64
551                                   : parameters->target().get_size());
552       byteshift = offset & ((target_size / 8) - 1);
553
554       // Set BYTESHIFT to the number of dummy bytes which must be
555       // inserted before the data in order for this data to be
556       // aligned.
557       if (byteshift != 0)
558         byteshift = (target_size / 8) - byteshift;
559     }
560
561   // If --map-whole-files is set, make sure we have a
562   // whole file view.  Options may not yet be ready, e.g.,
563   // when reading a version script.  We then default to
564   // --no-map-whole-files.
565   if (this->whole_file_view_ == NULL
566       && parameters->options_valid()
567       && parameters->options().map_whole_files())
568     this->whole_file_view_ = this->make_view(0, this->size_, 0, cache);
569
570   // Try to find a View with the required BYTESHIFT.
571   File_read::View* vshifted;
572   File_read::View* v = this->find_view(offset + start, size,
573                                        aligned ? byteshift : -1U,
574                                        &vshifted);
575   if (v != NULL)
576     {
577       if (cache)
578         v->set_cache();
579       return v;
580     }
581
582   // If VSHIFTED is not NULL, then it has the data we need, but with
583   // the wrong byteshift.
584   v = vshifted;
585   if (v != NULL)
586     {
587       gold_assert(aligned);
588
589       unsigned char* pbytes;
590       pbytes = static_cast<unsigned char*>(malloc(v->size() + byteshift));
591       if (pbytes == NULL)
592         gold_nomem();
593       memset(pbytes, 0, byteshift);
594       memcpy(pbytes + byteshift, v->data() + v->byteshift(), v->size());
595
596       File_read::View* shifted_view =
597           new File_read::View(v->start(), v->size(), pbytes, byteshift,
598                               cache, View::DATA_ALLOCATED_ARRAY);
599
600       this->add_view(shifted_view);
601       return shifted_view;
602     }
603
604   // Make a new view.  If we don't need an aligned view, use a
605   // byteshift of 0, so that we can use mmap.
606   return this->make_view(offset + start, size,
607                          aligned ? byteshift : 0,
608                          cache);
609 }
610
611 // Get a view into the file.
612
613 const unsigned char*
614 File_read::get_view(off_t offset, off_t start, section_size_type size,
615                     bool aligned, bool cache)
616 {
617   File_read::View* pv = this->find_or_make_view(offset, start, size,
618                                                 aligned, cache);
619   return pv->data() + (offset + start - pv->start() + pv->byteshift());
620 }
621
622 File_view*
623 File_read::get_lasting_view(off_t offset, off_t start, section_size_type size,
624                             bool aligned, bool cache)
625 {
626   File_read::View* pv = this->find_or_make_view(offset, start, size,
627                                                 aligned, cache);
628   pv->lock();
629   return new File_view(*this, pv,
630                        (pv->data()
631                         + (offset + start - pv->start() + pv->byteshift())));
632 }
633
634 // Use readv to read COUNT entries from RM starting at START.  BASE
635 // must be added to all file offsets in RM.
636
637 void
638 File_read::do_readv(off_t base, const Read_multiple& rm, size_t start,
639                     size_t count)
640 {
641   unsigned char discard[File_read::page_size];
642   iovec iov[File_read::max_readv_entries * 2];
643   size_t iov_index = 0;
644
645   off_t first_offset = rm[start].file_offset;
646   off_t last_offset = first_offset;
647   ssize_t want = 0;
648   for (size_t i = 0; i < count; ++i)
649     {
650       const Read_multiple_entry& i_entry(rm[start + i]);
651
652       if (i_entry.file_offset > last_offset)
653         {
654           size_t skip = i_entry.file_offset - last_offset;
655           gold_assert(skip <= sizeof discard);
656
657           iov[iov_index].iov_base = discard;
658           iov[iov_index].iov_len = skip;
659           ++iov_index;
660
661           want += skip;
662         }
663
664       iov[iov_index].iov_base = i_entry.buffer;
665       iov[iov_index].iov_len = i_entry.size;
666       ++iov_index;
667
668       want += i_entry.size;
669
670       last_offset = i_entry.file_offset + i_entry.size;
671     }
672
673   this->reopen_descriptor();
674
675   gold_assert(iov_index < sizeof iov / sizeof iov[0]);
676
677   if (::lseek(this->descriptor_, base + first_offset, SEEK_SET) < 0)
678     gold_fatal(_("%s: lseek failed: %s"),
679                this->filename().c_str(), strerror(errno));
680
681   ssize_t got = ::readv(this->descriptor_, iov, iov_index);
682
683   if (got < 0)
684     gold_fatal(_("%s: readv failed: %s"),
685                this->filename().c_str(), strerror(errno));
686   if (got != want)
687     gold_fatal(_("%s: file too short: read only %zd of %zd bytes at %lld"),
688                this->filename().c_str(),
689                got, want, static_cast<long long>(base + first_offset));
690 }
691
692 // Portable IOV_MAX.
693
694 #if !defined(HAVE_READV)
695 #define GOLD_IOV_MAX 1
696 #elif defined(IOV_MAX)
697 #define GOLD_IOV_MAX IOV_MAX
698 #else
699 #define GOLD_IOV_MAX (File_read::max_readv_entries * 2)
700 #endif
701
702 // Read several pieces of data from the file.
703
704 void
705 File_read::read_multiple(off_t base, const Read_multiple& rm)
706 {
707   static size_t iov_max = GOLD_IOV_MAX;
708   size_t count = rm.size();
709   size_t i = 0;
710   while (i < count)
711     {
712       // Find up to MAX_READV_ENTRIES consecutive entries which are
713       // less than one page apart.
714       const Read_multiple_entry& i_entry(rm[i]);
715       off_t i_off = i_entry.file_offset;
716       off_t end_off = i_off + i_entry.size;
717       size_t j;
718       for (j = i + 1; j < count; ++j)
719         {
720           if (j - i >= File_read::max_readv_entries || j - i >= iov_max / 2)
721             break;
722           const Read_multiple_entry& j_entry(rm[j]);
723           off_t j_off = j_entry.file_offset;
724           gold_assert(j_off >= end_off);
725           off_t j_end_off = j_off + j_entry.size;
726           if (j_end_off - end_off >= File_read::page_size)
727             break;
728           end_off = j_end_off;
729         }
730
731       if (j == i + 1)
732         this->read(base + i_off, i_entry.size, i_entry.buffer);
733       else
734         {
735           File_read::View* view = this->find_view(base + i_off,
736                                                   end_off - i_off,
737                                                   -1U, NULL);
738           if (view == NULL)
739             this->do_readv(base, rm, i, j - i);
740           else
741             {
742               const unsigned char* v = (view->data()
743                                         + (base + i_off - view->start()
744                                            + view->byteshift()));
745               for (size_t k = i; k < j; ++k)
746                 {
747                   const Read_multiple_entry& k_entry(rm[k]);
748                   gold_assert((convert_to_section_size_type(k_entry.file_offset
749                                                            - i_off)
750                                + k_entry.size)
751                               <= convert_to_section_size_type(end_off
752                                                               - i_off));
753                   memcpy(k_entry.buffer,
754                          v + (k_entry.file_offset - i_off),
755                          k_entry.size);
756                 }
757             }
758         }
759
760       i = j;
761     }
762 }
763
764 // Mark all views as no longer cached.
765
766 void
767 File_read::clear_view_cache_marks()
768 {
769   // Just ignore this if there are multiple objects associated with
770   // the file.  Otherwise we will wind up uncaching and freeing some
771   // views for other objects.
772   if (this->object_count_ > 1)
773     return;
774
775   for (Views::iterator p = this->views_.begin();
776        p != this->views_.end();
777        ++p)
778     p->second->clear_cache();
779   for (Saved_views::iterator p = this->saved_views_.begin();
780        p != this->saved_views_.end();
781        ++p)
782     (*p)->clear_cache();
783 }
784
785 // Remove all the file views.  For a file which has multiple
786 // associated objects (i.e., an archive), we keep accessed views
787 // around until next time, in the hopes that they will be useful for
788 // the next object.
789
790 void
791 File_read::clear_views(Clear_views_mode mode)
792 {
793   bool keep_files_mapped = (parameters->options_valid()
794                             && parameters->options().keep_files_mapped());
795   Views::iterator p = this->views_.begin();
796   while (p != this->views_.end())
797     {
798       bool should_delete;
799       if (p->second->is_locked() || p->second->is_permanent_view())
800         should_delete = false;
801       else if (mode == CLEAR_VIEWS_ALL)
802         should_delete = true;
803       else if ((p->second->should_cache()
804                 || p->second == this->whole_file_view_)
805                && keep_files_mapped)
806         should_delete = false;
807       else if (this->object_count_ > 1
808                && p->second->accessed()
809                && mode != CLEAR_VIEWS_ARCHIVE)
810         should_delete = false;
811       else
812         should_delete = true;
813
814       if (should_delete)
815         {
816           if (p->second == this->whole_file_view_)
817             this->whole_file_view_ = NULL;
818           delete p->second;
819
820           // map::erase invalidates only the iterator to the deleted
821           // element.
822           Views::iterator pe = p;
823           ++p;
824           this->views_.erase(pe);
825         }
826       else
827         {
828           p->second->clear_accessed();
829           ++p;
830         }
831     }
832
833   Saved_views::iterator q = this->saved_views_.begin();
834   while (q != this->saved_views_.end())
835     {
836       if (!(*q)->is_locked())
837         {
838           delete *q;
839           q = this->saved_views_.erase(q);
840         }
841       else
842         {
843           gold_assert(mode != CLEAR_VIEWS_ALL);
844           ++q;
845         }
846     }
847 }
848
849 // Print statistical information to stderr.  This is used for --stats.
850
851 void
852 File_read::print_stats()
853 {
854   fprintf(stderr, _("%s: total bytes mapped for read: %llu\n"),
855           program_name, File_read::total_mapped_bytes);
856   fprintf(stderr, _("%s: maximum bytes mapped for read at one time: %llu\n"),
857           program_name, File_read::maximum_mapped_bytes);
858 }
859
860 // Class File_view.
861
862 File_view::~File_view()
863 {
864   gold_assert(this->file_.is_locked());
865   this->view_->unlock();
866 }
867
868 // Class Input_file.
869
870 // Create a file given just the filename.
871
872 Input_file::Input_file(const char* name)
873   : found_name_(), file_(), is_in_sysroot_(false), format_(FORMAT_NONE)
874 {
875   this->input_argument_ =
876     new Input_file_argument(name, Input_file_argument::INPUT_FILE_TYPE_FILE,
877                             "", false, Position_dependent_options());
878 }
879
880 // Create a file for testing.
881
882 Input_file::Input_file(const Task* task, const char* name,
883                        const unsigned char* contents, off_t size)
884   : file_()
885 {
886   this->input_argument_ =
887     new Input_file_argument(name, Input_file_argument::INPUT_FILE_TYPE_FILE,
888                             "", false, Position_dependent_options());
889   bool ok = this->file_.open(task, name, contents, size);
890   gold_assert(ok);
891 }
892
893 // Return the position dependent options in force for this file.
894
895 const Position_dependent_options&
896 Input_file::options() const
897 {
898   return this->input_argument_->options();
899 }
900
901 // Return the name given by the user.  For -lc this will return "c".
902
903 const char*
904 Input_file::name() const
905 {
906   return this->input_argument_->name();
907 }
908
909 // Return whether this file is in a system directory.
910
911 bool
912 Input_file::is_in_system_directory() const
913 {
914   if (this->is_in_sysroot())
915     return true;
916   return parameters->options().is_in_system_directory(this->filename());
917 }
918
919 // Return whether we are only reading symbols.
920
921 bool
922 Input_file::just_symbols() const
923 {
924   return this->input_argument_->just_symbols();
925 }
926
927 // Return whether this is a file that we will search for in the list
928 // of directories.
929
930 bool
931 Input_file::will_search_for() const
932 {
933   return (!IS_ABSOLUTE_PATH(this->input_argument_->name())
934           && (this->input_argument_->is_lib()
935               || this->input_argument_->is_searched_file()
936               || this->input_argument_->extra_search_path() != NULL));
937 }
938
939 // Return the file last modification time.  Calls gold_fatal if the stat
940 // system call failed.
941
942 Timespec
943 File_read::get_mtime()
944 {
945   struct stat file_stat;
946   this->reopen_descriptor();
947
948   if (fstat(this->descriptor_, &file_stat) < 0)
949     gold_fatal(_("%s: stat failed: %s"), this->name_.c_str(),
950                strerror(errno));
951 #ifdef HAVE_STAT_ST_MTIM
952   return Timespec(file_stat.st_mtim.tv_sec, file_stat.st_mtim.tv_nsec);
953 #else
954   return Timespec(file_stat.st_mtime, 0);
955 #endif
956 }
957
958 // Try to find a file in the extra search dirs.  Returns true on success.
959
960 bool
961 Input_file::try_extra_search_path(int* pindex,
962                                   const Input_file_argument* input_argument,
963                                   std::string filename, std::string* found_name,
964                                   std::string* namep)
965 {
966   if (input_argument->extra_search_path() == NULL)
967     return false;
968
969   std::string name = input_argument->extra_search_path();
970   if (!IS_DIR_SEPARATOR(name[name.length() - 1]))
971     name += '/';
972   name += filename;
973
974   struct stat dummy_stat;
975   if (*pindex > 0 || ::stat(name.c_str(), &dummy_stat) < 0)
976     return false;
977
978   *found_name = filename;
979   *namep = name;
980   return true;
981 }
982
983 // Find the actual file.
984 // If the filename is not absolute, we assume it is in the current
985 // directory *except* when:
986 //    A) input_argument_->is_lib() is true;
987 //    B) input_argument_->is_searched_file() is true; or
988 //    C) input_argument_->extra_search_path() is not empty.
989 // In each, we look in extra_search_path + library_path to find
990 // the file location, rather than the current directory.
991
992 bool
993 Input_file::find_file(const Dirsearch& dirpath, int* pindex,
994                       const Input_file_argument* input_argument,
995                       bool* is_in_sysroot,
996                       std::string* found_name, std::string* namep)
997 {
998   std::string name;
999
1000   // Case 1: name is an absolute file, just try to open it
1001   // Case 2: name is relative but is_lib is false, is_searched_file is false,
1002   //         and extra_search_path is empty
1003   if (IS_ABSOLUTE_PATH(input_argument->name())
1004       || (!input_argument->is_lib()
1005           && !input_argument->is_searched_file()
1006           && input_argument->extra_search_path() == NULL))
1007     {
1008       name = input_argument->name();
1009       *found_name = name;
1010       *namep = name;
1011       return true;
1012     }
1013   // Case 3: is_lib is true or is_searched_file is true
1014   else if (input_argument->is_lib()
1015            || input_argument->is_searched_file())
1016     {
1017       std::vector<std::string> names;
1018       names.reserve(2);
1019       if (input_argument->is_lib())
1020         {
1021           std::string prefix = "lib";
1022           prefix += input_argument->name();
1023           if (parameters->options().is_static()
1024               || !input_argument->options().Bdynamic())
1025             names.push_back(prefix + ".a");
1026           else
1027             {
1028               names.push_back(prefix + ".so");
1029               names.push_back(prefix + ".a");
1030             }
1031         }
1032       else
1033         names.push_back(input_argument->name());
1034
1035       for (std::vector<std::string>::const_iterator n = names.begin();
1036            n != names.end();
1037            ++n)
1038         if (Input_file::try_extra_search_path(pindex, input_argument, *n,
1039                                               found_name, namep))
1040           return true;
1041
1042       // It is not in the extra_search_path.
1043       name = dirpath.find(names, is_in_sysroot, pindex, found_name);
1044       if (name.empty())
1045         {
1046           gold_error(_("cannot find %s%s"),
1047                      input_argument->is_lib() ? "-l" : "",
1048                      input_argument->name());
1049           return false;
1050         }
1051       *namep = name;
1052       return true;
1053     }
1054   // Case 4: extra_search_path is not empty
1055   else
1056     {
1057       gold_assert(input_argument->extra_search_path() != NULL);
1058
1059       if (try_extra_search_path(pindex, input_argument, input_argument->name(),
1060                                 found_name, namep))
1061         return true;
1062
1063       // extra_search_path failed, so check the normal search-path.
1064       int index = *pindex;
1065       if (index > 0)
1066         --index;
1067       name = dirpath.find(std::vector<std::string>(1, input_argument->name()),
1068                           is_in_sysroot, &index, found_name);
1069       if (name.empty())
1070         {
1071           gold_error(_("cannot find %s"),
1072                      input_argument->name());
1073           return false;
1074         }
1075       *namep = name;
1076       *pindex = index + 1;
1077       return true;
1078     }
1079 }
1080
1081 // Open the file.
1082
1083 bool
1084 Input_file::open(const Dirsearch& dirpath, const Task* task, int* pindex)
1085 {
1086   std::string name;
1087   if (!Input_file::find_file(dirpath, pindex, this->input_argument_,
1088                              &this->is_in_sysroot_, &this->found_name_, &name))
1089     return false;
1090
1091   // Now that we've figured out where the file lives, try to open it.
1092
1093   General_options::Object_format format =
1094     this->input_argument_->options().format_enum();
1095   bool ok;
1096   if (format == General_options::OBJECT_FORMAT_ELF)
1097     {
1098       ok = this->file_.open(task, name);
1099       this->format_ = FORMAT_ELF;
1100     }
1101   else
1102     {
1103       gold_assert(format == General_options::OBJECT_FORMAT_BINARY);
1104       ok = this->open_binary(task, name);
1105       this->format_ = FORMAT_BINARY;
1106     }
1107
1108   if (!ok)
1109     {
1110       gold_error(_("cannot open %s: %s"),
1111                  name.c_str(), strerror(errno));
1112       this->format_ = FORMAT_NONE;
1113       return false;
1114     }
1115
1116   return true;
1117 }
1118
1119 // Open a file for --format binary.
1120
1121 bool
1122 Input_file::open_binary(const Task* task, const std::string& name)
1123 {
1124   // In order to open a binary file, we need machine code, size, and
1125   // endianness.  We may not have a valid target at this point, in
1126   // which case we use the default target.
1127   parameters_force_valid_target();
1128   const Target& target(parameters->target());
1129
1130   Binary_to_elf binary_to_elf(target.machine_code(),
1131                               target.get_size(),
1132                               target.is_big_endian(),
1133                               name);
1134   if (!binary_to_elf.convert(task))
1135     return false;
1136   return this->file_.open(task, name, binary_to_elf.converted_data_leak(),
1137                           binary_to_elf.converted_size());
1138 }
1139
1140 } // End namespace gold.