merge from gcc
[binutils.git] / gold / fileread.cc
blob20820e4c2ee2c609c81e7a9219a32dbbb6fe1a81
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.
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 "debug.h"
34 #include "parameters.h"
35 #include "options.h"
36 #include "dirsearch.h"
37 #include "target.h"
38 #include "binary.h"
39 #include "fileread.h"
41 namespace gold
44 // Class File_read::View.
46 File_read::View::~View()
48 gold_assert(!this->is_locked());
49 if (!this->mapped_)
50 delete[] this->data_;
51 else
53 if (::munmap(const_cast<unsigned char*>(this->data_), this->size_) != 0)
54 gold_warning(_("munmap failed: %s"), strerror(errno));
56 File_read::current_mapped_bytes -= this->size_;
60 void
61 File_read::View::lock()
63 ++this->lock_count_;
66 void
67 File_read::View::unlock()
69 gold_assert(this->lock_count_ > 0);
70 --this->lock_count_;
73 bool
74 File_read::View::is_locked()
76 return this->lock_count_ > 0;
79 // Class File_read.
81 // The File_read static variables.
82 unsigned long long File_read::total_mapped_bytes;
83 unsigned long long File_read::current_mapped_bytes;
84 unsigned long long File_read::maximum_mapped_bytes;
86 // The File_read class is designed to support file descriptor caching,
87 // but this is not currently implemented.
89 File_read::~File_read()
91 gold_assert(this->token_.is_writable());
92 if (this->descriptor_ >= 0)
94 if (close(this->descriptor_) < 0)
95 gold_warning(_("close of %s failed: %s"),
96 this->name_.c_str(), strerror(errno));
97 this->descriptor_ = -1;
99 this->name_.clear();
100 this->clear_views(true);
103 // Open the file.
105 bool
106 File_read::open(const Task* task, const std::string& name)
108 gold_assert(this->token_.is_writable()
109 && this->descriptor_ < 0
110 && this->name_.empty());
111 this->name_ = name;
113 this->descriptor_ = ::open(this->name_.c_str(), O_RDONLY);
115 if (this->descriptor_ >= 0)
117 struct stat s;
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());
126 this->token_.add_writer(task);
128 return this->descriptor_ >= 0;
131 // Open the file with the contents in memory.
133 bool
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->name_.empty());
140 this->name_ = name;
141 this->contents_ = contents;
142 this->size_ = size;
143 this->token_.add_writer(task);
144 return true;
147 // Release the file. This is called when we are done with the file in
148 // a Task.
150 void
151 File_read::release()
153 gold_assert(this->is_locked());
155 File_read::total_mapped_bytes += this->mapped_bytes_;
156 File_read::current_mapped_bytes += this->mapped_bytes_;
157 this->mapped_bytes_ = 0;
158 if (File_read::current_mapped_bytes > File_read::maximum_mapped_bytes)
159 File_read::maximum_mapped_bytes = File_read::current_mapped_bytes;
161 this->clear_views(false);
163 this->released_ = true;
166 // Lock the file.
168 void
169 File_read::lock(const Task* task)
171 gold_assert(this->released_);
172 this->token_.add_writer(task);
173 this->released_ = false;
176 // Unlock the file.
178 void
179 File_read::unlock(const Task* task)
181 this->release();
182 this->token_.remove_writer(task);
185 // Return whether the file is locked.
187 bool
188 File_read::is_locked() const
190 if (!this->token_.is_writable())
191 return true;
192 // The file is not locked, so it should have been released.
193 gold_assert(this->released_);
194 return false;
197 // See if we have a view which covers the file starting at START for
198 // SIZE bytes. Return a pointer to the View if found, NULL if not.
200 inline File_read::View*
201 File_read::find_view(off_t start, section_size_type size) const
203 off_t page = File_read::page_offset(start);
205 Views::const_iterator p = this->views_.lower_bound(page);
206 if (p == this->views_.end() || p->first > page)
208 if (p == this->views_.begin())
209 return NULL;
210 --p;
213 if (p->second->start() + static_cast<off_t>(p->second->size())
214 < start + static_cast<off_t>(size))
215 return NULL;
217 p->second->set_accessed();
219 return p->second;
222 // Read SIZE bytes from the file starting at offset START. Read into
223 // the buffer at P.
225 void
226 File_read::do_read(off_t start, section_size_type size, void* p) const
228 ssize_t bytes;
229 if (this->contents_ != NULL)
231 bytes = this->size_ - start;
232 if (static_cast<section_size_type>(bytes) >= size)
234 memcpy(p, this->contents_ + start, size);
235 return;
238 else
240 bytes = ::pread(this->descriptor_, p, size, start);
241 if (static_cast<section_size_type>(bytes) == size)
242 return;
244 if (bytes < 0)
246 gold_fatal(_("%s: pread failed: %s"),
247 this->filename().c_str(), strerror(errno));
248 return;
252 gold_fatal(_("%s: file too short: read only %lld of %lld bytes at %lld"),
253 this->filename().c_str(),
254 static_cast<long long>(bytes),
255 static_cast<long long>(size),
256 static_cast<long long>(start));
259 // Read data from the file.
261 void
262 File_read::read(off_t start, section_size_type size, void* p) const
264 const File_read::View* pv = this->find_view(start, size);
265 if (pv != NULL)
267 memcpy(p, pv->data() + (start - pv->start()), size);
268 return;
271 this->do_read(start, size, p);
274 // Find an existing view or make a new one.
276 File_read::View*
277 File_read::find_or_make_view(off_t start, section_size_type size, bool cache)
279 gold_assert(!this->token_.is_writable());
280 this->released_ = false;
282 File_read::View* v = this->find_view(start, size);
283 if (v != NULL)
285 if (cache)
286 v->set_cache();
287 return v;
290 off_t poff = File_read::page_offset(start);
292 File_read::View* const vnull = NULL;
293 std::pair<Views::iterator, bool> ins =
294 this->views_.insert(std::make_pair(poff, vnull));
296 if (!ins.second)
298 // There was an existing view at this offset. It must not be
299 // large enough. We can't delete it here, since something might
300 // be using it; put it on a list to be deleted when the file is
301 // unlocked.
302 v = ins.first->second;
303 gold_assert(v->size() - (start - v->start()) < size);
304 if (v->should_cache())
305 cache = true;
306 v->clear_cache();
307 this->saved_views_.push_back(v);
310 // We need to map data from the file.
312 section_size_type psize = File_read::pages(size + (start - poff));
314 if (poff + static_cast<off_t>(psize) >= this->size_)
316 psize = this->size_ - poff;
317 gold_assert(psize >= size);
320 if (this->contents_ != NULL)
322 unsigned char* p = new unsigned char[psize];
323 this->do_read(poff, psize, p);
324 v = new File_read::View(poff, psize, p, cache, false);
326 else
328 void* p = ::mmap(NULL, psize, PROT_READ, MAP_PRIVATE,
329 this->descriptor_, poff);
330 if (p == MAP_FAILED)
331 gold_fatal(_("%s: mmap offset %lld size %lld failed: %s"),
332 this->filename().c_str(),
333 static_cast<long long>(poff),
334 static_cast<long long>(psize),
335 strerror(errno));
337 this->mapped_bytes_ += psize;
339 const unsigned char* pbytes = static_cast<const unsigned char*>(p);
340 v = new File_read::View(poff, psize, pbytes, cache, true);
343 ins.first->second = v;
344 return v;
347 // Get a view into the file.
349 const unsigned char*
350 File_read::get_view(off_t start, section_size_type size, bool cache)
352 File_read::View* pv = this->find_or_make_view(start, size, cache);
353 return pv->data() + (start - pv->start());
356 File_view*
357 File_read::get_lasting_view(off_t start, section_size_type size, bool cache)
359 File_read::View* pv = this->find_or_make_view(start, size, cache);
360 pv->lock();
361 return new File_view(*this, pv, pv->data() + (start - pv->start()));
364 // Use readv to read COUNT entries from RM starting at START. BASE
365 // must be added to all file offsets in RM.
367 void
368 File_read::do_readv(off_t base, const Read_multiple& rm, size_t start,
369 size_t count)
371 unsigned char discard[File_read::page_size];
372 iovec iov[File_read::max_readv_entries * 2];
373 size_t iov_index = 0;
375 off_t first_offset = rm[start].file_offset;
376 off_t last_offset = first_offset;
377 ssize_t want = 0;
378 for (size_t i = 0; i < count; ++i)
380 const Read_multiple_entry& i_entry(rm[start + i]);
382 if (i_entry.file_offset > last_offset)
384 size_t skip = i_entry.file_offset - last_offset;
385 gold_assert(skip <= sizeof discard);
387 iov[iov_index].iov_base = discard;
388 iov[iov_index].iov_len = skip;
389 ++iov_index;
391 want += skip;
394 iov[iov_index].iov_base = i_entry.buffer;
395 iov[iov_index].iov_len = i_entry.size;
396 ++iov_index;
398 want += i_entry.size;
400 last_offset = i_entry.file_offset + i_entry.size;
403 gold_assert(iov_index < sizeof iov / sizeof iov[0]);
405 if (::lseek(this->descriptor_, base + first_offset, SEEK_SET) < 0)
406 gold_fatal(_("%s: lseek failed: %s"),
407 this->filename().c_str(), strerror(errno));
409 ssize_t got = ::readv(this->descriptor_, iov, iov_index);
411 if (got < 0)
412 gold_fatal(_("%s: readv failed: %s"),
413 this->filename().c_str(), strerror(errno));
414 if (got != want)
415 gold_fatal(_("%s: file too short: read only %zd of %zd bytes at %lld"),
416 this->filename().c_str(),
417 got, want, static_cast<long long>(base + first_offset));
420 // Read several pieces of data from the file.
422 void
423 File_read::read_multiple(off_t base, const Read_multiple& rm)
425 size_t count = rm.size();
426 size_t i = 0;
427 while (i < count)
429 // Find up to MAX_READV_ENTRIES consecutive entries which are
430 // less than one page apart.
431 const Read_multiple_entry& i_entry(rm[i]);
432 off_t i_off = i_entry.file_offset;
433 off_t end_off = i_off + i_entry.size;
434 size_t j;
435 for (j = i + 1; j < count; ++j)
437 if (j - i >= File_read::max_readv_entries)
438 break;
439 const Read_multiple_entry& j_entry(rm[j]);
440 off_t j_off = j_entry.file_offset;
441 gold_assert(j_off >= end_off);
442 off_t j_end_off = j_off + j_entry.size;
443 if (j_end_off - end_off >= File_read::page_size)
444 break;
445 end_off = j_end_off;
448 if (j == i + 1)
449 this->read(base + i_off, i_entry.size, i_entry.buffer);
450 else
452 File_read::View* view = this->find_view(base + i_off,
453 end_off - i_off);
454 if (view == NULL)
455 this->do_readv(base, rm, i, j - i);
456 else
458 const unsigned char* v = (view->data()
459 + (base + i_off - view->start()));
460 for (size_t k = i; k < j; ++k)
462 const Read_multiple_entry& k_entry(rm[k]);
463 gold_assert((convert_to_section_size_type(k_entry.file_offset
464 - i_off)
465 + k_entry.size)
466 <= convert_to_section_size_type(end_off
467 - i_off));
468 memcpy(k_entry.buffer,
469 v + (k_entry.file_offset - i_off),
470 k_entry.size);
475 i = j;
479 // Mark all views as no longer cached.
481 void
482 File_read::clear_view_cache_marks()
484 // Just ignore this if there are multiple objects associated with
485 // the file. Otherwise we will wind up uncaching and freeing some
486 // views for other objects.
487 if (this->object_count_ > 1)
488 return;
490 for (Views::iterator p = this->views_.begin();
491 p != this->views_.end();
492 ++p)
493 p->second->clear_cache();
494 for (Saved_views::iterator p = this->saved_views_.begin();
495 p != this->saved_views_.end();
496 ++p)
497 (*p)->clear_cache();
500 // Remove all the file views. For a file which has multiple
501 // associated objects (i.e., an archive), we keep accessed views
502 // around until next time, in the hopes that they will be useful for
503 // the next object.
505 void
506 File_read::clear_views(bool destroying)
508 Views::iterator p = this->views_.begin();
509 while (p != this->views_.end())
511 bool should_delete;
512 if (p->second->is_locked())
513 should_delete = false;
514 else if (destroying)
515 should_delete = true;
516 else if (p->second->should_cache())
517 should_delete = false;
518 else if (this->object_count_ > 1 && p->second->accessed())
519 should_delete = false;
520 else
521 should_delete = true;
523 if (should_delete)
525 delete p->second;
527 // map::erase invalidates only the iterator to the deleted
528 // element.
529 Views::iterator pe = p;
530 ++p;
531 this->views_.erase(pe);
533 else
535 gold_assert(!destroying);
536 p->second->clear_accessed();
537 ++p;
541 Saved_views::iterator q = this->saved_views_.begin();
542 while (q != this->saved_views_.end())
544 if (!(*q)->is_locked())
546 delete *q;
547 q = this->saved_views_.erase(q);
549 else
551 gold_assert(!destroying);
552 ++q;
557 // Print statistical information to stderr. This is used for --stats.
559 void
560 File_read::print_stats()
562 fprintf(stderr, _("%s: total bytes mapped for read: %llu\n"),
563 program_name, File_read::total_mapped_bytes);
564 fprintf(stderr, _("%s: maximum bytes mapped for read at one time: %llu\n"),
565 program_name, File_read::maximum_mapped_bytes);
568 // Class File_view.
570 File_view::~File_view()
572 gold_assert(this->file_.is_locked());
573 this->view_->unlock();
576 // Class Input_file.
578 // Create a file for testing.
580 Input_file::Input_file(const Task* task, const char* name,
581 const unsigned char* contents, off_t size)
582 : file_()
584 this->input_argument_ =
585 new Input_file_argument(name, false, "", false,
586 Position_dependent_options());
587 bool ok = file_.open(task, name, contents, size);
588 gold_assert(ok);
591 // Return the position dependent options in force for this file.
593 const Position_dependent_options&
594 Input_file::options() const
596 return this->input_argument_->options();
599 // Return the name given by the user. For -lc this will return "c".
601 const char*
602 Input_file::name() const
604 return this->input_argument_->name();
607 // Return whether we are only reading symbols.
609 bool
610 Input_file::just_symbols() const
612 return this->input_argument_->just_symbols();
615 // Open the file.
617 // If the filename is not absolute, we assume it is in the current
618 // directory *except* when:
619 // A) input_argument_->is_lib() is true; or
620 // B) input_argument_->extra_search_path() is not empty.
621 // In both cases, we look in extra_search_path + library_path to find
622 // the file location, rather than the current directory.
624 bool
625 Input_file::open(const General_options& options, const Dirsearch& dirpath,
626 const Task* task)
628 std::string name;
630 // Case 1: name is an absolute file, just try to open it
631 // Case 2: name is relative but is_lib is false and extra_search_path
632 // is empty
633 if (IS_ABSOLUTE_PATH (this->input_argument_->name())
634 || (!this->input_argument_->is_lib()
635 && this->input_argument_->extra_search_path() == NULL))
637 name = this->input_argument_->name();
638 this->found_name_ = name;
640 // Case 3: is_lib is true
641 else if (this->input_argument_->is_lib())
643 // We don't yet support extra_search_path with -l.
644 gold_assert(this->input_argument_->extra_search_path() == NULL);
645 std::string n1("lib");
646 n1 += this->input_argument_->name();
647 std::string n2;
648 if (options.is_static()
649 || !this->input_argument_->options().Bdynamic())
650 n1 += ".a";
651 else
653 n2 = n1 + ".a";
654 n1 += ".so";
656 name = dirpath.find(n1, n2, &this->is_in_sysroot_);
657 if (name.empty())
659 gold_error(_("cannot find -l%s"),
660 this->input_argument_->name());
661 return false;
663 if (n2.empty() || name[name.length() - 1] == 'o')
664 this->found_name_ = n1;
665 else
666 this->found_name_ = n2;
668 // Case 4: extra_search_path is not empty
669 else
671 gold_assert(this->input_argument_->extra_search_path() != NULL);
673 // First, check extra_search_path.
674 name = this->input_argument_->extra_search_path();
675 if (!IS_DIR_SEPARATOR (name[name.length() - 1]))
676 name += '/';
677 name += this->input_argument_->name();
678 struct stat dummy_stat;
679 if (::stat(name.c_str(), &dummy_stat) < 0)
681 // extra_search_path failed, so check the normal search-path.
682 name = dirpath.find(this->input_argument_->name(), "",
683 &this->is_in_sysroot_);
684 if (name.empty())
686 gold_error(_("cannot find %s"),
687 this->input_argument_->name());
688 return false;
691 this->found_name_ = this->input_argument_->name();
694 // Now that we've figured out where the file lives, try to open it.
696 General_options::Object_format format =
697 this->input_argument_->options().format_enum();
698 bool ok;
699 if (format == General_options::OBJECT_FORMAT_ELF)
700 ok = this->file_.open(task, name);
701 else
703 gold_assert(format == General_options::OBJECT_FORMAT_BINARY);
704 ok = this->open_binary(options, task, name);
707 if (!ok)
709 gold_error(_("cannot open %s: %s"),
710 name.c_str(), strerror(errno));
711 return false;
714 return true;
717 // Open a file for --format binary.
719 bool
720 Input_file::open_binary(const General_options&,
721 const Task* task, const std::string& name)
723 // In order to open a binary file, we need machine code, size, and
724 // endianness. We may not have a valid target at this point, in
725 // which case we use the default target.
726 const Target* target;
727 if (parameters->target_valid())
728 target = &parameters->target();
729 else
730 target = &parameters->default_target();
732 Binary_to_elf binary_to_elf(target->machine_code(),
733 target->get_size(),
734 target->is_big_endian(),
735 name);
736 if (!binary_to_elf.convert(task))
737 return false;
738 return this->file_.open(task, name, binary_to_elf.converted_data_leak(),
739 binary_to_elf.converted_size());
742 } // End namespace gold.