fileread.cc 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. // fileread.cc -- read files for gold
  2. // Copyright (C) 2006-2015 Free Software Foundation, Inc.
  3. // Written by Ian Lance Taylor <iant@google.com>.
  4. // This file is part of gold.
  5. // This program is free software; you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License as published by
  7. // the Free Software Foundation; either version 3 of the License, or
  8. // (at your option) any later version.
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
  16. // MA 02110-1301, USA.
  17. #include "gold.h"
  18. #include <cstring>
  19. #include <cerrno>
  20. #include <climits>
  21. #include <fcntl.h>
  22. #include <unistd.h>
  23. #ifdef HAVE_SYS_MMAN_H
  24. #include <sys/mman.h>
  25. #endif
  26. #ifdef HAVE_READV
  27. #include <sys/uio.h>
  28. #endif
  29. #include <sys/stat.h>
  30. #include "filenames.h"
  31. #include "debug.h"
  32. #include "parameters.h"
  33. #include "options.h"
  34. #include "dirsearch.h"
  35. #include "target.h"
  36. #include "binary.h"
  37. #include "descriptors.h"
  38. #include "gold-threads.h"
  39. #include "fileread.h"
  40. // For systems without mmap support.
  41. #ifndef HAVE_MMAP
  42. # define mmap gold_mmap
  43. # define munmap gold_munmap
  44. # ifndef MAP_FAILED
  45. # define MAP_FAILED (reinterpret_cast<void*>(-1))
  46. # endif
  47. # ifndef PROT_READ
  48. # define PROT_READ 0
  49. # endif
  50. # ifndef MAP_PRIVATE
  51. # define MAP_PRIVATE 0
  52. # endif
  53. # ifndef ENOSYS
  54. # define ENOSYS EINVAL
  55. # endif
  56. static void *
  57. gold_mmap(void *, size_t, int, int, int, off_t)
  58. {
  59. errno = ENOSYS;
  60. return MAP_FAILED;
  61. }
  62. static int
  63. gold_munmap(void *, size_t)
  64. {
  65. errno = ENOSYS;
  66. return -1;
  67. }
  68. #endif
  69. #ifndef HAVE_READV
  70. struct iovec { void* iov_base; size_t iov_len; };
  71. ssize_t
  72. readv(int, const iovec*, int)
  73. {
  74. gold_unreachable();
  75. }
  76. #endif
  77. namespace gold
  78. {
  79. // Get the last modified time of an unopened file.
  80. bool
  81. get_mtime(const char* filename, Timespec* mtime)
  82. {
  83. struct stat file_stat;
  84. if (stat(filename, &file_stat) < 0)
  85. return false;
  86. #ifdef HAVE_STAT_ST_MTIM
  87. mtime->seconds = file_stat.st_mtim.tv_sec;
  88. mtime->nanoseconds = file_stat.st_mtim.tv_nsec;
  89. #else
  90. mtime->seconds = file_stat.st_mtime;
  91. mtime->nanoseconds = 0;
  92. #endif
  93. return true;
  94. }
  95. // Class File_read.
  96. // A lock for the File_read static variables.
  97. static Lock* file_counts_lock = NULL;
  98. static Initialize_lock file_counts_initialize_lock(&file_counts_lock);
  99. // The File_read static variables.
  100. unsigned long long File_read::total_mapped_bytes;
  101. unsigned long long File_read::current_mapped_bytes;
  102. unsigned long long File_read::maximum_mapped_bytes;
  103. // Class File_read::View.
  104. File_read::View::~View()
  105. {
  106. gold_assert(!this->is_locked());
  107. switch (this->data_ownership_)
  108. {
  109. case DATA_ALLOCATED_ARRAY:
  110. free(const_cast<unsigned char*>(this->data_));
  111. break;
  112. case DATA_MMAPPED:
  113. if (::munmap(const_cast<unsigned char*>(this->data_), this->size_) != 0)
  114. gold_warning(_("munmap failed: %s"), strerror(errno));
  115. if (!parameters->options_valid() || parameters->options().stats())
  116. {
  117. file_counts_initialize_lock.initialize();
  118. Hold_optional_lock hl(file_counts_lock);
  119. File_read::current_mapped_bytes -= this->size_;
  120. }
  121. break;
  122. case DATA_NOT_OWNED:
  123. break;
  124. default:
  125. gold_unreachable();
  126. }
  127. }
  128. void
  129. File_read::View::lock()
  130. {
  131. ++this->lock_count_;
  132. }
  133. void
  134. File_read::View::unlock()
  135. {
  136. gold_assert(this->lock_count_ > 0);
  137. --this->lock_count_;
  138. }
  139. bool
  140. File_read::View::is_locked()
  141. {
  142. return this->lock_count_ > 0;
  143. }
  144. // Class File_read.
  145. File_read::~File_read()
  146. {
  147. gold_assert(this->token_.is_writable());
  148. if (this->is_descriptor_opened_)
  149. {
  150. release_descriptor(this->descriptor_, true);
  151. this->descriptor_ = -1;
  152. this->is_descriptor_opened_ = false;
  153. }
  154. this->name_.clear();
  155. this->clear_views(CLEAR_VIEWS_ALL);
  156. }
  157. // Open the file.
  158. bool
  159. File_read::open(const Task* task, const std::string& name)
  160. {
  161. gold_assert(this->token_.is_writable()
  162. && this->descriptor_ < 0
  163. && !this->is_descriptor_opened_
  164. && this->name_.empty());
  165. this->name_ = name;
  166. this->descriptor_ = open_descriptor(-1, this->name_.c_str(),
  167. O_RDONLY);
  168. if (this->descriptor_ >= 0)
  169. {
  170. this->is_descriptor_opened_ = true;
  171. struct stat s;
  172. if (::fstat(this->descriptor_, &s) < 0)
  173. gold_error(_("%s: fstat failed: %s"),
  174. this->name_.c_str(), strerror(errno));
  175. this->size_ = s.st_size;
  176. gold_debug(DEBUG_FILES, "Attempt to open %s succeeded",
  177. this->name_.c_str());
  178. this->token_.add_writer(task);
  179. }
  180. return this->descriptor_ >= 0;
  181. }
  182. // Open the file with the contents in memory.
  183. bool
  184. File_read::open(const Task* task, const std::string& name,
  185. const unsigned char* contents, off_t size)
  186. {
  187. gold_assert(this->token_.is_writable()
  188. && this->descriptor_ < 0
  189. && !this->is_descriptor_opened_
  190. && this->name_.empty());
  191. this->name_ = name;
  192. this->whole_file_view_ = new View(0, size, contents, 0, false,
  193. View::DATA_NOT_OWNED);
  194. this->add_view(this->whole_file_view_);
  195. this->size_ = size;
  196. this->token_.add_writer(task);
  197. return true;
  198. }
  199. // Reopen a descriptor if necessary.
  200. void
  201. File_read::reopen_descriptor()
  202. {
  203. if (!this->is_descriptor_opened_)
  204. {
  205. this->descriptor_ = open_descriptor(this->descriptor_,
  206. this->name_.c_str(),
  207. O_RDONLY);
  208. if (this->descriptor_ < 0)
  209. gold_fatal(_("could not reopen file %s"), this->name_.c_str());
  210. this->is_descriptor_opened_ = true;
  211. }
  212. }
  213. // Release the file. This is called when we are done with the file in
  214. // a Task.
  215. void
  216. File_read::release()
  217. {
  218. gold_assert(this->is_locked());
  219. if (!parameters->options_valid() || parameters->options().stats())
  220. {
  221. file_counts_initialize_lock.initialize();
  222. Hold_optional_lock hl(file_counts_lock);
  223. File_read::total_mapped_bytes += this->mapped_bytes_;
  224. File_read::current_mapped_bytes += this->mapped_bytes_;
  225. if (File_read::current_mapped_bytes > File_read::maximum_mapped_bytes)
  226. File_read::maximum_mapped_bytes = File_read::current_mapped_bytes;
  227. }
  228. this->mapped_bytes_ = 0;
  229. // Only clear views if there is only one attached object. Otherwise
  230. // we waste time trying to clear cached archive views. Similarly
  231. // for releasing the descriptor.
  232. if (this->object_count_ <= 1)
  233. {
  234. this->clear_views(CLEAR_VIEWS_NORMAL);
  235. if (this->is_descriptor_opened_)
  236. {
  237. release_descriptor(this->descriptor_, false);
  238. this->is_descriptor_opened_ = false;
  239. }
  240. }
  241. this->released_ = true;
  242. }
  243. // Lock the file.
  244. void
  245. File_read::lock(const Task* task)
  246. {
  247. gold_assert(this->released_);
  248. gold_debug(DEBUG_FILES, "Locking file \"%s\"", this->name_.c_str());
  249. this->token_.add_writer(task);
  250. this->released_ = false;
  251. }
  252. // Unlock the file.
  253. void
  254. File_read::unlock(const Task* task)
  255. {
  256. gold_debug(DEBUG_FILES, "Unlocking file \"%s\"", this->name_.c_str());
  257. this->release();
  258. this->token_.remove_writer(task);
  259. }
  260. // Return whether the file is locked.
  261. bool
  262. File_read::is_locked() const
  263. {
  264. if (!this->token_.is_writable())
  265. return true;
  266. // The file is not locked, so it should have been released.
  267. gold_assert(this->released_);
  268. return false;
  269. }
  270. // See if we have a view which covers the file starting at START for
  271. // SIZE bytes. Return a pointer to the View if found, NULL if not.
  272. // If BYTESHIFT is not -1U, the returned View must have the specified
  273. // byte shift; otherwise, it may have any byte shift. If VSHIFTED is
  274. // not NULL, this sets *VSHIFTED to a view which would have worked if
  275. // not for the requested BYTESHIFT.
  276. inline File_read::View*
  277. File_read::find_view(off_t start, section_size_type size,
  278. unsigned int byteshift, File_read::View** vshifted) const
  279. {
  280. gold_assert(start <= this->size_
  281. && (static_cast<unsigned long long>(size)
  282. <= static_cast<unsigned long long>(this->size_ - start)));
  283. if (vshifted != NULL)
  284. *vshifted = NULL;
  285. // If we have the whole file mmapped, and the alignment is right,
  286. // we can return it.
  287. if (this->whole_file_view_)
  288. if (byteshift == -1U || byteshift == 0)
  289. return this->whole_file_view_;
  290. off_t page = File_read::page_offset(start);
  291. unsigned int bszero = 0;
  292. Views::const_iterator p = this->views_.upper_bound(std::make_pair(page - 1,
  293. bszero));
  294. while (p != this->views_.end() && p->first.first <= page)
  295. {
  296. if (p->second->start() <= start
  297. && (p->second->start() + static_cast<off_t>(p->second->size())
  298. >= start + static_cast<off_t>(size)))
  299. {
  300. if (byteshift == -1U || byteshift == p->second->byteshift())
  301. {
  302. p->second->set_accessed();
  303. return p->second;
  304. }
  305. if (vshifted != NULL && *vshifted == NULL)
  306. *vshifted = p->second;
  307. }
  308. ++p;
  309. }
  310. return NULL;
  311. }
  312. // Read SIZE bytes from the file starting at offset START. Read into
  313. // the buffer at P.
  314. void
  315. File_read::do_read(off_t start, section_size_type size, void* p)
  316. {
  317. ssize_t bytes;
  318. if (this->whole_file_view_ != NULL)
  319. {
  320. bytes = this->size_ - start;
  321. if (static_cast<section_size_type>(bytes) >= size)
  322. {
  323. memcpy(p, this->whole_file_view_->data() + start, size);
  324. return;
  325. }
  326. }
  327. else
  328. {
  329. this->reopen_descriptor();
  330. char *read_ptr = static_cast<char *>(p);
  331. off_t read_pos = start;
  332. size_t to_read = size;
  333. do
  334. {
  335. bytes = ::pread(this->descriptor_, read_ptr, to_read, read_pos);
  336. if (bytes < 0)
  337. gold_fatal(_("%s: pread failed: %s"),
  338. this->filename().c_str(), strerror(errno));
  339. read_pos += bytes;
  340. read_ptr += bytes;
  341. to_read -= bytes;
  342. if (to_read == 0)
  343. return;
  344. }
  345. while (bytes > 0);
  346. bytes = size - to_read;
  347. }
  348. gold_fatal(_("%s: file too short: read only %lld of %lld bytes at %lld"),
  349. this->filename().c_str(),
  350. static_cast<long long>(bytes),
  351. static_cast<long long>(size),
  352. static_cast<long long>(start));
  353. }
  354. // Read data from the file.
  355. void
  356. File_read::read(off_t start, section_size_type size, void* p)
  357. {
  358. const File_read::View* pv = this->find_view(start, size, -1U, NULL);
  359. if (pv != NULL)
  360. {
  361. memcpy(p, pv->data() + (start - pv->start() + pv->byteshift()), size);
  362. return;
  363. }
  364. this->do_read(start, size, p);
  365. }
  366. // Add a new view. There may already be an existing view at this
  367. // offset. If there is, the new view will be larger, and should
  368. // replace the old view.
  369. void
  370. File_read::add_view(File_read::View* v)
  371. {
  372. std::pair<Views::iterator, bool> ins =
  373. this->views_.insert(std::make_pair(std::make_pair(v->start(),
  374. v->byteshift()),
  375. v));
  376. if (ins.second)
  377. return;
  378. // There was an existing view at this offset. It must not be large
  379. // enough. We can't delete it here, since something might be using
  380. // it; we put it on a list to be deleted when the file is unlocked.
  381. File_read::View* vold = ins.first->second;
  382. gold_assert(vold->size() < v->size());
  383. if (vold->should_cache())
  384. {
  385. v->set_cache();
  386. vold->clear_cache();
  387. }
  388. this->saved_views_.push_back(vold);
  389. ins.first->second = v;
  390. }
  391. // Make a new view with a specified byteshift, reading the data from
  392. // the file.
  393. File_read::View*
  394. File_read::make_view(off_t start, section_size_type size,
  395. unsigned int byteshift, bool cache)
  396. {
  397. gold_assert(size > 0);
  398. gold_assert(start <= this->size_
  399. && (static_cast<unsigned long long>(size)
  400. <= static_cast<unsigned long long>(this->size_ - start)));
  401. off_t poff = File_read::page_offset(start);
  402. section_size_type psize = File_read::pages(size + (start - poff));
  403. if (poff + static_cast<off_t>(psize) >= this->size_)
  404. {
  405. psize = this->size_ - poff;
  406. gold_assert(psize >= size);
  407. }
  408. void* p;
  409. View::Data_ownership ownership;
  410. if (byteshift != 0)
  411. {
  412. p = malloc(psize + byteshift);
  413. if (p == NULL)
  414. gold_nomem();
  415. memset(p, 0, byteshift);
  416. this->do_read(poff, psize, static_cast<unsigned char*>(p) + byteshift);
  417. ownership = View::DATA_ALLOCATED_ARRAY;
  418. }
  419. else
  420. {
  421. this->reopen_descriptor();
  422. p = ::mmap(NULL, psize, PROT_READ, MAP_PRIVATE, this->descriptor_, poff);
  423. if (p != MAP_FAILED)
  424. {
  425. ownership = View::DATA_MMAPPED;
  426. this->mapped_bytes_ += psize;
  427. }
  428. else
  429. {
  430. p = malloc(psize);
  431. if (p == NULL)
  432. gold_nomem();
  433. this->do_read(poff, psize, p);
  434. ownership = View::DATA_ALLOCATED_ARRAY;
  435. }
  436. }
  437. const unsigned char* pbytes = static_cast<const unsigned char*>(p);
  438. File_read::View* v = new File_read::View(poff, psize, pbytes, byteshift,
  439. cache, ownership);
  440. this->add_view(v);
  441. return v;
  442. }
  443. // Find a View or make a new one, shifted as required by the file
  444. // offset OFFSET and ALIGNED.
  445. File_read::View*
  446. File_read::find_or_make_view(off_t offset, off_t start,
  447. section_size_type size, bool aligned, bool cache)
  448. {
  449. // Check that start and end of the view are within the file.
  450. if (start > this->size_
  451. || (static_cast<unsigned long long>(size)
  452. > static_cast<unsigned long long>(this->size_ - start)))
  453. gold_fatal(_("%s: attempt to map %lld bytes at offset %lld exceeds "
  454. "size of file; the file may be corrupt"),
  455. this->filename().c_str(),
  456. static_cast<long long>(size),
  457. static_cast<long long>(start));
  458. unsigned int byteshift;
  459. if (offset == 0)
  460. byteshift = 0;
  461. else
  462. {
  463. unsigned int target_size = (!parameters->target_valid()
  464. ? 64
  465. : parameters->target().get_size());
  466. byteshift = offset & ((target_size / 8) - 1);
  467. // Set BYTESHIFT to the number of dummy bytes which must be
  468. // inserted before the data in order for this data to be
  469. // aligned.
  470. if (byteshift != 0)
  471. byteshift = (target_size / 8) - byteshift;
  472. }
  473. // If --map-whole-files is set, make sure we have a
  474. // whole file view. Options may not yet be ready, e.g.,
  475. // when reading a version script. We then default to
  476. // --no-map-whole-files.
  477. if (this->whole_file_view_ == NULL
  478. && parameters->options_valid()
  479. && parameters->options().map_whole_files())
  480. this->whole_file_view_ = this->make_view(0, this->size_, 0, cache);
  481. // Try to find a View with the required BYTESHIFT.
  482. File_read::View* vshifted;
  483. File_read::View* v = this->find_view(offset + start, size,
  484. aligned ? byteshift : -1U,
  485. &vshifted);
  486. if (v != NULL)
  487. {
  488. if (cache)
  489. v->set_cache();
  490. return v;
  491. }
  492. // If VSHIFTED is not NULL, then it has the data we need, but with
  493. // the wrong byteshift.
  494. v = vshifted;
  495. if (v != NULL)
  496. {
  497. gold_assert(aligned);
  498. unsigned char* pbytes;
  499. pbytes = static_cast<unsigned char*>(malloc(v->size() + byteshift));
  500. if (pbytes == NULL)
  501. gold_nomem();
  502. memset(pbytes, 0, byteshift);
  503. memcpy(pbytes + byteshift, v->data() + v->byteshift(), v->size());
  504. File_read::View* shifted_view =
  505. new File_read::View(v->start(), v->size(), pbytes, byteshift,
  506. cache, View::DATA_ALLOCATED_ARRAY);
  507. this->add_view(shifted_view);
  508. return shifted_view;
  509. }
  510. // Make a new view. If we don't need an aligned view, use a
  511. // byteshift of 0, so that we can use mmap.
  512. return this->make_view(offset + start, size,
  513. aligned ? byteshift : 0,
  514. cache);
  515. }
  516. // Get a view into the file.
  517. const unsigned char*
  518. File_read::get_view(off_t offset, off_t start, section_size_type size,
  519. bool aligned, bool cache)
  520. {
  521. File_read::View* pv = this->find_or_make_view(offset, start, size,
  522. aligned, cache);
  523. return pv->data() + (offset + start - pv->start() + pv->byteshift());
  524. }
  525. File_view*
  526. File_read::get_lasting_view(off_t offset, off_t start, section_size_type size,
  527. bool aligned, bool cache)
  528. {
  529. File_read::View* pv = this->find_or_make_view(offset, start, size,
  530. aligned, cache);
  531. pv->lock();
  532. return new File_view(*this, pv,
  533. (pv->data()
  534. + (offset + start - pv->start() + pv->byteshift())));
  535. }
  536. // Use readv to read COUNT entries from RM starting at START. BASE
  537. // must be added to all file offsets in RM.
  538. void
  539. File_read::do_readv(off_t base, const Read_multiple& rm, size_t start,
  540. size_t count)
  541. {
  542. unsigned char discard[File_read::page_size];
  543. iovec iov[File_read::max_readv_entries * 2];
  544. size_t iov_index = 0;
  545. off_t first_offset = rm[start].file_offset;
  546. off_t last_offset = first_offset;
  547. ssize_t want = 0;
  548. for (size_t i = 0; i < count; ++i)
  549. {
  550. const Read_multiple_entry& i_entry(rm[start + i]);
  551. if (i_entry.file_offset > last_offset)
  552. {
  553. size_t skip = i_entry.file_offset - last_offset;
  554. gold_assert(skip <= sizeof discard);
  555. iov[iov_index].iov_base = discard;
  556. iov[iov_index].iov_len = skip;
  557. ++iov_index;
  558. want += skip;
  559. }
  560. iov[iov_index].iov_base = i_entry.buffer;
  561. iov[iov_index].iov_len = i_entry.size;
  562. ++iov_index;
  563. want += i_entry.size;
  564. last_offset = i_entry.file_offset + i_entry.size;
  565. }
  566. this->reopen_descriptor();
  567. gold_assert(iov_index < sizeof iov / sizeof iov[0]);
  568. if (::lseek(this->descriptor_, base + first_offset, SEEK_SET) < 0)
  569. gold_fatal(_("%s: lseek failed: %s"),
  570. this->filename().c_str(), strerror(errno));
  571. ssize_t got = ::readv(this->descriptor_, iov, iov_index);
  572. if (got < 0)
  573. gold_fatal(_("%s: readv failed: %s"),
  574. this->filename().c_str(), strerror(errno));
  575. if (got != want)
  576. gold_fatal(_("%s: file too short: read only %zd of %zd bytes at %lld"),
  577. this->filename().c_str(),
  578. got, want, static_cast<long long>(base + first_offset));
  579. }
  580. // Portable IOV_MAX.
  581. #if !defined(HAVE_READV)
  582. #define GOLD_IOV_MAX 1
  583. #elif defined(IOV_MAX)
  584. #define GOLD_IOV_MAX IOV_MAX
  585. #else
  586. #define GOLD_IOV_MAX (File_read::max_readv_entries * 2)
  587. #endif
  588. // Read several pieces of data from the file.
  589. void
  590. File_read::read_multiple(off_t base, const Read_multiple& rm)
  591. {
  592. static size_t iov_max = GOLD_IOV_MAX;
  593. size_t count = rm.size();
  594. size_t i = 0;
  595. while (i < count)
  596. {
  597. // Find up to MAX_READV_ENTRIES consecutive entries which are
  598. // less than one page apart.
  599. const Read_multiple_entry& i_entry(rm[i]);
  600. off_t i_off = i_entry.file_offset;
  601. off_t end_off = i_off + i_entry.size;
  602. size_t j;
  603. for (j = i + 1; j < count; ++j)
  604. {
  605. if (j - i >= File_read::max_readv_entries || j - i >= iov_max / 2)
  606. break;
  607. const Read_multiple_entry& j_entry(rm[j]);
  608. off_t j_off = j_entry.file_offset;
  609. gold_assert(j_off >= end_off);
  610. off_t j_end_off = j_off + j_entry.size;
  611. if (j_end_off - end_off >= File_read::page_size)
  612. break;
  613. end_off = j_end_off;
  614. }
  615. if (j == i + 1)
  616. this->read(base + i_off, i_entry.size, i_entry.buffer);
  617. else
  618. {
  619. File_read::View* view = this->find_view(base + i_off,
  620. end_off - i_off,
  621. -1U, NULL);
  622. if (view == NULL)
  623. this->do_readv(base, rm, i, j - i);
  624. else
  625. {
  626. const unsigned char* v = (view->data()
  627. + (base + i_off - view->start()
  628. + view->byteshift()));
  629. for (size_t k = i; k < j; ++k)
  630. {
  631. const Read_multiple_entry& k_entry(rm[k]);
  632. gold_assert((convert_to_section_size_type(k_entry.file_offset
  633. - i_off)
  634. + k_entry.size)
  635. <= convert_to_section_size_type(end_off
  636. - i_off));
  637. memcpy(k_entry.buffer,
  638. v + (k_entry.file_offset - i_off),
  639. k_entry.size);
  640. }
  641. }
  642. }
  643. i = j;
  644. }
  645. }
  646. // Mark all views as no longer cached.
  647. void
  648. File_read::clear_view_cache_marks()
  649. {
  650. // Just ignore this if there are multiple objects associated with
  651. // the file. Otherwise we will wind up uncaching and freeing some
  652. // views for other objects.
  653. if (this->object_count_ > 1)
  654. return;
  655. for (Views::iterator p = this->views_.begin();
  656. p != this->views_.end();
  657. ++p)
  658. p->second->clear_cache();
  659. for (Saved_views::iterator p = this->saved_views_.begin();
  660. p != this->saved_views_.end();
  661. ++p)
  662. (*p)->clear_cache();
  663. }
  664. // Remove all the file views. For a file which has multiple
  665. // associated objects (i.e., an archive), we keep accessed views
  666. // around until next time, in the hopes that they will be useful for
  667. // the next object.
  668. void
  669. File_read::clear_views(Clear_views_mode mode)
  670. {
  671. bool keep_files_mapped = (parameters->options_valid()
  672. && parameters->options().keep_files_mapped());
  673. Views::iterator p = this->views_.begin();
  674. while (p != this->views_.end())
  675. {
  676. bool should_delete;
  677. if (p->second->is_locked() || p->second->is_permanent_view())
  678. should_delete = false;
  679. else if (mode == CLEAR_VIEWS_ALL)
  680. should_delete = true;
  681. else if ((p->second->should_cache()
  682. || p->second == this->whole_file_view_)
  683. && keep_files_mapped)
  684. should_delete = false;
  685. else if (this->object_count_ > 1
  686. && p->second->accessed()
  687. && mode != CLEAR_VIEWS_ARCHIVE)
  688. should_delete = false;
  689. else
  690. should_delete = true;
  691. if (should_delete)
  692. {
  693. if (p->second == this->whole_file_view_)
  694. this->whole_file_view_ = NULL;
  695. delete p->second;
  696. // map::erase invalidates only the iterator to the deleted
  697. // element.
  698. Views::iterator pe = p;
  699. ++p;
  700. this->views_.erase(pe);
  701. }
  702. else
  703. {
  704. p->second->clear_accessed();
  705. ++p;
  706. }
  707. }
  708. Saved_views::iterator q = this->saved_views_.begin();
  709. while (q != this->saved_views_.end())
  710. {
  711. if (!(*q)->is_locked())
  712. {
  713. delete *q;
  714. q = this->saved_views_.erase(q);
  715. }
  716. else
  717. {
  718. gold_assert(mode != CLEAR_VIEWS_ALL);
  719. ++q;
  720. }
  721. }
  722. }
  723. // Print statistical information to stderr. This is used for --stats.
  724. void
  725. File_read::print_stats()
  726. {
  727. fprintf(stderr, _("%s: total bytes mapped for read: %llu\n"),
  728. program_name, File_read::total_mapped_bytes);
  729. fprintf(stderr, _("%s: maximum bytes mapped for read at one time: %llu\n"),
  730. program_name, File_read::maximum_mapped_bytes);
  731. }
  732. // Class File_view.
  733. File_view::~File_view()
  734. {
  735. gold_assert(this->file_.is_locked());
  736. this->view_->unlock();
  737. }
  738. // Class Input_file.
  739. // Create a file given just the filename.
  740. Input_file::Input_file(const char* name)
  741. : found_name_(), file_(), is_in_sysroot_(false), format_(FORMAT_NONE)
  742. {
  743. this->input_argument_ =
  744. new Input_file_argument(name, Input_file_argument::INPUT_FILE_TYPE_FILE,
  745. "", false, Position_dependent_options());
  746. }
  747. // Create a file for testing.
  748. Input_file::Input_file(const Task* task, const char* name,
  749. const unsigned char* contents, off_t size)
  750. : file_()
  751. {
  752. this->input_argument_ =
  753. new Input_file_argument(name, Input_file_argument::INPUT_FILE_TYPE_FILE,
  754. "", false, Position_dependent_options());
  755. bool ok = this->file_.open(task, name, contents, size);
  756. gold_assert(ok);
  757. }
  758. // Return the position dependent options in force for this file.
  759. const Position_dependent_options&
  760. Input_file::options() const
  761. {
  762. return this->input_argument_->options();
  763. }
  764. // Return the name given by the user. For -lc this will return "c".
  765. const char*
  766. Input_file::name() const
  767. {
  768. return this->input_argument_->name();
  769. }
  770. // Return whether this file is in a system directory.
  771. bool
  772. Input_file::is_in_system_directory() const
  773. {
  774. if (this->is_in_sysroot())
  775. return true;
  776. return parameters->options().is_in_system_directory(this->filename());
  777. }
  778. // Return whether we are only reading symbols.
  779. bool
  780. Input_file::just_symbols() const
  781. {
  782. return this->input_argument_->just_symbols();
  783. }
  784. // Return whether this is a file that we will search for in the list
  785. // of directories.
  786. bool
  787. Input_file::will_search_for() const
  788. {
  789. return (!IS_ABSOLUTE_PATH(this->input_argument_->name())
  790. && (this->input_argument_->is_lib()
  791. || this->input_argument_->is_searched_file()
  792. || this->input_argument_->extra_search_path() != NULL));
  793. }
  794. // Return the file last modification time. Calls gold_fatal if the stat
  795. // system call failed.
  796. Timespec
  797. File_read::get_mtime()
  798. {
  799. struct stat file_stat;
  800. this->reopen_descriptor();
  801. if (fstat(this->descriptor_, &file_stat) < 0)
  802. gold_fatal(_("%s: stat failed: %s"), this->name_.c_str(),
  803. strerror(errno));
  804. #ifdef HAVE_STAT_ST_MTIM
  805. return Timespec(file_stat.st_mtim.tv_sec, file_stat.st_mtim.tv_nsec);
  806. #else
  807. return Timespec(file_stat.st_mtime, 0);
  808. #endif
  809. }
  810. // Try to find a file in the extra search dirs. Returns true on success.
  811. bool
  812. Input_file::try_extra_search_path(int* pindex,
  813. const Input_file_argument* input_argument,
  814. std::string filename, std::string* found_name,
  815. std::string* namep)
  816. {
  817. if (input_argument->extra_search_path() == NULL)
  818. return false;
  819. std::string name = input_argument->extra_search_path();
  820. if (!IS_DIR_SEPARATOR(name[name.length() - 1]))
  821. name += '/';
  822. name += filename;
  823. struct stat dummy_stat;
  824. if (*pindex > 0 || ::stat(name.c_str(), &dummy_stat) < 0)
  825. return false;
  826. *found_name = filename;
  827. *namep = name;
  828. return true;
  829. }
  830. // Find the actual file.
  831. // If the filename is not absolute, we assume it is in the current
  832. // directory *except* when:
  833. // A) input_argument_->is_lib() is true;
  834. // B) input_argument_->is_searched_file() is true; or
  835. // C) input_argument_->extra_search_path() is not empty.
  836. // In each, we look in extra_search_path + library_path to find
  837. // the file location, rather than the current directory.
  838. bool
  839. Input_file::find_file(const Dirsearch& dirpath, int* pindex,
  840. const Input_file_argument* input_argument,
  841. bool* is_in_sysroot,
  842. std::string* found_name, std::string* namep)
  843. {
  844. std::string name;
  845. // Case 1: name is an absolute file, just try to open it
  846. // Case 2: name is relative but is_lib is false, is_searched_file is false,
  847. // and extra_search_path is empty
  848. if (IS_ABSOLUTE_PATH(input_argument->name())
  849. || (!input_argument->is_lib()
  850. && !input_argument->is_searched_file()
  851. && input_argument->extra_search_path() == NULL))
  852. {
  853. name = input_argument->name();
  854. *found_name = name;
  855. *namep = name;
  856. return true;
  857. }
  858. // Case 3: is_lib is true or is_searched_file is true
  859. else if (input_argument->is_lib()
  860. || input_argument->is_searched_file())
  861. {
  862. std::vector<std::string> names;
  863. names.reserve(2);
  864. if (input_argument->is_lib())
  865. {
  866. std::string prefix = "lib";
  867. prefix += input_argument->name();
  868. if (parameters->options().is_static()
  869. || !input_argument->options().Bdynamic())
  870. names.push_back(prefix + ".a");
  871. else
  872. {
  873. names.push_back(prefix + ".so");
  874. names.push_back(prefix + ".a");
  875. }
  876. }
  877. else
  878. names.push_back(input_argument->name());
  879. for (std::vector<std::string>::const_iterator n = names.begin();
  880. n != names.end();
  881. ++n)
  882. if (Input_file::try_extra_search_path(pindex, input_argument, *n,
  883. found_name, namep))
  884. return true;
  885. // It is not in the extra_search_path.
  886. name = dirpath.find(names, is_in_sysroot, pindex, found_name);
  887. if (name.empty())
  888. {
  889. gold_error(_("cannot find %s%s"),
  890. input_argument->is_lib() ? "-l" : "",
  891. input_argument->name());
  892. return false;
  893. }
  894. *namep = name;
  895. return true;
  896. }
  897. // Case 4: extra_search_path is not empty
  898. else
  899. {
  900. gold_assert(input_argument->extra_search_path() != NULL);
  901. if (try_extra_search_path(pindex, input_argument, input_argument->name(),
  902. found_name, namep))
  903. return true;
  904. // extra_search_path failed, so check the normal search-path.
  905. int index = *pindex;
  906. if (index > 0)
  907. --index;
  908. name = dirpath.find(std::vector<std::string>(1, input_argument->name()),
  909. is_in_sysroot, &index, found_name);
  910. if (name.empty())
  911. {
  912. gold_error(_("cannot find %s"),
  913. input_argument->name());
  914. return false;
  915. }
  916. *namep = name;
  917. *pindex = index + 1;
  918. return true;
  919. }
  920. }
  921. // Open the file.
  922. bool
  923. Input_file::open(const Dirsearch& dirpath, const Task* task, int* pindex)
  924. {
  925. std::string name;
  926. if (!Input_file::find_file(dirpath, pindex, this->input_argument_,
  927. &this->is_in_sysroot_, &this->found_name_, &name))
  928. return false;
  929. // Now that we've figured out where the file lives, try to open it.
  930. General_options::Object_format format =
  931. this->input_argument_->options().format_enum();
  932. bool ok;
  933. if (format == General_options::OBJECT_FORMAT_ELF)
  934. {
  935. ok = this->file_.open(task, name);
  936. this->format_ = FORMAT_ELF;
  937. }
  938. else
  939. {
  940. gold_assert(format == General_options::OBJECT_FORMAT_BINARY);
  941. ok = this->open_binary(task, name);
  942. this->format_ = FORMAT_BINARY;
  943. }
  944. if (!ok)
  945. {
  946. gold_error(_("cannot open %s: %s"),
  947. name.c_str(), strerror(errno));
  948. this->format_ = FORMAT_NONE;
  949. return false;
  950. }
  951. return true;
  952. }
  953. // Open a file for --format binary.
  954. bool
  955. Input_file::open_binary(const Task* task, const std::string& name)
  956. {
  957. // In order to open a binary file, we need machine code, size, and
  958. // endianness. We may not have a valid target at this point, in
  959. // which case we use the default target.
  960. parameters_force_valid_target();
  961. const Target& target(parameters->target());
  962. Binary_to_elf binary_to_elf(target.machine_code(),
  963. target.get_size(),
  964. target.is_big_endian(),
  965. name);
  966. if (!binary_to_elf.convert(task))
  967. return false;
  968. return this->file_.open(task, name, binary_to_elf.converted_data_leak(),
  969. binary_to_elf.converted_size());
  970. }
  971. } // End namespace gold.