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