OSDN Git Service

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