bfd/
[binutils.git] / gold / fileread.cc
blob901c52802d2f6682acfaf3a2d5df3fefb12ec287
1 // fileread.cc -- read files for gold
3 // Copyright 2006, 2007 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.
23 #include "gold.h"
25 #include <cstring>
26 #include <cerrno>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <sys/mman.h>
30 #include <sys/uio.h>
31 #include "filenames.h"
33 #include "parameters.h"
34 #include "options.h"
35 #include "dirsearch.h"
36 #include "target.h"
37 #include "binary.h"
38 #include "fileread.h"
40 namespace gold
43 // Class File_read::View.
45 File_read::View::~View()
47 gold_assert(!this->is_locked());
48 if (!this->mapped_)
49 delete[] this->data_;
50 else
52 if (::munmap(const_cast<unsigned char*>(this->data_), this->size_) != 0)
53 gold_warning(_("munmap failed: %s"), strerror(errno));
55 File_read::current_mapped_bytes -= this->size_;
59 void
60 File_read::View::lock()
62 ++this->lock_count_;
65 void
66 File_read::View::unlock()
68 gold_assert(this->lock_count_ > 0);
69 --this->lock_count_;
72 bool
73 File_read::View::is_locked()
75 return this->lock_count_ > 0;
78 // Class File_read.
80 // The File_read static variables.
81 unsigned long long File_read::total_mapped_bytes;
82 unsigned long long File_read::current_mapped_bytes;
83 unsigned long long File_read::maximum_mapped_bytes;
85 // The File_read class is designed to support file descriptor caching,
86 // but this is not currently implemented.
88 File_read::~File_read()
90 gold_assert(this->token_.is_writable());
91 if (this->descriptor_ >= 0)
93 if (close(this->descriptor_) < 0)
94 gold_warning(_("close of %s failed: %s"),
95 this->name_.c_str(), strerror(errno));
96 this->descriptor_ = -1;
98 this->name_.clear();
99 this->clear_views(true);
102 // Open the file.
104 bool
105 File_read::open(const Task* task, const std::string& name)
107 gold_assert(this->token_.is_writable()
108 && this->descriptor_ < 0
109 && this->name_.empty());
110 this->name_ = name;
112 this->descriptor_ = ::open(this->name_.c_str(), O_RDONLY);
114 if (this->descriptor_ >= 0)
116 struct stat s;
117 if (::fstat(this->descriptor_, &s) < 0)
118 gold_error(_("%s: fstat failed: %s"),
119 this->name_.c_str(), strerror(errno));
120 this->size_ = s.st_size;
123 this->token_.add_writer(task);
125 return this->descriptor_ >= 0;
128 // Open the file with the contents in memory.
130 bool
131 File_read::open(const Task* task, const std::string& name,
132 const unsigned char* contents, off_t size)
134 gold_assert(this->token_.is_writable()
135 && this->descriptor_ < 0
136 && this->name_.empty());
137 this->name_ = name;
138 this->contents_ = contents;
139 this->size_ = size;
140 this->token_.add_writer(task);
141 return true;
144 // Release the file. This is called when we are done with the file in
145 // a Task.
147 void
148 File_read::release()
150 gold_assert(this->is_locked());
152 File_read::total_mapped_bytes += this->mapped_bytes_;
153 File_read::current_mapped_bytes += this->mapped_bytes_;
154 this->mapped_bytes_ = 0;
155 if (File_read::current_mapped_bytes > File_read::maximum_mapped_bytes)
156 File_read::maximum_mapped_bytes = File_read::current_mapped_bytes;
158 this->clear_views(false);
160 this->released_ = true;
163 // Lock the file.
165 void
166 File_read::lock(const Task* task)
168 gold_assert(this->released_);
169 this->token_.add_writer(task);
170 this->released_ = false;
173 // Unlock the file.
175 void
176 File_read::unlock(const Task* task)
178 this->release();
179 this->token_.remove_writer(task);
182 // Return whether the file is locked.
184 bool
185 File_read::is_locked() const
187 if (!this->token_.is_writable())
188 return true;
189 // The file is not locked, so it should have been released.
190 gold_assert(this->released_);
191 return false;
194 // See if we have a view which covers the file starting at START for
195 // SIZE bytes. Return a pointer to the View if found, NULL if not.
197 inline File_read::View*
198 File_read::find_view(off_t start, section_size_type size) const
200 off_t page = File_read::page_offset(start);
202 Views::const_iterator p = this->views_.lower_bound(page);
203 if (p == this->views_.end() || p->first > page)
205 if (p == this->views_.begin())
206 return NULL;
207 --p;
210 if (p->second->start() + static_cast<off_t>(p->second->size())
211 < start + static_cast<off_t>(size))
212 return NULL;
214 p->second->set_accessed();
216 return p->second;
219 // Read SIZE bytes from the file starting at offset START. Read into
220 // the buffer at P.
222 void
223 File_read::do_read(off_t start, section_size_type size, void* p) const
225 ssize_t bytes;
226 if (this->contents_ != NULL)
228 bytes = this->size_ - start;
229 if (static_cast<section_size_type>(bytes) >= size)
231 memcpy(p, this->contents_ + start, size);
232 return;
235 else
237 bytes = ::pread(this->descriptor_, p, size, start);
238 if (static_cast<section_size_type>(bytes) == size)
239 return;
241 if (bytes < 0)
243 gold_fatal(_("%s: pread failed: %s"),
244 this->filename().c_str(), strerror(errno));
245 return;
249 gold_fatal(_("%s: file too short: read only %lld of %lld bytes at %lld"),
250 this->filename().c_str(),
251 static_cast<long long>(bytes),
252 static_cast<long long>(size),
253 static_cast<long long>(start));
256 // Read data from the file.
258 void
259 File_read::read(off_t start, section_size_type size, void* p) const
261 const File_read::View* pv = this->find_view(start, size);
262 if (pv != NULL)
264 memcpy(p, pv->data() + (start - pv->start()), size);
265 return;
268 this->do_read(start, size, p);
271 // Find an existing view or make a new one.
273 File_read::View*
274 File_read::find_or_make_view(off_t start, section_size_type size, bool cache)
276 gold_assert(!this->token_.is_writable());
277 this->released_ = false;
279 File_read::View* v = this->find_view(start, size);
280 if (v != NULL)
282 if (cache)
283 v->set_cache();
284 return v;
287 off_t poff = File_read::page_offset(start);
289 File_read::View* const vnull = NULL;
290 std::pair<Views::iterator, bool> ins =
291 this->views_.insert(std::make_pair(poff, vnull));
293 if (!ins.second)
295 // There was an existing view at this offset. It must not be
296 // large enough. We can't delete it here, since something might
297 // be using it; put it on a list to be deleted when the file is
298 // unlocked.
299 v = ins.first->second;
300 gold_assert(v->size() - (start - v->start()) < size);
301 if (v->should_cache())
302 cache = true;
303 v->clear_cache();
304 this->saved_views_.push_back(v);
307 // We need to map data from the file.
309 section_size_type psize = File_read::pages(size + (start - poff));
311 if (poff + static_cast<off_t>(psize) >= this->size_)
313 psize = this->size_ - poff;
314 gold_assert(psize >= size);
317 if (this->contents_ != NULL)
319 unsigned char* p = new unsigned char[psize];
320 this->do_read(poff, psize, p);
321 v = new File_read::View(poff, psize, p, cache, false);
323 else
325 void* p = ::mmap(NULL, psize, PROT_READ, MAP_PRIVATE,
326 this->descriptor_, poff);
327 if (p == MAP_FAILED)
328 gold_fatal(_("%s: mmap offset %lld size %lld failed: %s"),
329 this->filename().c_str(),
330 static_cast<long long>(poff),
331 static_cast<long long>(psize),
332 strerror(errno));
334 this->mapped_bytes_ += psize;
336 const unsigned char* pbytes = static_cast<const unsigned char*>(p);
337 v = new File_read::View(poff, psize, pbytes, cache, true);
340 ins.first->second = v;
341 return v;
344 // Get a view into the file.
346 const unsigned char*
347 File_read::get_view(off_t start, section_size_type size, bool cache)
349 File_read::View* pv = this->find_or_make_view(start, size, cache);
350 return pv->data() + (start - pv->start());
353 File_view*
354 File_read::get_lasting_view(off_t start, section_size_type size, bool cache)
356 File_read::View* pv = this->find_or_make_view(start, size, cache);
357 pv->lock();
358 return new File_view(*this, pv, pv->data() + (start - pv->start()));
361 // Use readv to read COUNT entries from RM starting at START. BASE
362 // must be added to all file offsets in RM.
364 void
365 File_read::do_readv(off_t base, const Read_multiple& rm, size_t start,
366 size_t count)
368 unsigned char discard[File_read::page_size];
369 iovec iov[File_read::max_readv_entries * 2];
370 size_t iov_index = 0;
372 off_t first_offset = rm[start].file_offset;
373 off_t last_offset = first_offset;
374 ssize_t want = 0;
375 for (size_t i = 0; i < count; ++i)
377 const Read_multiple_entry& i_entry(rm[start + i]);
379 if (i_entry.file_offset > last_offset)
381 size_t skip = i_entry.file_offset - last_offset;
382 gold_assert(skip <= sizeof discard);
384 iov[iov_index].iov_base = discard;
385 iov[iov_index].iov_len = skip;
386 ++iov_index;
388 want += skip;
391 iov[iov_index].iov_base = i_entry.buffer;
392 iov[iov_index].iov_len = i_entry.size;
393 ++iov_index;
395 want += i_entry.size;
397 last_offset = i_entry.file_offset + i_entry.size;
400 gold_assert(iov_index < sizeof iov / sizeof iov[0]);
402 if (::lseek(this->descriptor_, base + first_offset, SEEK_SET) < 0)
403 gold_fatal(_("%s: lseek failed: %s"),
404 this->filename().c_str(), strerror(errno));
406 ssize_t got = ::readv(this->descriptor_, iov, iov_index);
408 if (got < 0)
409 gold_fatal(_("%s: readv failed: %s"),
410 this->filename().c_str(), strerror(errno));
411 if (got != want)
412 gold_fatal(_("%s: file too short: read only %zd of %zd bytes at %lld"),
413 this->filename().c_str(),
414 got, want, static_cast<long long>(base + first_offset));
417 // Read several pieces of data from the file.
419 void
420 File_read::read_multiple(off_t base, const Read_multiple& rm)
422 size_t count = rm.size();
423 size_t i = 0;
424 while (i < count)
426 // Find up to MAX_READV_ENTRIES consecutive entries which are
427 // less than one page apart.
428 const Read_multiple_entry& i_entry(rm[i]);
429 off_t i_off = i_entry.file_offset;
430 off_t end_off = i_off + i_entry.size;
431 size_t j;
432 for (j = i + 1; j < count; ++j)
434 if (j - i >= File_read::max_readv_entries)
435 break;
436 const Read_multiple_entry& j_entry(rm[j]);
437 off_t j_off = j_entry.file_offset;
438 gold_assert(j_off >= end_off);
439 off_t j_end_off = j_off + j_entry.size;
440 if (j_end_off - end_off >= File_read::page_size)
441 break;
442 end_off = j_end_off;
445 if (j == i + 1)
446 this->read(base + i_off, i_entry.size, i_entry.buffer);
447 else
449 File_read::View* view = this->find_view(base + i_off,
450 end_off - i_off);
451 if (view == NULL)
452 this->do_readv(base, rm, i, j - i);
453 else
455 const unsigned char* v = (view->data()
456 + (base + i_off - view->start()));
457 for (size_t k = i; k < j; ++k)
459 const Read_multiple_entry& k_entry(rm[k]);
460 gold_assert((convert_to_section_size_type(k_entry.file_offset
461 - i_off)
462 + k_entry.size)
463 <= convert_to_section_size_type(end_off
464 - i_off));
465 memcpy(k_entry.buffer,
466 v + (k_entry.file_offset - i_off),
467 k_entry.size);
472 i = j;
476 // Mark all views as no longer cached.
478 void
479 File_read::clear_view_cache_marks()
481 // Just ignore this if there are multiple objects associated with
482 // the file. Otherwise we will wind up uncaching and freeing some
483 // views for other objects.
484 if (this->object_count_ > 1)
485 return;
487 for (Views::iterator p = this->views_.begin();
488 p != this->views_.end();
489 ++p)
490 p->second->clear_cache();
491 for (Saved_views::iterator p = this->saved_views_.begin();
492 p != this->saved_views_.end();
493 ++p)
494 (*p)->clear_cache();
497 // Remove all the file views. For a file which has multiple
498 // associated objects (i.e., an archive), we keep accessed views
499 // around until next time, in the hopes that they will be useful for
500 // the next object.
502 void
503 File_read::clear_views(bool destroying)
505 Views::iterator p = this->views_.begin();
506 while (p != this->views_.end())
508 bool should_delete;
509 if (p->second->is_locked())
510 should_delete = false;
511 else if (destroying)
512 should_delete = true;
513 else if (p->second->should_cache())
514 should_delete = false;
515 else if (this->object_count_ > 1 && p->second->accessed())
516 should_delete = false;
517 else
518 should_delete = true;
520 if (should_delete)
522 delete p->second;
524 // map::erase invalidates only the iterator to the deleted
525 // element.
526 Views::iterator pe = p;
527 ++p;
528 this->views_.erase(pe);
530 else
532 gold_assert(!destroying);
533 p->second->clear_accessed();
534 ++p;
538 Saved_views::iterator q = this->saved_views_.begin();
539 while (q != this->saved_views_.end())
541 if (!(*q)->is_locked())
543 delete *q;
544 q = this->saved_views_.erase(q);
546 else
548 gold_assert(!destroying);
549 ++q;
554 // Print statistical information to stderr. This is used for --stats.
556 void
557 File_read::print_stats()
559 fprintf(stderr, _("%s: total bytes mapped for read: %llu\n"),
560 program_name, File_read::total_mapped_bytes);
561 fprintf(stderr, _("%s: maximum bytes mapped for read at one time: %llu\n"),
562 program_name, File_read::maximum_mapped_bytes);
565 // Class File_view.
567 File_view::~File_view()
569 gold_assert(this->file_.is_locked());
570 this->view_->unlock();
573 // Class Input_file.
575 // Create a file for testing.
577 Input_file::Input_file(const Task* task, const char* name,
578 const unsigned char* contents, off_t size)
579 : file_()
581 this->input_argument_ =
582 new Input_file_argument(name, false, "", false,
583 Position_dependent_options());
584 bool ok = file_.open(task, name, contents, size);
585 gold_assert(ok);
588 // Return the position dependent options in force for this file.
590 const Position_dependent_options&
591 Input_file::options() const
593 return this->input_argument_->options();
596 // Return the name given by the user. For -lc this will return "c".
598 const char*
599 Input_file::name() const
601 return this->input_argument_->name();
604 // Return whether we are only reading symbols.
606 bool
607 Input_file::just_symbols() const
609 return this->input_argument_->just_symbols();
612 // Open the file.
614 // If the filename is not absolute, we assume it is in the current
615 // directory *except* when:
616 // A) input_argument_->is_lib() is true; or
617 // B) input_argument_->extra_search_path() is not empty.
618 // In both cases, we look in extra_search_path + library_path to find
619 // the file location, rather than the current directory.
621 bool
622 Input_file::open(const General_options& options, const Dirsearch& dirpath,
623 const Task* task)
625 std::string name;
627 // Case 1: name is an absolute file, just try to open it
628 // Case 2: name is relative but is_lib is false and extra_search_path
629 // is empty
630 if (IS_ABSOLUTE_PATH (this->input_argument_->name())
631 || (!this->input_argument_->is_lib()
632 && this->input_argument_->extra_search_path() == NULL))
634 name = this->input_argument_->name();
635 this->found_name_ = name;
637 // Case 3: is_lib is true
638 else if (this->input_argument_->is_lib())
640 // We don't yet support extra_search_path with -l.
641 gold_assert(this->input_argument_->extra_search_path() == NULL);
642 std::string n1("lib");
643 n1 += this->input_argument_->name();
644 std::string n2;
645 if (options.is_static()
646 || this->input_argument_->options().Bstatic())
647 n1 += ".a";
648 else
650 n2 = n1 + ".a";
651 n1 += ".so";
653 name = dirpath.find(n1, n2, &this->is_in_sysroot_);
654 if (name.empty())
656 gold_error(_("cannot find -l%s"),
657 this->input_argument_->name());
658 return false;
660 if (n2.empty() || name[name.length() - 1] == 'o')
661 this->found_name_ = n1;
662 else
663 this->found_name_ = n2;
665 // Case 4: extra_search_path is not empty
666 else
668 gold_assert(this->input_argument_->extra_search_path() != NULL);
670 // First, check extra_search_path.
671 name = this->input_argument_->extra_search_path();
672 if (!IS_DIR_SEPARATOR (name[name.length() - 1]))
673 name += '/';
674 name += this->input_argument_->name();
675 struct stat dummy_stat;
676 if (::stat(name.c_str(), &dummy_stat) < 0)
678 // extra_search_path failed, so check the normal search-path.
679 name = dirpath.find(this->input_argument_->name(), "",
680 &this->is_in_sysroot_);
681 if (name.empty())
683 gold_error(_("cannot find %s"),
684 this->input_argument_->name());
685 return false;
688 this->found_name_ = this->input_argument_->name();
691 // Now that we've figured out where the file lives, try to open it.
693 General_options::Object_format format =
694 this->input_argument_->options().format();
695 bool ok;
696 if (format == General_options::OBJECT_FORMAT_ELF)
697 ok = this->file_.open(task, name);
698 else
700 gold_assert(format == General_options::OBJECT_FORMAT_BINARY);
701 ok = this->open_binary(options, task, name);
704 if (!ok)
706 gold_error(_("cannot open %s: %s"),
707 name.c_str(), strerror(errno));
708 return false;
711 return true;
714 // Open a file for --format binary.
716 bool
717 Input_file::open_binary(const General_options&,
718 const Task* task, const std::string& name)
720 // In order to open a binary file, we need machine code, size, and
721 // endianness. We may not have a valid target at this point, in
722 // which case we use the default target.
723 const Target* target;
724 if (parameters->target_valid())
725 target = &parameters->target();
726 else
727 target = &parameters->default_target();
729 Binary_to_elf binary_to_elf(target->machine_code(),
730 target->get_size(),
731 target->is_big_endian(),
732 name);
733 if (!binary_to_elf.convert(task))
734 return false;
735 return this->file_.open(task, name, binary_to_elf.converted_data_leak(),
736 binary_to_elf.converted_size());
739 } // End namespace gold.