1 // fileread.cc -- read files for gold
3 // Copyright 2006, 2007, 2008 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.
31 #include "filenames.h"
34 #include "parameters.h"
36 #include "dirsearch.h"
39 #include "descriptors.h"
45 // Class File_read::View.
47 File_read::View::~View()
49 gold_assert(!this->is_locked());
54 if (::munmap(const_cast<unsigned char*>(this->data_
), this->size_
) != 0)
55 gold_warning(_("munmap failed: %s"), strerror(errno
));
57 File_read::current_mapped_bytes
-= this->size_
;
62 File_read::View::lock()
68 File_read::View::unlock()
70 gold_assert(this->lock_count_
> 0);
75 File_read::View::is_locked()
77 return this->lock_count_
> 0;
82 // The File_read static variables.
83 unsigned long long File_read::total_mapped_bytes
;
84 unsigned long long File_read::current_mapped_bytes
;
85 unsigned long long File_read::maximum_mapped_bytes
;
87 File_read::~File_read()
89 gold_assert(this->token_
.is_writable());
90 if (this->is_descriptor_opened_
)
92 release_descriptor(this->descriptor_
, true);
93 this->descriptor_
= -1;
94 this->is_descriptor_opened_
= false;
97 this->clear_views(true);
103 File_read::open(const Task
* task
, const std::string
& name
)
105 gold_assert(this->token_
.is_writable()
106 && this->descriptor_
< 0
107 && !this->is_descriptor_opened_
108 && this->name_
.empty());
111 this->descriptor_
= open_descriptor(-1, this->name_
.c_str(),
114 if (this->descriptor_
>= 0)
116 this->is_descriptor_opened_
= true;
118 if (::fstat(this->descriptor_
, &s
) < 0)
119 gold_error(_("%s: fstat failed: %s"),
120 this->name_
.c_str(), strerror(errno
));
121 this->size_
= s
.st_size
;
122 gold_debug(DEBUG_FILES
, "Attempt to open %s succeeded",
123 this->name_
.c_str());
125 this->token_
.add_writer(task
);
128 return this->descriptor_
>= 0;
131 // Open the file with the contents in memory.
134 File_read::open(const Task
* task
, const std::string
& name
,
135 const unsigned char* contents
, off_t size
)
137 gold_assert(this->token_
.is_writable()
138 && this->descriptor_
< 0
139 && !this->is_descriptor_opened_
140 && this->name_
.empty());
142 this->contents_
= contents
;
144 this->token_
.add_writer(task
);
148 // Reopen a descriptor if necessary.
151 File_read::reopen_descriptor()
153 if (!this->is_descriptor_opened_
)
155 this->descriptor_
= open_descriptor(this->descriptor_
,
158 if (this->descriptor_
< 0)
159 gold_fatal(_("could not reopen file %s"), this->name_
.c_str());
160 this->is_descriptor_opened_
= true;
164 // Release the file. This is called when we are done with the file in
170 gold_assert(this->is_locked());
172 File_read::total_mapped_bytes
+= this->mapped_bytes_
;
173 File_read::current_mapped_bytes
+= this->mapped_bytes_
;
174 this->mapped_bytes_
= 0;
175 if (File_read::current_mapped_bytes
> File_read::maximum_mapped_bytes
)
176 File_read::maximum_mapped_bytes
= File_read::current_mapped_bytes
;
178 // Only clear views if there is only one attached object. Otherwise
179 // we waste time trying to clear cached archive views. Similarly
180 // for releasing the descriptor.
181 if (this->object_count_
<= 1)
183 this->clear_views(false);
184 if (this->is_descriptor_opened_
)
186 release_descriptor(this->descriptor_
, false);
187 this->is_descriptor_opened_
= false;
191 this->released_
= true;
197 File_read::lock(const Task
* task
)
199 gold_assert(this->released_
);
200 this->token_
.add_writer(task
);
201 this->released_
= false;
207 File_read::unlock(const Task
* task
)
210 this->token_
.remove_writer(task
);
213 // Return whether the file is locked.
216 File_read::is_locked() const
218 if (!this->token_
.is_writable())
220 // The file is not locked, so it should have been released.
221 gold_assert(this->released_
);
225 // See if we have a view which covers the file starting at START for
226 // SIZE bytes. Return a pointer to the View if found, NULL if not.
227 // If BYTESHIFT is not -1U, the returned View must have the specified
228 // byte shift; otherwise, it may have any byte shift. If VSHIFTED is
229 // not NULL, this sets *VSHIFTED to a view which would have worked if
230 // not for the requested BYTESHIFT.
232 inline File_read::View
*
233 File_read::find_view(off_t start
, section_size_type size
,
234 unsigned int byteshift
, File_read::View
** vshifted
) const
236 if (vshifted
!= NULL
)
239 off_t page
= File_read::page_offset(start
);
241 unsigned int bszero
= 0;
242 Views::const_iterator p
= this->views_
.upper_bound(std::make_pair(page
- 1,
245 while (p
!= this->views_
.end() && p
->first
.first
<= page
)
247 if (p
->second
->start() <= start
248 && (p
->second
->start() + static_cast<off_t
>(p
->second
->size())
249 >= start
+ static_cast<off_t
>(size
)))
251 if (byteshift
== -1U || byteshift
== p
->second
->byteshift())
253 p
->second
->set_accessed();
257 if (vshifted
!= NULL
&& *vshifted
== NULL
)
258 *vshifted
= p
->second
;
267 // Read SIZE bytes from the file starting at offset START. Read into
271 File_read::do_read(off_t start
, section_size_type size
, void* p
)
274 if (this->contents_
!= NULL
)
276 bytes
= this->size_
- start
;
277 if (static_cast<section_size_type
>(bytes
) >= size
)
279 memcpy(p
, this->contents_
+ start
, size
);
285 this->reopen_descriptor();
286 bytes
= ::pread(this->descriptor_
, p
, size
, start
);
287 if (static_cast<section_size_type
>(bytes
) == size
)
292 gold_fatal(_("%s: pread failed: %s"),
293 this->filename().c_str(), strerror(errno
));
298 gold_fatal(_("%s: file too short: read only %lld of %lld bytes at %lld"),
299 this->filename().c_str(),
300 static_cast<long long>(bytes
),
301 static_cast<long long>(size
),
302 static_cast<long long>(start
));
305 // Read data from the file.
308 File_read::read(off_t start
, section_size_type size
, void* p
)
310 const File_read::View
* pv
= this->find_view(start
, size
, -1U, NULL
);
313 memcpy(p
, pv
->data() + (start
- pv
->start() + pv
->byteshift()), size
);
317 this->do_read(start
, size
, p
);
320 // Add a new view. There may already be an existing view at this
321 // offset. If there is, the new view will be larger, and should
322 // replace the old view.
325 File_read::add_view(File_read::View
* v
)
327 std::pair
<Views::iterator
, bool> ins
=
328 this->views_
.insert(std::make_pair(std::make_pair(v
->start(),
334 // There was an existing view at this offset. It must not be large
335 // enough. We can't delete it here, since something might be using
336 // it; we put it on a list to be deleted when the file is unlocked.
337 File_read::View
* vold
= ins
.first
->second
;
338 gold_assert(vold
->size() < v
->size());
339 if (vold
->should_cache())
344 this->saved_views_
.push_back(vold
);
346 ins
.first
->second
= v
;
349 // Make a new view with a specified byteshift, reading the data from
353 File_read::make_view(off_t start
, section_size_type size
,
354 unsigned int byteshift
, bool cache
)
356 gold_assert(size
> 0);
358 off_t poff
= File_read::page_offset(start
);
360 section_size_type psize
= File_read::pages(size
+ (start
- poff
));
362 if (poff
+ static_cast<off_t
>(psize
) >= this->size_
)
364 psize
= this->size_
- poff
;
365 gold_assert(psize
>= size
);
369 if (this->contents_
!= NULL
|| byteshift
!= 0)
371 unsigned char* p
= new unsigned char[psize
+ byteshift
];
372 memset(p
, 0, byteshift
);
373 this->do_read(poff
, psize
, p
+ byteshift
);
374 v
= new File_read::View(poff
, psize
, p
, byteshift
, cache
, false);
378 this->reopen_descriptor();
379 void* p
= ::mmap(NULL
, psize
, PROT_READ
, MAP_PRIVATE
,
380 this->descriptor_
, poff
);
382 gold_fatal(_("%s: mmap offset %lld size %lld failed: %s"),
383 this->filename().c_str(),
384 static_cast<long long>(poff
),
385 static_cast<long long>(psize
),
388 this->mapped_bytes_
+= psize
;
390 const unsigned char* pbytes
= static_cast<const unsigned char*>(p
);
391 v
= new File_read::View(poff
, psize
, pbytes
, 0, cache
, true);
399 // Find a View or make a new one, shifted as required by the file
400 // offset OFFSET and ALIGNED.
403 File_read::find_or_make_view(off_t offset
, off_t start
,
404 section_size_type size
, bool aligned
, bool cache
)
406 unsigned int byteshift
;
411 unsigned int target_size
= (!parameters
->target_valid()
413 : parameters
->target().get_size());
414 byteshift
= offset
& ((target_size
/ 8) - 1);
416 // Set BYTESHIFT to the number of dummy bytes which must be
417 // inserted before the data in order for this data to be
420 byteshift
= (target_size
/ 8) - byteshift
;
423 // Try to find a View with the required BYTESHIFT.
424 File_read::View
* vshifted
;
425 File_read::View
* v
= this->find_view(offset
+ start
, size
,
426 aligned
? byteshift
: -1U,
435 // If VSHIFTED is not NULL, then it has the data we need, but with
436 // the wrong byteshift.
440 gold_assert(aligned
);
442 unsigned char* pbytes
= new unsigned char[v
->size() + byteshift
];
443 memset(pbytes
, 0, byteshift
);
444 memcpy(pbytes
+ byteshift
, v
->data() + v
->byteshift(), v
->size());
446 File_read::View
* shifted_view
= new File_read::View(v
->start(), v
->size(),
450 this->add_view(shifted_view
);
454 // Make a new view. If we don't need an aligned view, use a
455 // byteshift of 0, so that we can use mmap.
456 return this->make_view(offset
+ start
, size
,
457 aligned
? byteshift
: 0,
461 // Get a view into the file.
464 File_read::get_view(off_t offset
, off_t start
, section_size_type size
,
465 bool aligned
, bool cache
)
467 File_read::View
* pv
= this->find_or_make_view(offset
, start
, size
,
469 return pv
->data() + (offset
+ start
- pv
->start() + pv
->byteshift());
473 File_read::get_lasting_view(off_t offset
, off_t start
, section_size_type size
,
474 bool aligned
, bool cache
)
476 File_read::View
* pv
= this->find_or_make_view(offset
, start
, size
,
479 return new File_view(*this, pv
,
481 + (offset
+ start
- pv
->start() + pv
->byteshift())));
484 // Use readv to read COUNT entries from RM starting at START. BASE
485 // must be added to all file offsets in RM.
488 File_read::do_readv(off_t base
, const Read_multiple
& rm
, size_t start
,
491 unsigned char discard
[File_read::page_size
];
492 iovec iov
[File_read::max_readv_entries
* 2];
493 size_t iov_index
= 0;
495 off_t first_offset
= rm
[start
].file_offset
;
496 off_t last_offset
= first_offset
;
498 for (size_t i
= 0; i
< count
; ++i
)
500 const Read_multiple_entry
& i_entry(rm
[start
+ i
]);
502 if (i_entry
.file_offset
> last_offset
)
504 size_t skip
= i_entry
.file_offset
- last_offset
;
505 gold_assert(skip
<= sizeof discard
);
507 iov
[iov_index
].iov_base
= discard
;
508 iov
[iov_index
].iov_len
= skip
;
514 iov
[iov_index
].iov_base
= i_entry
.buffer
;
515 iov
[iov_index
].iov_len
= i_entry
.size
;
518 want
+= i_entry
.size
;
520 last_offset
= i_entry
.file_offset
+ i_entry
.size
;
523 this->reopen_descriptor();
525 gold_assert(iov_index
< sizeof iov
/ sizeof iov
[0]);
527 if (::lseek(this->descriptor_
, base
+ first_offset
, SEEK_SET
) < 0)
528 gold_fatal(_("%s: lseek failed: %s"),
529 this->filename().c_str(), strerror(errno
));
531 ssize_t got
= ::readv(this->descriptor_
, iov
, iov_index
);
534 gold_fatal(_("%s: readv failed: %s"),
535 this->filename().c_str(), strerror(errno
));
537 gold_fatal(_("%s: file too short: read only %zd of %zd bytes at %lld"),
538 this->filename().c_str(),
539 got
, want
, static_cast<long long>(base
+ first_offset
));
542 // Read several pieces of data from the file.
545 File_read::read_multiple(off_t base
, const Read_multiple
& rm
)
547 size_t count
= rm
.size();
551 // Find up to MAX_READV_ENTRIES consecutive entries which are
552 // less than one page apart.
553 const Read_multiple_entry
& i_entry(rm
[i
]);
554 off_t i_off
= i_entry
.file_offset
;
555 off_t end_off
= i_off
+ i_entry
.size
;
557 for (j
= i
+ 1; j
< count
; ++j
)
559 if (j
- i
>= File_read::max_readv_entries
)
561 const Read_multiple_entry
& j_entry(rm
[j
]);
562 off_t j_off
= j_entry
.file_offset
;
563 gold_assert(j_off
>= end_off
);
564 off_t j_end_off
= j_off
+ j_entry
.size
;
565 if (j_end_off
- end_off
>= File_read::page_size
)
571 this->read(base
+ i_off
, i_entry
.size
, i_entry
.buffer
);
574 File_read::View
* view
= this->find_view(base
+ i_off
,
578 this->do_readv(base
, rm
, i
, j
- i
);
581 const unsigned char* v
= (view
->data()
582 + (base
+ i_off
- view
->start()
583 + view
->byteshift()));
584 for (size_t k
= i
; k
< j
; ++k
)
586 const Read_multiple_entry
& k_entry(rm
[k
]);
587 gold_assert((convert_to_section_size_type(k_entry
.file_offset
590 <= convert_to_section_size_type(end_off
592 memcpy(k_entry
.buffer
,
593 v
+ (k_entry
.file_offset
- i_off
),
603 // Mark all views as no longer cached.
606 File_read::clear_view_cache_marks()
608 // Just ignore this if there are multiple objects associated with
609 // the file. Otherwise we will wind up uncaching and freeing some
610 // views for other objects.
611 if (this->object_count_
> 1)
614 for (Views::iterator p
= this->views_
.begin();
615 p
!= this->views_
.end();
617 p
->second
->clear_cache();
618 for (Saved_views::iterator p
= this->saved_views_
.begin();
619 p
!= this->saved_views_
.end();
624 // Remove all the file views. For a file which has multiple
625 // associated objects (i.e., an archive), we keep accessed views
626 // around until next time, in the hopes that they will be useful for
630 File_read::clear_views(bool destroying
)
632 Views::iterator p
= this->views_
.begin();
633 while (p
!= this->views_
.end())
636 if (p
->second
->is_locked())
637 should_delete
= false;
639 should_delete
= true;
640 else if (p
->second
->should_cache())
641 should_delete
= false;
642 else if (this->object_count_
> 1 && p
->second
->accessed())
643 should_delete
= false;
645 should_delete
= true;
651 // map::erase invalidates only the iterator to the deleted
653 Views::iterator pe
= p
;
655 this->views_
.erase(pe
);
659 gold_assert(!destroying
);
660 p
->second
->clear_accessed();
665 Saved_views::iterator q
= this->saved_views_
.begin();
666 while (q
!= this->saved_views_
.end())
668 if (!(*q
)->is_locked())
671 q
= this->saved_views_
.erase(q
);
675 gold_assert(!destroying
);
681 // Print statistical information to stderr. This is used for --stats.
684 File_read::print_stats()
686 fprintf(stderr
, _("%s: total bytes mapped for read: %llu\n"),
687 program_name
, File_read::total_mapped_bytes
);
688 fprintf(stderr
, _("%s: maximum bytes mapped for read at one time: %llu\n"),
689 program_name
, File_read::maximum_mapped_bytes
);
694 File_view::~File_view()
696 gold_assert(this->file_
.is_locked());
697 this->view_
->unlock();
702 // Create a file for testing.
704 Input_file::Input_file(const Task
* task
, const char* name
,
705 const unsigned char* contents
, off_t size
)
708 this->input_argument_
=
709 new Input_file_argument(name
, false, "", false,
710 Position_dependent_options());
711 bool ok
= file_
.open(task
, name
, contents
, size
);
715 // Return the position dependent options in force for this file.
717 const Position_dependent_options
&
718 Input_file::options() const
720 return this->input_argument_
->options();
723 // Return the name given by the user. For -lc this will return "c".
726 Input_file::name() const
728 return this->input_argument_
->name();
731 // Return whether we are only reading symbols.
734 Input_file::just_symbols() const
736 return this->input_argument_
->just_symbols();
741 // If the filename is not absolute, we assume it is in the current
742 // directory *except* when:
743 // A) input_argument_->is_lib() is true; or
744 // B) input_argument_->extra_search_path() is not empty.
745 // In both cases, we look in extra_search_path + library_path to find
746 // the file location, rather than the current directory.
749 Input_file::open(const General_options
& options
, const Dirsearch
& dirpath
,
754 // Case 1: name is an absolute file, just try to open it
755 // Case 2: name is relative but is_lib is false and extra_search_path
757 if (IS_ABSOLUTE_PATH (this->input_argument_
->name())
758 || (!this->input_argument_
->is_lib()
759 && this->input_argument_
->extra_search_path() == NULL
))
761 name
= this->input_argument_
->name();
762 this->found_name_
= name
;
764 // Case 3: is_lib is true
765 else if (this->input_argument_
->is_lib())
767 // We don't yet support extra_search_path with -l.
768 gold_assert(this->input_argument_
->extra_search_path() == NULL
);
769 std::string
n1("lib");
770 n1
+= this->input_argument_
->name();
772 if (options
.is_static()
773 || !this->input_argument_
->options().Bdynamic())
780 name
= dirpath
.find(n1
, n2
, &this->is_in_sysroot_
);
783 gold_error(_("cannot find -l%s"),
784 this->input_argument_
->name());
787 if (n2
.empty() || name
[name
.length() - 1] == 'o')
788 this->found_name_
= n1
;
790 this->found_name_
= n2
;
792 // Case 4: extra_search_path is not empty
795 gold_assert(this->input_argument_
->extra_search_path() != NULL
);
797 // First, check extra_search_path.
798 name
= this->input_argument_
->extra_search_path();
799 if (!IS_DIR_SEPARATOR (name
[name
.length() - 1]))
801 name
+= this->input_argument_
->name();
802 struct stat dummy_stat
;
803 if (::stat(name
.c_str(), &dummy_stat
) < 0)
805 // extra_search_path failed, so check the normal search-path.
806 name
= dirpath
.find(this->input_argument_
->name(), "",
807 &this->is_in_sysroot_
);
810 gold_error(_("cannot find %s"),
811 this->input_argument_
->name());
815 this->found_name_
= this->input_argument_
->name();
818 // Now that we've figured out where the file lives, try to open it.
820 General_options::Object_format format
=
821 this->input_argument_
->options().format_enum();
823 if (format
== General_options::OBJECT_FORMAT_ELF
)
824 ok
= this->file_
.open(task
, name
);
827 gold_assert(format
== General_options::OBJECT_FORMAT_BINARY
);
828 ok
= this->open_binary(options
, task
, name
);
833 gold_error(_("cannot open %s: %s"),
834 name
.c_str(), strerror(errno
));
841 // Open a file for --format binary.
844 Input_file::open_binary(const General_options
&,
845 const Task
* task
, const std::string
& name
)
847 // In order to open a binary file, we need machine code, size, and
848 // endianness. We may not have a valid target at this point, in
849 // which case we use the default target.
850 const Target
* target
;
851 if (parameters
->target_valid())
852 target
= ¶meters
->target();
854 target
= ¶meters
->default_target();
856 Binary_to_elf
binary_to_elf(target
->machine_code(),
858 target
->is_big_endian(),
860 if (!binary_to_elf
.convert(task
))
862 return this->file_
.open(task
, name
, binary_to_elf
.converted_data_leak(),
863 binary_to_elf
.converted_size());
866 } // End namespace gold.