Don't include options.h in fileread.h. Remove General_options
[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 "options.h"
34 #include "dirsearch.h"
35 #include "fileread.h"
36
37 namespace gold
38 {
39
40 // Class File_read::View.
41
42 File_read::View::~View()
43 {
44   gold_assert(!this->is_locked());
45   if (!this->mapped_)
46     delete[] this->data_;
47   else
48     {
49       if (::munmap(const_cast<unsigned char*>(this->data_), this->size_) != 0)
50         gold_warning(_("munmap failed: %s"), strerror(errno));
51
52       File_read::current_mapped_bytes -= this->size_;
53     }
54 }
55
56 void
57 File_read::View::lock()
58 {
59   ++this->lock_count_;
60 }
61
62 void
63 File_read::View::unlock()
64 {
65   gold_assert(this->lock_count_ > 0);
66   --this->lock_count_;
67 }
68
69 bool
70 File_read::View::is_locked()
71 {
72   return this->lock_count_ > 0;
73 }
74
75 // Class File_read.
76
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;
81
82 // The File_read class is designed to support file descriptor caching,
83 // but this is not currently implemented.
84
85 File_read::~File_read()
86 {
87   gold_assert(this->token_.is_writable());
88   if (this->descriptor_ >= 0)
89     {
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;
94     }
95   this->name_.clear();
96   this->clear_views(true);
97 }
98
99 // Open the file.
100
101 bool
102 File_read::open(const Task* task, const std::string& name)
103 {
104   gold_assert(this->token_.is_writable()
105               && this->descriptor_ < 0
106               && this->name_.empty());
107   this->name_ = name;
108
109   this->descriptor_ = ::open(this->name_.c_str(), O_RDONLY);
110
111   if (this->descriptor_ >= 0)
112     {
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;
118     }
119
120   this->token_.add_writer(task);
121
122   return this->descriptor_ >= 0;
123 }
124
125 // Open the file for testing purposes.
126
127 bool
128 File_read::open(const Task* task, const std::string& name,
129                 const unsigned char* contents, off_t size)
130 {
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;
139 }
140
141 // Release the file.  This is called when we are done with the file in
142 // a Task.
143
144 void
145 File_read::release()
146 {
147   gold_assert(this->is_locked());
148
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;
154
155   this->clear_views(false);
156
157   this->released_ = true;
158 }
159
160 // Lock the file.
161
162 void
163 File_read::lock(const Task* task)
164 {
165   gold_assert(this->released_);
166   this->token_.add_writer(task);
167   this->released_ = false;
168 }
169
170 // Unlock the file.
171
172 void
173 File_read::unlock(const Task* task)
174 {
175   this->release();
176   this->token_.remove_writer(task);
177 }
178
179 // Return whether the file is locked.
180
181 bool
182 File_read::is_locked() const
183 {
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;
189 }
190
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.
193
194 inline File_read::View*
195 File_read::find_view(off_t start, section_size_type size) const
196 {
197   off_t page = File_read::page_offset(start);
198
199   Views::const_iterator p = this->views_.lower_bound(page);
200   if (p == this->views_.end() || p->first > page)
201     {
202       if (p == this->views_.begin())
203         return NULL;
204       --p;
205     }
206
207   if (p->second->start() + static_cast<off_t>(p->second->size())
208       < start + static_cast<off_t>(size))
209     return NULL;
210
211   p->second->set_accessed();
212
213   return p->second;
214 }
215
216 // Read SIZE bytes from the file starting at offset START.  Read into
217 // the buffer at P.
218
219 void
220 File_read::do_read(off_t start, section_size_type size, void* p) const
221 {
222   ssize_t bytes;
223   if (this->contents_ != NULL)
224     {
225       bytes = this->size_ - start;
226       if (static_cast<section_size_type>(bytes) >= size)
227         {
228           memcpy(p, this->contents_ + start, size);
229           return;
230         }
231     }
232   else
233     {
234       bytes = ::pread(this->descriptor_, p, size, start);
235       if (static_cast<section_size_type>(bytes) == size)
236         return;
237
238       if (bytes < 0)
239         {
240           gold_fatal(_("%s: pread failed: %s"),
241                      this->filename().c_str(), strerror(errno));
242           return;
243         }
244     }
245
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));
251 }
252
253 // Read data from the file.
254
255 void
256 File_read::read(off_t start, section_size_type size, void* p) const
257 {
258   const File_read::View* pv = this->find_view(start, size);
259   if (pv != NULL)
260     {
261       memcpy(p, pv->data() + (start - pv->start()), size);
262       return;
263     }
264
265   this->do_read(start, size, p);
266 }
267
268 // Find an existing view or make a new one.
269
270 File_read::View*
271 File_read::find_or_make_view(off_t start, section_size_type size, bool cache)
272 {
273   gold_assert(!this->token_.is_writable());
274   this->released_ = false;
275
276   File_read::View* v = this->find_view(start, size);
277   if (v != NULL)
278     {
279       if (cache)
280         v->set_cache();
281       return v;
282     }
283
284   off_t poff = File_read::page_offset(start);
285
286   File_read::View* const vnull = NULL;
287   std::pair<Views::iterator, bool> ins =
288     this->views_.insert(std::make_pair(poff, vnull));
289
290   if (!ins.second)
291     {
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);
302     }
303
304   // We need to map data from the file.
305
306   section_size_type psize = File_read::pages(size + (start - poff));
307
308   if (poff + static_cast<off_t>(psize) >= this->size_)
309     {
310       psize = this->size_ - poff;
311       gold_assert(psize >= size);
312     }
313
314   if (this->contents_ != NULL)
315     {
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);
319     }
320   else
321     {
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));
330
331       this->mapped_bytes_ += psize;
332
333       const unsigned char* pbytes = static_cast<const unsigned char*>(p);
334       v = new File_read::View(poff, psize, pbytes, cache, true);
335     }
336
337   ins.first->second = v;
338   return v;
339 }
340
341 // Get a view into the file.
342
343 const unsigned char*
344 File_read::get_view(off_t start, section_size_type size, bool cache)
345 {
346   File_read::View* pv = this->find_or_make_view(start, size, cache);
347   return pv->data() + (start - pv->start());
348 }
349
350 File_view*
351 File_read::get_lasting_view(off_t start, section_size_type size, bool cache)
352 {
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()));
356 }
357
358 // Use readv to read COUNT entries from RM starting at START.  BASE
359 // must be added to all file offsets in RM.
360
361 void
362 File_read::do_readv(off_t base, const Read_multiple& rm, size_t start,
363                     size_t count)
364 {
365   unsigned char discard[File_read::page_size];
366   iovec iov[File_read::max_readv_entries * 2];
367   size_t iov_index = 0;
368
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)
373     {
374       const Read_multiple_entry& i_entry(rm[start + i]);
375
376       if (i_entry.file_offset > last_offset)
377         {
378           size_t skip = i_entry.file_offset - last_offset;
379           gold_assert(skip <= sizeof discard);
380
381           iov[iov_index].iov_base = discard;
382           iov[iov_index].iov_len = skip;
383           ++iov_index;
384
385           want += skip;
386         }
387
388       iov[iov_index].iov_base = i_entry.buffer;
389       iov[iov_index].iov_len = i_entry.size;
390       ++iov_index;
391
392       want += i_entry.size;
393
394       last_offset = i_entry.file_offset + i_entry.size;
395     }
396
397   gold_assert(iov_index < sizeof iov / sizeof iov[0]);
398
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));
402
403   ssize_t got = ::readv(this->descriptor_, iov, iov_index);
404
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));
412 }
413
414 // Read several pieces of data from the file.
415
416 void
417 File_read::read_multiple(off_t base, const Read_multiple& rm)
418 {
419   size_t count = rm.size();
420   size_t i = 0;
421   while (i < count)
422     {
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)
430         {
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;
440         }
441
442       if (j == i + 1)
443         this->read(base + i_off, i_entry.size, i_entry.buffer);
444       else
445         {
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
451             {
452               const unsigned char* v = (view->data()
453                                         + (base + i_off - view->start()));
454               for (size_t k = i; k < j; ++k)
455                 {
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);
465                 }
466             }
467         }
468
469       i = j;
470     }
471 }
472
473 // Mark all views as no longer cached.
474
475 void
476 File_read::clear_view_cache_marks()
477 {
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;
483
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();
492 }
493
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.
498
499 void
500 File_read::clear_views(bool destroying)
501 {
502   Views::iterator p = this->views_.begin();
503   while (p != this->views_.end())
504     {
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;
516
517       if (should_delete)
518         {
519           delete p->second;
520
521           // map::erase invalidates only the iterator to the deleted
522           // element.
523           Views::iterator pe = p;
524           ++p;
525           this->views_.erase(pe);
526         }
527       else
528         {
529           gold_assert(!destroying);
530           p->second->clear_accessed();
531           ++p;
532         }
533     }
534
535   Saved_views::iterator q = this->saved_views_.begin();
536   while (q != this->saved_views_.end())
537     {
538       if (!(*q)->is_locked())
539         {
540           delete *q;
541           q = this->saved_views_.erase(q);
542         }
543       else
544         {
545           gold_assert(!destroying);
546           ++q;
547         }
548     }
549 }
550
551 // Print statistical information to stderr.  This is used for --stats.
552
553 void
554 File_read::print_stats()
555 {
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);
560 }
561
562 // Class File_view.
563
564 File_view::~File_view()
565 {
566   gold_assert(this->file_.is_locked());
567   this->view_->unlock();
568 }
569
570 // Class Input_file.
571
572 // Create a file for testing.
573
574 Input_file::Input_file(const Task* task, const char* name,
575                        const unsigned char* contents, off_t size)
576   : file_()
577 {
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);
582 }
583
584 // Return the position dependent options in force for this file.
585
586 const Position_dependent_options&
587 Input_file::options() const
588 {
589   return this->input_argument_->options();
590 }
591
592 // Return the name given by the user.  For -lc this will return "c".
593
594 const char*
595 Input_file::name() const
596 { return this->input_argument_->name(); }
597
598 // Open the file.
599
600 // If the filename is not absolute, we assume it is in the current
601 // directory *except* when:
602 //    A) input_argument_->is_lib() is true; or
603 //    B) input_argument_->extra_search_path() is not empty.
604 // In both cases, we look in extra_search_path + library_path to find
605 // the file location, rather than the current directory.
606
607 bool
608 Input_file::open(const General_options& options, const Dirsearch& dirpath,
609                  const Task* task)
610 {
611   std::string name;
612
613   // Case 1: name is an absolute file, just try to open it
614   // Case 2: name is relative but is_lib is false and extra_search_path
615   //         is empty
616   if (IS_ABSOLUTE_PATH (this->input_argument_->name())
617       || (!this->input_argument_->is_lib()
618           && this->input_argument_->extra_search_path() == NULL))
619     {
620       name = this->input_argument_->name();
621       this->found_name_ = name;
622     }
623   // Case 3: is_lib is true
624   else if (this->input_argument_->is_lib())
625     {
626       // We don't yet support extra_search_path with -l.
627       gold_assert(this->input_argument_->extra_search_path() == NULL);
628       std::string n1("lib");
629       n1 += this->input_argument_->name();
630       std::string n2;
631       if (options.is_static()
632           || this->input_argument_->options().do_static_search())
633         n1 += ".a";
634       else
635         {
636           n2 = n1 + ".a";
637           n1 += ".so";
638         }
639       name = dirpath.find(n1, n2, &this->is_in_sysroot_);
640       if (name.empty())
641         {
642           gold_error(_("cannot find -l%s"),
643                      this->input_argument_->name());
644           return false;
645         }
646       if (n2.empty() || name[name.length() - 1] == 'o')
647         this->found_name_ = n1;
648       else
649         this->found_name_ = n2;
650     }
651   // Case 4: extra_search_path is not empty
652   else
653     {
654       gold_assert(this->input_argument_->extra_search_path() != NULL);
655
656       // First, check extra_search_path.
657       name = this->input_argument_->extra_search_path();
658       if (!IS_DIR_SEPARATOR (name[name.length() - 1]))
659         name += '/';
660       name += this->input_argument_->name();
661       struct stat dummy_stat;
662       if (::stat(name.c_str(), &dummy_stat) < 0)
663         {
664           // extra_search_path failed, so check the normal search-path.
665           name = dirpath.find(this->input_argument_->name(), "",
666                               &this->is_in_sysroot_);
667           if (name.empty())
668             {
669               gold_error(_("cannot find %s"),
670                          this->input_argument_->name());
671               return false;
672             }
673         }
674       this->found_name_ = this->input_argument_->name();
675     }
676
677   // Now that we've figured out where the file lives, try to open it.
678   if (!this->file_.open(task, name))
679     {
680       gold_error(_("cannot open %s: %s"),
681                  name.c_str(), strerror(errno));
682       return false;
683     }
684
685   return true;
686 }
687
688 } // End namespace gold.