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());
60 switch (this->data_ownership_
)
62 case DATA_ALLOCATED_ARRAY
:
66 if (::munmap(const_cast<unsigned char*>(this->data_
), this->size_
) != 0)
67 gold_warning(_("munmap failed: %s"), strerror(errno
));
68 File_read::current_mapped_bytes
-= this->size_
;
78 File_read::View::lock()
84 File_read::View::unlock()
86 gold_assert(this->lock_count_
> 0);
91 File_read::View::is_locked()
93 return this->lock_count_
> 0;
98 // The File_read static variables.
99 unsigned long long File_read::total_mapped_bytes
;
100 unsigned long long File_read::current_mapped_bytes
;
101 unsigned long long File_read::maximum_mapped_bytes
;
103 File_read::~File_read()
105 gold_assert(this->token_
.is_writable());
106 if (this->is_descriptor_opened_
)
108 release_descriptor(this->descriptor_
, true);
109 this->descriptor_
= -1;
110 this->is_descriptor_opened_
= false;
113 this->clear_views(true);
114 if (this->whole_file_view_
)
115 delete this->whole_file_view_
;
121 File_read::open(const Task
* task
, const std::string
& name
)
123 gold_assert(this->token_
.is_writable()
124 && this->descriptor_
< 0
125 && !this->is_descriptor_opened_
126 && this->name_
.empty());
129 this->descriptor_
= open_descriptor(-1, this->name_
.c_str(),
132 if (this->descriptor_
>= 0)
134 this->is_descriptor_opened_
= true;
136 if (::fstat(this->descriptor_
, &s
) < 0)
137 gold_error(_("%s: fstat failed: %s"),
138 this->name_
.c_str(), strerror(errno
));
139 this->size_
= s
.st_size
;
140 gold_debug(DEBUG_FILES
, "Attempt to open %s succeeded",
141 this->name_
.c_str());
143 // Options may not yet be ready e.g. when reading a version
144 // script. We then default to --no-keep-files-mapped.
145 if (parameters
->options_valid()
146 && parameters
->options().keep_files_mapped())
148 const unsigned char* contents
= static_cast<const unsigned char*>(
149 ::mmap(NULL
, this->size_
, PROT_READ
, MAP_PRIVATE
,
150 this->descriptor_
, 0));
151 if (contents
== MAP_FAILED
)
152 gold_fatal(_("%s: mmap failed: %s"), this->filename().c_str(),
154 this->whole_file_view_
= new View(0, this->size_
, contents
, 0, false,
156 this->mapped_bytes_
+= this->size_
;
159 this->token_
.add_writer(task
);
162 return this->descriptor_
>= 0;
165 // Open the file with the contents in memory.
168 File_read::open(const Task
* task
, const std::string
& name
,
169 const unsigned char* contents
, off_t size
)
171 gold_assert(this->token_
.is_writable()
172 && this->descriptor_
< 0
173 && !this->is_descriptor_opened_
174 && this->name_
.empty());
176 this->whole_file_view_
= new View(0, size
, contents
, 0, false,
177 View::DATA_NOT_OWNED
);
179 this->token_
.add_writer(task
);
183 // Reopen a descriptor if necessary.
186 File_read::reopen_descriptor()
188 if (!this->is_descriptor_opened_
)
190 this->descriptor_
= open_descriptor(this->descriptor_
,
193 if (this->descriptor_
< 0)
194 gold_fatal(_("could not reopen file %s"), this->name_
.c_str());
195 this->is_descriptor_opened_
= true;
199 // Release the file. This is called when we are done with the file in
205 gold_assert(this->is_locked());
207 File_read::total_mapped_bytes
+= this->mapped_bytes_
;
208 File_read::current_mapped_bytes
+= this->mapped_bytes_
;
209 this->mapped_bytes_
= 0;
210 if (File_read::current_mapped_bytes
> File_read::maximum_mapped_bytes
)
211 File_read::maximum_mapped_bytes
= File_read::current_mapped_bytes
;
213 // Only clear views if there is only one attached object. Otherwise
214 // we waste time trying to clear cached archive views. Similarly
215 // for releasing the descriptor.
216 if (this->object_count_
<= 1)
218 this->clear_views(false);
219 if (this->is_descriptor_opened_
)
221 release_descriptor(this->descriptor_
, false);
222 this->is_descriptor_opened_
= false;
226 this->released_
= true;
232 File_read::lock(const Task
* task
)
234 gold_assert(this->released_
);
235 this->token_
.add_writer(task
);
236 this->released_
= false;
242 File_read::unlock(const Task
* task
)
245 this->token_
.remove_writer(task
);
248 // Return whether the file is locked.
251 File_read::is_locked() const
253 if (!this->token_
.is_writable())
255 // The file is not locked, so it should have been released.
256 gold_assert(this->released_
);
260 // See if we have a view which covers the file starting at START for
261 // SIZE bytes. Return a pointer to the View if found, NULL if not.
262 // If BYTESHIFT is not -1U, the returned View must have the specified
263 // byte shift; otherwise, it may have any byte shift. If VSHIFTED is
264 // not NULL, this sets *VSHIFTED to a view which would have worked if
265 // not for the requested BYTESHIFT.
267 inline File_read::View
*
268 File_read::find_view(off_t start
, section_size_type size
,
269 unsigned int byteshift
, File_read::View
** vshifted
) const
271 if (vshifted
!= NULL
)
274 // If we have the whole file mmapped, and the alignment is right,
276 if (this->whole_file_view_
)
277 if (byteshift
== -1U || byteshift
== 0)
278 return this->whole_file_view_
;
280 off_t page
= File_read::page_offset(start
);
282 unsigned int bszero
= 0;
283 Views::const_iterator p
= this->views_
.upper_bound(std::make_pair(page
- 1,
286 while (p
!= this->views_
.end() && p
->first
.first
<= page
)
288 if (p
->second
->start() <= start
289 && (p
->second
->start() + static_cast<off_t
>(p
->second
->size())
290 >= start
+ static_cast<off_t
>(size
)))
292 if (byteshift
== -1U || byteshift
== p
->second
->byteshift())
294 p
->second
->set_accessed();
298 if (vshifted
!= NULL
&& *vshifted
== NULL
)
299 *vshifted
= p
->second
;
308 // Read SIZE bytes from the file starting at offset START. Read into
312 File_read::do_read(off_t start
, section_size_type size
, void* p
)
315 if (this->whole_file_view_
!= NULL
)
317 bytes
= this->size_
- start
;
318 if (static_cast<section_size_type
>(bytes
) >= size
)
320 memcpy(p
, this->whole_file_view_
->data() + start
, size
);
326 this->reopen_descriptor();
327 bytes
= ::pread(this->descriptor_
, p
, size
, start
);
328 if (static_cast<section_size_type
>(bytes
) == size
)
333 gold_fatal(_("%s: pread failed: %s"),
334 this->filename().c_str(), strerror(errno
));
339 gold_fatal(_("%s: file too short: read only %lld of %lld bytes at %lld"),
340 this->filename().c_str(),
341 static_cast<long long>(bytes
),
342 static_cast<long long>(size
),
343 static_cast<long long>(start
));
346 // Read data from the file.
349 File_read::read(off_t start
, section_size_type size
, void* p
)
351 const File_read::View
* pv
= this->find_view(start
, size
, -1U, NULL
);
354 memcpy(p
, pv
->data() + (start
- pv
->start() + pv
->byteshift()), size
);
358 this->do_read(start
, size
, p
);
361 // Add a new view. There may already be an existing view at this
362 // offset. If there is, the new view will be larger, and should
363 // replace the old view.
366 File_read::add_view(File_read::View
* v
)
368 std::pair
<Views::iterator
, bool> ins
=
369 this->views_
.insert(std::make_pair(std::make_pair(v
->start(),
375 // There was an existing view at this offset. It must not be large
376 // enough. We can't delete it here, since something might be using
377 // it; we put it on a list to be deleted when the file is unlocked.
378 File_read::View
* vold
= ins
.first
->second
;
379 gold_assert(vold
->size() < v
->size());
380 if (vold
->should_cache())
385 this->saved_views_
.push_back(vold
);
387 ins
.first
->second
= v
;
390 // Make a new view with a specified byteshift, reading the data from
394 File_read::make_view(off_t start
, section_size_type size
,
395 unsigned int byteshift
, bool cache
)
397 gold_assert(size
> 0);
399 // Check that start and end of the view are within the file.
400 if (start
> this->size_
401 || (static_cast<unsigned long long>(size
)
402 > static_cast<unsigned long long>(this->size_
- start
)))
403 gold_fatal(_("%s: attempt to map %lld bytes at offset %lld exceeds "
404 "size of file; the file may be corrupt"),
405 this->filename().c_str(),
406 static_cast<long long>(size
),
407 static_cast<long long>(start
));
409 off_t poff
= File_read::page_offset(start
);
411 section_size_type psize
= File_read::pages(size
+ (start
- poff
));
413 if (poff
+ static_cast<off_t
>(psize
) >= this->size_
)
415 psize
= this->size_
- poff
;
416 gold_assert(psize
>= size
);
420 if (this->whole_file_view_
!= NULL
|| byteshift
!= 0)
422 unsigned char* p
= new unsigned char[psize
+ byteshift
];
423 memset(p
, 0, byteshift
);
424 this->do_read(poff
, psize
, p
+ byteshift
);
425 v
= new File_read::View(poff
, psize
, p
, byteshift
, cache
,
426 View::DATA_ALLOCATED_ARRAY
);
430 this->reopen_descriptor();
431 void* p
= ::mmap(NULL
, psize
, PROT_READ
, MAP_PRIVATE
,
432 this->descriptor_
, poff
);
434 gold_fatal(_("%s: mmap offset %lld size %lld failed: %s"),
435 this->filename().c_str(),
436 static_cast<long long>(poff
),
437 static_cast<long long>(psize
),
440 this->mapped_bytes_
+= psize
;
442 const unsigned char* pbytes
= static_cast<const unsigned char*>(p
);
443 v
= new File_read::View(poff
, psize
, pbytes
, 0, cache
,
452 // Find a View or make a new one, shifted as required by the file
453 // offset OFFSET and ALIGNED.
456 File_read::find_or_make_view(off_t offset
, off_t start
,
457 section_size_type size
, bool aligned
, bool cache
)
459 unsigned int byteshift
;
464 unsigned int target_size
= (!parameters
->target_valid()
466 : parameters
->target().get_size());
467 byteshift
= offset
& ((target_size
/ 8) - 1);
469 // Set BYTESHIFT to the number of dummy bytes which must be
470 // inserted before the data in order for this data to be
473 byteshift
= (target_size
/ 8) - byteshift
;
476 // Try to find a View with the required BYTESHIFT.
477 File_read::View
* vshifted
;
478 File_read::View
* v
= this->find_view(offset
+ start
, size
,
479 aligned
? byteshift
: -1U,
488 // If VSHIFTED is not NULL, then it has the data we need, but with
489 // the wrong byteshift.
493 gold_assert(aligned
);
495 unsigned char* pbytes
= new unsigned char[v
->size() + byteshift
];
496 memset(pbytes
, 0, byteshift
);
497 memcpy(pbytes
+ byteshift
, v
->data() + v
->byteshift(), v
->size());
499 File_read::View
* shifted_view
=
500 new File_read::View(v
->start(), v
->size(), pbytes
, byteshift
,
501 cache
, View::DATA_ALLOCATED_ARRAY
);
503 this->add_view(shifted_view
);
507 // Make a new view. If we don't need an aligned view, use a
508 // byteshift of 0, so that we can use mmap.
509 return this->make_view(offset
+ start
, size
,
510 aligned
? byteshift
: 0,
514 // Get a view into the file.
517 File_read::get_view(off_t offset
, off_t start
, section_size_type size
,
518 bool aligned
, bool cache
)
520 File_read::View
* pv
= this->find_or_make_view(offset
, start
, size
,
522 return pv
->data() + (offset
+ start
- pv
->start() + pv
->byteshift());
526 File_read::get_lasting_view(off_t offset
, off_t start
, section_size_type size
,
527 bool aligned
, bool cache
)
529 File_read::View
* pv
= this->find_or_make_view(offset
, start
, size
,
532 return new File_view(*this, pv
,
534 + (offset
+ start
- pv
->start() + pv
->byteshift())));
537 // Use readv to read COUNT entries from RM starting at START. BASE
538 // must be added to all file offsets in RM.
541 File_read::do_readv(off_t base
, const Read_multiple
& rm
, size_t start
,
544 unsigned char discard
[File_read::page_size
];
545 iovec iov
[File_read::max_readv_entries
* 2];
546 size_t iov_index
= 0;
548 off_t first_offset
= rm
[start
].file_offset
;
549 off_t last_offset
= first_offset
;
551 for (size_t i
= 0; i
< count
; ++i
)
553 const Read_multiple_entry
& i_entry(rm
[start
+ i
]);
555 if (i_entry
.file_offset
> last_offset
)
557 size_t skip
= i_entry
.file_offset
- last_offset
;
558 gold_assert(skip
<= sizeof discard
);
560 iov
[iov_index
].iov_base
= discard
;
561 iov
[iov_index
].iov_len
= skip
;
567 iov
[iov_index
].iov_base
= i_entry
.buffer
;
568 iov
[iov_index
].iov_len
= i_entry
.size
;
571 want
+= i_entry
.size
;
573 last_offset
= i_entry
.file_offset
+ i_entry
.size
;
576 this->reopen_descriptor();
578 gold_assert(iov_index
< sizeof iov
/ sizeof iov
[0]);
580 if (::lseek(this->descriptor_
, base
+ first_offset
, SEEK_SET
) < 0)
581 gold_fatal(_("%s: lseek failed: %s"),
582 this->filename().c_str(), strerror(errno
));
584 ssize_t got
= ::readv(this->descriptor_
, iov
, iov_index
);
587 gold_fatal(_("%s: readv failed: %s"),
588 this->filename().c_str(), strerror(errno
));
590 gold_fatal(_("%s: file too short: read only %zd of %zd bytes at %lld"),
591 this->filename().c_str(),
592 got
, want
, static_cast<long long>(base
+ first_offset
));
595 // Read several pieces of data from the file.
598 File_read::read_multiple(off_t base
, const Read_multiple
& rm
)
600 size_t count
= rm
.size();
604 // Find up to MAX_READV_ENTRIES consecutive entries which are
605 // less than one page apart.
606 const Read_multiple_entry
& i_entry(rm
[i
]);
607 off_t i_off
= i_entry
.file_offset
;
608 off_t end_off
= i_off
+ i_entry
.size
;
610 for (j
= i
+ 1; j
< count
; ++j
)
612 if (j
- i
>= File_read::max_readv_entries
)
614 const Read_multiple_entry
& j_entry(rm
[j
]);
615 off_t j_off
= j_entry
.file_offset
;
616 gold_assert(j_off
>= end_off
);
617 off_t j_end_off
= j_off
+ j_entry
.size
;
618 if (j_end_off
- end_off
>= File_read::page_size
)
624 this->read(base
+ i_off
, i_entry
.size
, i_entry
.buffer
);
627 File_read::View
* view
= this->find_view(base
+ i_off
,
631 this->do_readv(base
, rm
, i
, j
- i
);
634 const unsigned char* v
= (view
->data()
635 + (base
+ i_off
- view
->start()
636 + view
->byteshift()));
637 for (size_t k
= i
; k
< j
; ++k
)
639 const Read_multiple_entry
& k_entry(rm
[k
]);
640 gold_assert((convert_to_section_size_type(k_entry
.file_offset
643 <= convert_to_section_size_type(end_off
645 memcpy(k_entry
.buffer
,
646 v
+ (k_entry
.file_offset
- i_off
),
656 // Mark all views as no longer cached.
659 File_read::clear_view_cache_marks()
661 // Just ignore this if there are multiple objects associated with
662 // the file. Otherwise we will wind up uncaching and freeing some
663 // views for other objects.
664 if (this->object_count_
> 1)
667 for (Views::iterator p
= this->views_
.begin();
668 p
!= this->views_
.end();
670 p
->second
->clear_cache();
671 for (Saved_views::iterator p
= this->saved_views_
.begin();
672 p
!= this->saved_views_
.end();
677 // Remove all the file views. For a file which has multiple
678 // associated objects (i.e., an archive), we keep accessed views
679 // around until next time, in the hopes that they will be useful for
683 File_read::clear_views(bool destroying
)
685 Views::iterator p
= this->views_
.begin();
686 while (p
!= this->views_
.end())
689 if (p
->second
->is_locked())
690 should_delete
= false;
692 should_delete
= true;
693 else if (p
->second
->should_cache())
694 should_delete
= false;
695 else if (this->object_count_
> 1 && p
->second
->accessed())
696 should_delete
= false;
698 should_delete
= true;
704 // map::erase invalidates only the iterator to the deleted
706 Views::iterator pe
= p
;
708 this->views_
.erase(pe
);
712 gold_assert(!destroying
);
713 p
->second
->clear_accessed();
718 Saved_views::iterator q
= this->saved_views_
.begin();
719 while (q
!= this->saved_views_
.end())
721 if (!(*q
)->is_locked())
724 q
= this->saved_views_
.erase(q
);
728 gold_assert(!destroying
);
734 // Print statistical information to stderr. This is used for --stats.
737 File_read::print_stats()
739 fprintf(stderr
, _("%s: total bytes mapped for read: %llu\n"),
740 program_name
, File_read::total_mapped_bytes
);
741 fprintf(stderr
, _("%s: maximum bytes mapped for read at one time: %llu\n"),
742 program_name
, File_read::maximum_mapped_bytes
);
747 File_view::~File_view()
749 gold_assert(this->file_
.is_locked());
750 this->view_
->unlock();
755 // Create a file for testing.
757 Input_file::Input_file(const Task
* task
, const char* name
,
758 const unsigned char* contents
, off_t size
)
761 this->input_argument_
=
762 new Input_file_argument(name
, Input_file_argument::INPUT_FILE_TYPE_FILE
,
763 "", false, Position_dependent_options());
764 bool ok
= this->file_
.open(task
, name
, contents
, size
);
768 // Return the position dependent options in force for this file.
770 const Position_dependent_options
&
771 Input_file::options() const
773 return this->input_argument_
->options();
776 // Return the name given by the user. For -lc this will return "c".
779 Input_file::name() const
781 return this->input_argument_
->name();
784 // Return whether this file is in a system directory.
787 Input_file::is_in_system_directory() const
789 if (this->is_in_sysroot())
791 return parameters
->options().is_in_system_directory(this->filename());
794 // Return whether we are only reading symbols.
797 Input_file::just_symbols() const
799 return this->input_argument_
->just_symbols();
802 // Return whether this is a file that we will search for in the list
806 Input_file::will_search_for() const
808 return (!IS_ABSOLUTE_PATH(this->input_argument_
->name())
809 && (this->input_argument_
->is_lib()
810 || this->input_argument_
->is_searched_file()
811 || this->input_argument_
->extra_search_path() != NULL
));
814 // Return the file last modification time. Calls gold_fatal if the stat
815 // system call failed.
818 File_read::get_mtime()
820 struct stat file_stat
;
821 this->reopen_descriptor();
823 if (fstat(this->descriptor_
, &file_stat
) < 0)
824 gold_fatal(_("%s: stat failed: %s"), this->name_
.c_str(),
826 #ifdef HAVE_STAT_ST_MTIM
827 return Timespec(file_stat
.st_mtim
.tv_sec
, file_stat
.st_mtim
.tv_nsec
);
829 return Timespec(file_stat
.st_mtime
, 0);
835 // If the filename is not absolute, we assume it is in the current
836 // directory *except* when:
837 // A) input_argument_->is_lib() is true;
838 // B) input_argument_->is_searched_file() is true; or
839 // C) input_argument_->extra_search_path() is not empty.
840 // In each, we look in extra_search_path + library_path to find
841 // the file location, rather than the current directory.
844 Input_file::open(const Dirsearch
& dirpath
, const Task
* task
, int *pindex
)
848 // Case 1: name is an absolute file, just try to open it
849 // Case 2: name is relative but is_lib is false, is_searched_file is false,
850 // and extra_search_path is empty
851 if (IS_ABSOLUTE_PATH(this->input_argument_
->name())
852 || (!this->input_argument_
->is_lib()
853 && !this->input_argument_
->is_searched_file()
854 && this->input_argument_
->extra_search_path() == NULL
))
856 name
= this->input_argument_
->name();
857 this->found_name_
= name
;
859 // Case 3: is_lib is true or is_searched_file is true
860 else if (this->input_argument_
->is_lib()
861 || this->input_argument_
->is_searched_file())
863 // We don't yet support extra_search_path with -l.
864 gold_assert(this->input_argument_
->extra_search_path() == NULL
);
866 if (this->input_argument_
->is_lib())
869 n1
+= this->input_argument_
->name();
870 if (parameters
->options().is_static()
871 || !this->input_argument_
->options().Bdynamic())
880 n1
= this->input_argument_
->name();
881 name
= dirpath
.find(n1
, n2
, &this->is_in_sysroot_
, pindex
);
884 gold_error(_("cannot find %s%s"),
885 this->input_argument_
->is_lib() ? "-l" : "",
886 this->input_argument_
->name());
889 if (n2
.empty() || name
[name
.length() - 1] == 'o')
890 this->found_name_
= n1
;
892 this->found_name_
= n2
;
894 // Case 4: extra_search_path is not empty
897 gold_assert(this->input_argument_
->extra_search_path() != NULL
);
899 // First, check extra_search_path.
900 name
= this->input_argument_
->extra_search_path();
901 if (!IS_DIR_SEPARATOR (name
[name
.length() - 1]))
903 name
+= this->input_argument_
->name();
904 struct stat dummy_stat
;
905 if (*pindex
> 0 || ::stat(name
.c_str(), &dummy_stat
) < 0)
907 // extra_search_path failed, so check the normal search-path.
911 name
= dirpath
.find(this->input_argument_
->name(), "",
912 &this->is_in_sysroot_
, &index
);
915 gold_error(_("cannot find %s"),
916 this->input_argument_
->name());
921 this->found_name_
= this->input_argument_
->name();
924 // Now that we've figured out where the file lives, try to open it.
926 General_options::Object_format format
=
927 this->input_argument_
->options().format_enum();
929 if (format
== General_options::OBJECT_FORMAT_ELF
)
930 ok
= this->file_
.open(task
, name
);
933 gold_assert(format
== General_options::OBJECT_FORMAT_BINARY
);
934 ok
= this->open_binary(task
, name
);
939 gold_error(_("cannot open %s: %s"),
940 name
.c_str(), strerror(errno
));
947 // Open a file for --format binary.
950 Input_file::open_binary(const Task
* task
, const std::string
& name
)
952 // In order to open a binary file, we need machine code, size, and
953 // endianness. We may not have a valid target at this point, in
954 // which case we use the default target.
955 parameters_force_valid_target();
956 const Target
& target(parameters
->target());
958 Binary_to_elf
binary_to_elf(target
.machine_code(),
960 target
.is_big_endian(),
962 if (!binary_to_elf
.convert(task
))
964 return this->file_
.open(task
, name
, binary_to_elf
.converted_data_leak(),
965 binary_to_elf
.converted_size());
968 } // End namespace gold.