fileread.cc 30 KB

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