1 /* ldctor.c -- constructor support routines
2    Copyright (C) 1991-2024 Free Software Foundation, Inc.
3    By Steve Chamberlain <sac@cygnus.com>
4 
5    This file is part of the GNU Binutils.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
20    MA 02110-1301, USA.  */
21 
22 #include "sysdep.h"
23 #include "libiberty.h"
24 #include "bfd.h"
25 #include "bfdlink.h"
26 #include "safe-ctype.h"
27 #include "ctf-api.h"
28 
29 #include "ld.h"
30 #include "ldexp.h"
31 #include "ldlang.h"
32 #include "ldmisc.h"
33 #include <ldgram.h>
34 #include "ldmain.h"
35 #include "ldctor.h"
36 
37 /* The list of statements needed to handle constructors.  These are
38    invoked by the command CONSTRUCTORS in the linker script.  */
39 lang_statement_list_type constructor_list;
40 
41 /* Whether the constructors should be sorted.  Note that this is
42    global for the entire link; we assume that there is only a single
43    CONSTRUCTORS command in the linker script.  */
44 bool constructors_sorted;
45 
46 /* The sets we have seen.  */
47 struct set_info *sets;
48 
49 /* Add an entry to a set.  H is the entry in the linker hash table.
50    RELOC is the relocation to use for an entry in the set.  SECTION
51    and VALUE are the value to add.  This is called during the first
52    phase of the link, when we are still gathering symbols together.
53    We just record the information now.  The ldctor_build_sets
54    function will construct the sets.  */
55 
56 void
ldctor_add_set_entry(struct bfd_link_hash_entry * h,bfd_reloc_code_real_type reloc,const char * name,asection * section,bfd_vma value)57 ldctor_add_set_entry (struct bfd_link_hash_entry *h,
58                           bfd_reloc_code_real_type reloc,
59                           const char *name,
60                           asection *section,
61                           bfd_vma value)
62 {
63   struct set_info *p;
64   struct set_element *e;
65   struct set_element **epp;
66 
67   for (p = sets; p != NULL; p = p->next)
68     if (p->h == h)
69       break;
70 
71   if (p == NULL)
72     {
73       p = (struct set_info *) xmalloc (sizeof (struct set_info));
74       p->next = sets;
75       sets = p;
76       p->h = h;
77       p->reloc = reloc;
78       p->count = 0;
79       p->elements = NULL;
80     }
81   else
82     {
83       if (p->reloc != reloc)
84           {
85             einfo (_("%X%P: different relocs used in set %s\n"),
86                      h->root.string);
87             return;
88           }
89 
90       /* Don't permit a set to be constructed from different object
91            file formats.  The same reloc may have different results.  We
92            actually could sometimes handle this, but the case is
93            unlikely to ever arise.  Sometimes constructor symbols are in
94            unusual sections, such as the absolute section--this appears
95            to be the case in Linux a.out--and in such cases we just
96            assume everything is OK.  */
97       if (p->elements != NULL
98             && section->owner != NULL
99             && p->elements->section->owner != NULL
100             && strcmp (bfd_get_target (section->owner),
101                          bfd_get_target (p->elements->section->owner)) != 0)
102           {
103             einfo (_("%X%P: different object file formats composing set %s\n"),
104                      h->root.string);
105             return;
106           }
107     }
108 
109   e = (struct set_element *) xmalloc (sizeof (struct set_element));
110   e->u.next = NULL;
111   e->name = name;
112   e->section = section;
113   e->value = value;
114 
115   for (epp = &p->elements; *epp != NULL; epp = &(*epp)->u.next)
116     ;
117   *epp = e;
118 
119   ++p->count;
120 }
121 
122 /* Get the priority of a g++ global constructor or destructor from the
123    symbol name.  */
124 
125 static int
ctor_prio(const char * name)126 ctor_prio (const char *name)
127 {
128   /* The name will look something like _GLOBAL_$I$65535$test02__Fv.
129      There might be extra leading underscores, and the $ characters
130      might be something else.  The I might be a D.  */
131 
132   while (*name == '_')
133     ++name;
134 
135   if (!startswith (name, "GLOBAL_"))
136     return -1;
137 
138   name += sizeof "GLOBAL_" - 1;
139 
140   if (name[0] != name[2])
141     return -1;
142   if (name[1] != 'I' && name[1] != 'D')
143     return -1;
144   if (!ISDIGIT (name[3]))
145     return -1;
146 
147   return atoi (name + 3);
148 }
149 
150 /* This function is used to sort constructor elements by priority.  It
151    is called via qsort.  */
152 
153 static int
ctor_cmp(const void * p1,const void * p2)154 ctor_cmp (const void *p1, const void *p2)
155 {
156   const struct set_element *pe1 = *(const struct set_element **) p1;
157   const struct set_element *pe2 = *(const struct set_element **) p2;
158   const char *n1;
159   const char *n2;
160   int prio1;
161   int prio2;
162 
163   n1 = pe1->name;
164   if (n1 == NULL)
165     n1 = "";
166   n2 = pe2->name;
167   if (n2 == NULL)
168     n2 = "";
169 
170   /* We need to sort in reverse order by priority.  When two
171      constructors have the same priority, we should maintain their
172      current relative position.  */
173 
174   prio1 = ctor_prio (n1);
175   prio2 = ctor_prio (n2);
176 
177   /* We sort in reverse order because that is what g++ expects.  */
178   if (prio1 < prio2)
179     return 1;
180   if (prio1 > prio2)
181     return -1;
182 
183   /* Force a stable sort.  */
184   if (pe1->u.idx < pe2->u.idx)
185     return -1;
186   if (pe1->u.idx > pe2->u.idx)
187     return 1;
188   return 0;
189 }
190 
191 /* This function is called after the first phase of the link and
192    before the second phase.  At this point all set information has
193    been gathered.  We now put the statements to build the sets
194    themselves into constructor_list.  */
195 
196 void
ldctor_build_sets(void)197 ldctor_build_sets (void)
198 {
199   static bool called;
200   bool header_printed;
201   struct set_info *p;
202 
203   /* The emulation code may call us directly, but we only want to do
204      this once.  */
205   if (called)
206     return;
207   called = true;
208 
209   if (constructors_sorted)
210     {
211       for (p = sets; p != NULL; p = p->next)
212           {
213             int c, i;
214             struct set_element *e, *enext;
215             struct set_element **array;
216 
217             if (p->elements == NULL)
218               continue;
219 
220             c = 0;
221             for (e = p->elements; e != NULL; e = e->u.next)
222               ++c;
223 
224             array = (struct set_element **) xmalloc (c * sizeof *array);
225 
226             i = 0;
227             for (e = p->elements; e != NULL; e = enext)
228               {
229                 array[i] = e;
230                 enext = e->u.next;
231                 e->u.idx = i;
232                 ++i;
233               }
234 
235             qsort (array, c, sizeof *array, ctor_cmp);
236 
237             e = array[0];
238             p->elements = e;
239             for (i = 0; i < c - 1; i++)
240               array[i]->u.next = array[i + 1];
241             array[i]->u.next = NULL;
242 
243             free (array);
244           }
245     }
246 
247   lang_list_init (&constructor_list);
248   push_stat_ptr (&constructor_list);
249 
250   header_printed = false;
251   for (p = sets; p != NULL; p = p->next)
252     {
253       struct set_element *e;
254       reloc_howto_type *howto;
255       int reloc_size, size;
256 
257       /* If the symbol is defined, we may have been invoked from
258            collect, and the sets may already have been built, so we do
259            not do anything.  */
260       if (p->h->type == bfd_link_hash_defined
261             || p->h->type == bfd_link_hash_defweak)
262           continue;
263 
264       /* For each set we build:
265              set:
266                .long number_of_elements
267                .long element0
268                ...
269                .long elementN
270                .long 0
271            except that we use the right size instead of .long.  When
272            generating relocatable output, we generate relocs instead of
273            addresses.  */
274       howto = bfd_reloc_type_lookup (link_info.output_bfd, p->reloc);
275       if (howto == NULL)
276           {
277             if (bfd_link_relocatable (&link_info))
278               {
279                 einfo (_("%X%P: %s does not support reloc %s for set %s\n"),
280                          bfd_get_target (link_info.output_bfd),
281                          bfd_get_reloc_code_name (p->reloc),
282                          p->h->root.string);
283                 continue;
284               }
285 
286             /* If this is not a relocatable link, all we need is the
287                size, which we can get from the input BFD.  */
288             if (p->elements->section->owner != NULL)
289               howto = bfd_reloc_type_lookup (p->elements->section->owner,
290                                                      p->reloc);
291             if (howto == NULL)
292               {
293                 /* See PR 20911 for a reproducer.  */
294                 if (p->elements->section->owner == NULL)
295                     einfo (_("%X%P: special section %s does not support reloc %s for set %s\n"),
296                            bfd_section_name (p->elements->section),
297                            bfd_get_reloc_code_name (p->reloc),
298                            p->h->root.string);
299                 else
300                     einfo (_("%X%P: %s does not support reloc %s for set %s\n"),
301                            bfd_get_target (p->elements->section->owner),
302                            bfd_get_reloc_code_name (p->reloc),
303                            p->h->root.string);
304                 continue;
305               }
306           }
307 
308       reloc_size = bfd_get_reloc_size (howto);
309       switch (reloc_size)
310           {
311           case 1: size = BYTE; break;
312           case 2: size = SHORT; break;
313           case 4: size = LONG; break;
314           case 8:
315             if (howto->complain_on_overflow == complain_overflow_signed)
316               size = SQUAD;
317             else
318               size = QUAD;
319             break;
320           default:
321             einfo (_("%X%P: unsupported size %d for set %s\n"),
322                      bfd_get_reloc_size (howto), p->h->root.string);
323             size = LONG;
324             break;
325           }
326 
327       lang_add_assignment (exp_assign (".",
328                                                exp_unop (ALIGN_K,
329                                                              exp_intop (reloc_size)),
330                                                false));
331       lang_add_assignment (exp_assign (p->h->root.string,
332                                                exp_nameop (NAME, "."),
333                                                false));
334       lang_add_data (size, exp_intop (p->count));
335 
336       for (e = p->elements; e != NULL; e = e->u.next)
337           {
338             if (config.map_file != NULL)
339               {
340                 int len;
341 
342                 if (!header_printed)
343                     {
344                       minfo (_("\nSet                 Symbol\n\n"));
345                       header_printed = true;
346                     }
347 
348                 minfo ("%s", p->h->root.string);
349                 len = strlen (p->h->root.string);
350 
351                 if (len >= 19)
352                     {
353                       print_nl ();
354                       len = 0;
355                     }
356                 print_spaces (20 - len);
357 
358                 if (e->name != NULL)
359                     minfo ("%pT\n", e->name);
360                 else
361                     minfo ("%G\n", e->section->owner, e->section, e->value);
362               }
363 
364             /* Need SEC_KEEP for --gc-sections.  */
365             if (!bfd_is_abs_section (e->section))
366               e->section->flags |= SEC_KEEP;
367 
368             if (bfd_link_relocatable (&link_info))
369               lang_add_reloc (p->reloc, howto, e->section, e->name,
370                                   exp_intop (e->value));
371             else
372               lang_add_data (size, exp_relop (e->section, e->value));
373           }
374 
375       lang_add_data (size, exp_intop (0));
376     }
377 
378   pop_stat_ptr ();
379 }
380