Update copyright in comments to 2011.
[binutils.git] / gold / fileread.cc
blob14a02b2f52f9ae29274d97342d461bd5d81a8afe
1 // fileread.cc -- read files for gold
3 // Copyright 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
6 // This file is part of gold.
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.
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.
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.
23 #include "gold.h"
25 #include <cstring>
26 #include <cerrno>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <sys/mman.h>
31 #ifdef HAVE_READV
32 #include <sys/uio.h>
33 #endif
35 #include <sys/stat.h>
36 #include "filenames.h"
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"
48 #ifndef HAVE_READV
49 struct iovec { void* iov_base; size_t iov_len; };
50 ssize_t
51 readv(int, const iovec*, int)
53 gold_unreachable();
55 #endif
57 namespace gold
60 // Class File_read.
62 // A lock for the File_read static variables.
63 static Lock* file_counts_lock = NULL;
64 static Initialize_lock file_counts_initialize_lock(&file_counts_lock);
66 // The File_read static variables.
67 unsigned long long File_read::total_mapped_bytes;
68 unsigned long long File_read::current_mapped_bytes;
69 unsigned long long File_read::maximum_mapped_bytes;
71 // Class File_read::View.
73 File_read::View::~View()
75 gold_assert(!this->is_locked());
76 switch (this->data_ownership_)
78 case DATA_ALLOCATED_ARRAY:
79 delete[] this->data_;
80 break;
81 case DATA_MMAPPED:
82 if (::munmap(const_cast<unsigned char*>(this->data_), this->size_) != 0)
83 gold_warning(_("munmap failed: %s"), strerror(errno));
84 if (!parameters->options_valid() || parameters->options().stats())
86 file_counts_initialize_lock.initialize();
87 Hold_optional_lock hl(file_counts_lock);
88 File_read::current_mapped_bytes -= this->size_;
90 break;
91 case DATA_NOT_OWNED:
92 break;
93 default:
94 gold_unreachable();
98 void
99 File_read::View::lock()
101 ++this->lock_count_;
104 void
105 File_read::View::unlock()
107 gold_assert(this->lock_count_ > 0);
108 --this->lock_count_;
111 bool
112 File_read::View::is_locked()
114 return this->lock_count_ > 0;
117 // Class File_read.
119 File_read::~File_read()
121 gold_assert(this->token_.is_writable());
122 if (this->is_descriptor_opened_)
124 release_descriptor(this->descriptor_, true);
125 this->descriptor_ = -1;
126 this->is_descriptor_opened_ = false;
128 this->name_.clear();
129 this->clear_views(CLEAR_VIEWS_ALL);
132 // Open the file.
134 bool
135 File_read::open(const Task* task, const std::string& name)
137 gold_assert(this->token_.is_writable()
138 && this->descriptor_ < 0
139 && !this->is_descriptor_opened_
140 && this->name_.empty());
141 this->name_ = name;
143 this->descriptor_ = open_descriptor(-1, this->name_.c_str(),
144 O_RDONLY);
146 if (this->descriptor_ >= 0)
148 this->is_descriptor_opened_ = true;
149 struct stat s;
150 if (::fstat(this->descriptor_, &s) < 0)
151 gold_error(_("%s: fstat failed: %s"),
152 this->name_.c_str(), strerror(errno));
153 this->size_ = s.st_size;
154 gold_debug(DEBUG_FILES, "Attempt to open %s succeeded",
155 this->name_.c_str());
156 this->token_.add_writer(task);
159 return this->descriptor_ >= 0;
162 // Open the file with the contents in memory.
164 bool
165 File_read::open(const Task* task, const std::string& name,
166 const unsigned char* contents, off_t size)
168 gold_assert(this->token_.is_writable()
169 && this->descriptor_ < 0
170 && !this->is_descriptor_opened_
171 && this->name_.empty());
172 this->name_ = name;
173 this->whole_file_view_ = new View(0, size, contents, 0, false,
174 View::DATA_NOT_OWNED);
175 this->add_view(this->whole_file_view_);
176 this->size_ = size;
177 this->token_.add_writer(task);
178 return true;
181 // Reopen a descriptor if necessary.
183 void
184 File_read::reopen_descriptor()
186 if (!this->is_descriptor_opened_)
188 this->descriptor_ = open_descriptor(this->descriptor_,
189 this->name_.c_str(),
190 O_RDONLY);
191 if (this->descriptor_ < 0)
192 gold_fatal(_("could not reopen file %s"), this->name_.c_str());
193 this->is_descriptor_opened_ = true;
197 // Release the file. This is called when we are done with the file in
198 // a Task.
200 void
201 File_read::release()
203 gold_assert(this->is_locked());
205 if (!parameters->options_valid() || parameters->options().stats())
207 file_counts_initialize_lock.initialize();
208 Hold_optional_lock hl(file_counts_lock);
209 File_read::total_mapped_bytes += this->mapped_bytes_;
210 File_read::current_mapped_bytes += this->mapped_bytes_;
211 if (File_read::current_mapped_bytes > File_read::maximum_mapped_bytes)
212 File_read::maximum_mapped_bytes = File_read::current_mapped_bytes;
215 this->mapped_bytes_ = 0;
217 // Only clear views if there is only one attached object. Otherwise
218 // we waste time trying to clear cached archive views. Similarly
219 // for releasing the descriptor.
220 if (this->object_count_ <= 1)
222 this->clear_views(CLEAR_VIEWS_NORMAL);
223 if (this->is_descriptor_opened_)
225 release_descriptor(this->descriptor_, false);
226 this->is_descriptor_opened_ = false;
230 this->released_ = true;
233 // Lock the file.
235 void
236 File_read::lock(const Task* task)
238 gold_assert(this->released_);
239 this->token_.add_writer(task);
240 this->released_ = false;
243 // Unlock the file.
245 void
246 File_read::unlock(const Task* task)
248 this->release();
249 this->token_.remove_writer(task);
252 // Return whether the file is locked.
254 bool
255 File_read::is_locked() const
257 if (!this->token_.is_writable())
258 return true;
259 // The file is not locked, so it should have been released.
260 gold_assert(this->released_);
261 return false;
264 // See if we have a view which covers the file starting at START for
265 // SIZE bytes. Return a pointer to the View if found, NULL if not.
266 // If BYTESHIFT is not -1U, the returned View must have the specified
267 // byte shift; otherwise, it may have any byte shift. If VSHIFTED is
268 // not NULL, this sets *VSHIFTED to a view which would have worked if
269 // not for the requested BYTESHIFT.
271 inline File_read::View*
272 File_read::find_view(off_t start, section_size_type size,
273 unsigned int byteshift, File_read::View** vshifted) const
275 if (vshifted != NULL)
276 *vshifted = NULL;
278 // If we have the whole file mmapped, and the alignment is right,
279 // we can return it.
280 if (this->whole_file_view_)
281 if (byteshift == -1U || byteshift == 0)
282 return this->whole_file_view_;
284 off_t page = File_read::page_offset(start);
286 unsigned int bszero = 0;
287 Views::const_iterator p = this->views_.upper_bound(std::make_pair(page - 1,
288 bszero));
290 while (p != this->views_.end() && p->first.first <= page)
292 if (p->second->start() <= start
293 && (p->second->start() + static_cast<off_t>(p->second->size())
294 >= start + static_cast<off_t>(size)))
296 if (byteshift == -1U || byteshift == p->second->byteshift())
298 p->second->set_accessed();
299 return p->second;
302 if (vshifted != NULL && *vshifted == NULL)
303 *vshifted = p->second;
306 ++p;
309 return NULL;
312 // Read SIZE bytes from the file starting at offset START. Read into
313 // the buffer at P.
315 void
316 File_read::do_read(off_t start, section_size_type size, void* p)
318 ssize_t bytes;
319 if (this->whole_file_view_ != NULL)
321 bytes = this->size_ - start;
322 if (static_cast<section_size_type>(bytes) >= size)
324 memcpy(p, this->whole_file_view_->data() + start, size);
325 return;
328 else
330 this->reopen_descriptor();
331 bytes = ::pread(this->descriptor_, p, size, start);
332 if (static_cast<section_size_type>(bytes) == size)
333 return;
335 if (bytes < 0)
337 gold_fatal(_("%s: pread failed: %s"),
338 this->filename().c_str(), strerror(errno));
339 return;
343 gold_fatal(_("%s: file too short: read only %lld of %lld bytes at %lld"),
344 this->filename().c_str(),
345 static_cast<long long>(bytes),
346 static_cast<long long>(size),
347 static_cast<long long>(start));
350 // Read data from the file.
352 void
353 File_read::read(off_t start, section_size_type size, void* p)
355 const File_read::View* pv = this->find_view(start, size, -1U, NULL);
356 if (pv != NULL)
358 memcpy(p, pv->data() + (start - pv->start() + pv->byteshift()), size);
359 return;
362 this->do_read(start, size, p);
365 // Add a new view. There may already be an existing view at this
366 // offset. If there is, the new view will be larger, and should
367 // replace the old view.
369 void
370 File_read::add_view(File_read::View* v)
372 std::pair<Views::iterator, bool> ins =
373 this->views_.insert(std::make_pair(std::make_pair(v->start(),
374 v->byteshift()),
375 v));
376 if (ins.second)
377 return;
379 // There was an existing view at this offset. It must not be large
380 // enough. We can't delete it here, since something might be using
381 // it; we put it on a list to be deleted when the file is unlocked.
382 File_read::View* vold = ins.first->second;
383 gold_assert(vold->size() < v->size());
384 if (vold->should_cache())
386 v->set_cache();
387 vold->clear_cache();
389 this->saved_views_.push_back(vold);
391 ins.first->second = v;
394 // Make a new view with a specified byteshift, reading the data from
395 // the file.
397 File_read::View*
398 File_read::make_view(off_t start, section_size_type size,
399 unsigned int byteshift, bool cache)
401 gold_assert(size > 0);
403 // Check that start and end of the view are within the file.
404 if (start > this->size_
405 || (static_cast<unsigned long long>(size)
406 > static_cast<unsigned long long>(this->size_ - start)))
407 gold_fatal(_("%s: attempt to map %lld bytes at offset %lld exceeds "
408 "size of file; the file may be corrupt"),
409 this->filename().c_str(),
410 static_cast<long long>(size),
411 static_cast<long long>(start));
413 off_t poff = File_read::page_offset(start);
415 section_size_type psize = File_read::pages(size + (start - poff));
417 if (poff + static_cast<off_t>(psize) >= this->size_)
419 psize = this->size_ - poff;
420 gold_assert(psize >= size);
423 File_read::View* v;
424 if (byteshift != 0)
426 unsigned char* p = new unsigned char[psize + byteshift];
427 memset(p, 0, byteshift);
428 this->do_read(poff, psize, p + byteshift);
429 v = new File_read::View(poff, psize, p, byteshift, cache,
430 View::DATA_ALLOCATED_ARRAY);
432 else
434 this->reopen_descriptor();
435 void* p = ::mmap(NULL, psize, PROT_READ, MAP_PRIVATE,
436 this->descriptor_, poff);
437 if (p == MAP_FAILED)
438 gold_fatal(_("%s: mmap offset %lld size %lld failed: %s"),
439 this->filename().c_str(),
440 static_cast<long long>(poff),
441 static_cast<long long>(psize),
442 strerror(errno));
444 this->mapped_bytes_ += psize;
446 const unsigned char* pbytes = static_cast<const unsigned char*>(p);
447 v = new File_read::View(poff, psize, pbytes, 0, cache,
448 View::DATA_MMAPPED);
451 this->add_view(v);
453 return v;
456 // Find a View or make a new one, shifted as required by the file
457 // offset OFFSET and ALIGNED.
459 File_read::View*
460 File_read::find_or_make_view(off_t offset, off_t start,
461 section_size_type size, bool aligned, bool cache)
463 unsigned int byteshift;
464 if (offset == 0)
465 byteshift = 0;
466 else
468 unsigned int target_size = (!parameters->target_valid()
469 ? 64
470 : parameters->target().get_size());
471 byteshift = offset & ((target_size / 8) - 1);
473 // Set BYTESHIFT to the number of dummy bytes which must be
474 // inserted before the data in order for this data to be
475 // aligned.
476 if (byteshift != 0)
477 byteshift = (target_size / 8) - byteshift;
480 // If --map-whole-files is set, make sure we have a
481 // whole file view. Options may not yet be ready, e.g.,
482 // when reading a version script. We then default to
483 // --no-map-whole-files.
484 if (this->whole_file_view_ == NULL
485 && parameters->options_valid()
486 && parameters->options().map_whole_files())
487 this->whole_file_view_ = this->make_view(0, this->size_, 0, cache);
489 // Try to find a View with the required BYTESHIFT.
490 File_read::View* vshifted;
491 File_read::View* v = this->find_view(offset + start, size,
492 aligned ? byteshift : -1U,
493 &vshifted);
494 if (v != NULL)
496 if (cache)
497 v->set_cache();
498 return v;
501 // If VSHIFTED is not NULL, then it has the data we need, but with
502 // the wrong byteshift.
503 v = vshifted;
504 if (v != NULL)
506 gold_assert(aligned);
508 unsigned char* pbytes = new unsigned char[v->size() + byteshift];
509 memset(pbytes, 0, byteshift);
510 memcpy(pbytes + byteshift, v->data() + v->byteshift(), v->size());
512 File_read::View* shifted_view =
513 new File_read::View(v->start(), v->size(), pbytes, byteshift,
514 cache, View::DATA_ALLOCATED_ARRAY);
516 this->add_view(shifted_view);
517 return shifted_view;
520 // Make a new view. If we don't need an aligned view, use a
521 // byteshift of 0, so that we can use mmap.
522 return this->make_view(offset + start, size,
523 aligned ? byteshift : 0,
524 cache);
527 // Get a view into the file.
529 const unsigned char*
530 File_read::get_view(off_t offset, off_t start, section_size_type size,
531 bool aligned, bool cache)
533 File_read::View* pv = this->find_or_make_view(offset, start, size,
534 aligned, cache);
535 return pv->data() + (offset + start - pv->start() + pv->byteshift());
538 File_view*
539 File_read::get_lasting_view(off_t offset, off_t start, section_size_type size,
540 bool aligned, bool cache)
542 File_read::View* pv = this->find_or_make_view(offset, start, size,
543 aligned, cache);
544 pv->lock();
545 return new File_view(*this, pv,
546 (pv->data()
547 + (offset + start - pv->start() + pv->byteshift())));
550 // Use readv to read COUNT entries from RM starting at START. BASE
551 // must be added to all file offsets in RM.
553 void
554 File_read::do_readv(off_t base, const Read_multiple& rm, size_t start,
555 size_t count)
557 unsigned char discard[File_read::page_size];
558 iovec iov[File_read::max_readv_entries * 2];
559 size_t iov_index = 0;
561 off_t first_offset = rm[start].file_offset;
562 off_t last_offset = first_offset;
563 ssize_t want = 0;
564 for (size_t i = 0; i < count; ++i)
566 const Read_multiple_entry& i_entry(rm[start + i]);
568 if (i_entry.file_offset > last_offset)
570 size_t skip = i_entry.file_offset - last_offset;
571 gold_assert(skip <= sizeof discard);
573 iov[iov_index].iov_base = discard;
574 iov[iov_index].iov_len = skip;
575 ++iov_index;
577 want += skip;
580 iov[iov_index].iov_base = i_entry.buffer;
581 iov[iov_index].iov_len = i_entry.size;
582 ++iov_index;
584 want += i_entry.size;
586 last_offset = i_entry.file_offset + i_entry.size;
589 this->reopen_descriptor();
591 gold_assert(iov_index < sizeof iov / sizeof iov[0]);
593 if (::lseek(this->descriptor_, base + first_offset, SEEK_SET) < 0)
594 gold_fatal(_("%s: lseek failed: %s"),
595 this->filename().c_str(), strerror(errno));
597 ssize_t got = ::readv(this->descriptor_, iov, iov_index);
599 if (got < 0)
600 gold_fatal(_("%s: readv failed: %s"),
601 this->filename().c_str(), strerror(errno));
602 if (got != want)
603 gold_fatal(_("%s: file too short: read only %zd of %zd bytes at %lld"),
604 this->filename().c_str(),
605 got, want, static_cast<long long>(base + first_offset));
608 // Read several pieces of data from the file.
610 void
611 File_read::read_multiple(off_t base, const Read_multiple& rm)
613 size_t count = rm.size();
614 size_t i = 0;
615 while (i < count)
617 // Find up to MAX_READV_ENTRIES consecutive entries which are
618 // less than one page apart.
619 const Read_multiple_entry& i_entry(rm[i]);
620 off_t i_off = i_entry.file_offset;
621 off_t end_off = i_off + i_entry.size;
622 size_t j;
623 for (j = i + 1; j < count; ++j)
625 if (j - i >= File_read::max_readv_entries)
626 break;
627 const Read_multiple_entry& j_entry(rm[j]);
628 off_t j_off = j_entry.file_offset;
629 gold_assert(j_off >= end_off);
630 off_t j_end_off = j_off + j_entry.size;
631 if (j_end_off - end_off >= File_read::page_size)
632 break;
633 end_off = j_end_off;
636 if (j == i + 1)
637 this->read(base + i_off, i_entry.size, i_entry.buffer);
638 else
640 File_read::View* view = this->find_view(base + i_off,
641 end_off - i_off,
642 -1U, NULL);
643 if (view == NULL)
644 this->do_readv(base, rm, i, j - i);
645 else
647 const unsigned char* v = (view->data()
648 + (base + i_off - view->start()
649 + view->byteshift()));
650 for (size_t k = i; k < j; ++k)
652 const Read_multiple_entry& k_entry(rm[k]);
653 gold_assert((convert_to_section_size_type(k_entry.file_offset
654 - i_off)
655 + k_entry.size)
656 <= convert_to_section_size_type(end_off
657 - i_off));
658 memcpy(k_entry.buffer,
659 v + (k_entry.file_offset - i_off),
660 k_entry.size);
665 i = j;
669 // Mark all views as no longer cached.
671 void
672 File_read::clear_view_cache_marks()
674 // Just ignore this if there are multiple objects associated with
675 // the file. Otherwise we will wind up uncaching and freeing some
676 // views for other objects.
677 if (this->object_count_ > 1)
678 return;
680 for (Views::iterator p = this->views_.begin();
681 p != this->views_.end();
682 ++p)
683 p->second->clear_cache();
684 for (Saved_views::iterator p = this->saved_views_.begin();
685 p != this->saved_views_.end();
686 ++p)
687 (*p)->clear_cache();
690 // Remove all the file views. For a file which has multiple
691 // associated objects (i.e., an archive), we keep accessed views
692 // around until next time, in the hopes that they will be useful for
693 // the next object.
695 void
696 File_read::clear_views(Clear_views_mode mode)
698 bool keep_files_mapped = (parameters->options_valid()
699 && parameters->options().keep_files_mapped());
700 Views::iterator p = this->views_.begin();
701 while (p != this->views_.end())
703 bool should_delete;
704 if (p->second->is_locked() || p->second->is_permanent_view())
705 should_delete = false;
706 else if (mode == CLEAR_VIEWS_ALL)
707 should_delete = true;
708 else if (p->second->should_cache() && keep_files_mapped)
709 should_delete = false;
710 else if (this->object_count_ > 1
711 && p->second->accessed()
712 && mode != CLEAR_VIEWS_ARCHIVE)
713 should_delete = false;
714 else
715 should_delete = true;
717 if (should_delete)
719 if (p->second == this->whole_file_view_)
720 this->whole_file_view_ = NULL;
721 delete p->second;
723 // map::erase invalidates only the iterator to the deleted
724 // element.
725 Views::iterator pe = p;
726 ++p;
727 this->views_.erase(pe);
729 else
731 p->second->clear_accessed();
732 ++p;
736 Saved_views::iterator q = this->saved_views_.begin();
737 while (q != this->saved_views_.end())
739 if (!(*q)->is_locked())
741 delete *q;
742 q = this->saved_views_.erase(q);
744 else
746 gold_assert(mode != CLEAR_VIEWS_ALL);
747 ++q;
752 // Print statistical information to stderr. This is used for --stats.
754 void
755 File_read::print_stats()
757 fprintf(stderr, _("%s: total bytes mapped for read: %llu\n"),
758 program_name, File_read::total_mapped_bytes);
759 fprintf(stderr, _("%s: maximum bytes mapped for read at one time: %llu\n"),
760 program_name, File_read::maximum_mapped_bytes);
763 // Class File_view.
765 File_view::~File_view()
767 gold_assert(this->file_.is_locked());
768 this->view_->unlock();
771 // Class Input_file.
773 // Create a file for testing.
775 Input_file::Input_file(const Task* task, const char* name,
776 const unsigned char* contents, off_t size)
777 : file_()
779 this->input_argument_ =
780 new Input_file_argument(name, Input_file_argument::INPUT_FILE_TYPE_FILE,
781 "", false, Position_dependent_options());
782 bool ok = this->file_.open(task, name, contents, size);
783 gold_assert(ok);
786 // Return the position dependent options in force for this file.
788 const Position_dependent_options&
789 Input_file::options() const
791 return this->input_argument_->options();
794 // Return the name given by the user. For -lc this will return "c".
796 const char*
797 Input_file::name() const
799 return this->input_argument_->name();
802 // Return whether this file is in a system directory.
804 bool
805 Input_file::is_in_system_directory() const
807 if (this->is_in_sysroot())
808 return true;
809 return parameters->options().is_in_system_directory(this->filename());
812 // Return whether we are only reading symbols.
814 bool
815 Input_file::just_symbols() const
817 return this->input_argument_->just_symbols();
820 // Return whether this is a file that we will search for in the list
821 // of directories.
823 bool
824 Input_file::will_search_for() const
826 return (!IS_ABSOLUTE_PATH(this->input_argument_->name())
827 && (this->input_argument_->is_lib()
828 || this->input_argument_->is_searched_file()
829 || this->input_argument_->extra_search_path() != NULL));
832 // Return the file last modification time. Calls gold_fatal if the stat
833 // system call failed.
835 Timespec
836 File_read::get_mtime()
838 struct stat file_stat;
839 this->reopen_descriptor();
841 if (fstat(this->descriptor_, &file_stat) < 0)
842 gold_fatal(_("%s: stat failed: %s"), this->name_.c_str(),
843 strerror(errno));
844 #ifdef HAVE_STAT_ST_MTIM
845 return Timespec(file_stat.st_mtim.tv_sec, file_stat.st_mtim.tv_nsec);
846 #else
847 return Timespec(file_stat.st_mtime, 0);
848 #endif
851 // Try to find a file in the extra search dirs. Returns true on success.
853 bool
854 Input_file::try_extra_search_path(int* pindex,
855 const Input_file_argument* input_argument,
856 std::string filename, std::string* found_name,
857 std::string* namep)
859 if (input_argument->extra_search_path() == NULL)
860 return false;
862 std::string name = input_argument->extra_search_path();
863 if (!IS_DIR_SEPARATOR(name[name.length() - 1]))
864 name += '/';
865 name += filename;
867 struct stat dummy_stat;
868 if (*pindex > 0 || ::stat(name.c_str(), &dummy_stat) < 0)
869 return false;
871 *found_name = filename;
872 *namep = name;
873 return true;
876 // Find the actual file.
877 // If the filename is not absolute, we assume it is in the current
878 // directory *except* when:
879 // A) input_argument_->is_lib() is true;
880 // B) input_argument_->is_searched_file() is true; or
881 // C) input_argument_->extra_search_path() is not empty.
882 // In each, we look in extra_search_path + library_path to find
883 // the file location, rather than the current directory.
885 bool
886 Input_file::find_file(const Dirsearch& dirpath, int* pindex,
887 const Input_file_argument* input_argument,
888 bool* is_in_sysroot,
889 std::string* found_name, std::string* namep)
891 std::string name;
893 // Case 1: name is an absolute file, just try to open it
894 // Case 2: name is relative but is_lib is false, is_searched_file is false,
895 // and extra_search_path is empty
896 if (IS_ABSOLUTE_PATH(input_argument->name())
897 || (!input_argument->is_lib()
898 && !input_argument->is_searched_file()
899 && input_argument->extra_search_path() == NULL))
901 name = input_argument->name();
902 *found_name = name;
903 *namep = name;
904 return true;
906 // Case 3: is_lib is true or is_searched_file is true
907 else if (input_argument->is_lib()
908 || input_argument->is_searched_file())
910 std::string n1, n2;
911 if (input_argument->is_lib())
913 n1 = "lib";
914 n1 += input_argument->name();
915 if (parameters->options().is_static()
916 || !input_argument->options().Bdynamic())
917 n1 += ".a";
918 else
920 n2 = n1 + ".a";
921 n1 += ".so";
924 else
925 n1 = input_argument->name();
927 if (Input_file::try_extra_search_path(pindex, input_argument, n1,
928 found_name, namep))
929 return true;
931 if (!n2.empty() && Input_file::try_extra_search_path(pindex,
932 input_argument, n2,
933 found_name, namep))
934 return true;
936 // It is not in the extra_search_path.
937 name = dirpath.find(n1, n2, is_in_sysroot, pindex);
938 if (name.empty())
940 gold_error(_("cannot find %s%s"),
941 input_argument->is_lib() ? "-l" : "",
942 input_argument->name());
943 return false;
945 if (n2.empty() || name[name.length() - 1] == 'o')
946 *found_name = n1;
947 else
948 *found_name = n2;
949 *namep = name;
950 return true;
952 // Case 4: extra_search_path is not empty
953 else
955 gold_assert(input_argument->extra_search_path() != NULL);
957 if (try_extra_search_path(pindex, input_argument, input_argument->name(),
958 found_name, namep))
959 return true;
961 // extra_search_path failed, so check the normal search-path.
962 int index = *pindex;
963 if (index > 0)
964 --index;
965 name = dirpath.find(input_argument->name(), "",
966 is_in_sysroot, &index);
967 if (name.empty())
969 gold_error(_("cannot find %s"),
970 input_argument->name());
971 return false;
973 *found_name = input_argument->name();
974 *namep = name;
975 *pindex = index + 1;
976 return true;
980 // Open the file.
982 bool
983 Input_file::open(const Dirsearch& dirpath, const Task* task, int* pindex)
985 std::string name;
986 if (!Input_file::find_file(dirpath, pindex, this->input_argument_,
987 &this->is_in_sysroot_, &this->found_name_, &name))
988 return false;
990 // Now that we've figured out where the file lives, try to open it.
992 General_options::Object_format format =
993 this->input_argument_->options().format_enum();
994 bool ok;
995 if (format == General_options::OBJECT_FORMAT_ELF)
997 ok = this->file_.open(task, name);
998 this->format_ = FORMAT_ELF;
1000 else
1002 gold_assert(format == General_options::OBJECT_FORMAT_BINARY);
1003 ok = this->open_binary(task, name);
1004 this->format_ = FORMAT_BINARY;
1007 if (!ok)
1009 gold_error(_("cannot open %s: %s"),
1010 name.c_str(), strerror(errno));
1011 this->format_ = FORMAT_NONE;
1012 return false;
1015 return true;
1018 // Open a file for --format binary.
1020 bool
1021 Input_file::open_binary(const Task* task, const std::string& name)
1023 // In order to open a binary file, we need machine code, size, and
1024 // endianness. We may not have a valid target at this point, in
1025 // which case we use the default target.
1026 parameters_force_valid_target();
1027 const Target& target(parameters->target());
1029 Binary_to_elf binary_to_elf(target.machine_code(),
1030 target.get_size(),
1031 target.is_big_endian(),
1032 name);
1033 if (!binary_to_elf.convert(task))
1034 return false;
1035 return this->file_.open(task, name, binary_to_elf.converted_data_leak(),
1036 binary_to_elf.converted_size());
1039 } // End namespace gold.