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