daily update
[binutils.git] / gold / fileread.cc
blobac96f5fcf4ae5ed50ca6343334d2bee3ae00bddf
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 "options.h"
34 #include "dirsearch.h"
35 #include "fileread.h"
37 namespace gold
40 // Class File_read::View.
42 File_read::View::~View()
44 gold_assert(!this->is_locked());
45 if (!this->mapped_)
46 delete[] this->data_;
47 else
49 if (::munmap(const_cast<unsigned char*>(this->data_), this->size_) != 0)
50 gold_warning(_("munmap failed: %s"), strerror(errno));
52 File_read::current_mapped_bytes -= this->size_;
56 void
57 File_read::View::lock()
59 ++this->lock_count_;
62 void
63 File_read::View::unlock()
65 gold_assert(this->lock_count_ > 0);
66 --this->lock_count_;
69 bool
70 File_read::View::is_locked()
72 return this->lock_count_ > 0;
75 // Class File_read.
77 // The File_read static variables.
78 unsigned long long File_read::total_mapped_bytes;
79 unsigned long long File_read::current_mapped_bytes;
80 unsigned long long File_read::maximum_mapped_bytes;
82 // The File_read class is designed to support file descriptor caching,
83 // but this is not currently implemented.
85 File_read::~File_read()
87 gold_assert(this->token_.is_writable());
88 if (this->descriptor_ >= 0)
90 if (close(this->descriptor_) < 0)
91 gold_warning(_("close of %s failed: %s"),
92 this->name_.c_str(), strerror(errno));
93 this->descriptor_ = -1;
95 this->name_.clear();
96 this->clear_views(true);
99 // Open the file.
101 bool
102 File_read::open(const Task* task, const std::string& name)
104 gold_assert(this->token_.is_writable()
105 && this->descriptor_ < 0
106 && this->name_.empty());
107 this->name_ = name;
109 this->descriptor_ = ::open(this->name_.c_str(), O_RDONLY);
111 if (this->descriptor_ >= 0)
113 struct stat s;
114 if (::fstat(this->descriptor_, &s) < 0)
115 gold_error(_("%s: fstat failed: %s"),
116 this->name_.c_str(), strerror(errno));
117 this->size_ = s.st_size;
120 this->token_.add_writer(task);
122 return this->descriptor_ >= 0;
125 // Open the file for testing purposes.
127 bool
128 File_read::open(const Task* task, const std::string& name,
129 const unsigned char* contents, off_t size)
131 gold_assert(this->token_.is_writable()
132 && this->descriptor_ < 0
133 && this->name_.empty());
134 this->name_ = name;
135 this->contents_ = contents;
136 this->size_ = size;
137 this->token_.add_writer(task);
138 return true;
141 // Release the file. This is called when we are done with the file in
142 // a Task.
144 void
145 File_read::release()
147 gold_assert(this->is_locked());
149 File_read::total_mapped_bytes += this->mapped_bytes_;
150 File_read::current_mapped_bytes += this->mapped_bytes_;
151 this->mapped_bytes_ = 0;
152 if (File_read::current_mapped_bytes > File_read::maximum_mapped_bytes)
153 File_read::maximum_mapped_bytes = File_read::current_mapped_bytes;
155 this->clear_views(false);
157 this->released_ = true;
160 // Lock the file.
162 void
163 File_read::lock(const Task* task)
165 gold_assert(this->released_);
166 this->token_.add_writer(task);
167 this->released_ = false;
170 // Unlock the file.
172 void
173 File_read::unlock(const Task* task)
175 this->release();
176 this->token_.remove_writer(task);
179 // Return whether the file is locked.
181 bool
182 File_read::is_locked() const
184 if (!this->token_.is_writable())
185 return true;
186 // The file is not locked, so it should have been released.
187 gold_assert(this->released_);
188 return false;
191 // See if we have a view which covers the file starting at START for
192 // SIZE bytes. Return a pointer to the View if found, NULL if not.
194 inline File_read::View*
195 File_read::find_view(off_t start, section_size_type size) const
197 off_t page = File_read::page_offset(start);
199 Views::const_iterator p = this->views_.lower_bound(page);
200 if (p == this->views_.end() || p->first > page)
202 if (p == this->views_.begin())
203 return NULL;
204 --p;
207 if (p->second->start() + static_cast<off_t>(p->second->size())
208 < start + static_cast<off_t>(size))
209 return NULL;
211 p->second->set_accessed();
213 return p->second;
216 // Read SIZE bytes from the file starting at offset START. Read into
217 // the buffer at P.
219 void
220 File_read::do_read(off_t start, section_size_type size, void* p) const
222 ssize_t bytes;
223 if (this->contents_ != NULL)
225 bytes = this->size_ - start;
226 if (static_cast<section_size_type>(bytes) >= size)
228 memcpy(p, this->contents_ + start, size);
229 return;
232 else
234 bytes = ::pread(this->descriptor_, p, size, start);
235 if (static_cast<section_size_type>(bytes) == size)
236 return;
238 if (bytes < 0)
240 gold_fatal(_("%s: pread failed: %s"),
241 this->filename().c_str(), strerror(errno));
242 return;
246 gold_fatal(_("%s: file too short: read only %lld of %lld bytes at %lld"),
247 this->filename().c_str(),
248 static_cast<long long>(bytes),
249 static_cast<long long>(size),
250 static_cast<long long>(start));
253 // Read data from the file.
255 void
256 File_read::read(off_t start, section_size_type size, void* p) const
258 const File_read::View* pv = this->find_view(start, size);
259 if (pv != NULL)
261 memcpy(p, pv->data() + (start - pv->start()), size);
262 return;
265 this->do_read(start, size, p);
268 // Find an existing view or make a new one.
270 File_read::View*
271 File_read::find_or_make_view(off_t start, section_size_type size, bool cache)
273 gold_assert(!this->token_.is_writable());
274 this->released_ = false;
276 File_read::View* v = this->find_view(start, size);
277 if (v != NULL)
279 if (cache)
280 v->set_cache();
281 return v;
284 off_t poff = File_read::page_offset(start);
286 File_read::View* const vnull = NULL;
287 std::pair<Views::iterator, bool> ins =
288 this->views_.insert(std::make_pair(poff, vnull));
290 if (!ins.second)
292 // There was an existing view at this offset. It must not be
293 // large enough. We can't delete it here, since something might
294 // be using it; put it on a list to be deleted when the file is
295 // unlocked.
296 v = ins.first->second;
297 gold_assert(v->size() - (start - v->start()) < size);
298 if (v->should_cache())
299 cache = true;
300 v->clear_cache();
301 this->saved_views_.push_back(v);
304 // We need to map data from the file.
306 section_size_type psize = File_read::pages(size + (start - poff));
308 if (poff + static_cast<off_t>(psize) >= this->size_)
310 psize = this->size_ - poff;
311 gold_assert(psize >= size);
314 if (this->contents_ != NULL)
316 unsigned char* p = new unsigned char[psize];
317 this->do_read(poff, psize, p);
318 v = new File_read::View(poff, psize, p, cache, false);
320 else
322 void* p = ::mmap(NULL, psize, PROT_READ, MAP_PRIVATE,
323 this->descriptor_, poff);
324 if (p == MAP_FAILED)
325 gold_fatal(_("%s: mmap offset %lld size %lld failed: %s"),
326 this->filename().c_str(),
327 static_cast<long long>(poff),
328 static_cast<long long>(psize),
329 strerror(errno));
331 this->mapped_bytes_ += psize;
333 const unsigned char* pbytes = static_cast<const unsigned char*>(p);
334 v = new File_read::View(poff, psize, pbytes, cache, true);
337 ins.first->second = v;
338 return v;
341 // Get a view into the file.
343 const unsigned char*
344 File_read::get_view(off_t start, section_size_type size, bool cache)
346 File_read::View* pv = this->find_or_make_view(start, size, cache);
347 return pv->data() + (start - pv->start());
350 File_view*
351 File_read::get_lasting_view(off_t start, section_size_type size, bool cache)
353 File_read::View* pv = this->find_or_make_view(start, size, cache);
354 pv->lock();
355 return new File_view(*this, pv, pv->data() + (start - pv->start()));
358 // Use readv to read COUNT entries from RM starting at START. BASE
359 // must be added to all file offsets in RM.
361 void
362 File_read::do_readv(off_t base, const Read_multiple& rm, size_t start,
363 size_t count)
365 unsigned char discard[File_read::page_size];
366 iovec iov[File_read::max_readv_entries * 2];
367 size_t iov_index = 0;
369 off_t first_offset = rm[start].file_offset;
370 off_t last_offset = first_offset;
371 ssize_t want = 0;
372 for (size_t i = 0; i < count; ++i)
374 const Read_multiple_entry& i_entry(rm[start + i]);
376 if (i_entry.file_offset > last_offset)
378 size_t skip = i_entry.file_offset - last_offset;
379 gold_assert(skip <= sizeof discard);
381 iov[iov_index].iov_base = discard;
382 iov[iov_index].iov_len = skip;
383 ++iov_index;
385 want += skip;
388 iov[iov_index].iov_base = i_entry.buffer;
389 iov[iov_index].iov_len = i_entry.size;
390 ++iov_index;
392 want += i_entry.size;
394 last_offset = i_entry.file_offset + i_entry.size;
397 gold_assert(iov_index < sizeof iov / sizeof iov[0]);
399 if (::lseek(this->descriptor_, base + first_offset, SEEK_SET) < 0)
400 gold_fatal(_("%s: lseek failed: %s"),
401 this->filename().c_str(), strerror(errno));
403 ssize_t got = ::readv(this->descriptor_, iov, iov_index);
405 if (got < 0)
406 gold_fatal(_("%s: readv failed: %s"),
407 this->filename().c_str(), strerror(errno));
408 if (got != want)
409 gold_fatal(_("%s: file too short: read only %zd of %zd bytes at %lld"),
410 this->filename().c_str(),
411 got, want, static_cast<long long>(base + first_offset));
414 // Read several pieces of data from the file.
416 void
417 File_read::read_multiple(off_t base, const Read_multiple& rm)
419 size_t count = rm.size();
420 size_t i = 0;
421 while (i < count)
423 // Find up to MAX_READV_ENTRIES consecutive entries which are
424 // less than one page apart.
425 const Read_multiple_entry& i_entry(rm[i]);
426 off_t i_off = i_entry.file_offset;
427 off_t end_off = i_off + i_entry.size;
428 size_t j;
429 for (j = i + 1; j < count; ++j)
431 if (j - i >= File_read::max_readv_entries)
432 break;
433 const Read_multiple_entry& j_entry(rm[j]);
434 off_t j_off = j_entry.file_offset;
435 gold_assert(j_off >= end_off);
436 off_t j_end_off = j_off + j_entry.size;
437 if (j_end_off - end_off >= File_read::page_size)
438 break;
439 end_off = j_end_off;
442 if (j == i + 1)
443 this->read(base + i_off, i_entry.size, i_entry.buffer);
444 else
446 File_read::View* view = this->find_view(base + i_off,
447 end_off - i_off);
448 if (view == NULL)
449 this->do_readv(base, rm, i, j - i);
450 else
452 const unsigned char* v = (view->data()
453 + (base + i_off - view->start()));
454 for (size_t k = i; k < j; ++k)
456 const Read_multiple_entry& k_entry(rm[k]);
457 gold_assert((convert_to_section_size_type(k_entry.file_offset
458 - i_off)
459 + k_entry.size)
460 <= convert_to_section_size_type(end_off
461 - i_off));
462 memcpy(k_entry.buffer,
463 v + (k_entry.file_offset - i_off),
464 k_entry.size);
469 i = j;
473 // Mark all views as no longer cached.
475 void
476 File_read::clear_view_cache_marks()
478 // Just ignore this if there are multiple objects associated with
479 // the file. Otherwise we will wind up uncaching and freeing some
480 // views for other objects.
481 if (this->object_count_ > 1)
482 return;
484 for (Views::iterator p = this->views_.begin();
485 p != this->views_.end();
486 ++p)
487 p->second->clear_cache();
488 for (Saved_views::iterator p = this->saved_views_.begin();
489 p != this->saved_views_.end();
490 ++p)
491 (*p)->clear_cache();
494 // Remove all the file views. For a file which has multiple
495 // associated objects (i.e., an archive), we keep accessed views
496 // around until next time, in the hopes that they will be useful for
497 // the next object.
499 void
500 File_read::clear_views(bool destroying)
502 Views::iterator p = this->views_.begin();
503 while (p != this->views_.end())
505 bool should_delete;
506 if (p->second->is_locked())
507 should_delete = false;
508 else if (destroying)
509 should_delete = true;
510 else if (p->second->should_cache())
511 should_delete = false;
512 else if (this->object_count_ > 1 && p->second->accessed())
513 should_delete = false;
514 else
515 should_delete = true;
517 if (should_delete)
519 delete p->second;
521 // map::erase invalidates only the iterator to the deleted
522 // element.
523 Views::iterator pe = p;
524 ++p;
525 this->views_.erase(pe);
527 else
529 gold_assert(!destroying);
530 p->second->clear_accessed();
531 ++p;
535 Saved_views::iterator q = this->saved_views_.begin();
536 while (q != this->saved_views_.end())
538 if (!(*q)->is_locked())
540 delete *q;
541 q = this->saved_views_.erase(q);
543 else
545 gold_assert(!destroying);
546 ++q;
551 // Print statistical information to stderr. This is used for --stats.
553 void
554 File_read::print_stats()
556 fprintf(stderr, _("%s: total bytes mapped for read: %llu\n"),
557 program_name, File_read::total_mapped_bytes);
558 fprintf(stderr, _("%s: maximum bytes mapped for read at one time: %llu\n"),
559 program_name, File_read::maximum_mapped_bytes);
562 // Class File_view.
564 File_view::~File_view()
566 gold_assert(this->file_.is_locked());
567 this->view_->unlock();
570 // Class Input_file.
572 // Create a file for testing.
574 Input_file::Input_file(const Task* task, const char* name,
575 const unsigned char* contents, off_t size)
576 : file_()
578 this->input_argument_ =
579 new Input_file_argument(name, false, "", Position_dependent_options());
580 bool ok = file_.open(task, name, contents, size);
581 gold_assert(ok);
584 // Open the file.
586 // If the filename is not absolute, we assume it is in the current
587 // directory *except* when:
588 // A) input_argument_->is_lib() is true; or
589 // B) input_argument_->extra_search_path() is not empty.
590 // In both cases, we look in extra_search_path + library_path to find
591 // the file location, rather than the current directory.
593 bool
594 Input_file::open(const General_options& options, const Dirsearch& dirpath,
595 const Task* task)
597 std::string name;
599 // Case 1: name is an absolute file, just try to open it
600 // Case 2: name is relative but is_lib is false and extra_search_path
601 // is empty
602 if (IS_ABSOLUTE_PATH (this->input_argument_->name())
603 || (!this->input_argument_->is_lib()
604 && this->input_argument_->extra_search_path() == NULL))
606 name = this->input_argument_->name();
607 this->found_name_ = name;
609 // Case 3: is_lib is true
610 else if (this->input_argument_->is_lib())
612 // We don't yet support extra_search_path with -l.
613 gold_assert(this->input_argument_->extra_search_path() == NULL);
614 std::string n1("lib");
615 n1 += this->input_argument_->name();
616 std::string n2;
617 if (options.is_static()
618 || this->input_argument_->options().do_static_search())
619 n1 += ".a";
620 else
622 n2 = n1 + ".a";
623 n1 += ".so";
625 name = dirpath.find(n1, n2, &this->is_in_sysroot_);
626 if (name.empty())
628 gold_error(_("cannot find -l%s"),
629 this->input_argument_->name());
630 return false;
632 if (n2.empty() || name[name.length() - 1] == 'o')
633 this->found_name_ = n1;
634 else
635 this->found_name_ = n2;
637 // Case 4: extra_search_path is not empty
638 else
640 gold_assert(this->input_argument_->extra_search_path() != NULL);
642 // First, check extra_search_path.
643 name = this->input_argument_->extra_search_path();
644 if (!IS_DIR_SEPARATOR (name[name.length() - 1]))
645 name += '/';
646 name += this->input_argument_->name();
647 struct stat dummy_stat;
648 if (::stat(name.c_str(), &dummy_stat) < 0)
650 // extra_search_path failed, so check the normal search-path.
651 name = dirpath.find(this->input_argument_->name(), "",
652 &this->is_in_sysroot_);
653 if (name.empty())
655 gold_error(_("cannot find %s"),
656 this->input_argument_->name());
657 return false;
660 this->found_name_ = this->input_argument_->name();
663 // Now that we've figured out where the file lives, try to open it.
664 if (!this->file_.open(task, name))
666 gold_error(_("cannot open %s: %s"),
667 name.c_str(), strerror(errno));
668 return false;
671 return true;
674 } // End namespace gold.