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