1 // fileread.cc -- read files for gold
3 // Copyright 2006, 2007, 2008, 2009 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.
32 #include "filenames.h"
35 #include "parameters.h"
37 #include "dirsearch.h"
40 #include "descriptors.h"
44 struct iovec { void* iov_base; size_t iov_len };
46 readv(int, const iovec*, int)
55 // Class File_read::View.
57 File_read::View::~View()
59 gold_assert(!this->is_locked());
64 if (::munmap(const_cast<unsigned char*>(this->data_), this->size_) != 0)
65 gold_warning(_("munmap failed: %s"), strerror(errno));
67 File_read::current_mapped_bytes -= this->size_;
72 File_read::View::lock()
78 File_read::View::unlock()
80 gold_assert(this->lock_count_ > 0);
85 File_read::View::is_locked()
87 return this->lock_count_ > 0;
92 // The File_read static variables.
93 unsigned long long File_read::total_mapped_bytes;
94 unsigned long long File_read::current_mapped_bytes;
95 unsigned long long File_read::maximum_mapped_bytes;
97 File_read::~File_read()
99 gold_assert(this->token_.is_writable());
100 if (this->is_descriptor_opened_)
102 release_descriptor(this->descriptor_, true);
103 this->descriptor_ = -1;
104 this->is_descriptor_opened_ = false;
107 this->clear_views(true);
113 File_read::open(const Task* task, const std::string& name)
115 gold_assert(this->token_.is_writable()
116 && this->descriptor_ < 0
117 && !this->is_descriptor_opened_
118 && this->name_.empty());
121 this->descriptor_ = open_descriptor(-1, this->name_.c_str(),
124 if (this->descriptor_ >= 0)
126 this->is_descriptor_opened_ = true;
128 if (::fstat(this->descriptor_, &s) < 0)
129 gold_error(_("%s: fstat failed: %s"),
130 this->name_.c_str(), strerror(errno));
131 this->size_ = s.st_size;
132 gold_debug(DEBUG_FILES, "Attempt to open %s succeeded",
133 this->name_.c_str());
135 this->token_.add_writer(task);
138 return this->descriptor_ >= 0;
141 // Open the file with the contents in memory.
144 File_read::open(const Task* task, const std::string& name,
145 const unsigned char* contents, off_t size)
147 gold_assert(this->token_.is_writable()
148 && this->descriptor_ < 0
149 && !this->is_descriptor_opened_
150 && this->name_.empty());
152 this->contents_ = contents;
154 this->token_.add_writer(task);
158 // Reopen a descriptor if necessary.
161 File_read::reopen_descriptor()
163 if (!this->is_descriptor_opened_)
165 this->descriptor_ = open_descriptor(this->descriptor_,
168 if (this->descriptor_ < 0)
169 gold_fatal(_("could not reopen file %s"), this->name_.c_str());
170 this->is_descriptor_opened_ = true;
174 // Release the file. This is called when we are done with the file in
180 gold_assert(this->is_locked());
182 File_read::total_mapped_bytes += this->mapped_bytes_;
183 File_read::current_mapped_bytes += this->mapped_bytes_;
184 this->mapped_bytes_ = 0;
185 if (File_read::current_mapped_bytes > File_read::maximum_mapped_bytes)
186 File_read::maximum_mapped_bytes = File_read::current_mapped_bytes;
188 // Only clear views if there is only one attached object. Otherwise
189 // we waste time trying to clear cached archive views. Similarly
190 // for releasing the descriptor.
191 if (this->object_count_ <= 1)
193 this->clear_views(false);
194 if (this->is_descriptor_opened_)
196 release_descriptor(this->descriptor_, false);
197 this->is_descriptor_opened_ = false;
201 this->released_ = true;
207 File_read::lock(const Task* task)
209 gold_assert(this->released_);
210 this->token_.add_writer(task);
211 this->released_ = false;
217 File_read::unlock(const Task* task)
220 this->token_.remove_writer(task);
223 // Return whether the file is locked.
226 File_read::is_locked() const
228 if (!this->token_.is_writable())
230 // The file is not locked, so it should have been released.
231 gold_assert(this->released_);
235 // See if we have a view which covers the file starting at START for
236 // SIZE bytes. Return a pointer to the View if found, NULL if not.
237 // If BYTESHIFT is not -1U, the returned View must have the specified
238 // byte shift; otherwise, it may have any byte shift. If VSHIFTED is
239 // not NULL, this sets *VSHIFTED to a view which would have worked if
240 // not for the requested BYTESHIFT.
242 inline File_read::View*
243 File_read::find_view(off_t start, section_size_type size,
244 unsigned int byteshift, File_read::View** vshifted) const
246 if (vshifted != NULL)
249 off_t page = File_read::page_offset(start);
251 unsigned int bszero = 0;
252 Views::const_iterator p = this->views_.upper_bound(std::make_pair(page - 1,
255 while (p != this->views_.end() && p->first.first <= page)
257 if (p->second->start() <= start
258 && (p->second->start() + static_cast<off_t>(p->second->size())
259 >= start + static_cast<off_t>(size)))
261 if (byteshift == -1U || byteshift == p->second->byteshift())
263 p->second->set_accessed();
267 if (vshifted != NULL && *vshifted == NULL)
268 *vshifted = p->second;
277 // Read SIZE bytes from the file starting at offset START. Read into
281 File_read::do_read(off_t start, section_size_type size, void* p)
284 if (this->contents_ != NULL)
286 bytes = this->size_ - start;
287 if (static_cast<section_size_type>(bytes) >= size)
289 memcpy(p, this->contents_ + start, size);
295 this->reopen_descriptor();
296 bytes = ::pread(this->descriptor_, p, size, start);
297 if (static_cast<section_size_type>(bytes) == size)
302 gold_fatal(_("%s: pread failed: %s"),
303 this->filename().c_str(), strerror(errno));
308 gold_fatal(_("%s: file too short: read only %lld of %lld bytes at %lld"),
309 this->filename().c_str(),
310 static_cast<long long>(bytes),
311 static_cast<long long>(size),
312 static_cast<long long>(start));
315 // Read data from the file.
318 File_read::read(off_t start, section_size_type size, void* p)
320 const File_read::View* pv = this->find_view(start, size, -1U, NULL);
323 memcpy(p, pv->data() + (start - pv->start() + pv->byteshift()), size);
327 this->do_read(start, size, p);
330 // Add a new view. There may already be an existing view at this
331 // offset. If there is, the new view will be larger, and should
332 // replace the old view.
335 File_read::add_view(File_read::View* v)
337 std::pair<Views::iterator, bool> ins =
338 this->views_.insert(std::make_pair(std::make_pair(v->start(),
344 // There was an existing view at this offset. It must not be large
345 // enough. We can't delete it here, since something might be using
346 // it; we put it on a list to be deleted when the file is unlocked.
347 File_read::View* vold = ins.first->second;
348 gold_assert(vold->size() < v->size());
349 if (vold->should_cache())
354 this->saved_views_.push_back(vold);
356 ins.first->second = v;
359 // Make a new view with a specified byteshift, reading the data from
363 File_read::make_view(off_t start, section_size_type size,
364 unsigned int byteshift, bool cache)
366 gold_assert(size > 0);
368 // Check that start and end of the view are within the file.
369 if (start > this->size_
370 || (static_cast<unsigned long long>(size)
371 > static_cast<unsigned long long>(this->size_ - start)))
372 gold_fatal(_("%s: attempt to map %lld bytes at offset %lld exceeds "
373 "size of file; the file may be corrupt"),
374 this->filename().c_str(),
375 static_cast<long long>(size),
376 static_cast<long long>(start));
378 off_t poff = File_read::page_offset(start);
380 section_size_type psize = File_read::pages(size + (start - poff));
382 if (poff + static_cast<off_t>(psize) >= this->size_)
384 psize = this->size_ - poff;
385 gold_assert(psize >= size);
389 if (this->contents_ != NULL || byteshift != 0)
391 unsigned char* p = new unsigned char[psize + byteshift];
392 memset(p, 0, byteshift);
393 this->do_read(poff, psize, p + byteshift);
394 v = new File_read::View(poff, psize, p, byteshift, cache, false);
398 this->reopen_descriptor();
399 void* p = ::mmap(NULL, psize, PROT_READ, MAP_PRIVATE,
400 this->descriptor_, poff);
402 gold_fatal(_("%s: mmap offset %lld size %lld failed: %s"),
403 this->filename().c_str(),
404 static_cast<long long>(poff),
405 static_cast<long long>(psize),
408 this->mapped_bytes_ += psize;
410 const unsigned char* pbytes = static_cast<const unsigned char*>(p);
411 v = new File_read::View(poff, psize, pbytes, 0, cache, true);
419 // Find a View or make a new one, shifted as required by the file
420 // offset OFFSET and ALIGNED.
423 File_read::find_or_make_view(off_t offset, off_t start,
424 section_size_type size, bool aligned, bool cache)
426 unsigned int byteshift;
431 unsigned int target_size = (!parameters->target_valid()
433 : parameters->target().get_size());
434 byteshift = offset & ((target_size / 8) - 1);
436 // Set BYTESHIFT to the number of dummy bytes which must be
437 // inserted before the data in order for this data to be
440 byteshift = (target_size / 8) - byteshift;
443 // Try to find a View with the required BYTESHIFT.
444 File_read::View* vshifted;
445 File_read::View* v = this->find_view(offset + start, size,
446 aligned ? byteshift : -1U,
455 // If VSHIFTED is not NULL, then it has the data we need, but with
456 // the wrong byteshift.
460 gold_assert(aligned);
462 unsigned char* pbytes = new unsigned char[v->size() + byteshift];
463 memset(pbytes, 0, byteshift);
464 memcpy(pbytes + byteshift, v->data() + v->byteshift(), v->size());
466 File_read::View* shifted_view = new File_read::View(v->start(), v->size(),
470 this->add_view(shifted_view);
474 // Make a new view. If we don't need an aligned view, use a
475 // byteshift of 0, so that we can use mmap.
476 return this->make_view(offset + start, size,
477 aligned ? byteshift : 0,
481 // Get a view into the file.
484 File_read::get_view(off_t offset, off_t start, section_size_type size,
485 bool aligned, bool cache)
487 File_read::View* pv = this->find_or_make_view(offset, start, size,
489 return pv->data() + (offset + start - pv->start() + pv->byteshift());
493 File_read::get_lasting_view(off_t offset, off_t start, section_size_type size,
494 bool aligned, bool cache)
496 File_read::View* pv = this->find_or_make_view(offset, start, size,
499 return new File_view(*this, pv,
501 + (offset + start - pv->start() + pv->byteshift())));
504 // Use readv to read COUNT entries from RM starting at START. BASE
505 // must be added to all file offsets in RM.
508 File_read::do_readv(off_t base, const Read_multiple& rm, size_t start,
511 unsigned char discard[File_read::page_size];
512 iovec iov[File_read::max_readv_entries * 2];
513 size_t iov_index = 0;
515 off_t first_offset = rm[start].file_offset;
516 off_t last_offset = first_offset;
518 for (size_t i = 0; i < count; ++i)
520 const Read_multiple_entry& i_entry(rm[start + i]);
522 if (i_entry.file_offset > last_offset)
524 size_t skip = i_entry.file_offset - last_offset;
525 gold_assert(skip <= sizeof discard);
527 iov[iov_index].iov_base = discard;
528 iov[iov_index].iov_len = skip;
534 iov[iov_index].iov_base = i_entry.buffer;
535 iov[iov_index].iov_len = i_entry.size;
538 want += i_entry.size;
540 last_offset = i_entry.file_offset + i_entry.size;
543 this->reopen_descriptor();
545 gold_assert(iov_index < sizeof iov / sizeof iov[0]);
547 if (::lseek(this->descriptor_, base + first_offset, SEEK_SET) < 0)
548 gold_fatal(_("%s: lseek failed: %s"),
549 this->filename().c_str(), strerror(errno));
551 ssize_t got = ::readv(this->descriptor_, iov, iov_index);
554 gold_fatal(_("%s: readv failed: %s"),
555 this->filename().c_str(), strerror(errno));
557 gold_fatal(_("%s: file too short: read only %zd of %zd bytes at %lld"),
558 this->filename().c_str(),
559 got, want, static_cast<long long>(base + first_offset));
562 // Read several pieces of data from the file.
565 File_read::read_multiple(off_t base, const Read_multiple& rm)
567 size_t count = rm.size();
571 // Find up to MAX_READV_ENTRIES consecutive entries which are
572 // less than one page apart.
573 const Read_multiple_entry& i_entry(rm[i]);
574 off_t i_off = i_entry.file_offset;
575 off_t end_off = i_off + i_entry.size;
577 for (j = i + 1; j < count; ++j)
579 if (j - i >= File_read::max_readv_entries)
581 const Read_multiple_entry& j_entry(rm[j]);
582 off_t j_off = j_entry.file_offset;
583 gold_assert(j_off >= end_off);
584 off_t j_end_off = j_off + j_entry.size;
585 if (j_end_off - end_off >= File_read::page_size)
591 this->read(base + i_off, i_entry.size, i_entry.buffer);
594 File_read::View* view = this->find_view(base + i_off,
598 this->do_readv(base, rm, i, j - i);
601 const unsigned char* v = (view->data()
602 + (base + i_off - view->start()
603 + view->byteshift()));
604 for (size_t k = i; k < j; ++k)
606 const Read_multiple_entry& k_entry(rm[k]);
607 gold_assert((convert_to_section_size_type(k_entry.file_offset
610 <= convert_to_section_size_type(end_off
612 memcpy(k_entry.buffer,
613 v + (k_entry.file_offset - i_off),
623 // Mark all views as no longer cached.
626 File_read::clear_view_cache_marks()
628 // Just ignore this if there are multiple objects associated with
629 // the file. Otherwise we will wind up uncaching and freeing some
630 // views for other objects.
631 if (this->object_count_ > 1)
634 for (Views::iterator p = this->views_.begin();
635 p != this->views_.end();
637 p->second->clear_cache();
638 for (Saved_views::iterator p = this->saved_views_.begin();
639 p != this->saved_views_.end();
644 // Remove all the file views. For a file which has multiple
645 // associated objects (i.e., an archive), we keep accessed views
646 // around until next time, in the hopes that they will be useful for
650 File_read::clear_views(bool destroying)
652 Views::iterator p = this->views_.begin();
653 while (p != this->views_.end())
656 if (p->second->is_locked())
657 should_delete = false;
659 should_delete = true;
660 else if (p->second->should_cache())
661 should_delete = false;
662 else if (this->object_count_ > 1 && p->second->accessed())
663 should_delete = false;
665 should_delete = true;
671 // map::erase invalidates only the iterator to the deleted
673 Views::iterator pe = p;
675 this->views_.erase(pe);
679 gold_assert(!destroying);
680 p->second->clear_accessed();
685 Saved_views::iterator q = this->saved_views_.begin();
686 while (q != this->saved_views_.end())
688 if (!(*q)->is_locked())
691 q = this->saved_views_.erase(q);
695 gold_assert(!destroying);
701 // Print statistical information to stderr. This is used for --stats.
704 File_read::print_stats()
706 fprintf(stderr, _("%s: total bytes mapped for read: %llu\n"),
707 program_name, File_read::total_mapped_bytes);
708 fprintf(stderr, _("%s: maximum bytes mapped for read at one time: %llu\n"),
709 program_name, File_read::maximum_mapped_bytes);
714 File_view::~File_view()
716 gold_assert(this->file_.is_locked());
717 this->view_->unlock();
722 // Create a file for testing.
724 Input_file::Input_file(const Task* task, const char* name,
725 const unsigned char* contents, off_t size)
728 this->input_argument_ =
729 new Input_file_argument(name, Input_file_argument::INPUT_FILE_TYPE_FILE,
730 "", false, Position_dependent_options());
731 bool ok = this->file_.open(task, name, contents, size);
735 // Return the position dependent options in force for this file.
737 const Position_dependent_options&
738 Input_file::options() const
740 return this->input_argument_->options();
743 // Return the name given by the user. For -lc this will return "c".
746 Input_file::name() const
748 return this->input_argument_->name();
751 // Return whether this file is in a system directory.
754 Input_file::is_in_system_directory() const
756 if (this->is_in_sysroot())
758 return parameters->options().is_in_system_directory(this->filename());
761 // Return whether we are only reading symbols.
764 Input_file::just_symbols() const
766 return this->input_argument_->just_symbols();
769 // Return whether this is a file that we will search for in the list
773 Input_file::will_search_for() const
775 return (!IS_ABSOLUTE_PATH(this->input_argument_->name())
776 && (this->input_argument_->is_lib()
777 || this->input_argument_->is_searched_file()
778 || this->input_argument_->extra_search_path() != NULL));
781 // Return the file last modification time. Calls gold_fatal if the stat
782 // system call failed.
785 File_read::get_mtime()
787 struct stat file_stat;
788 this->reopen_descriptor();
790 if (fstat(this->descriptor_, &file_stat) < 0)
791 gold_fatal(_("%s: stat failed: %s"), this->name_.c_str(),
793 // TODO: do a configure check if st_mtim is present and get the
794 // nanoseconds part if it is.
795 return Timespec(file_stat.st_mtime, 0);
800 // If the filename is not absolute, we assume it is in the current
801 // directory *except* when:
802 // A) input_argument_->is_lib() is true;
803 // B) input_argument_->is_searched_file() is true; or
804 // C) input_argument_->extra_search_path() is not empty.
805 // In each, we look in extra_search_path + library_path to find
806 // the file location, rather than the current directory.
809 Input_file::open(const Dirsearch& dirpath, const Task* task, int *pindex)
813 // Case 1: name is an absolute file, just try to open it
814 // Case 2: name is relative but is_lib is false, is_searched_file is false,
815 // and extra_search_path is empty
816 if (IS_ABSOLUTE_PATH(this->input_argument_->name())
817 || (!this->input_argument_->is_lib()
818 && !this->input_argument_->is_searched_file()
819 && this->input_argument_->extra_search_path() == NULL))
821 name = this->input_argument_->name();
822 this->found_name_ = name;
824 // Case 3: is_lib is true or is_searched_file is true
825 else if (this->input_argument_->is_lib()
826 || this->input_argument_->is_searched_file())
828 // We don't yet support extra_search_path with -l.
829 gold_assert(this->input_argument_->extra_search_path() == NULL);
831 if (this->input_argument_->is_lib())
834 n1 += this->input_argument_->name();
835 if (parameters->options().is_static()
836 || !this->input_argument_->options().Bdynamic())
845 n1 = this->input_argument_->name();
846 name = dirpath.find(n1, n2, &this->is_in_sysroot_, pindex);
849 gold_error(_("cannot find %s%s"),
850 this->input_argument_->is_lib() ? "-l" : "",
851 this->input_argument_->name());
854 if (n2.empty() || name[name.length() - 1] == 'o')
855 this->found_name_ = n1;
857 this->found_name_ = n2;
859 // Case 4: extra_search_path is not empty
862 gold_assert(this->input_argument_->extra_search_path() != NULL);
864 // First, check extra_search_path.
865 name = this->input_argument_->extra_search_path();
866 if (!IS_DIR_SEPARATOR (name[name.length() - 1]))
868 name += this->input_argument_->name();
869 struct stat dummy_stat;
870 if (*pindex > 0 || ::stat(name.c_str(), &dummy_stat) < 0)
872 // extra_search_path failed, so check the normal search-path.
876 name = dirpath.find(this->input_argument_->name(), "",
877 &this->is_in_sysroot_, &index);
880 gold_error(_("cannot find %s"),
881 this->input_argument_->name());
886 this->found_name_ = this->input_argument_->name();
889 // Now that we've figured out where the file lives, try to open it.
891 General_options::Object_format format =
892 this->input_argument_->options().format_enum();
894 if (format == General_options::OBJECT_FORMAT_ELF)
895 ok = this->file_.open(task, name);
898 gold_assert(format == General_options::OBJECT_FORMAT_BINARY);
899 ok = this->open_binary(task, name);
904 gold_error(_("cannot open %s: %s"),
905 name.c_str(), strerror(errno));
912 // Open a file for --format binary.
915 Input_file::open_binary(const Task* task, const std::string& name)
917 // In order to open a binary file, we need machine code, size, and
918 // endianness. We may not have a valid target at this point, in
919 // which case we use the default target.
920 parameters_force_valid_target();
921 const Target& target(parameters->target());
923 Binary_to_elf binary_to_elf(target.machine_code(),
925 target.is_big_endian(),
927 if (!binary_to_elf.convert(task))
929 return this->file_.open(task, name, binary_to_elf.converted_data_leak(),
930 binary_to_elf.converted_size());
933 } // End namespace gold.