1 // fileread.cc -- read files for gold
3 // Copyright 2006, 2007, 2008, 2009, 2010, 2011 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.
37 #include "filenames.h"
40 #include "parameters.h"
42 #include "dirsearch.h"
45 #include "descriptors.h"
46 #include "gold-threads.h"
50 struct iovec { void* iov_base; size_t iov_len; };
52 readv(int, const iovec*, int)
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);
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;
72 // Class File_read::View.
74 File_read::View::~View()
76 gold_assert(!this->is_locked());
77 switch (this->data_ownership_)
79 case DATA_ALLOCATED_ARRAY:
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())
87 file_counts_initialize_lock.initialize();
88 Hold_optional_lock hl(file_counts_lock);
89 File_read::current_mapped_bytes -= this->size_;
100 File_read::View::lock()
106 File_read::View::unlock()
108 gold_assert(this->lock_count_ > 0);
113 File_read::View::is_locked()
115 return this->lock_count_ > 0;
120 File_read::~File_read()
122 gold_assert(this->token_.is_writable());
123 if (this->is_descriptor_opened_)
125 release_descriptor(this->descriptor_, true);
126 this->descriptor_ = -1;
127 this->is_descriptor_opened_ = false;
130 this->clear_views(CLEAR_VIEWS_ALL);
136 File_read::open(const Task* task, const std::string& name)
138 gold_assert(this->token_.is_writable()
139 && this->descriptor_ < 0
140 && !this->is_descriptor_opened_
141 && this->name_.empty());
144 this->descriptor_ = open_descriptor(-1, this->name_.c_str(),
147 if (this->descriptor_ >= 0)
149 this->is_descriptor_opened_ = true;
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);
160 return this->descriptor_ >= 0;
163 // Open the file with the contents in memory.
166 File_read::open(const Task* task, const std::string& name,
167 const unsigned char* contents, off_t size)
169 gold_assert(this->token_.is_writable()
170 && this->descriptor_ < 0
171 && !this->is_descriptor_opened_
172 && this->name_.empty());
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_);
178 this->token_.add_writer(task);
182 // Reopen a descriptor if necessary.
185 File_read::reopen_descriptor()
187 if (!this->is_descriptor_opened_)
189 this->descriptor_ = open_descriptor(this->descriptor_,
192 if (this->descriptor_ < 0)
193 gold_fatal(_("could not reopen file %s"), this->name_.c_str());
194 this->is_descriptor_opened_ = true;
198 // Release the file. This is called when we are done with the file in
204 gold_assert(this->is_locked());
206 if (!parameters->options_valid() || parameters->options().stats())
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;
216 this->mapped_bytes_ = 0;
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)
223 this->clear_views(CLEAR_VIEWS_NORMAL);
224 if (this->is_descriptor_opened_)
226 release_descriptor(this->descriptor_, false);
227 this->is_descriptor_opened_ = false;
231 this->released_ = true;
237 File_read::lock(const Task* task)
239 gold_assert(this->released_);
240 this->token_.add_writer(task);
241 this->released_ = false;
247 File_read::unlock(const Task* task)
250 this->token_.remove_writer(task);
253 // Return whether the file is locked.
256 File_read::is_locked() const
258 if (!this->token_.is_writable())
260 // The file is not locked, so it should have been released.
261 gold_assert(this->released_);
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.
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
276 if (vshifted != NULL)
279 // If we have the whole file mmapped, and the alignment is right,
281 if (this->whole_file_view_)
282 if (byteshift == -1U || byteshift == 0)
283 return this->whole_file_view_;
285 off_t page = File_read::page_offset(start);
287 unsigned int bszero = 0;
288 Views::const_iterator p = this->views_.upper_bound(std::make_pair(page - 1,
291 while (p != this->views_.end() && p->first.first <= page)
293 if (p->second->start() <= start
294 && (p->second->start() + static_cast<off_t>(p->second->size())
295 >= start + static_cast<off_t>(size)))
297 if (byteshift == -1U || byteshift == p->second->byteshift())
299 p->second->set_accessed();
303 if (vshifted != NULL && *vshifted == NULL)
304 *vshifted = p->second;
313 // Read SIZE bytes from the file starting at offset START. Read into
317 File_read::do_read(off_t start, section_size_type size, void* p)
320 if (this->whole_file_view_ != NULL)
322 bytes = this->size_ - start;
323 if (static_cast<section_size_type>(bytes) >= size)
325 memcpy(p, this->whole_file_view_->data() + start, size);
331 this->reopen_descriptor();
332 bytes = ::pread(this->descriptor_, p, size, start);
333 if (static_cast<section_size_type>(bytes) == size)
338 gold_fatal(_("%s: pread failed: %s"),
339 this->filename().c_str(), strerror(errno));
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));
351 // Read data from the file.
354 File_read::read(off_t start, section_size_type size, void* p)
356 const File_read::View* pv = this->find_view(start, size, -1U, NULL);
359 memcpy(p, pv->data() + (start - pv->start() + pv->byteshift()), size);
363 this->do_read(start, size, p);
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.
371 File_read::add_view(File_read::View* v)
373 std::pair<Views::iterator, bool> ins =
374 this->views_.insert(std::make_pair(std::make_pair(v->start(),
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())
390 this->saved_views_.push_back(vold);
392 ins.first->second = v;
395 // Make a new view with a specified byteshift, reading the data from
399 File_read::make_view(off_t start, section_size_type size,
400 unsigned int byteshift, bool cache)
402 gold_assert(size > 0);
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));
414 off_t poff = File_read::page_offset(start);
416 section_size_type psize = File_read::pages(size + (start - poff));
418 if (poff + static_cast<off_t>(psize) >= this->size_)
420 psize = this->size_ - poff;
421 gold_assert(psize >= size);
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);
435 this->reopen_descriptor();
436 void* p = ::mmap(NULL, psize, PROT_READ, MAP_PRIVATE,
437 this->descriptor_, poff);
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),
445 this->mapped_bytes_ += psize;
447 const unsigned char* pbytes = static_cast<const unsigned char*>(p);
448 v = new File_read::View(poff, psize, pbytes, 0, cache,
457 // Find a View or make a new one, shifted as required by the file
458 // offset OFFSET and ALIGNED.
461 File_read::find_or_make_view(off_t offset, off_t start,
462 section_size_type size, bool aligned, bool cache)
464 unsigned int byteshift;
469 unsigned int target_size = (!parameters->target_valid()
471 : parameters->target().get_size());
472 byteshift = offset & ((target_size / 8) - 1);
474 // Set BYTESHIFT to the number of dummy bytes which must be
475 // inserted before the data in order for this data to be
478 byteshift = (target_size / 8) - byteshift;
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);
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,
502 // If VSHIFTED is not NULL, then it has the data we need, but with
503 // the wrong byteshift.
507 gold_assert(aligned);
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());
513 File_read::View* shifted_view =
514 new File_read::View(v->start(), v->size(), pbytes, byteshift,
515 cache, View::DATA_ALLOCATED_ARRAY);
517 this->add_view(shifted_view);
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,
528 // Get a view into the file.
531 File_read::get_view(off_t offset, off_t start, section_size_type size,
532 bool aligned, bool cache)
534 File_read::View* pv = this->find_or_make_view(offset, start, size,
536 return pv->data() + (offset + start - pv->start() + pv->byteshift());
540 File_read::get_lasting_view(off_t offset, off_t start, section_size_type size,
541 bool aligned, bool cache)
543 File_read::View* pv = this->find_or_make_view(offset, start, size,
546 return new File_view(*this, pv,
548 + (offset + start - pv->start() + pv->byteshift())));
551 // Use readv to read COUNT entries from RM starting at START. BASE
552 // must be added to all file offsets in RM.
555 File_read::do_readv(off_t base, const Read_multiple& rm, size_t start,
558 unsigned char discard[File_read::page_size];
559 iovec iov[File_read::max_readv_entries * 2];
560 size_t iov_index = 0;
562 off_t first_offset = rm[start].file_offset;
563 off_t last_offset = first_offset;
565 for (size_t i = 0; i < count; ++i)
567 const Read_multiple_entry& i_entry(rm[start + i]);
569 if (i_entry.file_offset > last_offset)
571 size_t skip = i_entry.file_offset - last_offset;
572 gold_assert(skip <= sizeof discard);
574 iov[iov_index].iov_base = discard;
575 iov[iov_index].iov_len = skip;
581 iov[iov_index].iov_base = i_entry.buffer;
582 iov[iov_index].iov_len = i_entry.size;
585 want += i_entry.size;
587 last_offset = i_entry.file_offset + i_entry.size;
590 this->reopen_descriptor();
592 gold_assert(iov_index < sizeof iov / sizeof iov[0]);
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));
598 ssize_t got = ::readv(this->descriptor_, iov, iov_index);
601 gold_fatal(_("%s: readv failed: %s"),
602 this->filename().c_str(), strerror(errno));
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));
611 #if !defined(HAVE_READV)
612 #define GOLD_IOV_MAX 1
613 #elif defined(IOV_MAX)
614 #define GOLD_IOV_MAX IOV_MAX
616 #define GOLD_IOV_MAX (File_read::max_readv_entries * 2)
619 // Read several pieces of data from the file.
622 File_read::read_multiple(off_t base, const Read_multiple& rm)
624 static size_t iov_max = GOLD_IOV_MAX;
625 size_t count = rm.size();
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;
635 for (j = i + 1; j < count; ++j)
637 if (j - i >= File_read::max_readv_entries || j - i >= iov_max / 2)
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)
649 this->read(base + i_off, i_entry.size, i_entry.buffer);
652 File_read::View* view = this->find_view(base + i_off,
656 this->do_readv(base, rm, i, j - i);
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)
664 const Read_multiple_entry& k_entry(rm[k]);
665 gold_assert((convert_to_section_size_type(k_entry.file_offset
668 <= convert_to_section_size_type(end_off
670 memcpy(k_entry.buffer,
671 v + (k_entry.file_offset - i_off),
681 // Mark all views as no longer cached.
684 File_read::clear_view_cache_marks()
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)
692 for (Views::iterator p = this->views_.begin();
693 p != this->views_.end();
695 p->second->clear_cache();
696 for (Saved_views::iterator p = this->saved_views_.begin();
697 p != this->saved_views_.end();
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
708 File_read::clear_views(Clear_views_mode mode)
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())
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() && keep_files_mapped)
721 should_delete = false;
722 else if (this->object_count_ > 1
723 && p->second->accessed()
724 && mode != CLEAR_VIEWS_ARCHIVE)
725 should_delete = false;
727 should_delete = true;
731 if (p->second == this->whole_file_view_)
732 this->whole_file_view_ = NULL;
735 // map::erase invalidates only the iterator to the deleted
737 Views::iterator pe = p;
739 this->views_.erase(pe);
743 p->second->clear_accessed();
748 Saved_views::iterator q = this->saved_views_.begin();
749 while (q != this->saved_views_.end())
751 if (!(*q)->is_locked())
754 q = this->saved_views_.erase(q);
758 gold_assert(mode != CLEAR_VIEWS_ALL);
764 // Print statistical information to stderr. This is used for --stats.
767 File_read::print_stats()
769 fprintf(stderr, _("%s: total bytes mapped for read: %llu\n"),
770 program_name, File_read::total_mapped_bytes);
771 fprintf(stderr, _("%s: maximum bytes mapped for read at one time: %llu\n"),
772 program_name, File_read::maximum_mapped_bytes);
777 File_view::~File_view()
779 gold_assert(this->file_.is_locked());
780 this->view_->unlock();
785 // Create a file for testing.
787 Input_file::Input_file(const Task* task, const char* name,
788 const unsigned char* contents, off_t size)
791 this->input_argument_ =
792 new Input_file_argument(name, Input_file_argument::INPUT_FILE_TYPE_FILE,
793 "", false, Position_dependent_options());
794 bool ok = this->file_.open(task, name, contents, size);
798 // Return the position dependent options in force for this file.
800 const Position_dependent_options&
801 Input_file::options() const
803 return this->input_argument_->options();
806 // Return the name given by the user. For -lc this will return "c".
809 Input_file::name() const
811 return this->input_argument_->name();
814 // Return whether this file is in a system directory.
817 Input_file::is_in_system_directory() const
819 if (this->is_in_sysroot())
821 return parameters->options().is_in_system_directory(this->filename());
824 // Return whether we are only reading symbols.
827 Input_file::just_symbols() const
829 return this->input_argument_->just_symbols();
832 // Return whether this is a file that we will search for in the list
836 Input_file::will_search_for() const
838 return (!IS_ABSOLUTE_PATH(this->input_argument_->name())
839 && (this->input_argument_->is_lib()
840 || this->input_argument_->is_searched_file()
841 || this->input_argument_->extra_search_path() != NULL));
844 // Return the file last modification time. Calls gold_fatal if the stat
845 // system call failed.
848 File_read::get_mtime()
850 struct stat file_stat;
851 this->reopen_descriptor();
853 if (fstat(this->descriptor_, &file_stat) < 0)
854 gold_fatal(_("%s: stat failed: %s"), this->name_.c_str(),
856 #ifdef HAVE_STAT_ST_MTIM
857 return Timespec(file_stat.st_mtim.tv_sec, file_stat.st_mtim.tv_nsec);
859 return Timespec(file_stat.st_mtime, 0);
863 // Try to find a file in the extra search dirs. Returns true on success.
866 Input_file::try_extra_search_path(int* pindex,
867 const Input_file_argument* input_argument,
868 std::string filename, std::string* found_name,
871 if (input_argument->extra_search_path() == NULL)
874 std::string name = input_argument->extra_search_path();
875 if (!IS_DIR_SEPARATOR(name[name.length() - 1]))
879 struct stat dummy_stat;
880 if (*pindex > 0 || ::stat(name.c_str(), &dummy_stat) < 0)
883 *found_name = filename;
888 // Find the actual file.
889 // If the filename is not absolute, we assume it is in the current
890 // directory *except* when:
891 // A) input_argument_->is_lib() is true;
892 // B) input_argument_->is_searched_file() is true; or
893 // C) input_argument_->extra_search_path() is not empty.
894 // In each, we look in extra_search_path + library_path to find
895 // the file location, rather than the current directory.
898 Input_file::find_file(const Dirsearch& dirpath, int* pindex,
899 const Input_file_argument* input_argument,
901 std::string* found_name, std::string* namep)
905 // Case 1: name is an absolute file, just try to open it
906 // Case 2: name is relative but is_lib is false, is_searched_file is false,
907 // and extra_search_path is empty
908 if (IS_ABSOLUTE_PATH(input_argument->name())
909 || (!input_argument->is_lib()
910 && !input_argument->is_searched_file()
911 && input_argument->extra_search_path() == NULL))
913 name = input_argument->name();
918 // Case 3: is_lib is true or is_searched_file is true
919 else if (input_argument->is_lib()
920 || input_argument->is_searched_file())
923 if (input_argument->is_lib())
926 n1 += input_argument->name();
927 if (parameters->options().is_static()
928 || !input_argument->options().Bdynamic())
937 n1 = input_argument->name();
939 if (Input_file::try_extra_search_path(pindex, input_argument, n1,
943 if (!n2.empty() && Input_file::try_extra_search_path(pindex,
948 // It is not in the extra_search_path.
949 name = dirpath.find(n1, n2, is_in_sysroot, pindex);
952 gold_error(_("cannot find %s%s"),
953 input_argument->is_lib() ? "-l" : "",
954 input_argument->name());
957 if (n2.empty() || name[name.length() - 1] == 'o')
964 // Case 4: extra_search_path is not empty
967 gold_assert(input_argument->extra_search_path() != NULL);
969 if (try_extra_search_path(pindex, input_argument, input_argument->name(),
973 // extra_search_path failed, so check the normal search-path.
977 name = dirpath.find(input_argument->name(), "",
978 is_in_sysroot, &index);
981 gold_error(_("cannot find %s"),
982 input_argument->name());
985 *found_name = input_argument->name();
995 Input_file::open(const Dirsearch& dirpath, const Task* task, int* pindex)
998 if (!Input_file::find_file(dirpath, pindex, this->input_argument_,
999 &this->is_in_sysroot_, &this->found_name_, &name))
1002 // Now that we've figured out where the file lives, try to open it.
1004 General_options::Object_format format =
1005 this->input_argument_->options().format_enum();
1007 if (format == General_options::OBJECT_FORMAT_ELF)
1009 ok = this->file_.open(task, name);
1010 this->format_ = FORMAT_ELF;
1014 gold_assert(format == General_options::OBJECT_FORMAT_BINARY);
1015 ok = this->open_binary(task, name);
1016 this->format_ = FORMAT_BINARY;
1021 gold_error(_("cannot open %s: %s"),
1022 name.c_str(), strerror(errno));
1023 this->format_ = FORMAT_NONE;
1030 // Open a file for --format binary.
1033 Input_file::open_binary(const Task* task, const std::string& name)
1035 // In order to open a binary file, we need machine code, size, and
1036 // endianness. We may not have a valid target at this point, in
1037 // which case we use the default target.
1038 parameters_force_valid_target();
1039 const Target& target(parameters->target());
1041 Binary_to_elf binary_to_elf(target.machine_code(),
1043 target.is_big_endian(),
1045 if (!binary_to_elf.convert(task))
1047 return this->file_.open(task, name, binary_to_elf.converted_data_leak(),
1048 binary_to_elf.converted_size());
1051 } // End namespace gold.