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