Keep views on views_ list so that they can be found again.
[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 "filenames.h"
31
32 #include "options.h"
33 #include "dirsearch.h"
34 #include "fileread.h"
35
36 namespace gold
37 {
38
39 // Class File_read::View.
40
41 File_read::View::~View()
42 {
43   gold_assert(!this->is_locked());
44   if (!this->mapped_)
45     delete[] this->data_;
46   else
47     {
48       if (::munmap(const_cast<unsigned char*>(this->data_), this->size_) != 0)
49         gold_warning(_("munmap failed: %s"), strerror(errno));
50
51       File_read::current_mapped_bytes -= this->size_;
52     }
53 }
54
55 void
56 File_read::View::lock()
57 {
58   ++this->lock_count_;
59 }
60
61 void
62 File_read::View::unlock()
63 {
64   gold_assert(this->lock_count_ > 0);
65   --this->lock_count_;
66 }
67
68 bool
69 File_read::View::is_locked()
70 {
71   return this->lock_count_ > 0;
72 }
73
74 // Class File_read.
75
76 // The File_read static variables.
77 unsigned long long File_read::total_mapped_bytes;
78 unsigned long long File_read::current_mapped_bytes;
79 unsigned long long File_read::maximum_mapped_bytes;
80
81 // The File_read class is designed to support file descriptor caching,
82 // but this is not currently implemented.
83
84 File_read::~File_read()
85 {
86   gold_assert(this->lock_count_ == 0);
87   if (this->descriptor_ >= 0)
88     {
89       if (close(this->descriptor_) < 0)
90         gold_warning(_("close of %s failed: %s"),
91                      this->name_.c_str(), strerror(errno));
92       this->descriptor_ = -1;
93     }
94   this->name_.clear();
95   this->clear_views(true);
96 }
97
98 // Open the file.
99
100 bool
101 File_read::open(const std::string& name)
102 {
103   gold_assert(this->lock_count_ == 0
104               && this->descriptor_ < 0
105               && this->name_.empty());
106   this->name_ = name;
107
108   this->descriptor_ = ::open(this->name_.c_str(), O_RDONLY);
109
110   if (this->descriptor_ >= 0)
111     {
112       struct stat s;
113       if (::fstat(this->descriptor_, &s) < 0)
114         gold_error(_("%s: fstat failed: %s"),
115                    this->name_.c_str(), strerror(errno));
116       this->size_ = s.st_size;
117     }
118
119   ++this->lock_count_;
120
121   return this->descriptor_ >= 0;
122 }
123
124 // Open the file for testing purposes.
125
126 bool
127 File_read::open(const std::string& name, const unsigned char* contents,
128                 off_t size)
129 {
130   gold_assert(this->lock_count_ == 0
131               && this->descriptor_ < 0
132               && this->name_.empty());
133   this->name_ = name;
134   this->contents_ = contents;
135   this->size_ = size;
136   ++this->lock_count_;
137   return true;
138 }
139
140 void
141 File_read::lock()
142 {
143   ++this->lock_count_;
144 }
145
146 void
147 File_read::unlock()
148 {
149   gold_assert(this->lock_count_ > 0);
150   --this->lock_count_;
151   if (this->lock_count_ == 0)
152     {
153       File_read::total_mapped_bytes += this->mapped_bytes_;
154       File_read::current_mapped_bytes += this->mapped_bytes_;
155       this->mapped_bytes_ = 0;
156       if (File_read::current_mapped_bytes > File_read::maximum_mapped_bytes)
157         File_read::maximum_mapped_bytes = File_read::current_mapped_bytes;
158
159       this->clear_views(false);
160     }
161 }
162
163 bool
164 File_read::is_locked()
165 {
166   return this->lock_count_ > 0;
167 }
168
169 // See if we have a view which covers the file starting at START for
170 // SIZE bytes.  Return a pointer to the View if found, NULL if not.
171
172 inline File_read::View*
173 File_read::find_view(off_t start, off_t size)
174 {
175   off_t page = File_read::page_offset(start);
176   Views::iterator p = this->views_.find(page);
177   if (p == this->views_.end())
178     return NULL;
179   if (p->second->size() - (start - page) < size)
180     return NULL;
181   return p->second;
182 }
183
184 // Read SIZE bytes from the file starting at offset START.  Read into
185 // the buffer at P.
186
187 void
188 File_read::do_read(off_t start, off_t size, void* p)
189 {
190   gold_assert(this->lock_count_ > 0);
191
192   off_t bytes;
193   if (this->contents_ != NULL)
194     {
195       bytes = this->size_ - start;
196       if (bytes >= size)
197         {
198           memcpy(p, this->contents_ + start, size);
199           return;
200         }
201     }
202   else
203     {
204       bytes = ::pread(this->descriptor_, p, size, start);
205       if (bytes == size)
206         return;
207
208       if (bytes < 0)
209         {
210           gold_fatal(_("%s: pread failed: %s"),
211                      this->filename().c_str(), strerror(errno));
212           return;
213         }
214     }
215
216   gold_fatal(_("%s: file too short: read only %lld of %lld bytes at %lld"),
217              this->filename().c_str(),
218              static_cast<long long>(bytes),
219              static_cast<long long>(size),
220              static_cast<long long>(start));
221 }
222
223 // Read data from the file.
224
225 void
226 File_read::read(off_t start, off_t size, void* p)
227 {
228   gold_assert(this->lock_count_ > 0);
229
230   File_read::View* pv = this->find_view(start, size);
231   if (pv != NULL)
232     {
233       memcpy(p, pv->data() + (start - pv->start()), size);
234       return;
235     }
236
237   this->do_read(start, size, p);
238 }
239
240 // Find an existing view or make a new one.
241
242 File_read::View*
243 File_read::find_or_make_view(off_t start, off_t size, bool cache)
244 {
245   gold_assert(this->lock_count_ > 0);
246
247   off_t poff = File_read::page_offset(start);
248
249   File_read::View* const vnull = NULL;
250   std::pair<Views::iterator, bool> ins =
251     this->views_.insert(std::make_pair(poff, vnull));
252
253   if (!ins.second)
254     {
255       // There was an existing view at this offset.
256       File_read::View* v = ins.first->second;
257       if (v->size() - (start - v->start()) >= size)
258         {
259           if (cache)
260             v->set_cache();
261           return v;
262         }
263
264       // This view is not large enough.
265       this->saved_views_.push_back(v);
266     }
267
268   // We need to read data from the file.  We read full pages for
269   // greater efficiency on small files.
270
271   off_t psize = File_read::pages(size + (start - poff));
272
273   if (poff + psize >= this->size_)
274     {
275       psize = this->size_ - poff;
276       gold_assert(psize >= size);
277     }
278
279   File_read::View* v;
280
281   if (this->contents_ != NULL)
282     {
283       unsigned char* p = new unsigned char[psize];
284       this->do_read(poff, psize, p);
285       v = new File_read::View(poff, psize, p, cache, false);
286     }
287   else
288     {
289       void* p = ::mmap(NULL, psize, PROT_READ, MAP_SHARED,
290                        this->descriptor_, poff);
291       if (p == MAP_FAILED)
292         gold_fatal(_("%s: mmap offset %lld size %lld failed: %s"),
293                    this->filename().c_str(),
294                    static_cast<long long>(poff),
295                    static_cast<long long>(psize),
296                    strerror(errno));
297
298       this->mapped_bytes_ += psize;
299
300       const unsigned char* pbytes = static_cast<const unsigned char*>(p);
301       v = new File_read::View(poff, psize, pbytes, cache, true);
302     }
303
304   ins.first->second = v;
305   return v;
306 }
307
308 // This implementation of get_view just reads into a memory buffer,
309 // which we store on view_list_.  At some point we should support
310 // mmap.
311
312 const unsigned char*
313 File_read::get_view(off_t start, off_t size, bool cache)
314 {
315   gold_assert(this->lock_count_ > 0);
316   File_read::View* pv = this->find_or_make_view(start, size, cache);
317   return pv->data() + (start - pv->start());
318 }
319
320 File_view*
321 File_read::get_lasting_view(off_t start, off_t size, bool cache)
322 {
323   gold_assert(this->lock_count_ > 0);
324   File_read::View* pv = this->find_or_make_view(start, size, cache);
325   pv->lock();
326   return new File_view(*this, pv, pv->data() + (start - pv->start()));
327 }
328
329 // Remove all the file views.
330
331 void
332 File_read::clear_views(bool destroying)
333 {
334   Views::iterator p = this->views_.begin();
335   while (p != this->views_.end())
336     {
337       if (!p->second->is_locked()
338           && (destroying || !p->second->should_cache()))
339         {
340           delete p->second;
341
342           // map::erase invalidates only the iterator to the deleted
343           // element.
344           Views::iterator pe = p;
345           ++p;
346           this->views_.erase(pe);
347         }
348       else
349         {
350           gold_assert(!destroying);
351           ++p;
352         }
353     }
354
355   Saved_views::iterator q = this->saved_views_.begin();
356   while (q != this->saved_views_.end())
357     {
358       if (!(*q)->is_locked()
359           && (destroying || !(*q)->should_cache()))
360         {
361           delete *q;
362           q = this->saved_views_.erase(q);
363         }
364       else
365         {
366           gold_assert(!destroying);
367           ++q;
368         }
369     }
370 }
371
372 // Print statistical information to stderr.  This is used for --stats.
373
374 void
375 File_read::print_stats()
376 {
377   fprintf(stderr, _("%s: total bytes mapped for read: %llu\n"),
378           program_name, File_read::total_mapped_bytes);
379   fprintf(stderr, _("%s: maximum bytes mapped for read at one time: %llu\n"),
380           program_name, File_read::maximum_mapped_bytes);
381 }
382
383 // Class File_view.
384
385 File_view::~File_view()
386 {
387   gold_assert(this->file_.is_locked());
388   this->view_->unlock();
389 }
390
391 // Class Input_file.
392
393 // Create a file for testing.
394
395 Input_file::Input_file(const char* name, const unsigned char* contents,
396                        off_t size)
397   : file_()
398 {
399   this->input_argument_ =
400     new Input_file_argument(name, false, "", Position_dependent_options());
401   bool ok = file_.open(name, contents, size);
402   gold_assert(ok);
403 }
404
405 // Open the file.
406
407 // If the filename is not absolute, we assume it is in the current
408 // directory *except* when:
409 //    A) input_argument_->is_lib() is true; or
410 //    B) input_argument_->extra_search_path() is not empty.
411 // In both cases, we look in extra_search_path + library_path to find
412 // the file location, rather than the current directory.
413
414 bool
415 Input_file::open(const General_options& options, const Dirsearch& dirpath)
416 {
417   std::string name;
418
419   // Case 1: name is an absolute file, just try to open it
420   // Case 2: name is relative but is_lib is false and extra_search_path
421   //         is empty
422   if (IS_ABSOLUTE_PATH (this->input_argument_->name())
423       || (!this->input_argument_->is_lib()
424           && this->input_argument_->extra_search_path() == NULL))
425     {
426       name = this->input_argument_->name();
427       this->found_name_ = name;
428     }
429   // Case 3: is_lib is true
430   else if (this->input_argument_->is_lib())
431     {
432       // We don't yet support extra_search_path with -l.
433       gold_assert(this->input_argument_->extra_search_path() == NULL);
434       std::string n1("lib");
435       n1 += this->input_argument_->name();
436       std::string n2;
437       if (options.is_static()
438           || this->input_argument_->options().do_static_search())
439         n1 += ".a";
440       else
441         {
442           n2 = n1 + ".a";
443           n1 += ".so";
444         }
445       name = dirpath.find(n1, n2, &this->is_in_sysroot_);
446       if (name.empty())
447         {
448           gold_error(_("cannot find -l%s"),
449                      this->input_argument_->name());
450           return false;
451         }
452       if (n2.empty() || name[name.length() - 1] == 'o')
453         this->found_name_ = n1;
454       else
455         this->found_name_ = n2;
456     }
457   // Case 4: extra_search_path is not empty
458   else
459     {
460       gold_assert(this->input_argument_->extra_search_path() != NULL);
461
462       // First, check extra_search_path.
463       name = this->input_argument_->extra_search_path();
464       if (!IS_DIR_SEPARATOR (name[name.length() - 1]))
465         name += '/';
466       name += this->input_argument_->name();
467       struct stat dummy_stat;
468       if (::stat(name.c_str(), &dummy_stat) < 0)
469         {
470           // extra_search_path failed, so check the normal search-path.
471           name = dirpath.find(this->input_argument_->name(), "",
472                               &this->is_in_sysroot_);
473           if (name.empty())
474             {
475               gold_error(_("cannot find %s"),
476                          this->input_argument_->name());
477               return false;
478             }
479         }
480       this->found_name_ = this->input_argument_->name();
481     }
482
483   // Now that we've figured out where the file lives, try to open it.
484   if (!this->file_.open(name))
485     {
486       gold_error(_("cannot open %s: %s"),
487                  name.c_str(), strerror(errno));
488       return false;
489     }
490
491   return true;
492 }
493
494 } // End namespace gold.