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)
61 // Class File_read::View.
63 File_read::View::~View()
65 gold_assert(!this->is_locked());
66 switch (this->data_ownership_)
68 case DATA_ALLOCATED_ARRAY:
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_;
84 File_read::View::lock()
90 File_read::View::unlock()
92 gold_assert(this->lock_count_ > 0);
97 File_read::View::is_locked()
99 return this->lock_count_ > 0;
104 // A lock for the File_read static variables.
105 static Lock* file_counts_lock = NULL;
106 static Initialize_lock file_counts_initialize_lock(&file_counts_lock);
108 // The File_read static variables.
109 unsigned long long File_read::total_mapped_bytes;
110 unsigned long long File_read::current_mapped_bytes;
111 unsigned long long File_read::maximum_mapped_bytes;
113 File_read::~File_read()
115 gold_assert(this->token_.is_writable());
116 if (this->is_descriptor_opened_)
118 release_descriptor(this->descriptor_, true);
119 this->descriptor_ = -1;
120 this->is_descriptor_opened_ = false;
123 this->clear_views(CLEAR_VIEWS_ALL);
129 File_read::open(const Task* task, const std::string& name)
131 gold_assert(this->token_.is_writable()
132 && this->descriptor_ < 0
133 && !this->is_descriptor_opened_
134 && this->name_.empty());
137 this->descriptor_ = open_descriptor(-1, this->name_.c_str(),
140 if (this->descriptor_ >= 0)
142 this->is_descriptor_opened_ = true;
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);
153 return this->descriptor_ >= 0;
156 // Open the file with the contents in memory.
159 File_read::open(const Task* task, const std::string& name,
160 const unsigned char* contents, off_t size)
162 gold_assert(this->token_.is_writable()
163 && this->descriptor_ < 0
164 && !this->is_descriptor_opened_
165 && this->name_.empty());
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_);
171 this->token_.add_writer(task);
175 // Reopen a descriptor if necessary.
178 File_read::reopen_descriptor()
180 if (!this->is_descriptor_opened_)
182 this->descriptor_ = open_descriptor(this->descriptor_,
185 if (this->descriptor_ < 0)
186 gold_fatal(_("could not reopen file %s"), this->name_.c_str());
187 this->is_descriptor_opened_ = true;
191 // Release the file. This is called when we are done with the file in
197 gold_assert(this->is_locked());
199 if (!parameters->options_valid() || parameters->options().stats())
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;
209 this->mapped_bytes_ = 0;
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)
216 this->clear_views(CLEAR_VIEWS_NORMAL);
217 if (this->is_descriptor_opened_)
219 release_descriptor(this->descriptor_, false);
220 this->is_descriptor_opened_ = false;
224 this->released_ = true;
230 File_read::lock(const Task* task)
232 gold_assert(this->released_);
233 this->token_.add_writer(task);
234 this->released_ = false;
240 File_read::unlock(const Task* task)
243 this->token_.remove_writer(task);
246 // Return whether the file is locked.
249 File_read::is_locked() const
251 if (!this->token_.is_writable())
253 // The file is not locked, so it should have been released.
254 gold_assert(this->released_);
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.
265 inline File_read::View*
266 File_read::find_view(off_t start, section_size_type size,
267 unsigned int byteshift, File_read::View** vshifted) const
269 if (vshifted != NULL)
272 // If we have the whole file mmapped, and the alignment is right,
274 if (this->whole_file_view_)
275 if (byteshift == -1U || byteshift == 0)
276 return this->whole_file_view_;
278 off_t page = File_read::page_offset(start);
280 unsigned int bszero = 0;
281 Views::const_iterator p = this->views_.upper_bound(std::make_pair(page - 1,
284 while (p != this->views_.end() && p->first.first <= page)
286 if (p->second->start() <= start
287 && (p->second->start() + static_cast<off_t>(p->second->size())
288 >= start + static_cast<off_t>(size)))
290 if (byteshift == -1U || byteshift == p->second->byteshift())
292 p->second->set_accessed();
296 if (vshifted != NULL && *vshifted == NULL)
297 *vshifted = p->second;
306 // Read SIZE bytes from the file starting at offset START. Read into
310 File_read::do_read(off_t start, section_size_type size, void* p)
313 if (this->whole_file_view_ != NULL)
315 bytes = this->size_ - start;
316 if (static_cast<section_size_type>(bytes) >= size)
318 memcpy(p, this->whole_file_view_->data() + start, size);
324 this->reopen_descriptor();
325 bytes = ::pread(this->descriptor_, p, size, start);
326 if (static_cast<section_size_type>(bytes) == size)
331 gold_fatal(_("%s: pread failed: %s"),
332 this->filename().c_str(), strerror(errno));
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));
344 // Read data from the file.
347 File_read::read(off_t start, section_size_type size, void* p)
349 const File_read::View* pv = this->find_view(start, size, -1U, NULL);
352 memcpy(p, pv->data() + (start - pv->start() + pv->byteshift()), size);
356 this->do_read(start, size, p);
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.
364 File_read::add_view(File_read::View* v)
366 std::pair<Views::iterator, bool> ins =
367 this->views_.insert(std::make_pair(std::make_pair(v->start(),
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())
383 this->saved_views_.push_back(vold);
385 ins.first->second = v;
388 // Make a new view with a specified byteshift, reading the data from
392 File_read::make_view(off_t start, section_size_type size,
393 unsigned int byteshift, bool cache)
395 gold_assert(size > 0);
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));
407 off_t poff = File_read::page_offset(start);
409 section_size_type psize = File_read::pages(size + (start - poff));
411 if (poff + static_cast<off_t>(psize) >= this->size_)
413 psize = this->size_ - poff;
414 gold_assert(psize >= size);
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);
428 this->reopen_descriptor();
429 void* p = ::mmap(NULL, psize, PROT_READ, MAP_PRIVATE,
430 this->descriptor_, poff);
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),
438 this->mapped_bytes_ += psize;
440 const unsigned char* pbytes = static_cast<const unsigned char*>(p);
441 v = new File_read::View(poff, psize, pbytes, 0, cache,
450 // Find a View or make a new one, shifted as required by the file
451 // offset OFFSET and ALIGNED.
454 File_read::find_or_make_view(off_t offset, off_t start,
455 section_size_type size, bool aligned, bool cache)
457 unsigned int byteshift;
462 unsigned int target_size = (!parameters->target_valid()
464 : parameters->target().get_size());
465 byteshift = offset & ((target_size / 8) - 1);
467 // Set BYTESHIFT to the number of dummy bytes which must be
468 // inserted before the data in order for this data to be
471 byteshift = (target_size / 8) - byteshift;
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);
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,
495 // If VSHIFTED is not NULL, then it has the data we need, but with
496 // the wrong byteshift.
500 gold_assert(aligned);
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());
506 File_read::View* shifted_view =
507 new File_read::View(v->start(), v->size(), pbytes, byteshift,
508 cache, View::DATA_ALLOCATED_ARRAY);
510 this->add_view(shifted_view);
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,
521 // Get a view into the file.
524 File_read::get_view(off_t offset, off_t start, section_size_type size,
525 bool aligned, bool cache)
527 File_read::View* pv = this->find_or_make_view(offset, start, size,
529 return pv->data() + (offset + start - pv->start() + pv->byteshift());
533 File_read::get_lasting_view(off_t offset, off_t start, section_size_type size,
534 bool aligned, bool cache)
536 File_read::View* pv = this->find_or_make_view(offset, start, size,
539 return new File_view(*this, pv,
541 + (offset + start - pv->start() + pv->byteshift())));
544 // Use readv to read COUNT entries from RM starting at START. BASE
545 // must be added to all file offsets in RM.
548 File_read::do_readv(off_t base, const Read_multiple& rm, size_t start,
551 unsigned char discard[File_read::page_size];
552 iovec iov[File_read::max_readv_entries * 2];
553 size_t iov_index = 0;
555 off_t first_offset = rm[start].file_offset;
556 off_t last_offset = first_offset;
558 for (size_t i = 0; i < count; ++i)
560 const Read_multiple_entry& i_entry(rm[start + i]);
562 if (i_entry.file_offset > last_offset)
564 size_t skip = i_entry.file_offset - last_offset;
565 gold_assert(skip <= sizeof discard);
567 iov[iov_index].iov_base = discard;
568 iov[iov_index].iov_len = skip;
574 iov[iov_index].iov_base = i_entry.buffer;
575 iov[iov_index].iov_len = i_entry.size;
578 want += i_entry.size;
580 last_offset = i_entry.file_offset + i_entry.size;
583 this->reopen_descriptor();
585 gold_assert(iov_index < sizeof iov / sizeof iov[0]);
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));
591 ssize_t got = ::readv(this->descriptor_, iov, iov_index);
594 gold_fatal(_("%s: readv failed: %s"),
595 this->filename().c_str(), strerror(errno));
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));
604 #if !defined(HAVE_READV)
605 #define GOLD_IOV_MAX 1
606 #elif defined(IOV_MAX)
607 #define GOLD_IOV_MAX IOV_MAX
609 #define GOLD_IOV_MAX (File_read::max_readv_entries * 2)
612 // Read several pieces of data from the file.
615 File_read::read_multiple(off_t base, const Read_multiple& rm)
617 static size_t iov_max = GOLD_IOV_MAX;
618 size_t count = rm.size();
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;
628 for (j = i + 1; j < count; ++j)
630 if (j - i >= File_read::max_readv_entries || j - i >= iov_max / 2)
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)
642 this->read(base + i_off, i_entry.size, i_entry.buffer);
645 File_read::View* view = this->find_view(base + i_off,
649 this->do_readv(base, rm, i, j - i);
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)
657 const Read_multiple_entry& k_entry(rm[k]);
658 gold_assert((convert_to_section_size_type(k_entry.file_offset
661 <= convert_to_section_size_type(end_off
663 memcpy(k_entry.buffer,
664 v + (k_entry.file_offset - i_off),
674 // Mark all views as no longer cached.
677 File_read::clear_view_cache_marks()
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)
685 for (Views::iterator p = this->views_.begin();
686 p != this->views_.end();
688 p->second->clear_cache();
689 for (Saved_views::iterator p = this->saved_views_.begin();
690 p != this->saved_views_.end();
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
701 File_read::clear_views(Clear_views_mode mode)
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())
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;
720 should_delete = true;
724 if (p->second == this->whole_file_view_)
725 this->whole_file_view_ = NULL;
728 // map::erase invalidates only the iterator to the deleted
730 Views::iterator pe = p;
732 this->views_.erase(pe);
736 p->second->clear_accessed();
741 Saved_views::iterator q = this->saved_views_.begin();
742 while (q != this->saved_views_.end())
744 if (!(*q)->is_locked())
747 q = this->saved_views_.erase(q);
751 gold_assert(mode != CLEAR_VIEWS_ALL);
757 // Print statistical information to stderr. This is used for --stats.
760 File_read::print_stats()
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);
770 File_view::~File_view()
772 gold_assert(this->file_.is_locked());
773 this->view_->unlock();
778 // Create a file for testing.
780 Input_file::Input_file(const Task* task, const char* name,
781 const unsigned char* contents, off_t size)
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);
791 // Return the position dependent options in force for this file.
793 const Position_dependent_options&
794 Input_file::options() const
796 return this->input_argument_->options();
799 // Return the name given by the user. For -lc this will return "c".
802 Input_file::name() const
804 return this->input_argument_->name();
807 // Return whether this file is in a system directory.
810 Input_file::is_in_system_directory() const
812 if (this->is_in_sysroot())
814 return parameters->options().is_in_system_directory(this->filename());
817 // Return whether we are only reading symbols.
820 Input_file::just_symbols() const
822 return this->input_argument_->just_symbols();
825 // Return whether this is a file that we will search for in the list
829 Input_file::will_search_for() const
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));
837 // Return the file last modification time. Calls gold_fatal if the stat
838 // system call failed.
841 File_read::get_mtime()
843 struct stat file_stat;
844 this->reopen_descriptor();
846 if (fstat(this->descriptor_, &file_stat) < 0)
847 gold_fatal(_("%s: stat failed: %s"), this->name_.c_str(),
849 #ifdef HAVE_STAT_ST_MTIM
850 return Timespec(file_stat.st_mtim.tv_sec, file_stat.st_mtim.tv_nsec);
852 return Timespec(file_stat.st_mtime, 0);
856 // Try to find a file in the extra search dirs. Returns true on success.
859 Input_file::try_extra_search_path(int* pindex,
860 const Input_file_argument* input_argument,
861 std::string filename, std::string* found_name,
864 if (input_argument->extra_search_path() == NULL)
867 std::string name = input_argument->extra_search_path();
868 if (!IS_DIR_SEPARATOR(name[name.length() - 1]))
872 struct stat dummy_stat;
873 if (*pindex > 0 || ::stat(name.c_str(), &dummy_stat) < 0)
876 *found_name = filename;
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.
891 Input_file::find_file(const Dirsearch& dirpath, int* pindex,
892 const Input_file_argument* input_argument,
894 std::string* found_name, std::string* namep)
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))
906 name = input_argument->name();
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())
916 if (input_argument->is_lib())
919 n1 += input_argument->name();
920 if (parameters->options().is_static()
921 || !input_argument->options().Bdynamic())
930 n1 = input_argument->name();
932 if (Input_file::try_extra_search_path(pindex, input_argument, n1,
936 if (!n2.empty() && Input_file::try_extra_search_path(pindex,
941 // It is not in the extra_search_path.
942 name = dirpath.find(n1, n2, is_in_sysroot, pindex);
945 gold_error(_("cannot find %s%s"),
946 input_argument->is_lib() ? "-l" : "",
947 input_argument->name());
950 if (n2.empty() || name[name.length() - 1] == 'o')
957 // Case 4: extra_search_path is not empty
960 gold_assert(input_argument->extra_search_path() != NULL);
962 if (try_extra_search_path(pindex, input_argument, input_argument->name(),
966 // extra_search_path failed, so check the normal search-path.
970 name = dirpath.find(input_argument->name(), "",
971 is_in_sysroot, &index);
974 gold_error(_("cannot find %s"),
975 input_argument->name());
978 *found_name = input_argument->name();
988 Input_file::open(const Dirsearch& dirpath, const Task* task, int* pindex)
991 if (!Input_file::find_file(dirpath, pindex, this->input_argument_,
992 &this->is_in_sysroot_, &this->found_name_, &name))
995 // Now that we've figured out where the file lives, try to open it.
997 General_options::Object_format format =
998 this->input_argument_->options().format_enum();
1000 if (format == General_options::OBJECT_FORMAT_ELF)
1002 ok = this->file_.open(task, name);
1003 this->format_ = FORMAT_ELF;
1007 gold_assert(format == General_options::OBJECT_FORMAT_BINARY);
1008 ok = this->open_binary(task, name);
1009 this->format_ = FORMAT_BINARY;
1014 gold_error(_("cannot open %s: %s"),
1015 name.c_str(), strerror(errno));
1016 this->format_ = FORMAT_NONE;
1023 // Open a file for --format binary.
1026 Input_file::open_binary(const Task* task, const std::string& name)
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());
1034 Binary_to_elf binary_to_elf(target.machine_code(),
1036 target.is_big_endian(),
1038 if (!binary_to_elf.convert(task))
1040 return this->file_.open(task, name, binary_to_elf.converted_data_leak(),
1041 binary_to_elf.converted_size());
1044 } // End namespace gold.