icf.cc 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  1. // icf.cc -- Identical Code Folding.
  2. //
  3. // Copyright (C) 2009-2022 Free Software Foundation, Inc.
  4. // Written by Sriraman Tallam <tmsriram@google.com>.
  5. // This file is part of gold.
  6. // This program is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU General Public License as published by
  8. // the Free Software Foundation; either version 3 of the License, or
  9. // (at your option) any later version.
  10. // This program is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU General Public License for more details.
  14. // You should have received a copy of the GNU General Public License
  15. // along with this program; if not, write to the Free Software
  16. // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
  17. // MA 02110-1301, USA.
  18. // Identical Code Folding Algorithm
  19. // ----------------------------------
  20. // Detecting identical functions is done here and the basic algorithm
  21. // is as follows. A checksum is computed on each foldable section using
  22. // its contents and relocations. If the symbol name corresponding to
  23. // a relocation is known it is used to compute the checksum. If the
  24. // symbol name is not known the stringified name of the object and the
  25. // section number pointed to by the relocation is used. The checksums
  26. // are stored as keys in a hash map and a section is identical to some
  27. // other section if its checksum is already present in the hash map.
  28. // Checksum collisions are handled by using a multimap and explicitly
  29. // checking the contents when two sections have the same checksum.
  30. //
  31. // However, two functions A and B with identical text but with
  32. // relocations pointing to different foldable sections can be identical if
  33. // the corresponding foldable sections to which their relocations point to
  34. // turn out to be identical. Hence, this checksumming process must be
  35. // done repeatedly until convergence is obtained. Here is an example for
  36. // the following case :
  37. //
  38. // int funcA () int funcB ()
  39. // { {
  40. // return foo(); return goo();
  41. // } }
  42. //
  43. // The functions funcA and funcB are identical if functions foo() and
  44. // goo() are identical.
  45. //
  46. // Hence, as described above, we repeatedly do the checksumming,
  47. // assigning identical functions to the same group, until convergence is
  48. // obtained. Now, we have two different ways to do this depending on how
  49. // we initialize.
  50. //
  51. // Algorithm I :
  52. // -----------
  53. // We can start with marking all functions as different and repeatedly do
  54. // the checksumming. This has the advantage that we do not need to wait
  55. // for convergence. We can stop at any point and correctness will be
  56. // guaranteed although not all cases would have been found. However, this
  57. // has a problem that some cases can never be found even if it is run until
  58. // convergence. Here is an example with mutually recursive functions :
  59. //
  60. // int funcA (int a) int funcB (int a)
  61. // { {
  62. // if (a == 1) if (a == 1)
  63. // return 1; return 1;
  64. // return 1 + funcB(a - 1); return 1 + funcA(a - 1);
  65. // } }
  66. //
  67. // In this example funcA and funcB are identical and one of them could be
  68. // folded into the other. However, if we start with assuming that funcA
  69. // and funcB are not identical, the algorithm, even after it is run to
  70. // convergence, cannot detect that they are identical. It should be noted
  71. // that even if the functions were self-recursive, Algorithm I cannot catch
  72. // that they are identical, at least as is.
  73. //
  74. // Algorithm II :
  75. // ------------
  76. // Here we start with marking all functions as identical and then repeat
  77. // the checksumming until convergence. This can detect the above case
  78. // mentioned above. It can detect all cases that Algorithm I can and more.
  79. // However, the caveat is that it has to be run to convergence. It cannot
  80. // be stopped arbitrarily like Algorithm I as correctness cannot be
  81. // guaranteed. Algorithm II is not implemented.
  82. //
  83. // Algorithm I is used because experiments show that about three
  84. // iterations are more than enough to achieve convergence. Algorithm I can
  85. // handle recursive calls if it is changed to use a special common symbol
  86. // for recursive relocs. This seems to be the most common case that
  87. // Algorithm I could not catch as is. Mutually recursive calls are not
  88. // frequent and Algorithm I wins because of its ability to be stopped
  89. // arbitrarily.
  90. //
  91. // Caveat with using function pointers :
  92. // ------------------------------------
  93. //
  94. // Programs using function pointer comparisons/checks should use function
  95. // folding with caution as the result of such comparisons could be different
  96. // when folding takes place. This could lead to unexpected run-time
  97. // behaviour.
  98. //
  99. // Safe Folding :
  100. // ------------
  101. //
  102. // ICF in safe mode folds only ctors and dtors if their function pointers can
  103. // never be taken. Also, for X86-64, safe folding uses the relocation
  104. // type to determine if a function's pointer is taken or not and only folds
  105. // functions whose pointers are definitely not taken.
  106. //
  107. // Caveat with safe folding :
  108. // ------------------------
  109. //
  110. // This applies only to x86_64.
  111. //
  112. // Position independent executables are created from PIC objects (compiled
  113. // with -fPIC) and/or PIE objects (compiled with -fPIE). For PIE objects, the
  114. // relocation types for function pointer taken and a call are the same.
  115. // Now, it is not always possible to tell if an object used in the link of
  116. // a pie executable is a PIC object or a PIE object. Hence, for pie
  117. // executables, using relocation types to disambiguate function pointers is
  118. // currently disabled.
  119. //
  120. // Further, it is not correct to use safe folding to build non-pie
  121. // executables using PIC/PIE objects. PIC/PIE objects have different
  122. // relocation types for function pointers than non-PIC objects, and the
  123. // current implementation of safe folding does not handle those relocation
  124. // types. Hence, if used, functions whose pointers are taken could still be
  125. // folded causing unpredictable run-time behaviour if the pointers were used
  126. // in comparisons.
  127. //
  128. // Notes regarding C++ exception handling :
  129. // --------------------------------------
  130. //
  131. // It is possible for two sections to have identical text, identical
  132. // relocations, but different exception handling metadata (unwind
  133. // information in the .eh_frame section, and/or handler information in
  134. // a .gcc_except_table section). Thus, if a foldable section is
  135. // referenced from a .eh_frame FDE, we must include in its checksum
  136. // the contents of that FDE as well as of the CIE that the FDE refers
  137. // to. The CIE and FDE in turn probably contain relocations to the
  138. // personality routine and LSDA, which are handled like any other
  139. // relocation for ICF purposes. This logic is helped by the fact that
  140. // gcc with -ffunction-sections puts each function's LSDA in its own
  141. // .gcc_except_table.<functionname> section. Given sections for two
  142. // functions with nontrivial exception handling logic, we will
  143. // determine on the first iteration that their .gcc_except_table
  144. // sections are identical and can be folded, and on the second
  145. // iteration that their .text and .eh_frame contents (including the
  146. // now-merged .gcc_except_table relocations for the LSDA) are
  147. // identical and can be folded.
  148. //
  149. //
  150. // How to run : --icf=[safe|all|none]
  151. // Optional parameters : --icf-iterations <num> --print-icf-sections
  152. //
  153. // Performance : Less than 20 % link-time overhead on industry strength
  154. // applications. Up to 6 % text size reductions.
  155. #include "gold.h"
  156. #include "object.h"
  157. #include "gc.h"
  158. #include "icf.h"
  159. #include "symtab.h"
  160. #include "libiberty.h"
  161. #include "demangle.h"
  162. #include "elfcpp.h"
  163. #include "int_encoding.h"
  164. #include <limits>
  165. namespace gold
  166. {
  167. // This function determines if a section or a group of identical
  168. // sections has unique contents. Such unique sections or groups can be
  169. // declared final and need not be processed any further.
  170. // Parameters :
  171. // ID_SECTION : Vector mapping a section index to a Section_id pair.
  172. // IS_SECN_OR_GROUP_UNIQUE : To check if a section or a group of identical
  173. // sections is already known to be unique.
  174. // SECTION_CONTENTS : Contains the section's text and relocs to sections
  175. // that cannot be folded. SECTION_CONTENTS are NULL
  176. // implies that this function is being called for the
  177. // first time before the first iteration of icf.
  178. static void
  179. preprocess_for_unique_sections(const std::vector<Section_id>& id_section,
  180. std::vector<bool>* is_secn_or_group_unique,
  181. std::vector<std::string>* section_contents)
  182. {
  183. Unordered_map<uint32_t, unsigned int> uniq_map;
  184. std::pair<Unordered_map<uint32_t, unsigned int>::iterator, bool>
  185. uniq_map_insert;
  186. for (unsigned int i = 0; i < id_section.size(); i++)
  187. {
  188. if ((*is_secn_or_group_unique)[i])
  189. continue;
  190. uint32_t cksum;
  191. Section_id secn = id_section[i];
  192. section_size_type plen;
  193. if (section_contents == NULL)
  194. {
  195. // Lock the object so we can read from it. This is only called
  196. // single-threaded from queue_middle_tasks, so it is OK to lock.
  197. // Unfortunately we have no way to pass in a Task token.
  198. const Task* dummy_task = reinterpret_cast<const Task*>(-1);
  199. Task_lock_obj<Object> tl(dummy_task, secn.first);
  200. const unsigned char* contents;
  201. contents = secn.first->section_contents(secn.second,
  202. &plen,
  203. false);
  204. cksum = xcrc32(contents, plen, 0xffffffff);
  205. }
  206. else
  207. {
  208. const unsigned char* contents_array = reinterpret_cast
  209. <const unsigned char*>((*section_contents)[i].c_str());
  210. cksum = xcrc32(contents_array, (*section_contents)[i].length(),
  211. 0xffffffff);
  212. }
  213. uniq_map_insert = uniq_map.insert(std::make_pair(cksum, i));
  214. if (uniq_map_insert.second)
  215. {
  216. (*is_secn_or_group_unique)[i] = true;
  217. }
  218. else
  219. {
  220. (*is_secn_or_group_unique)[i] = false;
  221. (*is_secn_or_group_unique)[uniq_map_insert.first->second] = false;
  222. }
  223. }
  224. }
  225. // For SHF_MERGE sections that use REL relocations, the addend is stored in
  226. // the text section at the relocation offset. Read the addend value given
  227. // the pointer to the addend in the text section and the addend size.
  228. // Update the addend value if a valid addend is found.
  229. // Parameters:
  230. // RELOC_ADDEND_PTR : Pointer to the addend in the text section.
  231. // ADDEND_SIZE : The size of the addend.
  232. // RELOC_ADDEND_VALUE : Pointer to the addend that is updated.
  233. inline void
  234. get_rel_addend(const unsigned char* reloc_addend_ptr,
  235. const unsigned int addend_size,
  236. uint64_t* reloc_addend_value)
  237. {
  238. switch (addend_size)
  239. {
  240. case 0:
  241. break;
  242. case 1:
  243. *reloc_addend_value =
  244. read_from_pointer<8>(reloc_addend_ptr);
  245. break;
  246. case 2:
  247. *reloc_addend_value =
  248. read_from_pointer<16>(reloc_addend_ptr);
  249. break;
  250. case 4:
  251. *reloc_addend_value =
  252. read_from_pointer<32>(reloc_addend_ptr);
  253. break;
  254. case 8:
  255. *reloc_addend_value =
  256. read_from_pointer<64>(reloc_addend_ptr);
  257. break;
  258. default:
  259. gold_unreachable();
  260. }
  261. }
  262. // This returns the buffer containing the section's contents, both
  263. // text and relocs. Relocs are differentiated as those pointing to
  264. // sections that could be folded and those that cannot. Only relocs
  265. // pointing to sections that could be folded are recomputed on
  266. // subsequent invocations of this function.
  267. // Parameters :
  268. // FIRST_ITERATION : true if it is the first invocation.
  269. // FIXED_CACHE : String that stores the portion of the result that
  270. // does not change from iteration to iteration;
  271. // written if first_iteration is true, read if it's false.
  272. // SECN : Section for which contents are desired.
  273. // SELF_SECN : Relocations that target this section will be
  274. // considered "relocations to self" so that recursive
  275. // functions can be folded. Should normally be the
  276. // same as `secn` except when processing extra identity
  277. // regions.
  278. // NUM_TRACKED_RELOCS : Vector reference to store the number of relocs
  279. // to ICF sections.
  280. // KEPT_SECTION_ID : Vector which maps folded sections to kept sections.
  281. // START_OFFSET : Only consider the part of the section at and after
  282. // this offset.
  283. // END_OFFSET : Only consider the part of the section before this
  284. // offset.
  285. static std::string
  286. get_section_contents(bool first_iteration,
  287. std::string* fixed_cache,
  288. const Section_id& secn,
  289. const Section_id& self_secn,
  290. unsigned int* num_tracked_relocs,
  291. Symbol_table* symtab,
  292. const std::vector<unsigned int>& kept_section_id,
  293. section_offset_type start_offset = 0,
  294. section_offset_type end_offset =
  295. std::numeric_limits<section_offset_type>::max())
  296. {
  297. section_size_type plen;
  298. const unsigned char* contents = NULL;
  299. if (first_iteration)
  300. contents = secn.first->section_contents(secn.second, &plen, false);
  301. // The buffer to hold all the contents including relocs. A checksum
  302. // is then computed on this buffer.
  303. std::string buffer;
  304. std::string icf_reloc_buffer;
  305. Icf::Reloc_info_list& reloc_info_list =
  306. symtab->icf()->reloc_info_list();
  307. Icf::Reloc_info_list::iterator it_reloc_info_list =
  308. reloc_info_list.find(secn);
  309. buffer.clear();
  310. icf_reloc_buffer.clear();
  311. // Process relocs and put them into the buffer.
  312. if (it_reloc_info_list != reloc_info_list.end())
  313. {
  314. Icf::Sections_reachable_info &v =
  315. (it_reloc_info_list->second).section_info;
  316. // Stores the information of the symbol pointed to by the reloc.
  317. const Icf::Symbol_info &s = (it_reloc_info_list->second).symbol_info;
  318. // Stores the addend and the symbol value.
  319. Icf::Addend_info &a = (it_reloc_info_list->second).addend_info;
  320. // Stores the offset of the reloc.
  321. const Icf::Offset_info &o = (it_reloc_info_list->second).offset_info;
  322. const Icf::Reloc_addend_size_info &reloc_addend_size_info =
  323. (it_reloc_info_list->second).reloc_addend_size_info;
  324. Icf::Sections_reachable_info::iterator it_v = v.begin();
  325. Icf::Symbol_info::const_iterator it_s = s.begin();
  326. Icf::Addend_info::iterator it_a = a.begin();
  327. Icf::Offset_info::const_iterator it_o = o.begin();
  328. Icf::Reloc_addend_size_info::const_iterator it_addend_size =
  329. reloc_addend_size_info.begin();
  330. for (; it_v != v.end(); ++it_v, ++it_s, ++it_a, ++it_o, ++it_addend_size)
  331. {
  332. Symbol* gsym = *it_s;
  333. bool is_section_symbol = false;
  334. // Ignore relocations outside the region we were told to look at
  335. if (static_cast<section_offset_type>(*it_o) < start_offset
  336. || static_cast<section_offset_type>(*it_o) >= end_offset)
  337. continue;
  338. // A -1 value in the symbol vector indicates a local section symbol.
  339. if (gsym == reinterpret_cast<Symbol*>(-1))
  340. {
  341. is_section_symbol = true;
  342. gsym = NULL;
  343. }
  344. if (first_iteration
  345. && it_v->first != NULL)
  346. {
  347. Symbol_location loc;
  348. loc.object = it_v->first;
  349. loc.shndx = it_v->second;
  350. loc.offset = convert_types<off_t, long long>(it_a->first
  351. + it_a->second);
  352. // Look through function descriptors
  353. parameters->target().function_location(&loc);
  354. if (loc.shndx != it_v->second)
  355. {
  356. it_v->second = loc.shndx;
  357. // Modify symvalue/addend to the code entry.
  358. it_a->first = loc.offset;
  359. it_a->second = 0;
  360. }
  361. }
  362. // ADDEND_STR stores the symbol value and addend and offset,
  363. // each at most 16 hex digits long. it_a points to a pair
  364. // where first is the symbol value and second is the
  365. // addend.
  366. char addend_str[50];
  367. // It would be nice if we could use format macros in inttypes.h
  368. // here but there are not in ISO/IEC C++ 1998.
  369. snprintf(addend_str, sizeof(addend_str), "%llx %llx %llx",
  370. static_cast<long long>((*it_a).first),
  371. static_cast<long long>((*it_a).second),
  372. static_cast<unsigned long long>(*it_o - start_offset));
  373. // If the symbol pointed to by the reloc is not in an ordinary
  374. // section or if the symbol type is not FROM_OBJECT, then the
  375. // object is NULL.
  376. if (it_v->first == NULL)
  377. {
  378. if (first_iteration)
  379. {
  380. // If the symbol name is available, use it.
  381. if (gsym != NULL)
  382. buffer.append(gsym->name());
  383. // Append the addend.
  384. buffer.append(addend_str);
  385. buffer.append("@");
  386. }
  387. continue;
  388. }
  389. Section_id reloc_secn(it_v->first, it_v->second);
  390. // If this reloc turns back and points to the same section,
  391. // like a recursive call, use a special symbol to mark this.
  392. if (reloc_secn.first == self_secn.first
  393. && reloc_secn.second == self_secn.second)
  394. {
  395. if (first_iteration)
  396. {
  397. buffer.append("R");
  398. buffer.append(addend_str);
  399. buffer.append("@");
  400. }
  401. continue;
  402. }
  403. Icf::Uniq_secn_id_map& section_id_map =
  404. symtab->icf()->section_to_int_map();
  405. Icf::Uniq_secn_id_map::iterator section_id_map_it =
  406. section_id_map.find(reloc_secn);
  407. bool is_sym_preemptible = (gsym != NULL
  408. && !gsym->is_from_dynobj()
  409. && !gsym->is_undefined()
  410. && gsym->is_preemptible());
  411. if (!is_sym_preemptible
  412. && section_id_map_it != section_id_map.end())
  413. {
  414. // This is a reloc to a section that might be folded.
  415. if (num_tracked_relocs)
  416. (*num_tracked_relocs)++;
  417. char kept_section_str[10];
  418. unsigned int secn_id = section_id_map_it->second;
  419. snprintf(kept_section_str, sizeof(kept_section_str), "%u",
  420. kept_section_id[secn_id]);
  421. if (first_iteration)
  422. {
  423. buffer.append("ICF_R");
  424. buffer.append(addend_str);
  425. }
  426. icf_reloc_buffer.append(kept_section_str);
  427. // Append the addend.
  428. icf_reloc_buffer.append(addend_str);
  429. icf_reloc_buffer.append("@");
  430. }
  431. else
  432. {
  433. // This is a reloc to a section that cannot be folded.
  434. // Process it only in the first iteration.
  435. if (!first_iteration)
  436. continue;
  437. uint64_t secn_flags = (it_v->first)->section_flags(it_v->second);
  438. // This reloc points to a merge section. Hash the
  439. // contents of this section.
  440. if ((secn_flags & elfcpp::SHF_MERGE) != 0
  441. && parameters->target().can_icf_inline_merge_sections())
  442. {
  443. uint64_t entsize =
  444. (it_v->first)->section_entsize(it_v->second);
  445. long long offset = it_a->first;
  446. // Handle SHT_RELA and SHT_REL addends. Only one of these
  447. // addends exists. When pointing to a merge section, the
  448. // addend only matters if it's relative to a section
  449. // symbol. In order to unambiguously identify the target
  450. // of the relocation, the compiler (and assembler) must use
  451. // a local non-section symbol unless Symbol+Addend does in
  452. // fact point directly to the target. (In other words,
  453. // a bias for a pc-relative reference or a non-zero based
  454. // access forces the use of a local symbol, and the addend
  455. // is used only to provide that bias.)
  456. uint64_t reloc_addend_value = 0;
  457. if (is_section_symbol)
  458. {
  459. // Get the SHT_RELA addend. For RELA relocations,
  460. // we have the addend from the relocation.
  461. reloc_addend_value = it_a->second;
  462. // Handle SHT_REL addends.
  463. // For REL relocations, we need to fetch the addend
  464. // from the section contents.
  465. const unsigned char* reloc_addend_ptr =
  466. contents + static_cast<unsigned long long>(*it_o);
  467. // Update the addend value with the SHT_REL addend if
  468. // available.
  469. get_rel_addend(reloc_addend_ptr, *it_addend_size,
  470. &reloc_addend_value);
  471. // Ignore the addend when it is a negative value.
  472. // See the comments in Merged_symbol_value::value
  473. // in object.h.
  474. if (reloc_addend_value < 0xffffff00)
  475. offset = offset + reloc_addend_value;
  476. }
  477. section_size_type secn_len;
  478. const unsigned char* str_contents =
  479. (it_v->first)->section_contents(it_v->second,
  480. &secn_len,
  481. false) + offset;
  482. gold_assert (offset < (long long) secn_len);
  483. if ((secn_flags & elfcpp::SHF_STRINGS) != 0)
  484. {
  485. // String merge section.
  486. const char* str_char =
  487. reinterpret_cast<const char*>(str_contents);
  488. switch(entsize)
  489. {
  490. case 1:
  491. {
  492. buffer.append(str_char);
  493. break;
  494. }
  495. case 2:
  496. {
  497. const uint16_t* ptr_16 =
  498. reinterpret_cast<const uint16_t*>(str_char);
  499. unsigned int strlen_16 = 0;
  500. // Find the NULL character.
  501. while(*(ptr_16 + strlen_16) != 0)
  502. strlen_16++;
  503. buffer.append(str_char, strlen_16 * 2);
  504. }
  505. break;
  506. case 4:
  507. {
  508. const uint32_t* ptr_32 =
  509. reinterpret_cast<const uint32_t*>(str_char);
  510. unsigned int strlen_32 = 0;
  511. // Find the NULL character.
  512. while(*(ptr_32 + strlen_32) != 0)
  513. strlen_32++;
  514. buffer.append(str_char, strlen_32 * 4);
  515. }
  516. break;
  517. default:
  518. gold_unreachable();
  519. }
  520. }
  521. else
  522. {
  523. // Use the entsize to determine the length to copy.
  524. uint64_t bufsize = entsize;
  525. // If entsize is too big, copy all the remaining bytes.
  526. if ((offset + entsize) > secn_len)
  527. bufsize = secn_len - offset;
  528. buffer.append(reinterpret_cast<const
  529. char*>(str_contents),
  530. bufsize);
  531. }
  532. buffer.append("@");
  533. }
  534. else if (gsym != NULL)
  535. {
  536. // If symbol name is available use that.
  537. buffer.append(gsym->name());
  538. // Append the addend.
  539. buffer.append(addend_str);
  540. buffer.append("@");
  541. }
  542. else
  543. {
  544. // Symbol name is not available, like for a local symbol,
  545. // use object and section id.
  546. buffer.append(it_v->first->name());
  547. char secn_id[10];
  548. snprintf(secn_id, sizeof(secn_id), "%u",it_v->second);
  549. buffer.append(secn_id);
  550. // Append the addend.
  551. buffer.append(addend_str);
  552. buffer.append("@");
  553. }
  554. }
  555. }
  556. }
  557. if (first_iteration)
  558. {
  559. buffer.append("Contents = ");
  560. const unsigned char* slice_end =
  561. contents + std::min<section_offset_type>(plen, end_offset);
  562. if (contents + start_offset < slice_end)
  563. {
  564. buffer.append(reinterpret_cast<const char*>(contents + start_offset),
  565. slice_end - (contents + start_offset));
  566. }
  567. }
  568. // Add any extra identity regions.
  569. std::pair<Icf::Extra_identity_list::const_iterator,
  570. Icf::Extra_identity_list::const_iterator>
  571. extra_range = symtab->icf()->extra_identity_list().equal_range(secn);
  572. for (Icf::Extra_identity_list::const_iterator it_ext = extra_range.first;
  573. it_ext != extra_range.second; ++it_ext)
  574. {
  575. std::string external_fixed;
  576. std::string external_all =
  577. get_section_contents(first_iteration, &external_fixed,
  578. it_ext->second.section, self_secn,
  579. num_tracked_relocs, symtab,
  580. kept_section_id, it_ext->second.offset,
  581. it_ext->second.offset + it_ext->second.length);
  582. buffer.append(external_fixed);
  583. icf_reloc_buffer.append(external_all, external_fixed.length(),
  584. std::string::npos);
  585. }
  586. if (first_iteration)
  587. {
  588. // Store the section contents that don't change to avoid recomputing
  589. // during the next call to this function.
  590. *fixed_cache = buffer;
  591. }
  592. else
  593. {
  594. gold_assert(buffer.empty());
  595. // Reuse the contents computed in the previous iteration.
  596. buffer.append(*fixed_cache);
  597. }
  598. buffer.append(icf_reloc_buffer);
  599. return buffer;
  600. }
  601. // This function computes a checksum on each section to detect and form
  602. // groups of identical sections. The first iteration does this for all
  603. // sections.
  604. // Further iterations do this only for the kept sections from each group to
  605. // determine if larger groups of identical sections could be formed. The
  606. // first section in each group is the kept section for that group.
  607. //
  608. // CRC32 is the checksumming algorithm and can have collisions. That is,
  609. // two sections with different contents can have the same checksum. Hence,
  610. // a multimap is used to maintain more than one group of checksum
  611. // identical sections. A section is added to a group only after its
  612. // contents are explicitly compared with the kept section of the group.
  613. //
  614. // Parameters :
  615. // ITERATION_NUM : Invocation instance of this function.
  616. // NUM_TRACKED_RELOCS : Vector reference to store the number of relocs
  617. // to ICF sections.
  618. // KEPT_SECTION_ID : Vector which maps folded sections to kept sections.
  619. // ID_SECTION : Vector mapping a section to an unique integer.
  620. // IS_SECN_OR_GROUP_UNIQUE : To check if a section or a group of identical
  621. // sections is already known to be unique.
  622. // SECTION_CONTENTS : Store the section's text and relocs to non-ICF
  623. // sections.
  624. static bool
  625. match_sections(unsigned int iteration_num,
  626. Symbol_table* symtab,
  627. std::vector<unsigned int>* num_tracked_relocs,
  628. std::vector<unsigned int>* kept_section_id,
  629. const std::vector<Section_id>& id_section,
  630. const std::vector<uint64_t>& section_addraligns,
  631. std::vector<bool>* is_secn_or_group_unique,
  632. std::vector<std::string>* section_contents)
  633. {
  634. Unordered_multimap<uint32_t, unsigned int> section_cksum;
  635. std::pair<Unordered_multimap<uint32_t, unsigned int>::iterator,
  636. Unordered_multimap<uint32_t, unsigned int>::iterator> key_range;
  637. bool converged = true;
  638. if (iteration_num == 1)
  639. preprocess_for_unique_sections(id_section,
  640. is_secn_or_group_unique,
  641. NULL);
  642. else
  643. preprocess_for_unique_sections(id_section,
  644. is_secn_or_group_unique,
  645. section_contents);
  646. std::vector<std::string> full_section_contents;
  647. for (unsigned int i = 0; i < id_section.size(); i++)
  648. {
  649. full_section_contents.push_back("");
  650. if ((*is_secn_or_group_unique)[i])
  651. continue;
  652. Section_id secn = id_section[i];
  653. // Lock the object so we can read from it. This is only called
  654. // single-threaded from queue_middle_tasks, so it is OK to lock.
  655. // Unfortunately we have no way to pass in a Task token.
  656. const Task* dummy_task = reinterpret_cast<const Task*>(-1);
  657. Task_lock_obj<Object> tl(dummy_task, secn.first);
  658. std::string this_secn_contents;
  659. uint32_t cksum;
  660. std::string* this_secn_cache = &((*section_contents)[i]);
  661. if (iteration_num == 1)
  662. {
  663. unsigned int num_relocs = 0;
  664. this_secn_contents = get_section_contents(true, this_secn_cache,
  665. secn, secn, &num_relocs,
  666. symtab, (*kept_section_id));
  667. (*num_tracked_relocs)[i] = num_relocs;
  668. }
  669. else
  670. {
  671. if ((*kept_section_id)[i] != i)
  672. {
  673. // This section is already folded into something.
  674. continue;
  675. }
  676. this_secn_contents = get_section_contents(false, this_secn_cache,
  677. secn, secn, NULL,
  678. symtab, (*kept_section_id));
  679. }
  680. const unsigned char* this_secn_contents_array =
  681. reinterpret_cast<const unsigned char*>(this_secn_contents.c_str());
  682. cksum = xcrc32(this_secn_contents_array, this_secn_contents.length(),
  683. 0xffffffff);
  684. size_t count = section_cksum.count(cksum);
  685. if (count == 0)
  686. {
  687. // Start a group with this cksum.
  688. section_cksum.insert(std::make_pair(cksum, i));
  689. full_section_contents[i] = this_secn_contents;
  690. }
  691. else
  692. {
  693. key_range = section_cksum.equal_range(cksum);
  694. Unordered_multimap<uint32_t, unsigned int>::iterator it;
  695. // Search all the groups with this cksum for a match.
  696. for (it = key_range.first; it != key_range.second; ++it)
  697. {
  698. unsigned int kept_section = it->second;
  699. if (full_section_contents[kept_section].length()
  700. != this_secn_contents.length())
  701. continue;
  702. if (memcmp(full_section_contents[kept_section].c_str(),
  703. this_secn_contents.c_str(),
  704. this_secn_contents.length()) != 0)
  705. continue;
  706. // Check section alignment here.
  707. // The section with the larger alignment requirement
  708. // should be kept. We assume alignment can only be
  709. // zero or positive integral powers of two.
  710. uint64_t align_i = section_addraligns[i];
  711. uint64_t align_kept = section_addraligns[kept_section];
  712. if (align_i <= align_kept)
  713. {
  714. (*kept_section_id)[i] = kept_section;
  715. }
  716. else
  717. {
  718. (*kept_section_id)[kept_section] = i;
  719. it->second = i;
  720. full_section_contents[kept_section].swap(
  721. full_section_contents[i]);
  722. }
  723. converged = false;
  724. break;
  725. }
  726. if (it == key_range.second)
  727. {
  728. // Create a new group for this cksum.
  729. section_cksum.insert(std::make_pair(cksum, i));
  730. full_section_contents[i] = this_secn_contents;
  731. }
  732. }
  733. // If there are no relocs to foldable sections do not process
  734. // this section any further.
  735. if (iteration_num == 1 && (*num_tracked_relocs)[i] == 0)
  736. (*is_secn_or_group_unique)[i] = true;
  737. }
  738. // If a section was folded into another section that was later folded
  739. // again then the former has to be updated.
  740. for (unsigned int i = 0; i < id_section.size(); i++)
  741. {
  742. // Find the end of the folding chain
  743. unsigned int kept = i;
  744. while ((*kept_section_id)[kept] != kept)
  745. {
  746. kept = (*kept_section_id)[kept];
  747. }
  748. // Update every element of the chain
  749. unsigned int current = i;
  750. while ((*kept_section_id)[current] != kept)
  751. {
  752. unsigned int next = (*kept_section_id)[current];
  753. (*kept_section_id)[current] = kept;
  754. current = next;
  755. }
  756. }
  757. return converged;
  758. }
  759. // During safe icf (--icf=safe), only fold functions that are ctors or dtors.
  760. // This function returns true if the section name is that of a ctor or a dtor.
  761. static bool
  762. is_function_ctor_or_dtor(const std::string& section_name)
  763. {
  764. const char* mangled_func_name = strrchr(section_name.c_str(), '.');
  765. gold_assert(mangled_func_name != NULL);
  766. if ((is_prefix_of("._ZN", mangled_func_name)
  767. || is_prefix_of("._ZZ", mangled_func_name))
  768. && (is_gnu_v3_mangled_ctor(mangled_func_name + 1)
  769. || is_gnu_v3_mangled_dtor(mangled_func_name + 1)))
  770. {
  771. return true;
  772. }
  773. return false;
  774. }
  775. // Iterate through the .eh_frame section that has index
  776. // `ehframe_shndx` in `object`, adding entries to extra_identity_list_
  777. // that will cause the contents of each FDE and its CIE to be included
  778. // in the logical ICF identity of the function that the FDE refers to.
  779. bool
  780. Icf::add_ehframe_links(Relobj* object, unsigned int ehframe_shndx,
  781. Reloc_info& relocs)
  782. {
  783. section_size_type contents_len;
  784. const unsigned char* pcontents = object->section_contents(ehframe_shndx,
  785. &contents_len,
  786. false);
  787. const unsigned char* p = pcontents;
  788. const unsigned char* pend = pcontents + contents_len;
  789. Sections_reachable_info::iterator it_target = relocs.section_info.begin();
  790. Sections_reachable_info::iterator it_target_end = relocs.section_info.end();
  791. Offset_info::iterator it_offset = relocs.offset_info.begin();
  792. Offset_info::iterator it_offset_end = relocs.offset_info.end();
  793. // Maps section offset to the length of the CIE defined at that offset.
  794. typedef Unordered_map<section_offset_type, section_size_type> Cie_map;
  795. Cie_map cies;
  796. uint32_t (*read_swap_32)(const unsigned char*);
  797. if (object->is_big_endian())
  798. read_swap_32 = &elfcpp::Swap<32, true>::readval;
  799. else
  800. read_swap_32 = &elfcpp::Swap<32, false>::readval;
  801. // TODO: The logic for parsing the CIE/FDE framing is copied from
  802. // Eh_frame::do_add_ehframe_input_section() and might want to be
  803. // factored into a shared helper function.
  804. while (p < pend)
  805. {
  806. if (pend - p < 4)
  807. return false;
  808. unsigned int len = read_swap_32(p);
  809. p += 4;
  810. if (len == 0)
  811. {
  812. // We should only find a zero-length entry at the end of the
  813. // section.
  814. if (p < pend)
  815. return false;
  816. break;
  817. }
  818. // We don't support a 64-bit .eh_frame.
  819. if (len == 0xffffffff)
  820. return false;
  821. if (static_cast<unsigned int>(pend - p) < len)
  822. return false;
  823. const unsigned char* const pentend = p + len;
  824. if (pend - p < 4)
  825. return false;
  826. unsigned int id = read_swap_32(p);
  827. p += 4;
  828. if (id == 0)
  829. {
  830. // CIE.
  831. cies.insert(std::make_pair(p - pcontents, len - 4));
  832. }
  833. else
  834. {
  835. // FDE.
  836. Cie_map::const_iterator it;
  837. it = cies.find((p - pcontents) - (id - 4));
  838. if (it == cies.end())
  839. return false;
  840. // Figure out which section this FDE refers into. The word at `p`
  841. // is an address, and we expect to see a relocation there. If not,
  842. // this FDE isn't ICF-relevant.
  843. while (it_offset != it_offset_end
  844. && it_target != it_target_end
  845. && static_cast<ptrdiff_t>(*it_offset) < (p - pcontents))
  846. {
  847. ++it_offset;
  848. ++it_target;
  849. }
  850. if (it_offset != it_offset_end
  851. && it_target != it_target_end
  852. && static_cast<ptrdiff_t>(*it_offset) == (p - pcontents))
  853. {
  854. // Found a reloc. Add this FDE and its CIE as extra identity
  855. // info for the section it refers to.
  856. Extra_identity_info rec_fde = {Section_id(object, ehframe_shndx),
  857. p - pcontents, len - 4};
  858. Extra_identity_info rec_cie = {Section_id(object, ehframe_shndx),
  859. it->first, it->second};
  860. extra_identity_list_.insert(std::make_pair(*it_target, rec_fde));
  861. extra_identity_list_.insert(std::make_pair(*it_target, rec_cie));
  862. }
  863. }
  864. p = pentend;
  865. }
  866. return true;
  867. }
  868. // This is the main ICF function called in gold.cc. This does the
  869. // initialization and calls match_sections repeatedly (thrice by default)
  870. // which computes the crc checksums and detects identical functions.
  871. void
  872. Icf::find_identical_sections(const Input_objects* input_objects,
  873. Symbol_table* symtab)
  874. {
  875. unsigned int section_num = 0;
  876. std::vector<unsigned int> num_tracked_relocs;
  877. std::vector<uint64_t> section_addraligns;
  878. std::vector<bool> is_secn_or_group_unique;
  879. std::vector<std::string> section_contents;
  880. const Target& target = parameters->target();
  881. // Decide which sections are possible candidates first.
  882. for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
  883. p != input_objects->relobj_end();
  884. ++p)
  885. {
  886. // Lock the object so we can read from it. This is only called
  887. // single-threaded from queue_middle_tasks, so it is OK to lock.
  888. // Unfortunately we have no way to pass in a Task token.
  889. const Task* dummy_task = reinterpret_cast<const Task*>(-1);
  890. Task_lock_obj<Object> tl(dummy_task, *p);
  891. std::vector<unsigned int> eh_frame_ind;
  892. for (unsigned int i = 0; i < (*p)->shnum(); ++i)
  893. {
  894. if ((*p)->section_size(i) == 0)
  895. continue;
  896. const std::string section_name = (*p)->section_name(i);
  897. if (!is_section_foldable_candidate(section_name))
  898. {
  899. if (is_prefix_of(".eh_frame", section_name.c_str()))
  900. eh_frame_ind.push_back(i);
  901. continue;
  902. }
  903. if (!(*p)->is_section_included(i))
  904. continue;
  905. if (parameters->options().gc_sections()
  906. && symtab->gc()->is_section_garbage(*p, i))
  907. continue;
  908. // With --icf=safe, check if the mangled function name is a ctor
  909. // or a dtor. The mangled function name can be obtained from the
  910. // section name by stripping the section prefix.
  911. if (parameters->options().icf_safe_folding()
  912. && !is_function_ctor_or_dtor(section_name)
  913. && (!target.can_check_for_function_pointers()
  914. || section_has_function_pointers(*p, i)))
  915. {
  916. continue;
  917. }
  918. this->id_section_.push_back(Section_id(*p, i));
  919. this->section_id_[Section_id(*p, i)] = section_num;
  920. this->kept_section_id_.push_back(section_num);
  921. num_tracked_relocs.push_back(0);
  922. section_addraligns.push_back((*p)->section_addralign(i));
  923. is_secn_or_group_unique.push_back(false);
  924. section_contents.push_back("");
  925. section_num++;
  926. }
  927. for (std::vector<unsigned int>::iterator it_eh_ind = eh_frame_ind.begin();
  928. it_eh_ind != eh_frame_ind.end(); ++it_eh_ind)
  929. {
  930. // gc_process_relocs() recorded relocations for this
  931. // section even though we can't fold it. We need to
  932. // use those relocations to associate other foldable
  933. // sections with the FDEs and CIEs that are relevant
  934. // to them, so we can avoid merging sections that
  935. // don't have identical exception-handling behavior.
  936. Section_id sect(*p, *it_eh_ind);
  937. Reloc_info_list::iterator it_rel = this->reloc_info_list().find(sect);
  938. if (it_rel != this->reloc_info_list().end())
  939. {
  940. if (!add_ehframe_links(*p, *it_eh_ind, it_rel->second))
  941. {
  942. gold_warning(_("could not parse eh_frame section %s(%s); ICF "
  943. "might not preserve exception handling "
  944. "behavior"),
  945. (*p)->name().c_str(),
  946. (*p)->section_name(*it_eh_ind).c_str());
  947. }
  948. }
  949. }
  950. }
  951. unsigned int num_iterations = 0;
  952. // Default number of iterations to run ICF is 3.
  953. unsigned int max_iterations = (parameters->options().icf_iterations() > 0)
  954. ? parameters->options().icf_iterations()
  955. : 3;
  956. bool converged = false;
  957. while (!converged && (num_iterations < max_iterations))
  958. {
  959. num_iterations++;
  960. converged = match_sections(num_iterations, symtab,
  961. &num_tracked_relocs, &this->kept_section_id_,
  962. this->id_section_, section_addraligns,
  963. &is_secn_or_group_unique, &section_contents);
  964. }
  965. if (parameters->options().print_icf_sections())
  966. {
  967. if (converged)
  968. gold_info(_("%s: ICF Converged after %u iteration(s)"),
  969. program_name, num_iterations);
  970. else
  971. gold_info(_("%s: ICF stopped after %u iteration(s)"),
  972. program_name, num_iterations);
  973. }
  974. // Unfold --keep-unique symbols.
  975. for (options::String_set::const_iterator p =
  976. parameters->options().keep_unique_begin();
  977. p != parameters->options().keep_unique_end();
  978. ++p)
  979. {
  980. const char* name = p->c_str();
  981. Symbol* sym = symtab->lookup(name);
  982. if (sym == NULL)
  983. {
  984. gold_warning(_("Could not find symbol %s to unfold\n"), name);
  985. }
  986. else if (sym->source() == Symbol::FROM_OBJECT
  987. && !sym->object()->is_dynamic())
  988. {
  989. Relobj* obj = static_cast<Relobj*>(sym->object());
  990. bool is_ordinary;
  991. unsigned int shndx = sym->shndx(&is_ordinary);
  992. if (is_ordinary)
  993. {
  994. this->unfold_section(obj, shndx);
  995. }
  996. }
  997. }
  998. this->icf_ready();
  999. }
  1000. // Unfolds the section denoted by OBJ and SHNDX if folded.
  1001. void
  1002. Icf::unfold_section(Relobj* obj, unsigned int shndx)
  1003. {
  1004. Section_id secn(obj, shndx);
  1005. Uniq_secn_id_map::iterator it = this->section_id_.find(secn);
  1006. if (it == this->section_id_.end())
  1007. return;
  1008. unsigned int section_num = it->second;
  1009. unsigned int kept_section_id = this->kept_section_id_[section_num];
  1010. if (kept_section_id != section_num)
  1011. this->kept_section_id_[section_num] = section_num;
  1012. }
  1013. // This function determines if the section corresponding to the
  1014. // given object and index is folded based on if the kept section
  1015. // is different from this section.
  1016. bool
  1017. Icf::is_section_folded(Relobj* obj, unsigned int shndx)
  1018. {
  1019. Section_id secn(obj, shndx);
  1020. Uniq_secn_id_map::iterator it = this->section_id_.find(secn);
  1021. if (it == this->section_id_.end())
  1022. return false;
  1023. unsigned int section_num = it->second;
  1024. unsigned int kept_section_id = this->kept_section_id_[section_num];
  1025. return kept_section_id != section_num;
  1026. }
  1027. // This function returns the folded section for the given section.
  1028. Section_id
  1029. Icf::get_folded_section(Relobj* dup_obj, unsigned int dup_shndx)
  1030. {
  1031. Section_id dup_secn(dup_obj, dup_shndx);
  1032. Uniq_secn_id_map::iterator it = this->section_id_.find(dup_secn);
  1033. gold_assert(it != this->section_id_.end());
  1034. unsigned int section_num = it->second;
  1035. unsigned int kept_section_id = this->kept_section_id_[section_num];
  1036. Section_id folded_section = this->id_section_[kept_section_id];
  1037. return folded_section;
  1038. }
  1039. } // End of namespace gold.