From Craig Silverstein: Implement --debug=files to track file opens,
[external/binutils.git] / gold / fileread.cc
1 // fileread.cc -- read files for gold
2
3 // Copyright 2006, 2007 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
5
6 // This file is part of gold.
7
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.
12
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.
17
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.
22
23 #include "gold.h"
24
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"
32
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"
40
41 namespace gold
42 {
43
44 // Class File_read::View.
45
46 File_read::View::~View()
47 {
48   gold_assert(!this->is_locked());
49   if (!this->mapped_)
50     delete[] this->data_;
51   else
52     {
53       if (::munmap(const_cast<unsigned char*>(this->data_), this->size_) != 0)
54         gold_warning(_("munmap failed: %s"), strerror(errno));
55
56       File_read::current_mapped_bytes -= this->size_;
57     }
58 }
59
60 void
61 File_read::View::lock()
62 {
63   ++this->lock_count_;
64 }
65
66 void
67 File_read::View::unlock()
68 {
69   gold_assert(this->lock_count_ > 0);
70   --this->lock_count_;
71 }
72
73 bool
74 File_read::View::is_locked()
75 {
76   return this->lock_count_ > 0;
77 }
78
79 // Class File_read.
80
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;
85
86 // The File_read class is designed to support file descriptor caching,
87 // but this is not currently implemented.
88
89 File_read::~File_read()
90 {
91   gold_assert(this->token_.is_writable());
92   if (this->descriptor_ >= 0)
93     {
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;
98     }
99   this->name_.clear();
100   this->clear_views(true);
101 }
102
103 // Open the file.
104
105 bool
106 File_read::open(const Task* task, const std::string& name)
107 {
108   gold_assert(this->token_.is_writable()
109               && this->descriptor_ < 0
110               && this->name_.empty());
111   this->name_ = name;
112
113   this->descriptor_ = ::open(this->name_.c_str(), O_RDONLY);
114
115   if (this->descriptor_ >= 0)
116     {
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());
124     }
125
126   this->token_.add_writer(task);
127
128   return this->descriptor_ >= 0;
129 }
130
131 // Open the file with the contents in memory.
132
133 bool
134 File_read::open(const Task* task, const std::string& name,
135                 const unsigned char* contents, off_t size)
136 {
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;
145 }
146
147 // Release the file.  This is called when we are done with the file in
148 // a Task.
149
150 void
151 File_read::release()
152 {
153   gold_assert(this->is_locked());
154
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;
160
161   this->clear_views(false);
162
163   this->released_ = true;
164 }
165
166 // Lock the file.
167
168 void
169 File_read::lock(const Task* task)
170 {
171   gold_assert(this->released_);
172   this->token_.add_writer(task);
173   this->released_ = false;
174 }
175
176 // Unlock the file.
177
178 void
179 File_read::unlock(const Task* task)
180 {
181   this->release();
182   this->token_.remove_writer(task);
183 }
184
185 // Return whether the file is locked.
186
187 bool
188 File_read::is_locked() const
189 {
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;
195 }
196
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.
199
200 inline File_read::View*
201 File_read::find_view(off_t start, section_size_type size) const
202 {
203   off_t page = File_read::page_offset(start);
204
205   Views::const_iterator p = this->views_.lower_bound(page);
206   if (p == this->views_.end() || p->first > page)
207     {
208       if (p == this->views_.begin())
209         return NULL;
210       --p;
211     }
212
213   if (p->second->start() + static_cast<off_t>(p->second->size())
214       < start + static_cast<off_t>(size))
215     return NULL;
216
217   p->second->set_accessed();
218
219   return p->second;
220 }
221
222 // Read SIZE bytes from the file starting at offset START.  Read into
223 // the buffer at P.
224
225 void
226 File_read::do_read(off_t start, section_size_type size, void* p) const
227 {
228   ssize_t bytes;
229   if (this->contents_ != NULL)
230     {
231       bytes = this->size_ - start;
232       if (static_cast<section_size_type>(bytes) >= size)
233         {
234           memcpy(p, this->contents_ + start, size);
235           return;
236         }
237     }
238   else
239     {
240       bytes = ::pread(this->descriptor_, p, size, start);
241       if (static_cast<section_size_type>(bytes) == size)
242         return;
243
244       if (bytes < 0)
245         {
246           gold_fatal(_("%s: pread failed: %s"),
247                      this->filename().c_str(), strerror(errno));
248           return;
249         }
250     }
251
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));
257 }
258
259 // Read data from the file.
260
261 void
262 File_read::read(off_t start, section_size_type size, void* p) const
263 {
264   const File_read::View* pv = this->find_view(start, size);
265   if (pv != NULL)
266     {
267       memcpy(p, pv->data() + (start - pv->start()), size);
268       return;
269     }
270
271   this->do_read(start, size, p);
272 }
273
274 // Find an existing view or make a new one.
275
276 File_read::View*
277 File_read::find_or_make_view(off_t start, section_size_type size, bool cache)
278 {
279   gold_assert(!this->token_.is_writable());
280   this->released_ = false;
281
282   File_read::View* v = this->find_view(start, size);
283   if (v != NULL)
284     {
285       if (cache)
286         v->set_cache();
287       return v;
288     }
289
290   off_t poff = File_read::page_offset(start);
291
292   File_read::View* const vnull = NULL;
293   std::pair<Views::iterator, bool> ins =
294     this->views_.insert(std::make_pair(poff, vnull));
295
296   if (!ins.second)
297     {
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);
308     }
309
310   // We need to map data from the file.
311
312   section_size_type psize = File_read::pages(size + (start - poff));
313
314   if (poff + static_cast<off_t>(psize) >= this->size_)
315     {
316       psize = this->size_ - poff;
317       gold_assert(psize >= size);
318     }
319
320   if (this->contents_ != NULL)
321     {
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);
325     }
326   else
327     {
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));
336
337       this->mapped_bytes_ += psize;
338
339       const unsigned char* pbytes = static_cast<const unsigned char*>(p);
340       v = new File_read::View(poff, psize, pbytes, cache, true);
341     }
342
343   ins.first->second = v;
344   return v;
345 }
346
347 // Get a view into the file.
348
349 const unsigned char*
350 File_read::get_view(off_t start, section_size_type size, bool cache)
351 {
352   File_read::View* pv = this->find_or_make_view(start, size, cache);
353   return pv->data() + (start - pv->start());
354 }
355
356 File_view*
357 File_read::get_lasting_view(off_t start, section_size_type size, bool cache)
358 {
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()));
362 }
363
364 // Use readv to read COUNT entries from RM starting at START.  BASE
365 // must be added to all file offsets in RM.
366
367 void
368 File_read::do_readv(off_t base, const Read_multiple& rm, size_t start,
369                     size_t count)
370 {
371   unsigned char discard[File_read::page_size];
372   iovec iov[File_read::max_readv_entries * 2];
373   size_t iov_index = 0;
374
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)
379     {
380       const Read_multiple_entry& i_entry(rm[start + i]);
381
382       if (i_entry.file_offset > last_offset)
383         {
384           size_t skip = i_entry.file_offset - last_offset;
385           gold_assert(skip <= sizeof discard);
386
387           iov[iov_index].iov_base = discard;
388           iov[iov_index].iov_len = skip;
389           ++iov_index;
390
391           want += skip;
392         }
393
394       iov[iov_index].iov_base = i_entry.buffer;
395       iov[iov_index].iov_len = i_entry.size;
396       ++iov_index;
397
398       want += i_entry.size;
399
400       last_offset = i_entry.file_offset + i_entry.size;
401     }
402
403   gold_assert(iov_index < sizeof iov / sizeof iov[0]);
404
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));
408
409   ssize_t got = ::readv(this->descriptor_, iov, iov_index);
410
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));
418 }
419
420 // Read several pieces of data from the file.
421
422 void
423 File_read::read_multiple(off_t base, const Read_multiple& rm)
424 {
425   size_t count = rm.size();
426   size_t i = 0;
427   while (i < count)
428     {
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)
436         {
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;
446         }
447
448       if (j == i + 1)
449         this->read(base + i_off, i_entry.size, i_entry.buffer);
450       else
451         {
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
457             {
458               const unsigned char* v = (view->data()
459                                         + (base + i_off - view->start()));
460               for (size_t k = i; k < j; ++k)
461                 {
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);
471                 }
472             }
473         }
474
475       i = j;
476     }
477 }
478
479 // Mark all views as no longer cached.
480
481 void
482 File_read::clear_view_cache_marks()
483 {
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;
489
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();
498 }
499
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.
504
505 void
506 File_read::clear_views(bool destroying)
507 {
508   Views::iterator p = this->views_.begin();
509   while (p != this->views_.end())
510     {
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;
522
523       if (should_delete)
524         {
525           delete p->second;
526
527           // map::erase invalidates only the iterator to the deleted
528           // element.
529           Views::iterator pe = p;
530           ++p;
531           this->views_.erase(pe);
532         }
533       else
534         {
535           gold_assert(!destroying);
536           p->second->clear_accessed();
537           ++p;
538         }
539     }
540
541   Saved_views::iterator q = this->saved_views_.begin();
542   while (q != this->saved_views_.end())
543     {
544       if (!(*q)->is_locked())
545         {
546           delete *q;
547           q = this->saved_views_.erase(q);
548         }
549       else
550         {
551           gold_assert(!destroying);
552           ++q;
553         }
554     }
555 }
556
557 // Print statistical information to stderr.  This is used for --stats.
558
559 void
560 File_read::print_stats()
561 {
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);
566 }
567
568 // Class File_view.
569
570 File_view::~File_view()
571 {
572   gold_assert(this->file_.is_locked());
573   this->view_->unlock();
574 }
575
576 // Class Input_file.
577
578 // Create a file for testing.
579
580 Input_file::Input_file(const Task* task, const char* name,
581                        const unsigned char* contents, off_t size)
582   : file_()
583 {
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);
589 }
590
591 // Return the position dependent options in force for this file.
592
593 const Position_dependent_options&
594 Input_file::options() const
595 {
596   return this->input_argument_->options();
597 }
598
599 // Return the name given by the user.  For -lc this will return "c".
600
601 const char*
602 Input_file::name() const
603 {
604   return this->input_argument_->name();
605 }
606
607 // Return whether we are only reading symbols.
608
609 bool
610 Input_file::just_symbols() const
611 {
612   return this->input_argument_->just_symbols();
613 }
614
615 // Open the file.
616
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.
623
624 bool
625 Input_file::open(const General_options& options, const Dirsearch& dirpath,
626                  const Task* task)
627 {
628   std::string name;
629
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))
636     {
637       name = this->input_argument_->name();
638       this->found_name_ = name;
639     }
640   // Case 3: is_lib is true
641   else if (this->input_argument_->is_lib())
642     {
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
652         {
653           n2 = n1 + ".a";
654           n1 += ".so";
655         }
656       name = dirpath.find(n1, n2, &this->is_in_sysroot_);
657       if (name.empty())
658         {
659           gold_error(_("cannot find -l%s"),
660                      this->input_argument_->name());
661           return false;
662         }
663       if (n2.empty() || name[name.length() - 1] == 'o')
664         this->found_name_ = n1;
665       else
666         this->found_name_ = n2;
667     }
668   // Case 4: extra_search_path is not empty
669   else
670     {
671       gold_assert(this->input_argument_->extra_search_path() != NULL);
672
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)
680         {
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())
685             {
686               gold_error(_("cannot find %s"),
687                          this->input_argument_->name());
688               return false;
689             }
690         }
691       this->found_name_ = this->input_argument_->name();
692     }
693
694   // Now that we've figured out where the file lives, try to open it.
695
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
702     {
703       gold_assert(format == General_options::OBJECT_FORMAT_BINARY);
704       ok = this->open_binary(options, task, name);
705     }
706
707   if (!ok)
708     {
709       gold_error(_("cannot open %s: %s"),
710                  name.c_str(), strerror(errno));
711       return false;
712     }
713
714   return true;
715 }
716
717 // Open a file for --format binary.
718
719 bool
720 Input_file::open_binary(const General_options&,
721                         const Task* task, const std::string& name)
722 {
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();
731
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());
740 }
741
742 } // End namespace gold.