]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - bfd/peXXigen.c
Update year range in copyright notice of binutils files
[thirdparty/binutils-gdb.git] / bfd / peXXigen.c
1 /* Support for the generic parts of PE/PEI; the common executable parts.
2 Copyright (C) 1995-2024 Free Software Foundation, Inc.
3 Written by Cygnus Solutions.
4
5 This file is part of BFD, the Binary File Descriptor library.
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
23 /* Most of this hacked by Steve Chamberlain <sac@cygnus.com>.
24
25 PE/PEI rearrangement (and code added): Donn Terry
26 Softway Systems, Inc. */
27
28 /* Hey look, some documentation [and in a place you expect to find it]!
29
30 The main reference for the pei format is "Microsoft Portable Executable
31 and Common Object File Format Specification 4.1". Get it if you need to
32 do some serious hacking on this code.
33
34 Another reference:
35 "Peering Inside the PE: A Tour of the Win32 Portable Executable
36 File Format", MSJ 1994, Volume 9.
37
38 The PE/PEI format is also used by .NET. ECMA-335 describes this:
39
40 "Standard ECMA-335 Common Language Infrastructure (CLI)", 6th Edition, June 2012.
41
42 This is also available at
43 https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf.
44
45 The *sole* difference between the pe format and the pei format is that the
46 latter has an MSDOS 2.0 .exe header on the front that prints the message
47 "This app must be run under Windows." (or some such).
48 (FIXME: Whether that statement is *really* true or not is unknown.
49 Are there more subtle differences between pe and pei formats?
50 For now assume there aren't. If you find one, then for God sakes
51 document it here!)
52
53 The Microsoft docs use the word "image" instead of "executable" because
54 the former can also refer to a DLL (shared library). Confusion can arise
55 because the `i' in `pei' also refers to "image". The `pe' format can
56 also create images (i.e. executables), it's just that to run on a win32
57 system you need to use the pei format.
58
59 FIXME: Please add more docs here so the next poor fool that has to hack
60 on this code has a chance of getting something accomplished without
61 wasting too much time. */
62
63 /* This expands into COFF_WITH_pe, COFF_WITH_pep, COFF_WITH_pex64,
64 COFF_WITH_peAArch64 or COFF_WITH_peLoongArch64 or COFF_WITH_peRiscV64
65 depending on whether we're compiling for straight PE or PE+. */
66 #define COFF_WITH_XX
67
68 #include "sysdep.h"
69 #include "bfd.h"
70 #include "libbfd.h"
71 #include "coff/internal.h"
72 #include "bfdver.h"
73 #include "libiberty.h"
74 #include <wchar.h>
75 #include <wctype.h>
76
77 /* NOTE: it's strange to be including an architecture specific header
78 in what's supposed to be general (to PE/PEI) code. However, that's
79 where the definitions are, and they don't vary per architecture
80 within PE/PEI, so we get them from there. FIXME: The lack of
81 variance is an assumption which may prove to be incorrect if new
82 PE/PEI targets are created. */
83 #if defined COFF_WITH_pex64
84 # include "coff/x86_64.h"
85 #elif defined COFF_WITH_pep
86 # include "coff/ia64.h"
87 #elif defined COFF_WITH_peAArch64
88 # include "coff/aarch64.h"
89 #elif defined COFF_WITH_peLoongArch64
90 # include "coff/loongarch64.h"
91 #elif defined COFF_WITH_peRiscV64
92 # include "coff/riscv64.h"
93 #else
94 # include "coff/i386.h"
95 #endif
96
97 #include "coff/pe.h"
98 #include "libcoff.h"
99 #include "libpei.h"
100 #include "safe-ctype.h"
101
102 #if defined COFF_WITH_pep || defined COFF_WITH_pex64 || defined COFF_WITH_peAArch64 || defined COFF_WITH_peLoongArch64 || defined COFF_WITH_peRiscV64
103 # undef AOUTSZ
104 # define AOUTSZ PEPAOUTSZ
105 # define PEAOUTHDR PEPAOUTHDR
106 #endif
107
108 #define HighBitSet(val) ((val) & 0x80000000)
109 #define SetHighBit(val) ((val) | 0x80000000)
110 #define WithoutHighBit(val) ((val) & 0x7fffffff)
111 \f
112 void
113 _bfd_XXi_swap_sym_in (bfd * abfd, void * ext1, void * in1)
114 {
115 SYMENT *ext = (SYMENT *) ext1;
116 struct internal_syment *in = (struct internal_syment *) in1;
117
118 if (ext->e.e_name[0] == 0)
119 {
120 in->_n._n_n._n_zeroes = 0;
121 in->_n._n_n._n_offset = H_GET_32 (abfd, ext->e.e.e_offset);
122 }
123 else
124 memcpy (in->_n._n_name, ext->e.e_name, SYMNMLEN);
125
126 in->n_value = H_GET_32 (abfd, ext->e_value);
127 in->n_scnum = (short) H_GET_16 (abfd, ext->e_scnum);
128
129 if (sizeof (ext->e_type) == 2)
130 in->n_type = H_GET_16 (abfd, ext->e_type);
131 else
132 in->n_type = H_GET_32 (abfd, ext->e_type);
133
134 in->n_sclass = H_GET_8 (abfd, ext->e_sclass);
135 in->n_numaux = H_GET_8 (abfd, ext->e_numaux);
136
137 #ifndef STRICT_PE_FORMAT
138 /* This is for Gnu-created DLLs. */
139
140 /* The section symbols for the .idata$ sections have class 0x68
141 (C_SECTION), which MS documentation indicates is a section
142 symbol. Unfortunately, the value field in the symbol is simply a
143 copy of the .idata section's flags rather than something useful.
144 When these symbols are encountered, change the value to 0 so that
145 they will be handled somewhat correctly in the bfd code. */
146 if (in->n_sclass == C_SECTION)
147 {
148 char namebuf[SYMNMLEN + 1];
149 const char *name = NULL;
150
151 in->n_value = 0x0;
152
153 /* Create synthetic empty sections as needed. DJ */
154 if (in->n_scnum == 0)
155 {
156 asection *sec;
157
158 name = _bfd_coff_internal_syment_name (abfd, in, namebuf);
159 if (name == NULL)
160 {
161 _bfd_error_handler (_("%pB: unable to find name for empty section"),
162 abfd);
163 bfd_set_error (bfd_error_invalid_target);
164 return;
165 }
166
167 sec = bfd_get_section_by_name (abfd, name);
168 if (sec != NULL)
169 in->n_scnum = sec->target_index;
170 }
171
172 if (in->n_scnum == 0)
173 {
174 int unused_section_number = 0;
175 asection *sec;
176 flagword flags;
177 size_t name_len;
178 char *sec_name;
179
180 for (sec = abfd->sections; sec; sec = sec->next)
181 if (unused_section_number <= sec->target_index)
182 unused_section_number = sec->target_index + 1;
183
184 name_len = strlen (name) + 1;
185 sec_name = bfd_alloc (abfd, name_len);
186 if (sec_name == NULL)
187 {
188 _bfd_error_handler (_("%pB: out of memory creating name "
189 "for empty section"), abfd);
190 return;
191 }
192 memcpy (sec_name, name, name_len);
193
194 flags = (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_DATA | SEC_LOAD
195 | SEC_LINKER_CREATED);
196 sec = bfd_make_section_anyway_with_flags (abfd, sec_name, flags);
197 if (sec == NULL)
198 {
199 _bfd_error_handler (_("%pB: unable to create fake empty section"),
200 abfd);
201 return;
202 }
203
204 sec->alignment_power = 2;
205 sec->target_index = unused_section_number;
206
207 in->n_scnum = unused_section_number;
208 }
209 in->n_sclass = C_STAT;
210 }
211 #endif
212 }
213
214 static bool
215 abs_finder (bfd * abfd ATTRIBUTE_UNUSED, asection * sec, void * data)
216 {
217 bfd_vma abs_val = * (bfd_vma *) data;
218
219 return (sec->vma <= abs_val) && ((sec->vma + (1ULL << 32)) > abs_val);
220 }
221
222 unsigned int
223 _bfd_XXi_swap_sym_out (bfd * abfd, void * inp, void * extp)
224 {
225 struct internal_syment *in = (struct internal_syment *) inp;
226 SYMENT *ext = (SYMENT *) extp;
227
228 if (in->_n._n_name[0] == 0)
229 {
230 H_PUT_32 (abfd, 0, ext->e.e.e_zeroes);
231 H_PUT_32 (abfd, in->_n._n_n._n_offset, ext->e.e.e_offset);
232 }
233 else
234 memcpy (ext->e.e_name, in->_n._n_name, SYMNMLEN);
235
236 /* The PE32 and PE32+ formats only use 4 bytes to hold the value of a
237 symbol. This is a problem on 64-bit targets where we can generate
238 absolute symbols with values >= 1^32. We try to work around this
239 problem by finding a section whose base address is sufficient to
240 reduce the absolute value to < 1^32, and then transforming the
241 symbol into a section relative symbol. This of course is a hack. */
242 if (sizeof (in->n_value) > 4
243 /* The strange computation of the shift amount is here in order to
244 avoid a compile time warning about the comparison always being
245 false. It does not matter if this test fails to work as expected
246 as the worst that can happen is that some absolute symbols are
247 needlessly converted into section relative symbols. */
248 && in->n_value > ((1ULL << (sizeof (in->n_value) > 4 ? 32 : 31)) - 1)
249 && in->n_scnum == N_ABS)
250 {
251 asection * sec;
252
253 sec = bfd_sections_find_if (abfd, abs_finder, & in->n_value);
254 if (sec)
255 {
256 in->n_value -= sec->vma;
257 in->n_scnum = sec->target_index;
258 }
259 /* else: FIXME: The value is outside the range of any section. This
260 happens for __image_base__ and __ImageBase and maybe some other
261 symbols as well. We should find a way to handle these values. */
262 }
263
264 H_PUT_32 (abfd, in->n_value, ext->e_value);
265 H_PUT_16 (abfd, in->n_scnum, ext->e_scnum);
266
267 if (sizeof (ext->e_type) == 2)
268 H_PUT_16 (abfd, in->n_type, ext->e_type);
269 else
270 H_PUT_32 (abfd, in->n_type, ext->e_type);
271
272 H_PUT_8 (abfd, in->n_sclass, ext->e_sclass);
273 H_PUT_8 (abfd, in->n_numaux, ext->e_numaux);
274
275 return SYMESZ;
276 }
277
278 void
279 _bfd_XXi_swap_aux_in (bfd * abfd,
280 void * ext1,
281 int type,
282 int in_class,
283 int indx ATTRIBUTE_UNUSED,
284 int numaux ATTRIBUTE_UNUSED,
285 void * in1)
286 {
287 AUXENT *ext = (AUXENT *) ext1;
288 union internal_auxent *in = (union internal_auxent *) in1;
289
290 /* PR 17521: Make sure that all fields in the aux structure
291 are initialised. */
292 memset (in, 0, sizeof * in);
293 switch (in_class)
294 {
295 case C_FILE:
296 if (ext->x_file.x_fname[0] == 0)
297 {
298 in->x_file.x_n.x_n.x_zeroes = 0;
299 in->x_file.x_n.x_n.x_offset = H_GET_32 (abfd, ext->x_file.x_n.x_offset);
300 }
301 else
302 memcpy (in->x_file.x_n.x_fname, ext->x_file.x_fname, FILNMLEN);
303 return;
304
305 case C_STAT:
306 case C_LEAFSTAT:
307 case C_HIDDEN:
308 if (type == T_NULL)
309 {
310 in->x_scn.x_scnlen = GET_SCN_SCNLEN (abfd, ext);
311 in->x_scn.x_nreloc = GET_SCN_NRELOC (abfd, ext);
312 in->x_scn.x_nlinno = GET_SCN_NLINNO (abfd, ext);
313 in->x_scn.x_checksum = H_GET_32 (abfd, ext->x_scn.x_checksum);
314 in->x_scn.x_associated = H_GET_16 (abfd, ext->x_scn.x_associated);
315 in->x_scn.x_comdat = H_GET_8 (abfd, ext->x_scn.x_comdat);
316 return;
317 }
318 break;
319 }
320
321 in->x_sym.x_tagndx.u32 = H_GET_32 (abfd, ext->x_sym.x_tagndx);
322 in->x_sym.x_tvndx = H_GET_16 (abfd, ext->x_sym.x_tvndx);
323
324 if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
325 || ISTAG (in_class))
326 {
327 in->x_sym.x_fcnary.x_fcn.x_lnnoptr = GET_FCN_LNNOPTR (abfd, ext);
328 in->x_sym.x_fcnary.x_fcn.x_endndx.u32 = GET_FCN_ENDNDX (abfd, ext);
329 }
330 else
331 {
332 in->x_sym.x_fcnary.x_ary.x_dimen[0] =
333 H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
334 in->x_sym.x_fcnary.x_ary.x_dimen[1] =
335 H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
336 in->x_sym.x_fcnary.x_ary.x_dimen[2] =
337 H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
338 in->x_sym.x_fcnary.x_ary.x_dimen[3] =
339 H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
340 }
341
342 if (ISFCN (type))
343 {
344 in->x_sym.x_misc.x_fsize = H_GET_32 (abfd, ext->x_sym.x_misc.x_fsize);
345 }
346 else
347 {
348 in->x_sym.x_misc.x_lnsz.x_lnno = GET_LNSZ_LNNO (abfd, ext);
349 in->x_sym.x_misc.x_lnsz.x_size = GET_LNSZ_SIZE (abfd, ext);
350 }
351 }
352
353 unsigned int
354 _bfd_XXi_swap_aux_out (bfd * abfd,
355 void * inp,
356 int type,
357 int in_class,
358 int indx ATTRIBUTE_UNUSED,
359 int numaux ATTRIBUTE_UNUSED,
360 void * extp)
361 {
362 union internal_auxent *in = (union internal_auxent *) inp;
363 AUXENT *ext = (AUXENT *) extp;
364
365 memset (ext, 0, AUXESZ);
366
367 switch (in_class)
368 {
369 case C_FILE:
370 if (in->x_file.x_n.x_fname[0] == 0)
371 {
372 H_PUT_32 (abfd, 0, ext->x_file.x_n.x_zeroes);
373 H_PUT_32 (abfd, in->x_file.x_n.x_n.x_offset, ext->x_file.x_n.x_offset);
374 }
375 else
376 memcpy (ext->x_file.x_fname, in->x_file.x_n.x_fname, sizeof (ext->x_file.x_fname));
377
378 return AUXESZ;
379
380 case C_STAT:
381 case C_LEAFSTAT:
382 case C_HIDDEN:
383 if (type == T_NULL)
384 {
385 PUT_SCN_SCNLEN (abfd, in->x_scn.x_scnlen, ext);
386 PUT_SCN_NRELOC (abfd, in->x_scn.x_nreloc, ext);
387 PUT_SCN_NLINNO (abfd, in->x_scn.x_nlinno, ext);
388 H_PUT_32 (abfd, in->x_scn.x_checksum, ext->x_scn.x_checksum);
389 H_PUT_16 (abfd, in->x_scn.x_associated, ext->x_scn.x_associated);
390 H_PUT_8 (abfd, in->x_scn.x_comdat, ext->x_scn.x_comdat);
391 return AUXESZ;
392 }
393 break;
394 }
395
396 H_PUT_32 (abfd, in->x_sym.x_tagndx.u32, ext->x_sym.x_tagndx);
397 H_PUT_16 (abfd, in->x_sym.x_tvndx, ext->x_sym.x_tvndx);
398
399 if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
400 || ISTAG (in_class))
401 {
402 PUT_FCN_LNNOPTR (abfd, in->x_sym.x_fcnary.x_fcn.x_lnnoptr, ext);
403 PUT_FCN_ENDNDX (abfd, in->x_sym.x_fcnary.x_fcn.x_endndx.u32, ext);
404 }
405 else
406 {
407 H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[0],
408 ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
409 H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[1],
410 ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
411 H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[2],
412 ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
413 H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[3],
414 ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
415 }
416
417 if (ISFCN (type))
418 H_PUT_32 (abfd, in->x_sym.x_misc.x_fsize, ext->x_sym.x_misc.x_fsize);
419 else
420 {
421 PUT_LNSZ_LNNO (abfd, in->x_sym.x_misc.x_lnsz.x_lnno, ext);
422 PUT_LNSZ_SIZE (abfd, in->x_sym.x_misc.x_lnsz.x_size, ext);
423 }
424
425 return AUXESZ;
426 }
427
428 void
429 _bfd_XXi_swap_lineno_in (bfd * abfd, void * ext1, void * in1)
430 {
431 LINENO *ext = (LINENO *) ext1;
432 struct internal_lineno *in = (struct internal_lineno *) in1;
433
434 in->l_addr.l_symndx = H_GET_32 (abfd, ext->l_addr.l_symndx);
435 in->l_lnno = GET_LINENO_LNNO (abfd, ext);
436 }
437
438 unsigned int
439 _bfd_XXi_swap_lineno_out (bfd * abfd, void * inp, void * outp)
440 {
441 struct internal_lineno *in = (struct internal_lineno *) inp;
442 struct external_lineno *ext = (struct external_lineno *) outp;
443 H_PUT_32 (abfd, in->l_addr.l_symndx, ext->l_addr.l_symndx);
444
445 PUT_LINENO_LNNO (abfd, in->l_lnno, ext);
446 return LINESZ;
447 }
448
449 void
450 _bfd_XXi_swap_aouthdr_in (bfd * abfd,
451 void * aouthdr_ext1,
452 void * aouthdr_int1)
453 {
454 PEAOUTHDR * src = (PEAOUTHDR *) aouthdr_ext1;
455 AOUTHDR * aouthdr_ext = (AOUTHDR *) aouthdr_ext1;
456 struct internal_aouthdr *aouthdr_int
457 = (struct internal_aouthdr *) aouthdr_int1;
458 struct internal_extra_pe_aouthdr *a = &aouthdr_int->pe;
459
460 aouthdr_int->magic = H_GET_16 (abfd, aouthdr_ext->magic);
461 aouthdr_int->vstamp = H_GET_16 (abfd, aouthdr_ext->vstamp);
462 aouthdr_int->tsize = GET_AOUTHDR_TSIZE (abfd, aouthdr_ext->tsize);
463 aouthdr_int->dsize = GET_AOUTHDR_DSIZE (abfd, aouthdr_ext->dsize);
464 aouthdr_int->bsize = GET_AOUTHDR_BSIZE (abfd, aouthdr_ext->bsize);
465 aouthdr_int->entry = GET_AOUTHDR_ENTRY (abfd, aouthdr_ext->entry);
466 aouthdr_int->text_start =
467 GET_AOUTHDR_TEXT_START (abfd, aouthdr_ext->text_start);
468
469 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
470 /* PE32+ does not have data_start member! */
471 aouthdr_int->data_start =
472 GET_AOUTHDR_DATA_START (abfd, aouthdr_ext->data_start);
473 a->BaseOfData = aouthdr_int->data_start;
474 #endif
475
476 a->Magic = aouthdr_int->magic;
477 a->MajorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp);
478 a->MinorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp + 1);
479 a->SizeOfCode = aouthdr_int->tsize ;
480 a->SizeOfInitializedData = aouthdr_int->dsize ;
481 a->SizeOfUninitializedData = aouthdr_int->bsize ;
482 a->AddressOfEntryPoint = aouthdr_int->entry;
483 a->BaseOfCode = aouthdr_int->text_start;
484 a->ImageBase = GET_OPTHDR_IMAGE_BASE (abfd, src->ImageBase);
485 a->SectionAlignment = H_GET_32 (abfd, src->SectionAlignment);
486 a->FileAlignment = H_GET_32 (abfd, src->FileAlignment);
487 a->MajorOperatingSystemVersion =
488 H_GET_16 (abfd, src->MajorOperatingSystemVersion);
489 a->MinorOperatingSystemVersion =
490 H_GET_16 (abfd, src->MinorOperatingSystemVersion);
491 a->MajorImageVersion = H_GET_16 (abfd, src->MajorImageVersion);
492 a->MinorImageVersion = H_GET_16 (abfd, src->MinorImageVersion);
493 a->MajorSubsystemVersion = H_GET_16 (abfd, src->MajorSubsystemVersion);
494 a->MinorSubsystemVersion = H_GET_16 (abfd, src->MinorSubsystemVersion);
495 a->Reserved1 = H_GET_32 (abfd, src->Reserved1);
496 a->SizeOfImage = H_GET_32 (abfd, src->SizeOfImage);
497 a->SizeOfHeaders = H_GET_32 (abfd, src->SizeOfHeaders);
498 a->CheckSum = H_GET_32 (abfd, src->CheckSum);
499 a->Subsystem = H_GET_16 (abfd, src->Subsystem);
500 a->DllCharacteristics = H_GET_16 (abfd, src->DllCharacteristics);
501 a->SizeOfStackReserve =
502 GET_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, src->SizeOfStackReserve);
503 a->SizeOfStackCommit =
504 GET_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, src->SizeOfStackCommit);
505 a->SizeOfHeapReserve =
506 GET_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, src->SizeOfHeapReserve);
507 a->SizeOfHeapCommit =
508 GET_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, src->SizeOfHeapCommit);
509 a->LoaderFlags = H_GET_32 (abfd, src->LoaderFlags);
510 a->NumberOfRvaAndSizes = H_GET_32 (abfd, src->NumberOfRvaAndSizes);
511
512 /* PR 17512: Don't blindly trust NumberOfRvaAndSizes. */
513 unsigned idx;
514 for (idx = 0;
515 idx < a->NumberOfRvaAndSizes && idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
516 idx++)
517 {
518 /* If data directory is empty, rva also should be 0. */
519 int size = H_GET_32 (abfd, src->DataDirectory[idx][1]);
520 int vma = size ? H_GET_32 (abfd, src->DataDirectory[idx][0]) : 0;
521
522 a->DataDirectory[idx].Size = size;
523 a->DataDirectory[idx].VirtualAddress = vma;
524 }
525
526 while (idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
527 {
528 a->DataDirectory[idx].Size = 0;
529 a->DataDirectory[idx].VirtualAddress = 0;
530 idx++;
531 }
532
533 if (aouthdr_int->entry)
534 {
535 aouthdr_int->entry += a->ImageBase;
536 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
537 aouthdr_int->entry &= 0xffffffff;
538 #endif
539 }
540
541 if (aouthdr_int->tsize)
542 {
543 aouthdr_int->text_start += a->ImageBase;
544 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
545 aouthdr_int->text_start &= 0xffffffff;
546 #endif
547 }
548
549 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
550 /* PE32+ does not have data_start member! */
551 if (aouthdr_int->dsize)
552 {
553 aouthdr_int->data_start += a->ImageBase;
554 aouthdr_int->data_start &= 0xffffffff;
555 }
556 #endif
557 }
558
559 /* A support function for below. */
560
561 static void
562 add_data_entry (bfd * abfd,
563 struct internal_extra_pe_aouthdr *aout,
564 int idx,
565 char *name,
566 bfd_vma base)
567 {
568 asection *sec = bfd_get_section_by_name (abfd, name);
569
570 /* Add import directory information if it exists. */
571 if ((sec != NULL)
572 && (coff_section_data (abfd, sec) != NULL)
573 && (pei_section_data (abfd, sec) != NULL))
574 {
575 /* If data directory is empty, rva also should be 0. */
576 int size = pei_section_data (abfd, sec)->virt_size;
577 aout->DataDirectory[idx].Size = size;
578
579 if (size)
580 {
581 aout->DataDirectory[idx].VirtualAddress =
582 (sec->vma - base) & 0xffffffff;
583 sec->flags |= SEC_DATA;
584 }
585 }
586 }
587
588 unsigned int
589 _bfd_XXi_swap_aouthdr_out (bfd * abfd, void * in, void * out)
590 {
591 struct internal_aouthdr *aouthdr_in = (struct internal_aouthdr *) in;
592 pe_data_type *pe = pe_data (abfd);
593 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
594 PEAOUTHDR *aouthdr_out = (PEAOUTHDR *) out;
595 bfd_vma sa, fa, ib;
596 IMAGE_DATA_DIRECTORY idata2, idata5, tls;
597
598 sa = extra->SectionAlignment;
599 fa = extra->FileAlignment;
600 ib = extra->ImageBase;
601
602 idata2 = pe->pe_opthdr.DataDirectory[PE_IMPORT_TABLE];
603 idata5 = pe->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE];
604 tls = pe->pe_opthdr.DataDirectory[PE_TLS_TABLE];
605
606 if (aouthdr_in->tsize)
607 {
608 aouthdr_in->text_start -= ib;
609 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
610 aouthdr_in->text_start &= 0xffffffff;
611 #endif
612 }
613
614 if (aouthdr_in->dsize)
615 {
616 aouthdr_in->data_start -= ib;
617 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
618 aouthdr_in->data_start &= 0xffffffff;
619 #endif
620 }
621
622 if (aouthdr_in->entry)
623 {
624 aouthdr_in->entry -= ib;
625 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
626 aouthdr_in->entry &= 0xffffffff;
627 #endif
628 }
629
630 #define FA(x) (((x) + fa -1 ) & (- fa))
631 #define SA(x) (((x) + sa -1 ) & (- sa))
632
633 /* We like to have the sizes aligned. */
634 aouthdr_in->bsize = FA (aouthdr_in->bsize);
635
636 extra->NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
637
638 add_data_entry (abfd, extra, PE_EXPORT_TABLE, ".edata", ib);
639 add_data_entry (abfd, extra, PE_RESOURCE_TABLE, ".rsrc", ib);
640 add_data_entry (abfd, extra, PE_EXCEPTION_TABLE, ".pdata", ib);
641
642 /* In theory we do not need to call add_data_entry for .idata$2 or
643 .idata$5. It will be done in bfd_coff_final_link where all the
644 required information is available. If however, we are not going
645 to perform a final link, eg because we have been invoked by objcopy
646 or strip, then we need to make sure that these Data Directory
647 entries are initialised properly.
648
649 So - we copy the input values into the output values, and then, if
650 a final link is going to be performed, it can overwrite them. */
651 extra->DataDirectory[PE_IMPORT_TABLE] = idata2;
652 extra->DataDirectory[PE_IMPORT_ADDRESS_TABLE] = idata5;
653 extra->DataDirectory[PE_TLS_TABLE] = tls;
654
655 if (extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress == 0)
656 /* Until other .idata fixes are made (pending patch), the entry for
657 .idata is needed for backwards compatibility. FIXME. */
658 add_data_entry (abfd, extra, PE_IMPORT_TABLE, ".idata", ib);
659
660 /* For some reason, the virtual size (which is what's set by
661 add_data_entry) for .reloc is not the same as the size recorded
662 in this slot by MSVC; it doesn't seem to cause problems (so far),
663 but since it's the best we've got, use it. It does do the right
664 thing for .pdata. */
665 if (pe->has_reloc_section)
666 add_data_entry (abfd, extra, PE_BASE_RELOCATION_TABLE, ".reloc", ib);
667
668 {
669 asection *sec;
670 bfd_vma hsize = 0;
671 bfd_vma dsize = 0;
672 bfd_vma isize = 0;
673 bfd_vma tsize = 0;
674
675 for (sec = abfd->sections; sec; sec = sec->next)
676 {
677 int rounded = FA (sec->size);
678
679 if (rounded == 0)
680 continue;
681
682 /* The first non-zero section filepos is the header size.
683 Sections without contents will have a filepos of 0. */
684 if (hsize == 0)
685 hsize = sec->filepos;
686 if (sec->flags & SEC_DATA)
687 dsize += rounded;
688 if (sec->flags & SEC_CODE)
689 tsize += rounded;
690 /* The image size is the total VIRTUAL size (which is what is
691 in the virt_size field). Files have been seen (from MSVC
692 5.0 link.exe) where the file size of the .data segment is
693 quite small compared to the virtual size. Without this
694 fix, strip munges the file.
695
696 FIXME: We need to handle holes between sections, which may
697 happpen when we covert from another format. We just use
698 the virtual address and virtual size of the last section
699 for the image size. */
700 if (coff_section_data (abfd, sec) != NULL
701 && pei_section_data (abfd, sec) != NULL)
702 isize = (sec->vma - extra->ImageBase
703 + SA (FA (pei_section_data (abfd, sec)->virt_size)));
704 }
705
706 aouthdr_in->dsize = dsize;
707 aouthdr_in->tsize = tsize;
708 extra->SizeOfHeaders = hsize;
709 extra->SizeOfImage = isize;
710 }
711
712 H_PUT_16 (abfd, aouthdr_in->magic, aouthdr_out->standard.magic);
713
714 if (extra->MajorLinkerVersion || extra->MinorLinkerVersion)
715 {
716 H_PUT_8 (abfd, extra->MajorLinkerVersion,
717 aouthdr_out->standard.vstamp);
718 H_PUT_8 (abfd, extra->MinorLinkerVersion,
719 aouthdr_out->standard.vstamp + 1);
720 }
721 else
722 {
723 /* e.g. 219510000 is linker version 2.19 */
724 #define LINKER_VERSION ((short) (BFD_VERSION / 1000000))
725
726 /* This piece of magic sets the "linker version" field to
727 LINKER_VERSION. */
728 H_PUT_16 (abfd, (LINKER_VERSION / 100 + (LINKER_VERSION % 100) * 256),
729 aouthdr_out->standard.vstamp);
730 }
731
732 PUT_AOUTHDR_TSIZE (abfd, aouthdr_in->tsize, aouthdr_out->standard.tsize);
733 PUT_AOUTHDR_DSIZE (abfd, aouthdr_in->dsize, aouthdr_out->standard.dsize);
734 PUT_AOUTHDR_BSIZE (abfd, aouthdr_in->bsize, aouthdr_out->standard.bsize);
735 PUT_AOUTHDR_ENTRY (abfd, aouthdr_in->entry, aouthdr_out->standard.entry);
736 PUT_AOUTHDR_TEXT_START (abfd, aouthdr_in->text_start,
737 aouthdr_out->standard.text_start);
738
739 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
740 /* PE32+ does not have data_start member! */
741 PUT_AOUTHDR_DATA_START (abfd, aouthdr_in->data_start,
742 aouthdr_out->standard.data_start);
743 #endif
744
745 PUT_OPTHDR_IMAGE_BASE (abfd, extra->ImageBase, aouthdr_out->ImageBase);
746 H_PUT_32 (abfd, extra->SectionAlignment, aouthdr_out->SectionAlignment);
747 H_PUT_32 (abfd, extra->FileAlignment, aouthdr_out->FileAlignment);
748 H_PUT_16 (abfd, extra->MajorOperatingSystemVersion,
749 aouthdr_out->MajorOperatingSystemVersion);
750 H_PUT_16 (abfd, extra->MinorOperatingSystemVersion,
751 aouthdr_out->MinorOperatingSystemVersion);
752 H_PUT_16 (abfd, extra->MajorImageVersion, aouthdr_out->MajorImageVersion);
753 H_PUT_16 (abfd, extra->MinorImageVersion, aouthdr_out->MinorImageVersion);
754 H_PUT_16 (abfd, extra->MajorSubsystemVersion,
755 aouthdr_out->MajorSubsystemVersion);
756 H_PUT_16 (abfd, extra->MinorSubsystemVersion,
757 aouthdr_out->MinorSubsystemVersion);
758 H_PUT_32 (abfd, extra->Reserved1, aouthdr_out->Reserved1);
759 H_PUT_32 (abfd, extra->SizeOfImage, aouthdr_out->SizeOfImage);
760 H_PUT_32 (abfd, extra->SizeOfHeaders, aouthdr_out->SizeOfHeaders);
761 H_PUT_32 (abfd, extra->CheckSum, aouthdr_out->CheckSum);
762 H_PUT_16 (abfd, extra->Subsystem, aouthdr_out->Subsystem);
763 H_PUT_16 (abfd, extra->DllCharacteristics, aouthdr_out->DllCharacteristics);
764 PUT_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, extra->SizeOfStackReserve,
765 aouthdr_out->SizeOfStackReserve);
766 PUT_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, extra->SizeOfStackCommit,
767 aouthdr_out->SizeOfStackCommit);
768 PUT_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, extra->SizeOfHeapReserve,
769 aouthdr_out->SizeOfHeapReserve);
770 PUT_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, extra->SizeOfHeapCommit,
771 aouthdr_out->SizeOfHeapCommit);
772 H_PUT_32 (abfd, extra->LoaderFlags, aouthdr_out->LoaderFlags);
773 H_PUT_32 (abfd, extra->NumberOfRvaAndSizes,
774 aouthdr_out->NumberOfRvaAndSizes);
775 {
776 int idx;
777
778 for (idx = 0; idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; idx++)
779 {
780 H_PUT_32 (abfd, extra->DataDirectory[idx].VirtualAddress,
781 aouthdr_out->DataDirectory[idx][0]);
782 H_PUT_32 (abfd, extra->DataDirectory[idx].Size,
783 aouthdr_out->DataDirectory[idx][1]);
784 }
785 }
786
787 return AOUTSZ;
788 }
789
790 unsigned int
791 _bfd_XXi_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
792 {
793 int idx;
794 struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
795 struct external_PEI_filehdr *filehdr_out = (struct external_PEI_filehdr *) out;
796
797 if (pe_data (abfd)->has_reloc_section
798 || pe_data (abfd)->dont_strip_reloc)
799 filehdr_in->f_flags &= ~F_RELFLG;
800
801 if (pe_data (abfd)->dll)
802 filehdr_in->f_flags |= F_DLL;
803
804 filehdr_in->pe.e_magic = IMAGE_DOS_SIGNATURE;
805 filehdr_in->pe.e_cblp = 0x90;
806 filehdr_in->pe.e_cp = 0x3;
807 filehdr_in->pe.e_crlc = 0x0;
808 filehdr_in->pe.e_cparhdr = 0x4;
809 filehdr_in->pe.e_minalloc = 0x0;
810 filehdr_in->pe.e_maxalloc = 0xffff;
811 filehdr_in->pe.e_ss = 0x0;
812 filehdr_in->pe.e_sp = 0xb8;
813 filehdr_in->pe.e_csum = 0x0;
814 filehdr_in->pe.e_ip = 0x0;
815 filehdr_in->pe.e_cs = 0x0;
816 filehdr_in->pe.e_lfarlc = 0x40;
817 filehdr_in->pe.e_ovno = 0x0;
818
819 for (idx = 0; idx < 4; idx++)
820 filehdr_in->pe.e_res[idx] = 0x0;
821
822 filehdr_in->pe.e_oemid = 0x0;
823 filehdr_in->pe.e_oeminfo = 0x0;
824
825 for (idx = 0; idx < 10; idx++)
826 filehdr_in->pe.e_res2[idx] = 0x0;
827
828 filehdr_in->pe.e_lfanew = 0x80;
829
830 /* This next collection of data are mostly just characters. It
831 appears to be constant within the headers put on NT exes. */
832 memcpy (filehdr_in->pe.dos_message, pe_data (abfd)->dos_message,
833 sizeof (filehdr_in->pe.dos_message));
834
835 filehdr_in->pe.nt_signature = IMAGE_NT_SIGNATURE;
836
837 H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
838 H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
839
840 /* Use a real timestamp by default, unless the no-insert-timestamp
841 option was chosen. */
842 if ((pe_data (abfd)->timestamp) == -1)
843 {
844 time_t now = bfd_get_current_time (0);
845 H_PUT_32 (abfd, now, filehdr_out->f_timdat);
846 }
847 else
848 H_PUT_32 (abfd, pe_data (abfd)->timestamp, filehdr_out->f_timdat);
849
850 PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr,
851 filehdr_out->f_symptr);
852 H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms);
853 H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr);
854 H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags);
855
856 /* Put in extra dos header stuff. This data remains essentially
857 constant, it just has to be tacked on to the beginning of all exes
858 for NT. */
859 H_PUT_16 (abfd, filehdr_in->pe.e_magic, filehdr_out->e_magic);
860 H_PUT_16 (abfd, filehdr_in->pe.e_cblp, filehdr_out->e_cblp);
861 H_PUT_16 (abfd, filehdr_in->pe.e_cp, filehdr_out->e_cp);
862 H_PUT_16 (abfd, filehdr_in->pe.e_crlc, filehdr_out->e_crlc);
863 H_PUT_16 (abfd, filehdr_in->pe.e_cparhdr, filehdr_out->e_cparhdr);
864 H_PUT_16 (abfd, filehdr_in->pe.e_minalloc, filehdr_out->e_minalloc);
865 H_PUT_16 (abfd, filehdr_in->pe.e_maxalloc, filehdr_out->e_maxalloc);
866 H_PUT_16 (abfd, filehdr_in->pe.e_ss, filehdr_out->e_ss);
867 H_PUT_16 (abfd, filehdr_in->pe.e_sp, filehdr_out->e_sp);
868 H_PUT_16 (abfd, filehdr_in->pe.e_csum, filehdr_out->e_csum);
869 H_PUT_16 (abfd, filehdr_in->pe.e_ip, filehdr_out->e_ip);
870 H_PUT_16 (abfd, filehdr_in->pe.e_cs, filehdr_out->e_cs);
871 H_PUT_16 (abfd, filehdr_in->pe.e_lfarlc, filehdr_out->e_lfarlc);
872 H_PUT_16 (abfd, filehdr_in->pe.e_ovno, filehdr_out->e_ovno);
873
874 for (idx = 0; idx < 4; idx++)
875 H_PUT_16 (abfd, filehdr_in->pe.e_res[idx], filehdr_out->e_res[idx]);
876
877 H_PUT_16 (abfd, filehdr_in->pe.e_oemid, filehdr_out->e_oemid);
878 H_PUT_16 (abfd, filehdr_in->pe.e_oeminfo, filehdr_out->e_oeminfo);
879
880 for (idx = 0; idx < 10; idx++)
881 H_PUT_16 (abfd, filehdr_in->pe.e_res2[idx], filehdr_out->e_res2[idx]);
882
883 H_PUT_32 (abfd, filehdr_in->pe.e_lfanew, filehdr_out->e_lfanew);
884
885 memcpy (filehdr_out->dos_message, filehdr_in->pe.dos_message,
886 sizeof (filehdr_out->dos_message));
887
888 /* Also put in the NT signature. */
889 H_PUT_32 (abfd, filehdr_in->pe.nt_signature, filehdr_out->nt_signature);
890
891 return FILHSZ;
892 }
893
894 unsigned int
895 _bfd_XX_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
896 {
897 struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
898 FILHDR *filehdr_out = (FILHDR *) out;
899
900 H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
901 H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
902 H_PUT_32 (abfd, filehdr_in->f_timdat, filehdr_out->f_timdat);
903 PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr, filehdr_out->f_symptr);
904 H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms);
905 H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr);
906 H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags);
907
908 return FILHSZ;
909 }
910
911 unsigned int
912 _bfd_XXi_swap_scnhdr_out (bfd * abfd, void * in, void * out)
913 {
914 struct internal_scnhdr *scnhdr_int = (struct internal_scnhdr *) in;
915 SCNHDR *scnhdr_ext = (SCNHDR *) out;
916 unsigned int ret = SCNHSZ;
917 bfd_vma ps;
918 bfd_vma ss;
919
920 memcpy (scnhdr_ext->s_name, scnhdr_int->s_name, sizeof (scnhdr_int->s_name));
921
922 ss = scnhdr_int->s_vaddr - pe_data (abfd)->pe_opthdr.ImageBase;
923 if (scnhdr_int->s_vaddr < pe_data (abfd)->pe_opthdr.ImageBase)
924 _bfd_error_handler (_("%pB:%.8s: section below image base"),
925 abfd, scnhdr_int->s_name);
926 /* Do not compare lower 32-bits for 64-bit vma. */
927 #if !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
928 else if(ss != (ss & 0xffffffff))
929 _bfd_error_handler (_("%pB:%.8s: RVA truncated"), abfd, scnhdr_int->s_name);
930 PUT_SCNHDR_VADDR (abfd, ss & 0xffffffff, scnhdr_ext->s_vaddr);
931 #else
932 PUT_SCNHDR_VADDR (abfd, ss, scnhdr_ext->s_vaddr);
933 #endif
934
935 /* NT wants the size data to be rounded up to the next
936 NT_FILE_ALIGNMENT, but zero if it has no content (as in .bss,
937 sometimes). */
938 if ((scnhdr_int->s_flags & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0)
939 {
940 if (bfd_pei_p (abfd))
941 {
942 ps = scnhdr_int->s_size;
943 ss = 0;
944 }
945 else
946 {
947 ps = 0;
948 ss = scnhdr_int->s_size;
949 }
950 }
951 else
952 {
953 if (bfd_pei_p (abfd))
954 ps = scnhdr_int->s_paddr;
955 else
956 ps = 0;
957
958 ss = scnhdr_int->s_size;
959 }
960
961 PUT_SCNHDR_SIZE (abfd, ss,
962 scnhdr_ext->s_size);
963
964 /* s_paddr in PE is really the virtual size. */
965 PUT_SCNHDR_PADDR (abfd, ps, scnhdr_ext->s_paddr);
966
967 PUT_SCNHDR_SCNPTR (abfd, scnhdr_int->s_scnptr,
968 scnhdr_ext->s_scnptr);
969 PUT_SCNHDR_RELPTR (abfd, scnhdr_int->s_relptr,
970 scnhdr_ext->s_relptr);
971 PUT_SCNHDR_LNNOPTR (abfd, scnhdr_int->s_lnnoptr,
972 scnhdr_ext->s_lnnoptr);
973
974 {
975 /* Extra flags must be set when dealing with PE. All sections should also
976 have the IMAGE_SCN_MEM_READ (0x40000000) flag set. In addition, the
977 .text section must have IMAGE_SCN_MEM_EXECUTE (0x20000000) and the data
978 sections (.idata, .data, .bss, .CRT) must have IMAGE_SCN_MEM_WRITE set
979 (this is especially important when dealing with the .idata section since
980 the addresses for routines from .dlls must be overwritten). If .reloc
981 section data is ever generated, we must add IMAGE_SCN_MEM_DISCARDABLE
982 (0x02000000). Also, the resource data should also be read and
983 writable. */
984
985 /* FIXME: Alignment is also encoded in this field, at least on
986 ARM-WINCE. Although - how do we get the original alignment field
987 back ? */
988
989 typedef struct
990 {
991 char section_name[SCNNMLEN];
992 unsigned long must_have;
993 }
994 pe_required_section_flags;
995
996 pe_required_section_flags known_sections [] =
997 {
998 { ".arch", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_ALIGN_8BYTES },
999 { ".bss", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1000 { ".data", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1001 { ".edata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1002 { ".idata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1003 { ".pdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1004 { ".rdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1005 { ".reloc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE },
1006 { ".rsrc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1007 { ".text" , IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE },
1008 { ".tls", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1009 { ".xdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1010 };
1011
1012 pe_required_section_flags * p;
1013
1014 /* We have defaulted to adding the IMAGE_SCN_MEM_WRITE flag, but now
1015 we know exactly what this specific section wants so we remove it
1016 and then allow the must_have field to add it back in if necessary.
1017 However, we don't remove IMAGE_SCN_MEM_WRITE flag from .text if the
1018 default WP_TEXT file flag has been cleared. WP_TEXT may be cleared
1019 by ld --enable-auto-import (if auto-import is actually needed),
1020 by ld --omagic, or by obcopy --writable-text. */
1021
1022 for (p = known_sections;
1023 p < known_sections + ARRAY_SIZE (known_sections);
1024 p++)
1025 if (memcmp (scnhdr_int->s_name, p->section_name, SCNNMLEN) == 0)
1026 {
1027 if (memcmp (scnhdr_int->s_name, ".text", sizeof ".text")
1028 || (bfd_get_file_flags (abfd) & WP_TEXT))
1029 scnhdr_int->s_flags &= ~IMAGE_SCN_MEM_WRITE;
1030 scnhdr_int->s_flags |= p->must_have;
1031 break;
1032 }
1033
1034 H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
1035 }
1036
1037 if (coff_data (abfd)->link_info
1038 && ! bfd_link_relocatable (coff_data (abfd)->link_info)
1039 && ! bfd_link_pic (coff_data (abfd)->link_info)
1040 && memcmp (scnhdr_int->s_name, ".text", sizeof ".text") == 0)
1041 {
1042 /* By inference from looking at MS output, the 32 bit field
1043 which is the combination of the number_of_relocs and
1044 number_of_linenos is used for the line number count in
1045 executables. A 16-bit field won't do for cc1. The MS
1046 document says that the number of relocs is zero for
1047 executables, but the 17-th bit has been observed to be there.
1048 Overflow is not an issue: a 4G-line program will overflow a
1049 bunch of other fields long before this! */
1050 H_PUT_16 (abfd, (scnhdr_int->s_nlnno & 0xffff), scnhdr_ext->s_nlnno);
1051 H_PUT_16 (abfd, (scnhdr_int->s_nlnno >> 16), scnhdr_ext->s_nreloc);
1052 }
1053 else
1054 {
1055 if (scnhdr_int->s_nlnno <= 0xffff)
1056 H_PUT_16 (abfd, scnhdr_int->s_nlnno, scnhdr_ext->s_nlnno);
1057 else
1058 {
1059 /* xgettext:c-format */
1060 _bfd_error_handler (_("%pB: line number overflow: 0x%lx > 0xffff"),
1061 abfd, scnhdr_int->s_nlnno);
1062 bfd_set_error (bfd_error_file_truncated);
1063 H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nlnno);
1064 ret = 0;
1065 }
1066
1067 /* Although we could encode 0xffff relocs here, we do not, to be
1068 consistent with other parts of bfd. Also it lets us warn, as
1069 we should never see 0xffff here w/o having the overflow flag
1070 set. */
1071 if (scnhdr_int->s_nreloc < 0xffff)
1072 H_PUT_16 (abfd, scnhdr_int->s_nreloc, scnhdr_ext->s_nreloc);
1073 else
1074 {
1075 /* PE can deal with large #s of relocs, but not here. */
1076 H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nreloc);
1077 scnhdr_int->s_flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
1078 H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
1079 }
1080 }
1081 return ret;
1082 }
1083
1084 void
1085 _bfd_XXi_swap_debugdir_in (bfd * abfd, void * ext1, void * in1)
1086 {
1087 struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) ext1;
1088 struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) in1;
1089
1090 in->Characteristics = H_GET_32(abfd, ext->Characteristics);
1091 in->TimeDateStamp = H_GET_32(abfd, ext->TimeDateStamp);
1092 in->MajorVersion = H_GET_16(abfd, ext->MajorVersion);
1093 in->MinorVersion = H_GET_16(abfd, ext->MinorVersion);
1094 in->Type = H_GET_32(abfd, ext->Type);
1095 in->SizeOfData = H_GET_32(abfd, ext->SizeOfData);
1096 in->AddressOfRawData = H_GET_32(abfd, ext->AddressOfRawData);
1097 in->PointerToRawData = H_GET_32(abfd, ext->PointerToRawData);
1098 }
1099
1100 unsigned int
1101 _bfd_XXi_swap_debugdir_out (bfd * abfd, void * inp, void * extp)
1102 {
1103 struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) extp;
1104 struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) inp;
1105
1106 H_PUT_32(abfd, in->Characteristics, ext->Characteristics);
1107 H_PUT_32(abfd, in->TimeDateStamp, ext->TimeDateStamp);
1108 H_PUT_16(abfd, in->MajorVersion, ext->MajorVersion);
1109 H_PUT_16(abfd, in->MinorVersion, ext->MinorVersion);
1110 H_PUT_32(abfd, in->Type, ext->Type);
1111 H_PUT_32(abfd, in->SizeOfData, ext->SizeOfData);
1112 H_PUT_32(abfd, in->AddressOfRawData, ext->AddressOfRawData);
1113 H_PUT_32(abfd, in->PointerToRawData, ext->PointerToRawData);
1114
1115 return sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1116 }
1117
1118 CODEVIEW_INFO *
1119 _bfd_XXi_slurp_codeview_record (bfd * abfd, file_ptr where, unsigned long length, CODEVIEW_INFO *cvinfo,
1120 char **pdb)
1121 {
1122 char buffer[256+1];
1123 bfd_size_type nread;
1124
1125 if (bfd_seek (abfd, where, SEEK_SET) != 0)
1126 return NULL;
1127
1128 if (length <= sizeof (CV_INFO_PDB70) && length <= sizeof (CV_INFO_PDB20))
1129 return NULL;
1130 if (length > 256)
1131 length = 256;
1132 nread = bfd_read (buffer, length, abfd);
1133 if (length != nread)
1134 return NULL;
1135
1136 /* Ensure null termination of filename. */
1137 memset (buffer + nread, 0, sizeof (buffer) - nread);
1138
1139 cvinfo->CVSignature = H_GET_32 (abfd, buffer);
1140 cvinfo->Age = 0;
1141
1142 if ((cvinfo->CVSignature == CVINFO_PDB70_CVSIGNATURE)
1143 && (length > sizeof (CV_INFO_PDB70)))
1144 {
1145 CV_INFO_PDB70 *cvinfo70 = (CV_INFO_PDB70 *)(buffer);
1146
1147 cvinfo->Age = H_GET_32(abfd, cvinfo70->Age);
1148
1149 /* A GUID consists of 4,2,2 byte values in little-endian order, followed
1150 by 8 single bytes. Byte swap them so we can conveniently treat the GUID
1151 as 16 bytes in big-endian order. */
1152 bfd_putb32 (bfd_getl32 (cvinfo70->Signature), cvinfo->Signature);
1153 bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[4])), &(cvinfo->Signature[4]));
1154 bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[6])), &(cvinfo->Signature[6]));
1155 memcpy (&(cvinfo->Signature[8]), &(cvinfo70->Signature[8]), 8);
1156
1157 cvinfo->SignatureLength = CV_INFO_SIGNATURE_LENGTH;
1158 /* cvinfo->PdbFileName = cvinfo70->PdbFileName; */
1159
1160 if (pdb)
1161 *pdb = xstrdup (cvinfo70->PdbFileName);
1162
1163 return cvinfo;
1164 }
1165 else if ((cvinfo->CVSignature == CVINFO_PDB20_CVSIGNATURE)
1166 && (length > sizeof (CV_INFO_PDB20)))
1167 {
1168 CV_INFO_PDB20 *cvinfo20 = (CV_INFO_PDB20 *)(buffer);
1169 cvinfo->Age = H_GET_32(abfd, cvinfo20->Age);
1170 memcpy (cvinfo->Signature, cvinfo20->Signature, 4);
1171 cvinfo->SignatureLength = 4;
1172 /* cvinfo->PdbFileName = cvinfo20->PdbFileName; */
1173
1174 if (pdb)
1175 *pdb = xstrdup (cvinfo20->PdbFileName);
1176
1177 return cvinfo;
1178 }
1179
1180 return NULL;
1181 }
1182
1183 unsigned int
1184 _bfd_XXi_write_codeview_record (bfd * abfd, file_ptr where, CODEVIEW_INFO *cvinfo,
1185 const char *pdb)
1186 {
1187 size_t pdb_len = pdb ? strlen (pdb) : 0;
1188 const bfd_size_type size = sizeof (CV_INFO_PDB70) + pdb_len + 1;
1189 bfd_size_type written;
1190 CV_INFO_PDB70 *cvinfo70;
1191 char * buffer;
1192
1193 if (bfd_seek (abfd, where, SEEK_SET) != 0)
1194 return 0;
1195
1196 buffer = bfd_malloc (size);
1197 if (buffer == NULL)
1198 return 0;
1199
1200 cvinfo70 = (CV_INFO_PDB70 *) buffer;
1201 H_PUT_32 (abfd, CVINFO_PDB70_CVSIGNATURE, cvinfo70->CvSignature);
1202
1203 /* Byte swap the GUID from 16 bytes in big-endian order to 4,2,2 byte values
1204 in little-endian order, followed by 8 single bytes. */
1205 bfd_putl32 (bfd_getb32 (cvinfo->Signature), cvinfo70->Signature);
1206 bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[4])), &(cvinfo70->Signature[4]));
1207 bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[6])), &(cvinfo70->Signature[6]));
1208 memcpy (&(cvinfo70->Signature[8]), &(cvinfo->Signature[8]), 8);
1209
1210 H_PUT_32 (abfd, cvinfo->Age, cvinfo70->Age);
1211
1212 if (pdb == NULL)
1213 cvinfo70->PdbFileName[0] = '\0';
1214 else
1215 memcpy (cvinfo70->PdbFileName, pdb, pdb_len + 1);
1216
1217 written = bfd_write (buffer, size, abfd);
1218
1219 free (buffer);
1220
1221 return written == size ? size : 0;
1222 }
1223
1224 static char * dir_names[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] =
1225 {
1226 N_("Export Directory [.edata (or where ever we found it)]"),
1227 N_("Import Directory [parts of .idata]"),
1228 N_("Resource Directory [.rsrc]"),
1229 N_("Exception Directory [.pdata]"),
1230 N_("Security Directory"),
1231 N_("Base Relocation Directory [.reloc]"),
1232 N_("Debug Directory"),
1233 N_("Description Directory"),
1234 N_("Special Directory"),
1235 N_("Thread Storage Directory [.tls]"),
1236 N_("Load Configuration Directory"),
1237 N_("Bound Import Directory"),
1238 N_("Import Address Table Directory"),
1239 N_("Delay Import Directory"),
1240 N_("CLR Runtime Header"),
1241 N_("Reserved")
1242 };
1243
1244 static bool
1245 get_contents_sanity_check (bfd *abfd, asection *section,
1246 bfd_size_type dataoff, bfd_size_type datasize)
1247 {
1248 if ((section->flags & SEC_HAS_CONTENTS) == 0)
1249 return false;
1250 if (dataoff > section->size
1251 || datasize > section->size - dataoff)
1252 return false;
1253 ufile_ptr filesize = bfd_get_file_size (abfd);
1254 if (filesize != 0
1255 && ((ufile_ptr) section->filepos > filesize
1256 || dataoff > filesize - section->filepos
1257 || datasize > filesize - section->filepos - dataoff))
1258 return false;
1259 return true;
1260 }
1261
1262 static bool
1263 pe_print_idata (bfd * abfd, void * vfile)
1264 {
1265 FILE *file = (FILE *) vfile;
1266 bfd_byte *data;
1267 asection *section;
1268 bfd_signed_vma adj;
1269 bfd_size_type datasize = 0;
1270 bfd_size_type dataoff;
1271 bfd_size_type i;
1272 int onaline = 20;
1273
1274 pe_data_type *pe = pe_data (abfd);
1275 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1276
1277 bfd_vma addr;
1278
1279 addr = extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress;
1280
1281 if (addr == 0 && extra->DataDirectory[PE_IMPORT_TABLE].Size == 0)
1282 {
1283 /* Maybe the extra header isn't there. Look for the section. */
1284 section = bfd_get_section_by_name (abfd, ".idata");
1285 if (section == NULL || (section->flags & SEC_HAS_CONTENTS) == 0)
1286 return true;
1287
1288 addr = section->vma;
1289 datasize = section->size;
1290 if (datasize == 0)
1291 return true;
1292 }
1293 else
1294 {
1295 addr += extra->ImageBase;
1296 for (section = abfd->sections; section != NULL; section = section->next)
1297 {
1298 datasize = section->size;
1299 if (addr >= section->vma && addr < section->vma + datasize)
1300 break;
1301 }
1302
1303 if (section == NULL)
1304 {
1305 fprintf (file,
1306 _("\nThere is an import table, but the section containing it could not be found\n"));
1307 return true;
1308 }
1309 else if (!(section->flags & SEC_HAS_CONTENTS))
1310 {
1311 fprintf (file,
1312 _("\nThere is an import table in %s, but that section has no contents\n"),
1313 section->name);
1314 return true;
1315 }
1316 }
1317
1318 /* xgettext:c-format */
1319 fprintf (file, _("\nThere is an import table in %s at 0x%lx\n"),
1320 section->name, (unsigned long) addr);
1321
1322 dataoff = addr - section->vma;
1323
1324 fprintf (file,
1325 _("\nThe Import Tables (interpreted %s section contents)\n"),
1326 section->name);
1327 fprintf (file,
1328 _("\
1329 vma: Hint Time Forward DLL First\n\
1330 Table Stamp Chain Name Thunk\n"));
1331
1332 /* Read the whole section. Some of the fields might be before dataoff. */
1333 if (!bfd_malloc_and_get_section (abfd, section, &data))
1334 {
1335 free (data);
1336 return false;
1337 }
1338
1339 adj = section->vma - extra->ImageBase;
1340
1341 /* Print all image import descriptors. */
1342 for (i = dataoff; i + onaline <= datasize; i += onaline)
1343 {
1344 bfd_vma hint_addr;
1345 bfd_vma time_stamp;
1346 bfd_vma forward_chain;
1347 bfd_vma dll_name;
1348 bfd_vma first_thunk;
1349 int idx = 0;
1350 bfd_size_type j;
1351 char *dll;
1352
1353 /* Print (i + extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress). */
1354 fprintf (file, " %08lx\t", (unsigned long) (i + adj));
1355 hint_addr = bfd_get_32 (abfd, data + i);
1356 time_stamp = bfd_get_32 (abfd, data + i + 4);
1357 forward_chain = bfd_get_32 (abfd, data + i + 8);
1358 dll_name = bfd_get_32 (abfd, data + i + 12);
1359 first_thunk = bfd_get_32 (abfd, data + i + 16);
1360
1361 fprintf (file, "%08lx %08lx %08lx %08lx %08lx\n",
1362 (unsigned long) hint_addr,
1363 (unsigned long) time_stamp,
1364 (unsigned long) forward_chain,
1365 (unsigned long) dll_name,
1366 (unsigned long) first_thunk);
1367
1368 if (hint_addr == 0 && first_thunk == 0)
1369 break;
1370
1371 if (dll_name - adj >= section->size)
1372 break;
1373
1374 dll = (char *) data + dll_name - adj;
1375 /* PR 17512 file: 078-12277-0.004. */
1376 bfd_size_type maxlen = (char *)(data + datasize) - dll - 1;
1377 fprintf (file, _("\n\tDLL Name: %.*s\n"), (int) maxlen, dll);
1378
1379 /* PR 21546: When the Hint Address is zero,
1380 we try the First Thunk instead. */
1381 if (hint_addr == 0)
1382 hint_addr = first_thunk;
1383
1384 if (hint_addr != 0 && hint_addr - adj < datasize)
1385 {
1386 bfd_byte *ft_data;
1387 asection *ft_section;
1388 bfd_vma ft_addr;
1389 bfd_size_type ft_datasize;
1390 int ft_idx;
1391 int ft_allocated;
1392
1393 fprintf (file, _("\tvma: Hint/Ord Member-Name Bound-To\n"));
1394
1395 idx = hint_addr - adj;
1396
1397 ft_addr = first_thunk + extra->ImageBase;
1398 ft_idx = first_thunk - adj;
1399 ft_data = data + ft_idx;
1400 ft_datasize = datasize - ft_idx;
1401 ft_allocated = 0;
1402
1403 if (first_thunk != hint_addr)
1404 {
1405 /* Find the section which contains the first thunk. */
1406 for (ft_section = abfd->sections;
1407 ft_section != NULL;
1408 ft_section = ft_section->next)
1409 {
1410 if (ft_addr >= ft_section->vma
1411 && ft_addr < ft_section->vma + ft_section->size)
1412 break;
1413 }
1414
1415 if (ft_section == NULL)
1416 {
1417 fprintf (file,
1418 _("\nThere is a first thunk, but the section containing it could not be found\n"));
1419 continue;
1420 }
1421
1422 /* Now check to see if this section is the same as our current
1423 section. If it is not then we will have to load its data in. */
1424 if (ft_section != section)
1425 {
1426 ft_idx = first_thunk - (ft_section->vma - extra->ImageBase);
1427 ft_datasize = ft_section->size - ft_idx;
1428 if (!get_contents_sanity_check (abfd, ft_section,
1429 ft_idx, ft_datasize))
1430 continue;
1431 ft_data = (bfd_byte *) bfd_malloc (ft_datasize);
1432 if (ft_data == NULL)
1433 continue;
1434
1435 /* Read ft_datasize bytes starting at offset ft_idx. */
1436 if (!bfd_get_section_contents (abfd, ft_section, ft_data,
1437 (bfd_vma) ft_idx, ft_datasize))
1438 {
1439 free (ft_data);
1440 continue;
1441 }
1442 ft_allocated = 1;
1443 }
1444 }
1445
1446 /* Print HintName vector entries. */
1447 #ifdef COFF_WITH_pex64
1448 for (j = 0; idx + j + 8 <= datasize; j += 8)
1449 {
1450 bfd_size_type amt;
1451 unsigned long member = bfd_get_32 (abfd, data + idx + j);
1452 unsigned long member_high = bfd_get_32 (abfd, data + idx + j + 4);
1453
1454 if (!member && !member_high)
1455 break;
1456
1457 amt = member - adj;
1458
1459 if (HighBitSet (member_high))
1460 fprintf (file, "\t%lx%08lx\t %4lx%08lx <none>",
1461 member_high, member,
1462 WithoutHighBit (member_high), member);
1463 /* PR binutils/17512: Handle corrupt PE data. */
1464 else if (amt >= datasize || amt + 2 >= datasize)
1465 fprintf (file, _("\t<corrupt: 0x%04lx>"), member);
1466 else
1467 {
1468 int ordinal;
1469 char *member_name;
1470
1471 ordinal = bfd_get_16 (abfd, data + amt);
1472 member_name = (char *) data + amt + 2;
1473 fprintf (file, "\t%04lx\t %4d %.*s",member, ordinal,
1474 (int) (datasize - (amt + 2)), member_name);
1475 }
1476
1477 /* If the time stamp is not zero, the import address
1478 table holds actual addresses. */
1479 if (time_stamp != 0
1480 && first_thunk != 0
1481 && first_thunk != hint_addr
1482 && j + 4 <= ft_datasize)
1483 fprintf (file, "\t%04lx",
1484 (unsigned long) bfd_get_32 (abfd, ft_data + j));
1485 fprintf (file, "\n");
1486 }
1487 #else
1488 for (j = 0; idx + j + 4 <= datasize; j += 4)
1489 {
1490 bfd_size_type amt;
1491 unsigned long member = bfd_get_32 (abfd, data + idx + j);
1492
1493 /* Print single IMAGE_IMPORT_BY_NAME vector. */
1494 if (member == 0)
1495 break;
1496
1497 amt = member - adj;
1498
1499 if (HighBitSet (member))
1500 fprintf (file, "\t%04lx\t %4lu <none>",
1501 member, WithoutHighBit (member));
1502 /* PR binutils/17512: Handle corrupt PE data. */
1503 else if (amt >= datasize || amt + 2 >= datasize)
1504 fprintf (file, _("\t<corrupt: 0x%04lx>"), member);
1505 else
1506 {
1507 int ordinal;
1508 char *member_name;
1509
1510 ordinal = bfd_get_16 (abfd, data + amt);
1511 member_name = (char *) data + amt + 2;
1512 fprintf (file, "\t%04lx\t %4d %.*s",
1513 member, ordinal,
1514 (int) (datasize - (amt + 2)), member_name);
1515 }
1516
1517 /* If the time stamp is not zero, the import address
1518 table holds actual addresses. */
1519 if (time_stamp != 0
1520 && first_thunk != 0
1521 && first_thunk != hint_addr
1522 && j + 4 <= ft_datasize)
1523 fprintf (file, "\t%04lx",
1524 (unsigned long) bfd_get_32 (abfd, ft_data + j));
1525
1526 fprintf (file, "\n");
1527 }
1528 #endif
1529 if (ft_allocated)
1530 free (ft_data);
1531 }
1532
1533 fprintf (file, "\n");
1534 }
1535
1536 free (data);
1537
1538 return true;
1539 }
1540
1541 static bool
1542 pe_print_edata (bfd * abfd, void * vfile)
1543 {
1544 FILE *file = (FILE *) vfile;
1545 bfd_byte *data;
1546 asection *section;
1547 bfd_size_type datasize = 0;
1548 bfd_size_type dataoff;
1549 bfd_size_type i;
1550 bfd_vma adj;
1551 struct EDT_type
1552 {
1553 long export_flags; /* Reserved - should be zero. */
1554 long time_stamp;
1555 short major_ver;
1556 short minor_ver;
1557 bfd_vma name; /* RVA - relative to image base. */
1558 long base; /* Ordinal base. */
1559 unsigned long num_functions;/* Number in the export address table. */
1560 unsigned long num_names; /* Number in the name pointer table. */
1561 bfd_vma eat_addr; /* RVA to the export address table. */
1562 bfd_vma npt_addr; /* RVA to the Export Name Pointer Table. */
1563 bfd_vma ot_addr; /* RVA to the Ordinal Table. */
1564 } edt;
1565
1566 pe_data_type *pe = pe_data (abfd);
1567 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1568
1569 bfd_vma addr;
1570
1571 addr = extra->DataDirectory[PE_EXPORT_TABLE].VirtualAddress;
1572
1573 if (addr == 0 && extra->DataDirectory[PE_EXPORT_TABLE].Size == 0)
1574 {
1575 /* Maybe the extra header isn't there. Look for the section. */
1576 section = bfd_get_section_by_name (abfd, ".edata");
1577 if (section == NULL)
1578 return true;
1579
1580 addr = section->vma;
1581 dataoff = 0;
1582 datasize = section->size;
1583 if (datasize == 0)
1584 return true;
1585 }
1586 else
1587 {
1588 addr += extra->ImageBase;
1589
1590 for (section = abfd->sections; section != NULL; section = section->next)
1591 if (addr >= section->vma && addr < section->vma + section->size)
1592 break;
1593
1594 if (section == NULL)
1595 {
1596 fprintf (file,
1597 _("\nThere is an export table, but the section containing it could not be found\n"));
1598 return true;
1599 }
1600
1601 dataoff = addr - section->vma;
1602 datasize = extra->DataDirectory[PE_EXPORT_TABLE].Size;
1603 }
1604
1605 /* PR 17512: Handle corrupt PE binaries. */
1606 if (datasize < 40)
1607 {
1608 fprintf (file,
1609 /* xgettext:c-format */
1610 _("\nThere is an export table in %s, but it is too small (%d)\n"),
1611 section->name, (int) datasize);
1612 return true;
1613 }
1614
1615 if (!get_contents_sanity_check (abfd, section, dataoff, datasize))
1616 {
1617 fprintf (file,
1618 _("\nThere is an export table in %s, but contents cannot be read\n"),
1619 section->name);
1620 return true;
1621 }
1622
1623 /* xgettext:c-format */
1624 fprintf (file, _("\nThere is an export table in %s at 0x%lx\n"),
1625 section->name, (unsigned long) addr);
1626
1627 data = (bfd_byte *) bfd_malloc (datasize);
1628 if (data == NULL)
1629 return false;
1630
1631 if (! bfd_get_section_contents (abfd, section, data,
1632 (file_ptr) dataoff, datasize))
1633 {
1634 free (data);
1635 return false;
1636 }
1637
1638 /* Go get Export Directory Table. */
1639 edt.export_flags = bfd_get_32 (abfd, data + 0);
1640 edt.time_stamp = bfd_get_32 (abfd, data + 4);
1641 edt.major_ver = bfd_get_16 (abfd, data + 8);
1642 edt.minor_ver = bfd_get_16 (abfd, data + 10);
1643 edt.name = bfd_get_32 (abfd, data + 12);
1644 edt.base = bfd_get_32 (abfd, data + 16);
1645 edt.num_functions = bfd_get_32 (abfd, data + 20);
1646 edt.num_names = bfd_get_32 (abfd, data + 24);
1647 edt.eat_addr = bfd_get_32 (abfd, data + 28);
1648 edt.npt_addr = bfd_get_32 (abfd, data + 32);
1649 edt.ot_addr = bfd_get_32 (abfd, data + 36);
1650
1651 adj = section->vma - extra->ImageBase + dataoff;
1652
1653 /* Dump the EDT first. */
1654 fprintf (file,
1655 _("\nThe Export Tables (interpreted %s section contents)\n\n"),
1656 section->name);
1657
1658 fprintf (file,
1659 _("Export Flags \t\t\t%lx\n"), (unsigned long) edt.export_flags);
1660
1661 fprintf (file,
1662 _("Time/Date stamp \t\t%lx\n"), (unsigned long) edt.time_stamp);
1663
1664 fprintf (file,
1665 /* xgettext:c-format */
1666 _("Major/Minor \t\t\t%d/%d\n"), edt.major_ver, edt.minor_ver);
1667
1668 fprintf (file,
1669 _("Name \t\t\t\t"));
1670 bfd_fprintf_vma (abfd, file, edt.name);
1671
1672 if ((edt.name >= adj) && (edt.name < adj + datasize))
1673 fprintf (file, " %.*s\n",
1674 (int) (datasize - (edt.name - adj)),
1675 data + edt.name - adj);
1676 else
1677 fprintf (file, "(outside .edata section)\n");
1678
1679 fprintf (file,
1680 _("Ordinal Base \t\t\t%ld\n"), edt.base);
1681
1682 fprintf (file,
1683 _("Number in:\n"));
1684
1685 fprintf (file,
1686 _("\tExport Address Table \t\t%08lx\n"),
1687 edt.num_functions);
1688
1689 fprintf (file,
1690 _("\t[Name Pointer/Ordinal] Table\t%08lx\n"), edt.num_names);
1691
1692 fprintf (file,
1693 _("Table Addresses\n"));
1694
1695 fprintf (file,
1696 _("\tExport Address Table \t\t"));
1697 bfd_fprintf_vma (abfd, file, edt.eat_addr);
1698 fprintf (file, "\n");
1699
1700 fprintf (file,
1701 _("\tName Pointer Table \t\t"));
1702 bfd_fprintf_vma (abfd, file, edt.npt_addr);
1703 fprintf (file, "\n");
1704
1705 fprintf (file,
1706 _("\tOrdinal Table \t\t\t"));
1707 bfd_fprintf_vma (abfd, file, edt.ot_addr);
1708 fprintf (file, "\n");
1709
1710 /* The next table to find is the Export Address Table. It's basically
1711 a list of pointers that either locate a function in this dll, or
1712 forward the call to another dll. Something like:
1713 typedef union
1714 {
1715 long export_rva;
1716 long forwarder_rva;
1717 } export_address_table_entry; */
1718
1719 fprintf (file,
1720 _("\nExport Address Table -- Ordinal Base %ld\n"),
1721 edt.base);
1722
1723 /* PR 17512: Handle corrupt PE binaries. */
1724 /* PR 17512 file: 140-165018-0.004. */
1725 if (edt.eat_addr - adj >= datasize
1726 /* PR 17512: file: 092b1829 */
1727 || (edt.num_functions + 1) * 4 < edt.num_functions
1728 || edt.eat_addr - adj + (edt.num_functions + 1) * 4 > datasize)
1729 fprintf (file, _("\tInvalid Export Address Table rva (0x%lx) or entry count (0x%lx)\n"),
1730 (long) edt.eat_addr,
1731 (long) edt.num_functions);
1732 else for (i = 0; i < edt.num_functions; ++i)
1733 {
1734 bfd_vma eat_member = bfd_get_32 (abfd,
1735 data + edt.eat_addr + (i * 4) - adj);
1736 if (eat_member == 0)
1737 continue;
1738
1739 if (eat_member - adj <= datasize)
1740 {
1741 /* This rva is to a name (forwarding function) in our section. */
1742 /* Should locate a function descriptor. */
1743 fprintf (file,
1744 "\t[%4ld] +base[%4ld] %04lx %s -- %.*s\n",
1745 (long) i,
1746 (long) (i + edt.base),
1747 (unsigned long) eat_member,
1748 _("Forwarder RVA"),
1749 (int)(datasize - (eat_member - adj)),
1750 data + eat_member - adj);
1751 }
1752 else
1753 {
1754 /* Should locate a function descriptor in the reldata section. */
1755 fprintf (file,
1756 "\t[%4ld] +base[%4ld] %04lx %s\n",
1757 (long) i,
1758 (long) (i + edt.base),
1759 (unsigned long) eat_member,
1760 _("Export RVA"));
1761 }
1762 }
1763
1764 /* The Export Name Pointer Table is paired with the Export Ordinal Table. */
1765 /* Dump them in parallel for clarity. */
1766 fprintf (file,
1767 _("\n[Ordinal/Name Pointer] Table\n"));
1768
1769 /* PR 17512: Handle corrupt PE binaries. */
1770 if (edt.npt_addr + (edt.num_names * 4) - adj >= datasize
1771 /* PR 17512: file: bb68816e. */
1772 || edt.num_names * 4 < edt.num_names
1773 || (data + edt.npt_addr - adj) < data)
1774 /* xgettext:c-format */
1775 fprintf (file, _("\tInvalid Name Pointer Table rva (0x%lx) or entry count (0x%lx)\n"),
1776 (long) edt.npt_addr,
1777 (long) edt.num_names);
1778 /* PR 17512: file: 140-147171-0.004. */
1779 else if (edt.ot_addr + (edt.num_names * 2) - adj >= datasize
1780 || data + edt.ot_addr - adj < data)
1781 /* xgettext:c-format */
1782 fprintf (file, _("\tInvalid Ordinal Table rva (0x%lx) or entry count (0x%lx)\n"),
1783 (long) edt.ot_addr,
1784 (long) edt.num_names);
1785 else for (i = 0; i < edt.num_names; ++i)
1786 {
1787 bfd_vma name_ptr;
1788 bfd_vma ord;
1789
1790 ord = bfd_get_16 (abfd, data + edt.ot_addr + (i * 2) - adj);
1791 name_ptr = bfd_get_32 (abfd, data + edt.npt_addr + (i * 4) - adj);
1792
1793 if ((name_ptr - adj) >= datasize)
1794 {
1795 /* xgettext:c-format */
1796 fprintf (file, _("\t[%4ld] <corrupt offset: %lx>\n"),
1797 (long) ord, (long) name_ptr);
1798 }
1799 else
1800 {
1801 char * name = (char *) data + name_ptr - adj;
1802
1803 fprintf (file, "\t[%4ld] %.*s\n", (long) ord,
1804 (int)((char *)(data + datasize) - name), name);
1805 }
1806 }
1807
1808 free (data);
1809
1810 return true;
1811 }
1812
1813 /* This really is architecture dependent. On IA-64, a .pdata entry
1814 consists of three dwords containing relative virtual addresses that
1815 specify the start and end address of the code range the entry
1816 covers and the address of the corresponding unwind info data.
1817
1818 On ARM and SH-4, a compressed PDATA structure is used :
1819 _IMAGE_CE_RUNTIME_FUNCTION_ENTRY, whereas MIPS is documented to use
1820 _IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY.
1821 See http://msdn2.microsoft.com/en-us/library/ms253988(VS.80).aspx .
1822
1823 This is the version for uncompressed data. */
1824
1825 static bool
1826 pe_print_pdata (bfd * abfd, void * vfile)
1827 {
1828 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
1829 # define PDATA_ROW_SIZE (3 * 8)
1830 #else
1831 # define PDATA_ROW_SIZE (5 * 4)
1832 #endif
1833 FILE *file = (FILE *) vfile;
1834 bfd_byte *data = 0;
1835 asection *section = bfd_get_section_by_name (abfd, ".pdata");
1836 bfd_size_type datasize = 0;
1837 bfd_size_type i;
1838 bfd_size_type start, stop;
1839 int onaline = PDATA_ROW_SIZE;
1840
1841 if (section == NULL
1842 || (section->flags & SEC_HAS_CONTENTS) == 0
1843 || coff_section_data (abfd, section) == NULL
1844 || pei_section_data (abfd, section) == NULL)
1845 return true;
1846
1847 stop = pei_section_data (abfd, section)->virt_size;
1848 if ((stop % onaline) != 0)
1849 fprintf (file,
1850 /* xgettext:c-format */
1851 _("warning, .pdata section size (%ld) is not a multiple of %d\n"),
1852 (long) stop, onaline);
1853
1854 fprintf (file,
1855 _("\nThe Function Table (interpreted .pdata section contents)\n"));
1856 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
1857 fprintf (file,
1858 _(" vma:\t\t\tBegin Address End Address Unwind Info\n"));
1859 #else
1860 fprintf (file, _("\
1861 vma:\t\tBegin End EH EH PrologEnd Exception\n\
1862 \t\tAddress Address Handler Data Address Mask\n"));
1863 #endif
1864
1865 datasize = section->size;
1866 if (datasize == 0)
1867 return true;
1868
1869 /* PR 17512: file: 002-193900-0.004. */
1870 if (datasize < stop)
1871 {
1872 /* xgettext:c-format */
1873 fprintf (file, _("Virtual size of .pdata section (%ld) larger than real size (%ld)\n"),
1874 (long) stop, (long) datasize);
1875 return false;
1876 }
1877
1878 if (! bfd_malloc_and_get_section (abfd, section, &data))
1879 {
1880 free (data);
1881 return false;
1882 }
1883
1884 start = 0;
1885
1886 for (i = start; i < stop; i += onaline)
1887 {
1888 bfd_vma begin_addr;
1889 bfd_vma end_addr;
1890 bfd_vma eh_handler;
1891 bfd_vma eh_data;
1892 bfd_vma prolog_end_addr;
1893 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64)
1894 int em_data;
1895 #endif
1896
1897 if (i + PDATA_ROW_SIZE > stop)
1898 break;
1899
1900 begin_addr = GET_PDATA_ENTRY (abfd, data + i );
1901 end_addr = GET_PDATA_ENTRY (abfd, data + i + 4);
1902 eh_handler = GET_PDATA_ENTRY (abfd, data + i + 8);
1903 eh_data = GET_PDATA_ENTRY (abfd, data + i + 12);
1904 prolog_end_addr = GET_PDATA_ENTRY (abfd, data + i + 16);
1905
1906 if (begin_addr == 0 && end_addr == 0 && eh_handler == 0
1907 && eh_data == 0 && prolog_end_addr == 0)
1908 /* We are probably into the padding of the section now. */
1909 break;
1910
1911 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64)
1912 em_data = ((eh_handler & 0x1) << 2) | (prolog_end_addr & 0x3);
1913 #endif
1914 eh_handler &= ~(bfd_vma) 0x3;
1915 prolog_end_addr &= ~(bfd_vma) 0x3;
1916
1917 fputc (' ', file);
1918 bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
1919 bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
1920 bfd_fprintf_vma (abfd, file, end_addr); fputc (' ', file);
1921 bfd_fprintf_vma (abfd, file, eh_handler);
1922 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64)
1923 fputc (' ', file);
1924 bfd_fprintf_vma (abfd, file, eh_data); fputc (' ', file);
1925 bfd_fprintf_vma (abfd, file, prolog_end_addr);
1926 fprintf (file, " %x", em_data);
1927 #endif
1928 fprintf (file, "\n");
1929 }
1930
1931 free (data);
1932
1933 return true;
1934 #undef PDATA_ROW_SIZE
1935 }
1936
1937 typedef struct sym_cache
1938 {
1939 int symcount;
1940 asymbol ** syms;
1941 } sym_cache;
1942
1943 static asymbol **
1944 slurp_symtab (bfd *abfd, sym_cache *psc)
1945 {
1946 asymbol ** sy = NULL;
1947 long storage;
1948
1949 if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
1950 {
1951 psc->symcount = 0;
1952 return NULL;
1953 }
1954
1955 storage = bfd_get_symtab_upper_bound (abfd);
1956 if (storage < 0)
1957 return NULL;
1958 if (storage)
1959 {
1960 sy = (asymbol **) bfd_malloc (storage);
1961 if (sy == NULL)
1962 return NULL;
1963 }
1964
1965 psc->symcount = bfd_canonicalize_symtab (abfd, sy);
1966 if (psc->symcount < 0)
1967 return NULL;
1968 return sy;
1969 }
1970
1971 static const char *
1972 my_symbol_for_address (bfd *abfd, bfd_vma func, sym_cache *psc)
1973 {
1974 int i;
1975
1976 if (psc->syms == 0)
1977 psc->syms = slurp_symtab (abfd, psc);
1978
1979 for (i = 0; i < psc->symcount; i++)
1980 {
1981 if (psc->syms[i]->section->vma + psc->syms[i]->value == func)
1982 return psc->syms[i]->name;
1983 }
1984
1985 return NULL;
1986 }
1987
1988 static void
1989 cleanup_syms (sym_cache *psc)
1990 {
1991 psc->symcount = 0;
1992 free (psc->syms);
1993 psc->syms = NULL;
1994 }
1995
1996 /* This is the version for "compressed" pdata. */
1997
1998 bool
1999 _bfd_XX_print_ce_compressed_pdata (bfd * abfd, void * vfile)
2000 {
2001 # define PDATA_ROW_SIZE (2 * 4)
2002 FILE *file = (FILE *) vfile;
2003 bfd_byte *data = NULL;
2004 asection *section = bfd_get_section_by_name (abfd, ".pdata");
2005 bfd_size_type datasize = 0;
2006 bfd_size_type i;
2007 bfd_size_type start, stop;
2008 int onaline = PDATA_ROW_SIZE;
2009 struct sym_cache cache = {0, 0} ;
2010
2011 if (section == NULL
2012 || (section->flags & SEC_HAS_CONTENTS) == 0
2013 || coff_section_data (abfd, section) == NULL
2014 || pei_section_data (abfd, section) == NULL)
2015 return true;
2016
2017 stop = pei_section_data (abfd, section)->virt_size;
2018 if ((stop % onaline) != 0)
2019 fprintf (file,
2020 /* xgettext:c-format */
2021 _("warning, .pdata section size (%ld) is not a multiple of %d\n"),
2022 (long) stop, onaline);
2023
2024 fprintf (file,
2025 _("\nThe Function Table (interpreted .pdata section contents)\n"));
2026
2027 fprintf (file, _("\
2028 vma:\t\tBegin Prolog Function Flags Exception EH\n\
2029 \t\tAddress Length Length 32b exc Handler Data\n"));
2030
2031 datasize = section->size;
2032 if (datasize == 0)
2033 return true;
2034
2035 if (! bfd_malloc_and_get_section (abfd, section, &data))
2036 {
2037 free (data);
2038 return false;
2039 }
2040
2041 start = 0;
2042 if (stop > datasize)
2043 stop = datasize;
2044
2045 for (i = start; i < stop; i += onaline)
2046 {
2047 bfd_vma begin_addr;
2048 bfd_vma other_data;
2049 bfd_vma prolog_length, function_length;
2050 int flag32bit, exception_flag;
2051 asection *tsection;
2052
2053 if (i + PDATA_ROW_SIZE > stop)
2054 break;
2055
2056 begin_addr = GET_PDATA_ENTRY (abfd, data + i );
2057 other_data = GET_PDATA_ENTRY (abfd, data + i + 4);
2058
2059 if (begin_addr == 0 && other_data == 0)
2060 /* We are probably into the padding of the section now. */
2061 break;
2062
2063 prolog_length = (other_data & 0x000000FF);
2064 function_length = (other_data & 0x3FFFFF00) >> 8;
2065 flag32bit = (int)((other_data & 0x40000000) >> 30);
2066 exception_flag = (int)((other_data & 0x80000000) >> 31);
2067
2068 fputc (' ', file);
2069 bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
2070 bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
2071 bfd_fprintf_vma (abfd, file, prolog_length); fputc (' ', file);
2072 bfd_fprintf_vma (abfd, file, function_length); fputc (' ', file);
2073 fprintf (file, "%2d %2d ", flag32bit, exception_flag);
2074
2075 /* Get the exception handler's address and the data passed from the
2076 .text section. This is really the data that belongs with the .pdata
2077 but got "compressed" out for the ARM and SH4 architectures. */
2078 tsection = bfd_get_section_by_name (abfd, ".text");
2079 if (tsection && coff_section_data (abfd, tsection)
2080 && pei_section_data (abfd, tsection))
2081 {
2082 bfd_vma eh_off = (begin_addr - 8) - tsection->vma;
2083 bfd_byte *tdata;
2084
2085 tdata = (bfd_byte *) bfd_malloc (8);
2086 if (tdata)
2087 {
2088 if (bfd_get_section_contents (abfd, tsection, tdata, eh_off, 8))
2089 {
2090 bfd_vma eh, eh_data;
2091
2092 eh = bfd_get_32 (abfd, tdata);
2093 eh_data = bfd_get_32 (abfd, tdata + 4);
2094 fprintf (file, "%08x ", (unsigned int) eh);
2095 fprintf (file, "%08x", (unsigned int) eh_data);
2096 if (eh != 0)
2097 {
2098 const char *s = my_symbol_for_address (abfd, eh, &cache);
2099
2100 if (s)
2101 fprintf (file, " (%s) ", s);
2102 }
2103 }
2104 free (tdata);
2105 }
2106 }
2107
2108 fprintf (file, "\n");
2109 }
2110
2111 free (data);
2112
2113 cleanup_syms (& cache);
2114
2115 return true;
2116 #undef PDATA_ROW_SIZE
2117 }
2118
2119 \f
2120 #define IMAGE_REL_BASED_HIGHADJ 4
2121 static const char * const tbl[] =
2122 {
2123 "ABSOLUTE",
2124 "HIGH",
2125 "LOW",
2126 "HIGHLOW",
2127 "HIGHADJ",
2128 "MIPS_JMPADDR",
2129 "SECTION",
2130 "REL32",
2131 "RESERVED1",
2132 "MIPS_JMPADDR16",
2133 "DIR64",
2134 "HIGH3ADJ",
2135 "UNKNOWN", /* MUST be last. */
2136 };
2137
2138 static bool
2139 pe_print_reloc (bfd * abfd, void * vfile)
2140 {
2141 FILE *file = (FILE *) vfile;
2142 bfd_byte *data = 0;
2143 asection *section = bfd_get_section_by_name (abfd, ".reloc");
2144 bfd_byte *p, *end;
2145
2146 if (section == NULL
2147 || section->size == 0
2148 || (section->flags & SEC_HAS_CONTENTS) == 0)
2149 return true;
2150
2151 fprintf (file,
2152 _("\n\nPE File Base Relocations (interpreted .reloc section contents)\n"));
2153
2154 if (! bfd_malloc_and_get_section (abfd, section, &data))
2155 {
2156 free (data);
2157 return false;
2158 }
2159
2160 p = data;
2161 end = data + section->size;
2162 while (p + 8 <= end)
2163 {
2164 int j;
2165 bfd_vma virtual_address;
2166 unsigned long number, size;
2167 bfd_byte *chunk_end;
2168
2169 /* The .reloc section is a sequence of blocks, with a header consisting
2170 of two 32 bit quantities, followed by a number of 16 bit entries. */
2171 virtual_address = bfd_get_32 (abfd, p);
2172 size = bfd_get_32 (abfd, p + 4);
2173 p += 8;
2174 number = (size - 8) / 2;
2175
2176 if (size == 0)
2177 break;
2178
2179 fprintf (file,
2180 /* xgettext:c-format */
2181 _("\nVirtual Address: %08lx Chunk size %ld (0x%lx) Number of fixups %ld\n"),
2182 (unsigned long) virtual_address, size, size, number);
2183
2184 chunk_end = p - 8 + size;
2185 if (chunk_end > end)
2186 chunk_end = end;
2187 j = 0;
2188 while (p + 2 <= chunk_end)
2189 {
2190 unsigned short e = bfd_get_16 (abfd, p);
2191 unsigned int t = (e & 0xF000) >> 12;
2192 int off = e & 0x0FFF;
2193
2194 if (t >= sizeof (tbl) / sizeof (tbl[0]))
2195 t = (sizeof (tbl) / sizeof (tbl[0])) - 1;
2196
2197 fprintf (file,
2198 /* xgettext:c-format */
2199 _("\treloc %4d offset %4x [%4lx] %s"),
2200 j, off, (unsigned long) (off + virtual_address), tbl[t]);
2201
2202 p += 2;
2203 j++;
2204
2205 /* HIGHADJ takes an argument, - the next record *is* the
2206 low 16 bits of addend. */
2207 if (t == IMAGE_REL_BASED_HIGHADJ && p + 2 <= chunk_end)
2208 {
2209 fprintf (file, " (%4x)", (unsigned int) bfd_get_16 (abfd, p));
2210 p += 2;
2211 j++;
2212 }
2213
2214 fprintf (file, "\n");
2215 }
2216 }
2217
2218 free (data);
2219
2220 return true;
2221 }
2222 \f
2223 /* A data structure describing the regions of a .rsrc section.
2224 Some fields are filled in as the section is parsed. */
2225
2226 typedef struct rsrc_regions
2227 {
2228 bfd_byte * section_start;
2229 bfd_byte * section_end;
2230 bfd_byte * strings_start;
2231 bfd_byte * resource_start;
2232 } rsrc_regions;
2233
2234 static bfd_byte *
2235 rsrc_print_resource_directory (FILE * , bfd *, unsigned int, bfd_byte *,
2236 rsrc_regions *, bfd_vma);
2237
2238 /* Print the resource entry at DATA, with the text indented by INDENT.
2239 Recusively calls rsrc_print_resource_directory to print the contents
2240 of directory entries.
2241 Returns the address of the end of the data associated with the entry
2242 or section_end + 1 upon failure. */
2243
2244 static bfd_byte *
2245 rsrc_print_resource_entries (FILE *file,
2246 bfd *abfd,
2247 unsigned int indent,
2248 bool is_name,
2249 bfd_byte *data,
2250 rsrc_regions *regions,
2251 bfd_vma rva_bias)
2252 {
2253 unsigned long entry, addr, size;
2254 bfd_byte * leaf;
2255
2256 if (data + 8 >= regions->section_end)
2257 return regions->section_end + 1;
2258
2259 /* xgettext:c-format */
2260 fprintf (file, _("%03x %*.s Entry: "), (int)(data - regions->section_start), indent, " ");
2261
2262 entry = (unsigned long) bfd_get_32 (abfd, data);
2263 if (is_name)
2264 {
2265 bfd_byte * name;
2266
2267 /* Note - the documentation says that this field is an RVA value
2268 but windres appears to produce a section relative offset with
2269 the top bit set. Support both styles for now. */
2270 if (HighBitSet (entry))
2271 name = regions->section_start + WithoutHighBit (entry);
2272 else
2273 name = regions->section_start + entry - rva_bias;
2274
2275 if (name + 2 < regions->section_end && name > regions->section_start)
2276 {
2277 unsigned int len;
2278
2279 if (regions->strings_start == NULL)
2280 regions->strings_start = name;
2281
2282 len = bfd_get_16 (abfd, name);
2283
2284 fprintf (file, _("name: [val: %08lx len %d]: "), entry, len);
2285
2286 if (name + 2 + len * 2 < regions->section_end)
2287 {
2288 /* This strange loop is to cope with multibyte characters. */
2289 while (len --)
2290 {
2291 char c;
2292
2293 name += 2;
2294 c = * name;
2295 /* Avoid printing control characters. */
2296 if (c > 0 && c < 32)
2297 fprintf (file, "^%c", c + 64);
2298 else
2299 fprintf (file, "%.1s", name);
2300 }
2301 }
2302 else
2303 {
2304 fprintf (file, _("<corrupt string length: %#x>\n"), len);
2305 /* PR binutils/17512: Do not try to continue decoding a
2306 corrupted resource section. It is likely to end up with
2307 reams of extraneous output. FIXME: We could probably
2308 continue if we disable the printing of strings... */
2309 return regions->section_end + 1;
2310 }
2311 }
2312 else
2313 {
2314 fprintf (file, _("<corrupt string offset: %#lx>\n"), entry);
2315 return regions->section_end + 1;
2316 }
2317 }
2318 else
2319 fprintf (file, _("ID: %#08lx"), entry);
2320
2321 entry = (long) bfd_get_32 (abfd, data + 4);
2322 fprintf (file, _(", Value: %#08lx\n"), entry);
2323
2324 if (HighBitSet (entry))
2325 {
2326 data = regions->section_start + WithoutHighBit (entry);
2327 if (data <= regions->section_start || data > regions->section_end)
2328 return regions->section_end + 1;
2329
2330 /* FIXME: PR binutils/17512: A corrupt file could contain a loop
2331 in the resource table. We need some way to detect this. */
2332 return rsrc_print_resource_directory (file, abfd, indent + 1, data,
2333 regions, rva_bias);
2334 }
2335
2336 leaf = regions->section_start + entry;
2337
2338 if (leaf + 16 >= regions->section_end
2339 /* PR 17512: file: 055dff7e. */
2340 || leaf < regions->section_start)
2341 return regions->section_end + 1;
2342
2343 /* xgettext:c-format */
2344 fprintf (file, _("%03x %*.s Leaf: Addr: %#08lx, Size: %#08lx, Codepage: %d\n"),
2345 (int) (entry), indent, " ",
2346 addr = (long) bfd_get_32 (abfd, leaf),
2347 size = (long) bfd_get_32 (abfd, leaf + 4),
2348 (int) bfd_get_32 (abfd, leaf + 8));
2349
2350 /* Check that the reserved entry is 0. */
2351 if (bfd_get_32 (abfd, leaf + 12) != 0
2352 /* And that the data address/size is valid too. */
2353 || (regions->section_start + (addr - rva_bias) + size > regions->section_end))
2354 return regions->section_end + 1;
2355
2356 if (regions->resource_start == NULL)
2357 regions->resource_start = regions->section_start + (addr - rva_bias);
2358
2359 return regions->section_start + (addr - rva_bias) + size;
2360 }
2361
2362 #define max(a,b) ((a) > (b) ? (a) : (b))
2363 #define min(a,b) ((a) < (b) ? (a) : (b))
2364
2365 static bfd_byte *
2366 rsrc_print_resource_directory (FILE * file,
2367 bfd * abfd,
2368 unsigned int indent,
2369 bfd_byte * data,
2370 rsrc_regions * regions,
2371 bfd_vma rva_bias)
2372 {
2373 unsigned int num_names, num_ids;
2374 bfd_byte * highest_data = data;
2375
2376 if (data + 16 >= regions->section_end)
2377 return regions->section_end + 1;
2378
2379 fprintf (file, "%03x %*.s ", (int)(data - regions->section_start), indent, " ");
2380 switch (indent)
2381 {
2382 case 0: fprintf (file, "Type"); break;
2383 case 2: fprintf (file, "Name"); break;
2384 case 4: fprintf (file, "Language"); break;
2385 default:
2386 fprintf (file, _("<unknown directory type: %d>\n"), indent);
2387 /* FIXME: For now we end the printing here. If in the
2388 future more directory types are added to the RSRC spec
2389 then we will need to change this. */
2390 return regions->section_end + 1;
2391 }
2392
2393 /* xgettext:c-format */
2394 fprintf (file, _(" Table: Char: %d, Time: %08lx, Ver: %d/%d, Num Names: %d, IDs: %d\n"),
2395 (int) bfd_get_32 (abfd, data),
2396 (long) bfd_get_32 (abfd, data + 4),
2397 (int) bfd_get_16 (abfd, data + 8),
2398 (int) bfd_get_16 (abfd, data + 10),
2399 num_names = (int) bfd_get_16 (abfd, data + 12),
2400 num_ids = (int) bfd_get_16 (abfd, data + 14));
2401 data += 16;
2402
2403 while (num_names --)
2404 {
2405 bfd_byte * entry_end;
2406
2407 entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, true,
2408 data, regions, rva_bias);
2409 data += 8;
2410 highest_data = max (highest_data, entry_end);
2411 if (entry_end >= regions->section_end)
2412 return entry_end;
2413 }
2414
2415 while (num_ids --)
2416 {
2417 bfd_byte * entry_end;
2418
2419 entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, false,
2420 data, regions, rva_bias);
2421 data += 8;
2422 highest_data = max (highest_data, entry_end);
2423 if (entry_end >= regions->section_end)
2424 return entry_end;
2425 }
2426
2427 return max (highest_data, data);
2428 }
2429
2430 /* Display the contents of a .rsrc section. We do not try to
2431 reproduce the resources, windres does that. Instead we dump
2432 the tables in a human readable format. */
2433
2434 static bool
2435 rsrc_print_section (bfd * abfd, void * vfile)
2436 {
2437 bfd_vma rva_bias;
2438 pe_data_type * pe;
2439 FILE * file = (FILE *) vfile;
2440 bfd_size_type datasize;
2441 asection * section;
2442 bfd_byte * data;
2443 rsrc_regions regions;
2444
2445 pe = pe_data (abfd);
2446 if (pe == NULL)
2447 return true;
2448
2449 section = bfd_get_section_by_name (abfd, ".rsrc");
2450 if (section == NULL)
2451 return true;
2452 if (!(section->flags & SEC_HAS_CONTENTS))
2453 return true;
2454
2455 datasize = section->size;
2456 if (datasize == 0)
2457 return true;
2458
2459 rva_bias = section->vma - pe->pe_opthdr.ImageBase;
2460
2461 if (! bfd_malloc_and_get_section (abfd, section, & data))
2462 {
2463 free (data);
2464 return false;
2465 }
2466
2467 regions.section_start = data;
2468 regions.section_end = data + datasize;
2469 regions.strings_start = NULL;
2470 regions.resource_start = NULL;
2471
2472 fflush (file);
2473 fprintf (file, "\nThe .rsrc Resource Directory section:\n");
2474
2475 while (data < regions.section_end)
2476 {
2477 bfd_byte * p = data;
2478
2479 data = rsrc_print_resource_directory (file, abfd, 0, data, & regions, rva_bias);
2480
2481 if (data == regions.section_end + 1)
2482 fprintf (file, _("Corrupt .rsrc section detected!\n"));
2483 else
2484 {
2485 /* Align data before continuing. */
2486 int align = (1 << section->alignment_power) - 1;
2487
2488 data = (bfd_byte *) (((ptrdiff_t) (data + align)) & ~ align);
2489 rva_bias += data - p;
2490
2491 /* For reasons that are unclear .rsrc sections are sometimes created
2492 aligned to a 1^3 boundary even when their alignment is set at
2493 1^2. Catch that case here before we issue a spurious warning
2494 message. */
2495 if (data == (regions.section_end - 4))
2496 data = regions.section_end;
2497 else if (data < regions.section_end)
2498 {
2499 /* If the extra data is all zeros then do not complain.
2500 This is just padding so that the section meets the
2501 page size requirements. */
2502 while (++ data < regions.section_end)
2503 if (*data != 0)
2504 break;
2505 if (data < regions.section_end)
2506 fprintf (file, _("\nWARNING: Extra data in .rsrc section - it will be ignored by Windows:\n"));
2507 }
2508 }
2509 }
2510
2511 if (regions.strings_start != NULL)
2512 fprintf (file, _(" String table starts at offset: %#03x\n"),
2513 (int) (regions.strings_start - regions.section_start));
2514 if (regions.resource_start != NULL)
2515 fprintf (file, _(" Resources start at offset: %#03x\n"),
2516 (int) (regions.resource_start - regions.section_start));
2517
2518 free (regions.section_start);
2519 return true;
2520 }
2521
2522 #define IMAGE_NUMBEROF_DEBUG_TYPES 17
2523
2524 static char * debug_type_names[IMAGE_NUMBEROF_DEBUG_TYPES] =
2525 {
2526 "Unknown",
2527 "COFF",
2528 "CodeView",
2529 "FPO",
2530 "Misc",
2531 "Exception",
2532 "Fixup",
2533 "OMAP-to-SRC",
2534 "OMAP-from-SRC",
2535 "Borland",
2536 "Reserved",
2537 "CLSID",
2538 "Feature",
2539 "CoffGrp",
2540 "ILTCG",
2541 "MPX",
2542 "Repro",
2543 };
2544
2545 static bool
2546 pe_print_debugdata (bfd * abfd, void * vfile)
2547 {
2548 FILE *file = (FILE *) vfile;
2549 pe_data_type *pe = pe_data (abfd);
2550 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
2551 asection *section;
2552 bfd_byte *data = 0;
2553 bfd_size_type dataoff;
2554 unsigned int i, j;
2555
2556 bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress;
2557 bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size;
2558
2559 if (size == 0)
2560 return true;
2561
2562 addr += extra->ImageBase;
2563 for (section = abfd->sections; section != NULL; section = section->next)
2564 {
2565 if ((addr >= section->vma) && (addr < (section->vma + section->size)))
2566 break;
2567 }
2568
2569 if (section == NULL)
2570 {
2571 fprintf (file,
2572 _("\nThere is a debug directory, but the section containing it could not be found\n"));
2573 return true;
2574 }
2575 else if (!(section->flags & SEC_HAS_CONTENTS))
2576 {
2577 fprintf (file,
2578 _("\nThere is a debug directory in %s, but that section has no contents\n"),
2579 section->name);
2580 return true;
2581 }
2582 else if (section->size < size)
2583 {
2584 fprintf (file,
2585 _("\nError: section %s contains the debug data starting address but it is too small\n"),
2586 section->name);
2587 return false;
2588 }
2589
2590 fprintf (file, _("\nThere is a debug directory in %s at 0x%lx\n\n"),
2591 section->name, (unsigned long) addr);
2592
2593 dataoff = addr - section->vma;
2594
2595 if (size > (section->size - dataoff))
2596 {
2597 fprintf (file, _("The debug data size field in the data directory is too big for the section"));
2598 return false;
2599 }
2600
2601 fprintf (file,
2602 _("Type Size Rva Offset\n"));
2603
2604 /* Read the whole section. */
2605 if (!bfd_malloc_and_get_section (abfd, section, &data))
2606 {
2607 free (data);
2608 return false;
2609 }
2610
2611 for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
2612 {
2613 const char *type_name;
2614 struct external_IMAGE_DEBUG_DIRECTORY *ext
2615 = &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i];
2616 struct internal_IMAGE_DEBUG_DIRECTORY idd;
2617
2618 _bfd_XXi_swap_debugdir_in (abfd, ext, &idd);
2619
2620 if ((idd.Type) >= IMAGE_NUMBEROF_DEBUG_TYPES)
2621 type_name = debug_type_names[0];
2622 else
2623 type_name = debug_type_names[idd.Type];
2624
2625 fprintf (file, " %2ld %14s %08lx %08lx %08lx\n",
2626 idd.Type, type_name, idd.SizeOfData,
2627 idd.AddressOfRawData, idd.PointerToRawData);
2628
2629 if (idd.Type == PE_IMAGE_DEBUG_TYPE_CODEVIEW)
2630 {
2631 char signature[CV_INFO_SIGNATURE_LENGTH * 2 + 1];
2632 /* PR 17512: file: 065-29434-0.001:0.1
2633 We need to use a 32-bit aligned buffer
2634 to safely read in a codeview record. */
2635 char buffer[256 + 1] ATTRIBUTE_ALIGNED_ALIGNOF (CODEVIEW_INFO);
2636 char *pdb;
2637
2638 CODEVIEW_INFO *cvinfo = (CODEVIEW_INFO *) buffer;
2639
2640 /* The debug entry doesn't have to have to be in a section,
2641 in which case AddressOfRawData is 0, so always use PointerToRawData. */
2642 if (!_bfd_XXi_slurp_codeview_record (abfd, (file_ptr) idd.PointerToRawData,
2643 idd.SizeOfData, cvinfo, &pdb))
2644 continue;
2645
2646 for (j = 0; j < cvinfo->SignatureLength; j++)
2647 sprintf (&signature[j*2], "%02x", cvinfo->Signature[j] & 0xff);
2648
2649 /* xgettext:c-format */
2650 fprintf (file, _("(format %c%c%c%c signature %s age %ld pdb %s)\n"),
2651 buffer[0], buffer[1], buffer[2], buffer[3],
2652 signature, cvinfo->Age, pdb[0] ? pdb : "(none)");
2653
2654 free (pdb);
2655 }
2656 }
2657
2658 free(data);
2659
2660 if (size % sizeof (struct external_IMAGE_DEBUG_DIRECTORY) != 0)
2661 fprintf (file,
2662 _("The debug directory size is not a multiple of the debug directory entry size\n"));
2663
2664 return true;
2665 }
2666
2667 static bool
2668 pe_is_repro (bfd * abfd)
2669 {
2670 pe_data_type *pe = pe_data (abfd);
2671 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
2672 asection *section;
2673 bfd_byte *data = 0;
2674 bfd_size_type dataoff;
2675 unsigned int i;
2676 bool res = false;
2677
2678 bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress;
2679 bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size;
2680
2681 if (size == 0)
2682 return false;
2683
2684 addr += extra->ImageBase;
2685 for (section = abfd->sections; section != NULL; section = section->next)
2686 {
2687 if ((addr >= section->vma) && (addr < (section->vma + section->size)))
2688 break;
2689 }
2690
2691 if ((section == NULL)
2692 || (!(section->flags & SEC_HAS_CONTENTS))
2693 || (section->size < size))
2694 {
2695 return false;
2696 }
2697
2698 dataoff = addr - section->vma;
2699
2700 if (size > (section->size - dataoff))
2701 {
2702 return false;
2703 }
2704
2705 if (!bfd_malloc_and_get_section (abfd, section, &data))
2706 {
2707 free (data);
2708 return false;
2709 }
2710
2711 for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
2712 {
2713 struct external_IMAGE_DEBUG_DIRECTORY *ext
2714 = &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i];
2715 struct internal_IMAGE_DEBUG_DIRECTORY idd;
2716
2717 _bfd_XXi_swap_debugdir_in (abfd, ext, &idd);
2718
2719 if (idd.Type == PE_IMAGE_DEBUG_TYPE_REPRO)
2720 {
2721 res = true;
2722 break;
2723 }
2724 }
2725
2726 free(data);
2727
2728 return res;
2729 }
2730
2731 /* Print out the program headers. */
2732
2733 bool
2734 _bfd_XX_print_private_bfd_data_common (bfd * abfd, void * vfile)
2735 {
2736 FILE *file = (FILE *) vfile;
2737 int j;
2738 pe_data_type *pe = pe_data (abfd);
2739 struct internal_extra_pe_aouthdr *i = &pe->pe_opthdr;
2740 const char *subsystem_name = NULL;
2741 const char *name;
2742
2743 /* The MS dumpbin program reportedly ands with 0xff0f before
2744 printing the characteristics field. Not sure why. No reason to
2745 emulate it here. */
2746 fprintf (file, _("\nCharacteristics 0x%x\n"), pe->real_flags);
2747 #undef PF
2748 #define PF(x, y) if (pe->real_flags & x) { fprintf (file, "\t%s\n", y); }
2749 PF (IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped");
2750 PF (IMAGE_FILE_EXECUTABLE_IMAGE, "executable");
2751 PF (IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped");
2752 PF (IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped");
2753 PF (IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware");
2754 PF (IMAGE_FILE_BYTES_REVERSED_LO, "little endian");
2755 PF (IMAGE_FILE_32BIT_MACHINE, "32 bit words");
2756 PF (IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed");
2757 PF (IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, "copy to swap file if on removable media");
2758 PF (IMAGE_FILE_NET_RUN_FROM_SWAP, "copy to swap file if on network media");
2759 PF (IMAGE_FILE_SYSTEM, "system file");
2760 PF (IMAGE_FILE_DLL, "DLL");
2761 PF (IMAGE_FILE_UP_SYSTEM_ONLY, "run only on uniprocessor machine");
2762 PF (IMAGE_FILE_BYTES_REVERSED_HI, "big endian");
2763 #undef PF
2764
2765 /*
2766 If a PE_IMAGE_DEBUG_TYPE_REPRO entry is present in the debug directory, the
2767 timestamp is to be interpreted as the hash of a reproducible build.
2768 */
2769 if (pe_is_repro (abfd))
2770 {
2771 fprintf (file, "\nTime/Date\t\t%08lx", pe->coff.timestamp);
2772 fprintf (file, "\t(This is a reproducible build file hash, not a timestamp)\n");
2773 }
2774 else
2775 {
2776 /* ctime implies '\n'. */
2777 time_t t = pe->coff.timestamp;
2778 fprintf (file, "\nTime/Date\t\t%s", ctime (&t));
2779 }
2780
2781 #ifndef IMAGE_NT_OPTIONAL_HDR_MAGIC
2782 # define IMAGE_NT_OPTIONAL_HDR_MAGIC 0x10b
2783 #endif
2784 #ifndef IMAGE_NT_OPTIONAL_HDR64_MAGIC
2785 # define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
2786 #endif
2787 #ifndef IMAGE_NT_OPTIONAL_HDRROM_MAGIC
2788 # define IMAGE_NT_OPTIONAL_HDRROM_MAGIC 0x107
2789 #endif
2790
2791 switch (i->Magic)
2792 {
2793 case IMAGE_NT_OPTIONAL_HDR_MAGIC:
2794 name = "PE32";
2795 break;
2796 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
2797 name = "PE32+";
2798 break;
2799 case IMAGE_NT_OPTIONAL_HDRROM_MAGIC:
2800 name = "ROM";
2801 break;
2802 default:
2803 name = NULL;
2804 break;
2805 }
2806 fprintf (file, "Magic\t\t\t%04x", i->Magic);
2807 if (name)
2808 fprintf (file, "\t(%s)",name);
2809 fprintf (file, "\nMajorLinkerVersion\t%d\n", i->MajorLinkerVersion);
2810 fprintf (file, "MinorLinkerVersion\t%d\n", i->MinorLinkerVersion);
2811 fprintf (file, "SizeOfCode\t\t");
2812 bfd_fprintf_vma (abfd, file, i->SizeOfCode);
2813 fprintf (file, "\nSizeOfInitializedData\t");
2814 bfd_fprintf_vma (abfd, file, i->SizeOfInitializedData);
2815 fprintf (file, "\nSizeOfUninitializedData\t");
2816 bfd_fprintf_vma (abfd, file, i->SizeOfUninitializedData);
2817 fprintf (file, "\nAddressOfEntryPoint\t");
2818 bfd_fprintf_vma (abfd, file, i->AddressOfEntryPoint);
2819 fprintf (file, "\nBaseOfCode\t\t");
2820 bfd_fprintf_vma (abfd, file, i->BaseOfCode);
2821 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
2822 /* PE32+ does not have BaseOfData member! */
2823 fprintf (file, "\nBaseOfData\t\t");
2824 bfd_fprintf_vma (abfd, file, i->BaseOfData);
2825 #endif
2826
2827 fprintf (file, "\nImageBase\t\t");
2828 bfd_fprintf_vma (abfd, file, i->ImageBase);
2829 fprintf (file, "\nSectionAlignment\t%08x\n", i->SectionAlignment);
2830 fprintf (file, "FileAlignment\t\t%08x\n", i->FileAlignment);
2831 fprintf (file, "MajorOSystemVersion\t%d\n", i->MajorOperatingSystemVersion);
2832 fprintf (file, "MinorOSystemVersion\t%d\n", i->MinorOperatingSystemVersion);
2833 fprintf (file, "MajorImageVersion\t%d\n", i->MajorImageVersion);
2834 fprintf (file, "MinorImageVersion\t%d\n", i->MinorImageVersion);
2835 fprintf (file, "MajorSubsystemVersion\t%d\n", i->MajorSubsystemVersion);
2836 fprintf (file, "MinorSubsystemVersion\t%d\n", i->MinorSubsystemVersion);
2837 fprintf (file, "Win32Version\t\t%08x\n", i->Reserved1);
2838 fprintf (file, "SizeOfImage\t\t%08x\n", i->SizeOfImage);
2839 fprintf (file, "SizeOfHeaders\t\t%08x\n", i->SizeOfHeaders);
2840 fprintf (file, "CheckSum\t\t%08x\n", i->CheckSum);
2841
2842 switch (i->Subsystem)
2843 {
2844 case IMAGE_SUBSYSTEM_UNKNOWN:
2845 subsystem_name = "unspecified";
2846 break;
2847 case IMAGE_SUBSYSTEM_NATIVE:
2848 subsystem_name = "NT native";
2849 break;
2850 case IMAGE_SUBSYSTEM_WINDOWS_GUI:
2851 subsystem_name = "Windows GUI";
2852 break;
2853 case IMAGE_SUBSYSTEM_WINDOWS_CUI:
2854 subsystem_name = "Windows CUI";
2855 break;
2856 case IMAGE_SUBSYSTEM_POSIX_CUI:
2857 subsystem_name = "POSIX CUI";
2858 break;
2859 case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
2860 subsystem_name = "Wince CUI";
2861 break;
2862 /* These are from UEFI Platform Initialization Specification 1.1. */
2863 case IMAGE_SUBSYSTEM_EFI_APPLICATION:
2864 subsystem_name = "EFI application";
2865 break;
2866 case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
2867 subsystem_name = "EFI boot service driver";
2868 break;
2869 case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
2870 subsystem_name = "EFI runtime driver";
2871 break;
2872 case IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
2873 subsystem_name = "SAL runtime driver";
2874 break;
2875 /* This is from revision 8.0 of the MS PE/COFF spec */
2876 case IMAGE_SUBSYSTEM_XBOX:
2877 subsystem_name = "XBOX";
2878 break;
2879 /* Added default case for clarity - subsystem_name is NULL anyway. */
2880 default:
2881 subsystem_name = NULL;
2882 }
2883
2884 fprintf (file, "Subsystem\t\t%08x", i->Subsystem);
2885 if (subsystem_name)
2886 fprintf (file, "\t(%s)", subsystem_name);
2887 fprintf (file, "\nDllCharacteristics\t%08x\n", i->DllCharacteristics);
2888 if (i->DllCharacteristics)
2889 {
2890 unsigned short dllch = i->DllCharacteristics;
2891 const char *indent = "\t\t\t\t\t";
2892
2893 if (dllch & IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA)
2894 fprintf (file, "%sHIGH_ENTROPY_VA\n", indent);
2895 if (dllch & IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE)
2896 fprintf (file, "%sDYNAMIC_BASE\n", indent);
2897 if (dllch & IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY)
2898 fprintf (file, "%sFORCE_INTEGRITY\n", indent);
2899 if (dllch & IMAGE_DLL_CHARACTERISTICS_NX_COMPAT)
2900 fprintf (file, "%sNX_COMPAT\n", indent);
2901 if (dllch & IMAGE_DLLCHARACTERISTICS_NO_ISOLATION)
2902 fprintf (file, "%sNO_ISOLATION\n", indent);
2903 if (dllch & IMAGE_DLLCHARACTERISTICS_NO_SEH)
2904 fprintf (file, "%sNO_SEH\n", indent);
2905 if (dllch & IMAGE_DLLCHARACTERISTICS_NO_BIND)
2906 fprintf (file, "%sNO_BIND\n", indent);
2907 if (dllch & IMAGE_DLLCHARACTERISTICS_APPCONTAINER)
2908 fprintf (file, "%sAPPCONTAINER\n", indent);
2909 if (dllch & IMAGE_DLLCHARACTERISTICS_WDM_DRIVER)
2910 fprintf (file, "%sWDM_DRIVER\n", indent);
2911 if (dllch & IMAGE_DLLCHARACTERISTICS_GUARD_CF)
2912 fprintf (file, "%sGUARD_CF\n", indent);
2913 if (dllch & IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE)
2914 fprintf (file, "%sTERMINAL_SERVICE_AWARE\n", indent);
2915 }
2916 fprintf (file, "SizeOfStackReserve\t");
2917 bfd_fprintf_vma (abfd, file, i->SizeOfStackReserve);
2918 fprintf (file, "\nSizeOfStackCommit\t");
2919 bfd_fprintf_vma (abfd, file, i->SizeOfStackCommit);
2920 fprintf (file, "\nSizeOfHeapReserve\t");
2921 bfd_fprintf_vma (abfd, file, i->SizeOfHeapReserve);
2922 fprintf (file, "\nSizeOfHeapCommit\t");
2923 bfd_fprintf_vma (abfd, file, i->SizeOfHeapCommit);
2924 fprintf (file, "\nLoaderFlags\t\t%08lx\n", (unsigned long) i->LoaderFlags);
2925 fprintf (file, "NumberOfRvaAndSizes\t%08lx\n",
2926 (unsigned long) i->NumberOfRvaAndSizes);
2927
2928 fprintf (file, "\nThe Data Directory\n");
2929 for (j = 0; j < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; j++)
2930 {
2931 fprintf (file, "Entry %1x ", j);
2932 bfd_fprintf_vma (abfd, file, i->DataDirectory[j].VirtualAddress);
2933 fprintf (file, " %08lx ", (unsigned long) i->DataDirectory[j].Size);
2934 fprintf (file, "%s\n", dir_names[j]);
2935 }
2936
2937 pe_print_idata (abfd, vfile);
2938 pe_print_edata (abfd, vfile);
2939 if (bfd_coff_have_print_pdata (abfd))
2940 bfd_coff_print_pdata (abfd, vfile);
2941 else
2942 pe_print_pdata (abfd, vfile);
2943 pe_print_reloc (abfd, vfile);
2944 pe_print_debugdata (abfd, file);
2945
2946 rsrc_print_section (abfd, vfile);
2947
2948 return true;
2949 }
2950
2951 static bool
2952 is_vma_in_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj)
2953 {
2954 bfd_vma addr = * (bfd_vma *) obj;
2955 return (addr >= sect->vma) && (addr < (sect->vma + sect->size));
2956 }
2957
2958 static asection *
2959 find_section_by_vma (bfd *abfd, bfd_vma addr)
2960 {
2961 return bfd_sections_find_if (abfd, is_vma_in_section, (void *) & addr);
2962 }
2963
2964 /* Copy any private info we understand from the input bfd
2965 to the output bfd. */
2966
2967 bool
2968 _bfd_XX_bfd_copy_private_bfd_data_common (bfd * ibfd, bfd * obfd)
2969 {
2970 pe_data_type *ipe, *ope;
2971 bfd_size_type size;
2972
2973 /* One day we may try to grok other private data. */
2974 if (ibfd->xvec->flavour != bfd_target_coff_flavour
2975 || obfd->xvec->flavour != bfd_target_coff_flavour)
2976 return true;
2977
2978 ipe = pe_data (ibfd);
2979 ope = pe_data (obfd);
2980
2981 /* pe_opthdr is copied in copy_object. */
2982 ope->dll = ipe->dll;
2983
2984 /* Don't copy input subsystem if output is different from input. */
2985 if (obfd->xvec != ibfd->xvec)
2986 ope->pe_opthdr.Subsystem = IMAGE_SUBSYSTEM_UNKNOWN;
2987
2988 /* For strip: if we removed .reloc, we'll make a real mess of things
2989 if we don't remove this entry as well. */
2990 if (! pe_data (obfd)->has_reloc_section)
2991 {
2992 pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].VirtualAddress = 0;
2993 pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].Size = 0;
2994 }
2995
2996 /* For PIE, if there is .reloc, we won't add IMAGE_FILE_RELOCS_STRIPPED.
2997 But there is no .reloc, we make sure that IMAGE_FILE_RELOCS_STRIPPED
2998 won't be added. */
2999 if (! pe_data (ibfd)->has_reloc_section
3000 && ! (pe_data (ibfd)->real_flags & IMAGE_FILE_RELOCS_STRIPPED))
3001 pe_data (obfd)->dont_strip_reloc = 1;
3002
3003 memcpy (ope->dos_message, ipe->dos_message, sizeof (ope->dos_message));
3004
3005 /* The file offsets contained in the debug directory need rewriting. */
3006 size = ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size;
3007 if (size != 0)
3008 {
3009 bfd_vma addr = ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
3010 + ope->pe_opthdr.ImageBase;
3011 /* In particular a .buildid section may overlap (in VA space) with
3012 whatever section comes ahead of it (largely because of section->size
3013 representing s_size, not virt_size). Therefore don't look for the
3014 section containing the first byte, but for that covering the last
3015 one. */
3016 bfd_vma last = addr + size - 1;
3017 asection *section = find_section_by_vma (obfd, last);
3018
3019 if (section != NULL)
3020 {
3021 bfd_byte *data;
3022 bfd_vma dataoff = addr - section->vma;
3023
3024 /* PR 17512: file: 0f15796a. */
3025 if (addr < section->vma
3026 || section->size < dataoff
3027 || section->size - dataoff < size)
3028 {
3029 /* xgettext:c-format */
3030 _bfd_error_handler
3031 (_("%pB: Data Directory (%lx bytes at %" PRIx64 ") "
3032 "extends across section boundary at %" PRIx64),
3033 obfd, ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size,
3034 (uint64_t) addr, (uint64_t) section->vma);
3035 return false;
3036 }
3037
3038 if ((section->flags & SEC_HAS_CONTENTS) != 0
3039 && bfd_malloc_and_get_section (obfd, section, &data))
3040 {
3041 unsigned int i;
3042 struct external_IMAGE_DEBUG_DIRECTORY *dd =
3043 (struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff);
3044
3045 for (i = 0; i < ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
3046 / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
3047 {
3048 asection *ddsection;
3049 struct external_IMAGE_DEBUG_DIRECTORY *edd = &(dd[i]);
3050 struct internal_IMAGE_DEBUG_DIRECTORY idd;
3051 bfd_vma idd_vma;
3052
3053 _bfd_XXi_swap_debugdir_in (obfd, edd, &idd);
3054
3055 /* RVA 0 means only offset is valid, not handled yet. */
3056 if (idd.AddressOfRawData == 0)
3057 continue;
3058
3059 idd_vma = idd.AddressOfRawData + ope->pe_opthdr.ImageBase;
3060 ddsection = find_section_by_vma (obfd, idd_vma);
3061 if (!ddsection)
3062 continue; /* Not in a section! */
3063
3064 idd.PointerToRawData
3065 = ddsection->filepos + idd_vma - ddsection->vma;
3066 _bfd_XXi_swap_debugdir_out (obfd, &idd, edd);
3067 }
3068
3069 if (!bfd_set_section_contents (obfd, section, data, 0,
3070 section->size))
3071 {
3072 _bfd_error_handler (_("failed to update file offsets"
3073 " in debug directory"));
3074 free (data);
3075 return false;
3076 }
3077 free (data);
3078 }
3079 else
3080 {
3081 _bfd_error_handler (_("%pB: failed to read "
3082 "debug data section"), obfd);
3083 return false;
3084 }
3085 }
3086 }
3087
3088 return true;
3089 }
3090
3091 /* Copy private section data. */
3092
3093 bool
3094 _bfd_XX_bfd_copy_private_section_data (bfd *ibfd,
3095 asection *isec,
3096 bfd *obfd,
3097 asection *osec)
3098 {
3099 if (bfd_get_flavour (ibfd) != bfd_target_coff_flavour
3100 || bfd_get_flavour (obfd) != bfd_target_coff_flavour)
3101 return true;
3102
3103 if (coff_section_data (ibfd, isec) != NULL
3104 && pei_section_data (ibfd, isec) != NULL)
3105 {
3106 if (coff_section_data (obfd, osec) == NULL)
3107 {
3108 size_t amt = sizeof (struct coff_section_tdata);
3109 osec->used_by_bfd = bfd_zalloc (obfd, amt);
3110 if (osec->used_by_bfd == NULL)
3111 return false;
3112 }
3113
3114 if (pei_section_data (obfd, osec) == NULL)
3115 {
3116 size_t amt = sizeof (struct pei_section_tdata);
3117 coff_section_data (obfd, osec)->tdata = bfd_zalloc (obfd, amt);
3118 if (coff_section_data (obfd, osec)->tdata == NULL)
3119 return false;
3120 }
3121
3122 pei_section_data (obfd, osec)->virt_size =
3123 pei_section_data (ibfd, isec)->virt_size;
3124 pei_section_data (obfd, osec)->pe_flags =
3125 pei_section_data (ibfd, isec)->pe_flags;
3126 }
3127
3128 return true;
3129 }
3130
3131 void
3132 _bfd_XX_get_symbol_info (bfd * abfd, asymbol *symbol, symbol_info *ret)
3133 {
3134 coff_get_symbol_info (abfd, symbol, ret);
3135 }
3136
3137 #if !defined(COFF_WITH_pep) && (defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64))
3138 static int
3139 sort_x64_pdata (const void *l, const void *r)
3140 {
3141 const char *lp = (const char *) l;
3142 const char *rp = (const char *) r;
3143 bfd_vma vl, vr;
3144 vl = bfd_getl32 (lp); vr = bfd_getl32 (rp);
3145 if (vl != vr)
3146 return (vl < vr ? -1 : 1);
3147 /* We compare just begin address. */
3148 return 0;
3149 }
3150 #endif
3151 \f
3152 /* Functions to process a .rsrc section. */
3153
3154 static unsigned int sizeof_leaves;
3155 static unsigned int sizeof_strings;
3156 static unsigned int sizeof_tables_and_entries;
3157
3158 static bfd_byte *
3159 rsrc_count_directory (bfd *, bfd_byte *, bfd_byte *, bfd_byte *, bfd_vma);
3160
3161 static bfd_byte *
3162 rsrc_count_entries (bfd *abfd,
3163 bool is_name,
3164 bfd_byte *datastart,
3165 bfd_byte *data,
3166 bfd_byte *dataend,
3167 bfd_vma rva_bias)
3168 {
3169 unsigned long entry, addr, size;
3170
3171 if (data + 8 >= dataend)
3172 return dataend + 1;
3173
3174 if (is_name)
3175 {
3176 bfd_byte * name;
3177
3178 entry = (long) bfd_get_32 (abfd, data);
3179
3180 if (HighBitSet (entry))
3181 name = datastart + WithoutHighBit (entry);
3182 else
3183 name = datastart + entry - rva_bias;
3184
3185 if (name + 2 >= dataend || name < datastart)
3186 return dataend + 1;
3187
3188 unsigned int len = bfd_get_16 (abfd, name);
3189 if (len == 0 || len > 256)
3190 return dataend + 1;
3191 }
3192
3193 entry = (long) bfd_get_32 (abfd, data + 4);
3194
3195 if (HighBitSet (entry))
3196 {
3197 data = datastart + WithoutHighBit (entry);
3198
3199 if (data <= datastart || data >= dataend)
3200 return dataend + 1;
3201
3202 return rsrc_count_directory (abfd, datastart, data, dataend, rva_bias);
3203 }
3204
3205 if (datastart + entry + 16 >= dataend)
3206 return dataend + 1;
3207
3208 addr = (long) bfd_get_32 (abfd, datastart + entry);
3209 size = (long) bfd_get_32 (abfd, datastart + entry + 4);
3210
3211 return datastart + addr - rva_bias + size;
3212 }
3213
3214 static bfd_byte *
3215 rsrc_count_directory (bfd * abfd,
3216 bfd_byte * datastart,
3217 bfd_byte * data,
3218 bfd_byte * dataend,
3219 bfd_vma rva_bias)
3220 {
3221 unsigned int num_entries, num_ids;
3222 bfd_byte * highest_data = data;
3223
3224 if (data + 16 >= dataend)
3225 return dataend + 1;
3226
3227 num_entries = (int) bfd_get_16 (abfd, data + 12);
3228 num_ids = (int) bfd_get_16 (abfd, data + 14);
3229
3230 num_entries += num_ids;
3231
3232 data += 16;
3233
3234 while (num_entries --)
3235 {
3236 bfd_byte * entry_end;
3237
3238 entry_end = rsrc_count_entries (abfd, num_entries >= num_ids,
3239 datastart, data, dataend, rva_bias);
3240 data += 8;
3241 highest_data = max (highest_data, entry_end);
3242 if (entry_end >= dataend)
3243 break;
3244 }
3245
3246 return max (highest_data, data);
3247 }
3248
3249 typedef struct rsrc_dir_chain
3250 {
3251 unsigned int num_entries;
3252 struct rsrc_entry * first_entry;
3253 struct rsrc_entry * last_entry;
3254 } rsrc_dir_chain;
3255
3256 typedef struct rsrc_directory
3257 {
3258 unsigned int characteristics;
3259 unsigned int time;
3260 unsigned int major;
3261 unsigned int minor;
3262
3263 rsrc_dir_chain names;
3264 rsrc_dir_chain ids;
3265
3266 struct rsrc_entry * entry;
3267 } rsrc_directory;
3268
3269 typedef struct rsrc_string
3270 {
3271 unsigned int len;
3272 bfd_byte * string;
3273 } rsrc_string;
3274
3275 typedef struct rsrc_leaf
3276 {
3277 unsigned int size;
3278 unsigned int codepage;
3279 bfd_byte * data;
3280 } rsrc_leaf;
3281
3282 typedef struct rsrc_entry
3283 {
3284 bool is_name;
3285 union
3286 {
3287 unsigned int id;
3288 struct rsrc_string name;
3289 } name_id;
3290
3291 bool is_dir;
3292 union
3293 {
3294 struct rsrc_directory * directory;
3295 struct rsrc_leaf * leaf;
3296 } value;
3297
3298 struct rsrc_entry * next_entry;
3299 struct rsrc_directory * parent;
3300 } rsrc_entry;
3301
3302 static bfd_byte *
3303 rsrc_parse_directory (bfd *, rsrc_directory *, bfd_byte *,
3304 bfd_byte *, bfd_byte *, bfd_vma, rsrc_entry *);
3305
3306 static bfd_byte *
3307 rsrc_parse_entry (bfd *abfd,
3308 bool is_name,
3309 rsrc_entry *entry,
3310 bfd_byte *datastart,
3311 bfd_byte * data,
3312 bfd_byte *dataend,
3313 bfd_vma rva_bias,
3314 rsrc_directory *parent)
3315 {
3316 unsigned long val, addr, size;
3317
3318 val = bfd_get_32 (abfd, data);
3319
3320 entry->parent = parent;
3321 entry->is_name = is_name;
3322
3323 if (is_name)
3324 {
3325 bfd_byte * address;
3326
3327 if (HighBitSet (val))
3328 {
3329 val = WithoutHighBit (val);
3330
3331 address = datastart + val;
3332 }
3333 else
3334 {
3335 address = datastart + val - rva_bias;
3336 }
3337
3338 if (address + 3 > dataend)
3339 return dataend;
3340
3341 entry->name_id.name.len = bfd_get_16 (abfd, address);
3342 entry->name_id.name.string = address + 2;
3343 }
3344 else
3345 entry->name_id.id = val;
3346
3347 val = bfd_get_32 (abfd, data + 4);
3348
3349 if (HighBitSet (val))
3350 {
3351 entry->is_dir = true;
3352 entry->value.directory = bfd_malloc (sizeof (*entry->value.directory));
3353 if (entry->value.directory == NULL)
3354 return dataend;
3355
3356 return rsrc_parse_directory (abfd, entry->value.directory,
3357 datastart,
3358 datastart + WithoutHighBit (val),
3359 dataend, rva_bias, entry);
3360 }
3361
3362 entry->is_dir = false;
3363 entry->value.leaf = bfd_malloc (sizeof (*entry->value.leaf));
3364 if (entry->value.leaf == NULL)
3365 return dataend;
3366
3367 data = datastart + val;
3368 if (data < datastart || data + 12 > dataend)
3369 return dataend;
3370
3371 addr = bfd_get_32 (abfd, data);
3372 size = entry->value.leaf->size = bfd_get_32 (abfd, data + 4);
3373 entry->value.leaf->codepage = bfd_get_32 (abfd, data + 8);
3374 /* FIXME: We assume that the reserved field (data + 12) is OK. */
3375
3376 if (size > dataend - datastart - (addr - rva_bias))
3377 return dataend;
3378 entry->value.leaf->data = bfd_malloc (size);
3379 if (entry->value.leaf->data == NULL)
3380 return dataend;
3381
3382 memcpy (entry->value.leaf->data, datastart + addr - rva_bias, size);
3383 return datastart + (addr - rva_bias) + size;
3384 }
3385
3386 static bfd_byte *
3387 rsrc_parse_entries (bfd *abfd,
3388 rsrc_dir_chain *chain,
3389 bool is_name,
3390 bfd_byte *highest_data,
3391 bfd_byte *datastart,
3392 bfd_byte *data,
3393 bfd_byte *dataend,
3394 bfd_vma rva_bias,
3395 rsrc_directory *parent)
3396 {
3397 unsigned int i;
3398 rsrc_entry * entry;
3399
3400 if (chain->num_entries == 0)
3401 {
3402 chain->first_entry = chain->last_entry = NULL;
3403 return highest_data;
3404 }
3405
3406 entry = bfd_malloc (sizeof (*entry));
3407 if (entry == NULL)
3408 return dataend;
3409
3410 chain->first_entry = entry;
3411
3412 for (i = chain->num_entries; i--;)
3413 {
3414 bfd_byte * entry_end;
3415
3416 entry_end = rsrc_parse_entry (abfd, is_name, entry, datastart,
3417 data, dataend, rva_bias, parent);
3418 data += 8;
3419 highest_data = max (entry_end, highest_data);
3420 if (entry_end > dataend)
3421 return dataend;
3422
3423 if (i)
3424 {
3425 entry->next_entry = bfd_malloc (sizeof (*entry));
3426 entry = entry->next_entry;
3427 if (entry == NULL)
3428 return dataend;
3429 }
3430 else
3431 entry->next_entry = NULL;
3432 }
3433
3434 chain->last_entry = entry;
3435
3436 return highest_data;
3437 }
3438
3439 static bfd_byte *
3440 rsrc_parse_directory (bfd * abfd,
3441 rsrc_directory * table,
3442 bfd_byte * datastart,
3443 bfd_byte * data,
3444 bfd_byte * dataend,
3445 bfd_vma rva_bias,
3446 rsrc_entry * entry)
3447 {
3448 bfd_byte * highest_data = data;
3449
3450 if (table == NULL)
3451 return dataend;
3452
3453 table->characteristics = bfd_get_32 (abfd, data);
3454 table->time = bfd_get_32 (abfd, data + 4);
3455 table->major = bfd_get_16 (abfd, data + 8);
3456 table->minor = bfd_get_16 (abfd, data + 10);
3457 table->names.num_entries = bfd_get_16 (abfd, data + 12);
3458 table->ids.num_entries = bfd_get_16 (abfd, data + 14);
3459 table->entry = entry;
3460
3461 data += 16;
3462
3463 highest_data = rsrc_parse_entries (abfd, & table->names, true, data,
3464 datastart, data, dataend, rva_bias, table);
3465 data += table->names.num_entries * 8;
3466
3467 highest_data = rsrc_parse_entries (abfd, & table->ids, false, highest_data,
3468 datastart, data, dataend, rva_bias, table);
3469 data += table->ids.num_entries * 8;
3470
3471 return max (highest_data, data);
3472 }
3473
3474 typedef struct rsrc_write_data
3475 {
3476 bfd * abfd;
3477 bfd_byte * datastart;
3478 bfd_byte * next_table;
3479 bfd_byte * next_leaf;
3480 bfd_byte * next_string;
3481 bfd_byte * next_data;
3482 bfd_vma rva_bias;
3483 } rsrc_write_data;
3484
3485 static void
3486 rsrc_write_string (rsrc_write_data * data,
3487 rsrc_string * string)
3488 {
3489 bfd_put_16 (data->abfd, string->len, data->next_string);
3490 memcpy (data->next_string + 2, string->string, string->len * 2);
3491 data->next_string += (string->len + 1) * 2;
3492 }
3493
3494 static inline unsigned int
3495 rsrc_compute_rva (rsrc_write_data * data,
3496 bfd_byte * addr)
3497 {
3498 return (addr - data->datastart) + data->rva_bias;
3499 }
3500
3501 static void
3502 rsrc_write_leaf (rsrc_write_data * data,
3503 rsrc_leaf * leaf)
3504 {
3505 bfd_put_32 (data->abfd, rsrc_compute_rva (data, data->next_data),
3506 data->next_leaf);
3507 bfd_put_32 (data->abfd, leaf->size, data->next_leaf + 4);
3508 bfd_put_32 (data->abfd, leaf->codepage, data->next_leaf + 8);
3509 bfd_put_32 (data->abfd, 0 /*reserved*/, data->next_leaf + 12);
3510 data->next_leaf += 16;
3511
3512 memcpy (data->next_data, leaf->data, leaf->size);
3513 /* An undocumented feature of Windows resources is that each unit
3514 of raw data is 8-byte aligned... */
3515 data->next_data += ((leaf->size + 7) & ~7);
3516 }
3517
3518 static void rsrc_write_directory (rsrc_write_data *, rsrc_directory *);
3519
3520 static void
3521 rsrc_write_entry (rsrc_write_data * data,
3522 bfd_byte * where,
3523 rsrc_entry * entry)
3524 {
3525 if (entry->is_name)
3526 {
3527 bfd_put_32 (data->abfd,
3528 SetHighBit (data->next_string - data->datastart),
3529 where);
3530 rsrc_write_string (data, & entry->name_id.name);
3531 }
3532 else
3533 bfd_put_32 (data->abfd, entry->name_id.id, where);
3534
3535 if (entry->is_dir)
3536 {
3537 bfd_put_32 (data->abfd,
3538 SetHighBit (data->next_table - data->datastart),
3539 where + 4);
3540 rsrc_write_directory (data, entry->value.directory);
3541 }
3542 else
3543 {
3544 bfd_put_32 (data->abfd, data->next_leaf - data->datastart, where + 4);
3545 rsrc_write_leaf (data, entry->value.leaf);
3546 }
3547 }
3548
3549 static void
3550 rsrc_compute_region_sizes (rsrc_directory * dir)
3551 {
3552 struct rsrc_entry * entry;
3553
3554 if (dir == NULL)
3555 return;
3556
3557 sizeof_tables_and_entries += 16;
3558
3559 for (entry = dir->names.first_entry; entry != NULL; entry = entry->next_entry)
3560 {
3561 sizeof_tables_and_entries += 8;
3562
3563 sizeof_strings += (entry->name_id.name.len + 1) * 2;
3564
3565 if (entry->is_dir)
3566 rsrc_compute_region_sizes (entry->value.directory);
3567 else
3568 sizeof_leaves += 16;
3569 }
3570
3571 for (entry = dir->ids.first_entry; entry != NULL; entry = entry->next_entry)
3572 {
3573 sizeof_tables_and_entries += 8;
3574
3575 if (entry->is_dir)
3576 rsrc_compute_region_sizes (entry->value.directory);
3577 else
3578 sizeof_leaves += 16;
3579 }
3580 }
3581
3582 static void
3583 rsrc_write_directory (rsrc_write_data * data,
3584 rsrc_directory * dir)
3585 {
3586 rsrc_entry * entry;
3587 unsigned int i;
3588 bfd_byte * next_entry;
3589 bfd_byte * nt;
3590
3591 bfd_put_32 (data->abfd, dir->characteristics, data->next_table);
3592 bfd_put_32 (data->abfd, 0 /*dir->time*/, data->next_table + 4);
3593 bfd_put_16 (data->abfd, dir->major, data->next_table + 8);
3594 bfd_put_16 (data->abfd, dir->minor, data->next_table + 10);
3595 bfd_put_16 (data->abfd, dir->names.num_entries, data->next_table + 12);
3596 bfd_put_16 (data->abfd, dir->ids.num_entries, data->next_table + 14);
3597
3598 /* Compute where the entries and the next table will be placed. */
3599 next_entry = data->next_table + 16;
3600 data->next_table = next_entry + (dir->names.num_entries * 8)
3601 + (dir->ids.num_entries * 8);
3602 nt = data->next_table;
3603
3604 /* Write the entries. */
3605 for (i = dir->names.num_entries, entry = dir->names.first_entry;
3606 i > 0 && entry != NULL;
3607 i--, entry = entry->next_entry)
3608 {
3609 BFD_ASSERT (entry->is_name);
3610 rsrc_write_entry (data, next_entry, entry);
3611 next_entry += 8;
3612 }
3613 BFD_ASSERT (i == 0);
3614 BFD_ASSERT (entry == NULL);
3615
3616 for (i = dir->ids.num_entries, entry = dir->ids.first_entry;
3617 i > 0 && entry != NULL;
3618 i--, entry = entry->next_entry)
3619 {
3620 BFD_ASSERT (! entry->is_name);
3621 rsrc_write_entry (data, next_entry, entry);
3622 next_entry += 8;
3623 }
3624 BFD_ASSERT (i == 0);
3625 BFD_ASSERT (entry == NULL);
3626 BFD_ASSERT (nt == next_entry);
3627 }
3628
3629 #if ! defined __CYGWIN__ && ! defined __MINGW32__
3630 /* Return the length (number of units) of the first character in S,
3631 putting its 'ucs4_t' representation in *PUC. */
3632
3633 static unsigned int
3634 u16_mbtouc (wint_t * puc, const unsigned short * s, unsigned int n)
3635 {
3636 unsigned short c = * s;
3637
3638 if (c < 0xd800 || c >= 0xe000)
3639 {
3640 *puc = c;
3641 return 1;
3642 }
3643
3644 if (c < 0xdc00)
3645 {
3646 if (n >= 2)
3647 {
3648 if (s[1] >= 0xdc00 && s[1] < 0xe000)
3649 {
3650 *puc = 0x10000 + ((c - 0xd800) << 10) + (s[1] - 0xdc00);
3651 return 2;
3652 }
3653 }
3654 else
3655 {
3656 /* Incomplete multibyte character. */
3657 *puc = 0xfffd;
3658 return n;
3659 }
3660 }
3661
3662 /* Invalid multibyte character. */
3663 *puc = 0xfffd;
3664 return 1;
3665 }
3666 #endif /* not Cygwin/Mingw */
3667
3668 /* Perform a comparison of two entries. */
3669 static signed int
3670 rsrc_cmp (bool is_name, rsrc_entry * a, rsrc_entry * b)
3671 {
3672 signed int res;
3673 bfd_byte * astring;
3674 unsigned int alen;
3675 bfd_byte * bstring;
3676 unsigned int blen;
3677
3678 if (! is_name)
3679 return a->name_id.id - b->name_id.id;
3680
3681 /* We have to perform a case insenstive, unicode string comparison... */
3682 astring = a->name_id.name.string;
3683 alen = a->name_id.name.len;
3684 bstring = b->name_id.name.string;
3685 blen = b->name_id.name.len;
3686
3687 #if defined __CYGWIN__ || defined __MINGW32__
3688 /* Under Windows hosts (both Cygwin and Mingw types),
3689 unicode == UTF-16 == wchar_t. The case insensitive string comparison
3690 function however goes by different names in the two environments... */
3691
3692 #undef rscpcmp
3693 #ifdef __CYGWIN__
3694 #define rscpcmp wcsncasecmp
3695 #endif
3696 #ifdef __MINGW32__
3697 #define rscpcmp wcsnicmp
3698 #endif
3699
3700 res = rscpcmp ((const wchar_t *) astring, (const wchar_t *) bstring,
3701 min (alen, blen));
3702
3703 #else
3704 {
3705 unsigned int i;
3706
3707 res = 0;
3708 for (i = min (alen, blen); i--; astring += 2, bstring += 2)
3709 {
3710 wint_t awc;
3711 wint_t bwc;
3712
3713 /* Convert UTF-16 unicode characters into wchar_t characters
3714 so that we can then perform a case insensitive comparison. */
3715 unsigned int Alen = u16_mbtouc (& awc, (const unsigned short *) astring, 2);
3716 unsigned int Blen = u16_mbtouc (& bwc, (const unsigned short *) bstring, 2);
3717
3718 if (Alen != Blen)
3719 return Alen - Blen;
3720
3721 awc = towlower (awc);
3722 bwc = towlower (bwc);
3723
3724 res = awc - bwc;
3725 if (res)
3726 break;
3727 }
3728 }
3729 #endif
3730
3731 if (res == 0)
3732 res = alen - blen;
3733
3734 return res;
3735 }
3736
3737 static void
3738 rsrc_print_name (char * buffer, rsrc_string string)
3739 {
3740 unsigned int i;
3741 bfd_byte * name = string.string;
3742
3743 for (i = string.len; i--; name += 2)
3744 sprintf (buffer + strlen (buffer), "%.1s", name);
3745 }
3746
3747 static const char *
3748 rsrc_resource_name (rsrc_entry *entry, rsrc_directory *dir, char *buffer)
3749 {
3750 bool is_string = false;
3751
3752 buffer[0] = 0;
3753
3754 if (dir != NULL && dir->entry != NULL && dir->entry->parent != NULL
3755 && dir->entry->parent->entry != NULL)
3756 {
3757 strcpy (buffer, "type: ");
3758 if (dir->entry->parent->entry->is_name)
3759 rsrc_print_name (buffer + strlen (buffer),
3760 dir->entry->parent->entry->name_id.name);
3761 else
3762 {
3763 unsigned int id = dir->entry->parent->entry->name_id.id;
3764
3765 sprintf (buffer + strlen (buffer), "%x", id);
3766 switch (id)
3767 {
3768 case 1: strcat (buffer, " (CURSOR)"); break;
3769 case 2: strcat (buffer, " (BITMAP)"); break;
3770 case 3: strcat (buffer, " (ICON)"); break;
3771 case 4: strcat (buffer, " (MENU)"); break;
3772 case 5: strcat (buffer, " (DIALOG)"); break;
3773 case 6: strcat (buffer, " (STRING)"); is_string = true; break;
3774 case 7: strcat (buffer, " (FONTDIR)"); break;
3775 case 8: strcat (buffer, " (FONT)"); break;
3776 case 9: strcat (buffer, " (ACCELERATOR)"); break;
3777 case 10: strcat (buffer, " (RCDATA)"); break;
3778 case 11: strcat (buffer, " (MESSAGETABLE)"); break;
3779 case 12: strcat (buffer, " (GROUP_CURSOR)"); break;
3780 case 14: strcat (buffer, " (GROUP_ICON)"); break;
3781 case 16: strcat (buffer, " (VERSION)"); break;
3782 case 17: strcat (buffer, " (DLGINCLUDE)"); break;
3783 case 19: strcat (buffer, " (PLUGPLAY)"); break;
3784 case 20: strcat (buffer, " (VXD)"); break;
3785 case 21: strcat (buffer, " (ANICURSOR)"); break;
3786 case 22: strcat (buffer, " (ANIICON)"); break;
3787 case 23: strcat (buffer, " (HTML)"); break;
3788 case 24: strcat (buffer, " (MANIFEST)"); break;
3789 case 240: strcat (buffer, " (DLGINIT)"); break;
3790 case 241: strcat (buffer, " (TOOLBAR)"); break;
3791 }
3792 }
3793 }
3794
3795 if (dir != NULL && dir->entry != NULL)
3796 {
3797 strcat (buffer, " name: ");
3798 if (dir->entry->is_name)
3799 rsrc_print_name (buffer + strlen (buffer), dir->entry->name_id.name);
3800 else
3801 {
3802 unsigned int id = dir->entry->name_id.id;
3803
3804 sprintf (buffer + strlen (buffer), "%x", id);
3805
3806 if (is_string)
3807 sprintf (buffer + strlen (buffer), " (resource id range: %d - %d)",
3808 (id - 1) << 4, (id << 4) - 1);
3809 }
3810 }
3811
3812 if (entry != NULL)
3813 {
3814 strcat (buffer, " lang: ");
3815
3816 if (entry->is_name)
3817 rsrc_print_name (buffer + strlen (buffer), entry->name_id.name);
3818 else
3819 sprintf (buffer + strlen (buffer), "%x", entry->name_id.id);
3820 }
3821
3822 return buffer;
3823 }
3824
3825 /* *sigh* Windows resource strings are special. Only the top 28-bits of
3826 their ID is stored in the NAME entry. The bottom four bits are used as
3827 an index into unicode string table that makes up the data of the leaf.
3828 So identical type-name-lang string resources may not actually be
3829 identical at all.
3830
3831 This function is called when we have detected two string resources with
3832 match top-28-bit IDs. We have to scan the string tables inside the leaves
3833 and discover if there are any real collisions. If there are then we report
3834 them and return FALSE. Otherwise we copy any strings from B into A and
3835 then return TRUE. */
3836
3837 static bool
3838 rsrc_merge_string_entries (rsrc_entry * a ATTRIBUTE_UNUSED,
3839 rsrc_entry * b ATTRIBUTE_UNUSED)
3840 {
3841 unsigned int copy_needed = 0;
3842 unsigned int i;
3843 bfd_byte * astring;
3844 bfd_byte * bstring;
3845 bfd_byte * new_data;
3846 bfd_byte * nstring;
3847
3848 /* Step one: Find out what we have to do. */
3849 BFD_ASSERT (! a->is_dir);
3850 astring = a->value.leaf->data;
3851
3852 BFD_ASSERT (! b->is_dir);
3853 bstring = b->value.leaf->data;
3854
3855 for (i = 0; i < 16; i++)
3856 {
3857 unsigned int alen = astring[0] + (astring[1] << 8);
3858 unsigned int blen = bstring[0] + (bstring[1] << 8);
3859
3860 if (alen == 0)
3861 {
3862 copy_needed += blen * 2;
3863 }
3864 else if (blen == 0)
3865 ;
3866 else if (alen != blen)
3867 /* FIXME: Should we continue the loop in order to report other duplicates ? */
3868 break;
3869 /* alen == blen != 0. We might have two identical strings. If so we
3870 can ignore the second one. There is no need for wchar_t vs UTF-16
3871 theatrics here - we are only interested in (case sensitive) equality. */
3872 else if (memcmp (astring + 2, bstring + 2, alen * 2) != 0)
3873 break;
3874
3875 astring += (alen + 1) * 2;
3876 bstring += (blen + 1) * 2;
3877 }
3878
3879 if (i != 16)
3880 {
3881 if (a->parent != NULL
3882 && a->parent->entry != NULL
3883 && !a->parent->entry->is_name)
3884 _bfd_error_handler (_(".rsrc merge failure: duplicate string resource: %d"),
3885 ((a->parent->entry->name_id.id - 1) << 4) + i);
3886 return false;
3887 }
3888
3889 if (copy_needed == 0)
3890 return true;
3891
3892 /* If we reach here then A and B must both have non-colliding strings.
3893 (We never get string resources with fully empty string tables).
3894 We need to allocate an extra COPY_NEEDED bytes in A and then bring
3895 in B's strings. */
3896 new_data = bfd_malloc (a->value.leaf->size + copy_needed);
3897 if (new_data == NULL)
3898 return false;
3899
3900 nstring = new_data;
3901 astring = a->value.leaf->data;
3902 bstring = b->value.leaf->data;
3903
3904 for (i = 0; i < 16; i++)
3905 {
3906 unsigned int alen = astring[0] + (astring[1] << 8);
3907 unsigned int blen = bstring[0] + (bstring[1] << 8);
3908
3909 if (alen != 0)
3910 {
3911 memcpy (nstring, astring, (alen + 1) * 2);
3912 nstring += (alen + 1) * 2;
3913 }
3914 else if (blen != 0)
3915 {
3916 memcpy (nstring, bstring, (blen + 1) * 2);
3917 nstring += (blen + 1) * 2;
3918 }
3919 else
3920 {
3921 * nstring++ = 0;
3922 * nstring++ = 0;
3923 }
3924
3925 astring += (alen + 1) * 2;
3926 bstring += (blen + 1) * 2;
3927 }
3928
3929 BFD_ASSERT (nstring - new_data == (signed) (a->value.leaf->size + copy_needed));
3930
3931 free (a->value.leaf->data);
3932 a->value.leaf->data = new_data;
3933 a->value.leaf->size += copy_needed;
3934
3935 return true;
3936 }
3937
3938 static void rsrc_merge (rsrc_entry *, rsrc_entry *);
3939
3940 /* Sort the entries in given part of the directory.
3941 We use an old fashioned bubble sort because we are dealing
3942 with lists and we want to handle matches specially. */
3943
3944 static void
3945 rsrc_sort_entries (rsrc_dir_chain *chain,
3946 bool is_name,
3947 rsrc_directory *dir)
3948 {
3949 rsrc_entry * entry;
3950 rsrc_entry * next;
3951 rsrc_entry ** points_to_entry;
3952 bool swapped;
3953
3954 if (chain->num_entries < 2)
3955 return;
3956
3957 do
3958 {
3959 swapped = false;
3960 points_to_entry = & chain->first_entry;
3961 entry = * points_to_entry;
3962 next = entry->next_entry;
3963
3964 do
3965 {
3966 signed int cmp = rsrc_cmp (is_name, entry, next);
3967
3968 if (cmp > 0)
3969 {
3970 entry->next_entry = next->next_entry;
3971 next->next_entry = entry;
3972 * points_to_entry = next;
3973 points_to_entry = & next->next_entry;
3974 next = entry->next_entry;
3975 swapped = true;
3976 }
3977 else if (cmp == 0)
3978 {
3979 if (entry->is_dir && next->is_dir)
3980 {
3981 /* When we encounter identical directory entries we have to
3982 merge them together. The exception to this rule is for
3983 resource manifests - there can only be one of these,
3984 even if they differ in language. Zero-language manifests
3985 are assumed to be default manifests (provided by the
3986 Cygwin/MinGW build system) and these can be silently dropped,
3987 unless that would reduce the number of manifests to zero.
3988 There should only ever be one non-zero lang manifest -
3989 if there are more it is an error. A non-zero lang
3990 manifest takes precedence over a default manifest. */
3991 if (!entry->is_name
3992 && entry->name_id.id == 1
3993 && dir != NULL
3994 && dir->entry != NULL
3995 && !dir->entry->is_name
3996 && dir->entry->name_id.id == 0x18)
3997 {
3998 if (next->value.directory->names.num_entries == 0
3999 && next->value.directory->ids.num_entries == 1
4000 && !next->value.directory->ids.first_entry->is_name
4001 && next->value.directory->ids.first_entry->name_id.id == 0)
4002 /* Fall through so that NEXT is dropped. */
4003 ;
4004 else if (entry->value.directory->names.num_entries == 0
4005 && entry->value.directory->ids.num_entries == 1
4006 && !entry->value.directory->ids.first_entry->is_name
4007 && entry->value.directory->ids.first_entry->name_id.id == 0)
4008 {
4009 /* Swap ENTRY and NEXT. Then fall through so that the old ENTRY is dropped. */
4010 entry->next_entry = next->next_entry;
4011 next->next_entry = entry;
4012 * points_to_entry = next;
4013 points_to_entry = & next->next_entry;
4014 next = entry->next_entry;
4015 swapped = true;
4016 }
4017 else
4018 {
4019 _bfd_error_handler (_(".rsrc merge failure: multiple non-default manifests"));
4020 bfd_set_error (bfd_error_file_truncated);
4021 return;
4022 }
4023
4024 /* Unhook NEXT from the chain. */
4025 /* FIXME: memory loss here. */
4026 entry->next_entry = next->next_entry;
4027 chain->num_entries --;
4028 if (chain->num_entries < 2)
4029 return;
4030 next = next->next_entry;
4031 }
4032 else
4033 rsrc_merge (entry, next);
4034 }
4035 else if (entry->is_dir != next->is_dir)
4036 {
4037 _bfd_error_handler (_(".rsrc merge failure: a directory matches a leaf"));
4038 bfd_set_error (bfd_error_file_truncated);
4039 return;
4040 }
4041 else
4042 {
4043 /* Otherwise with identical leaves we issue an error
4044 message - because there should never be duplicates.
4045 The exception is Type 18/Name 1/Lang 0 which is the
4046 defaul manifest - this can just be dropped. */
4047 if (!entry->is_name
4048 && entry->name_id.id == 0
4049 && dir != NULL
4050 && dir->entry != NULL
4051 && !dir->entry->is_name
4052 && dir->entry->name_id.id == 1
4053 && dir->entry->parent != NULL
4054 && dir->entry->parent->entry != NULL
4055 && !dir->entry->parent->entry->is_name
4056 && dir->entry->parent->entry->name_id.id == 0x18 /* RT_MANIFEST */)
4057 ;
4058 else if (dir != NULL
4059 && dir->entry != NULL
4060 && dir->entry->parent != NULL
4061 && dir->entry->parent->entry != NULL
4062 && !dir->entry->parent->entry->is_name
4063 && dir->entry->parent->entry->name_id.id == 0x6 /* RT_STRING */)
4064 {
4065 /* Strings need special handling. */
4066 if (! rsrc_merge_string_entries (entry, next))
4067 {
4068 /* _bfd_error_handler should have been called inside merge_strings. */
4069 bfd_set_error (bfd_error_file_truncated);
4070 return;
4071 }
4072 }
4073 else
4074 {
4075 if (dir == NULL
4076 || dir->entry == NULL
4077 || dir->entry->parent == NULL
4078 || dir->entry->parent->entry == NULL)
4079 _bfd_error_handler (_(".rsrc merge failure: duplicate leaf"));
4080 else
4081 {
4082 char buff[256];
4083
4084 _bfd_error_handler (_(".rsrc merge failure: duplicate leaf: %s"),
4085 rsrc_resource_name (entry, dir, buff));
4086 }
4087 bfd_set_error (bfd_error_file_truncated);
4088 return;
4089 }
4090 }
4091
4092 /* Unhook NEXT from the chain. */
4093 entry->next_entry = next->next_entry;
4094 chain->num_entries --;
4095 if (chain->num_entries < 2)
4096 return;
4097 next = next->next_entry;
4098 }
4099 else
4100 {
4101 points_to_entry = & entry->next_entry;
4102 entry = next;
4103 next = next->next_entry;
4104 }
4105 }
4106 while (next);
4107
4108 chain->last_entry = entry;
4109 }
4110 while (swapped);
4111 }
4112
4113 /* Attach B's chain onto A. */
4114 static void
4115 rsrc_attach_chain (rsrc_dir_chain * achain, rsrc_dir_chain * bchain)
4116 {
4117 if (bchain->num_entries == 0)
4118 return;
4119
4120 achain->num_entries += bchain->num_entries;
4121
4122 if (achain->first_entry == NULL)
4123 {
4124 achain->first_entry = bchain->first_entry;
4125 achain->last_entry = bchain->last_entry;
4126 }
4127 else
4128 {
4129 achain->last_entry->next_entry = bchain->first_entry;
4130 achain->last_entry = bchain->last_entry;
4131 }
4132
4133 bchain->num_entries = 0;
4134 bchain->first_entry = bchain->last_entry = NULL;
4135 }
4136
4137 static void
4138 rsrc_merge (struct rsrc_entry * a, struct rsrc_entry * b)
4139 {
4140 rsrc_directory * adir;
4141 rsrc_directory * bdir;
4142
4143 BFD_ASSERT (a->is_dir);
4144 BFD_ASSERT (b->is_dir);
4145
4146 adir = a->value.directory;
4147 bdir = b->value.directory;
4148
4149 if (adir->characteristics != bdir->characteristics)
4150 {
4151 _bfd_error_handler (_(".rsrc merge failure: dirs with differing characteristics"));
4152 bfd_set_error (bfd_error_file_truncated);
4153 return;
4154 }
4155
4156 if (adir->major != bdir->major || adir->minor != bdir->minor)
4157 {
4158 _bfd_error_handler (_(".rsrc merge failure: differing directory versions"));
4159 bfd_set_error (bfd_error_file_truncated);
4160 return;
4161 }
4162
4163 /* Attach B's name chain to A. */
4164 rsrc_attach_chain (& adir->names, & bdir->names);
4165
4166 /* Attach B's ID chain to A. */
4167 rsrc_attach_chain (& adir->ids, & bdir->ids);
4168
4169 /* Now sort A's entries. */
4170 rsrc_sort_entries (& adir->names, true, adir);
4171 rsrc_sort_entries (& adir->ids, false, adir);
4172 }
4173
4174 /* Check the .rsrc section. If it contains multiple concatenated
4175 resources then we must merge them properly. Otherwise Windows
4176 will ignore all but the first set. */
4177
4178 static void
4179 rsrc_process_section (bfd * abfd,
4180 struct coff_final_link_info * pfinfo)
4181 {
4182 rsrc_directory new_table;
4183 bfd_size_type size;
4184 asection * sec;
4185 pe_data_type * pe;
4186 bfd_vma rva_bias;
4187 bfd_byte * data;
4188 bfd_byte * datastart;
4189 bfd_byte * dataend;
4190 bfd_byte * new_data;
4191 unsigned int num_resource_sets;
4192 rsrc_directory * type_tables;
4193 rsrc_write_data write_data;
4194 unsigned int indx;
4195 bfd * input;
4196 unsigned int num_input_rsrc = 0;
4197 unsigned int max_num_input_rsrc = 4;
4198 ptrdiff_t * rsrc_sizes = NULL;
4199
4200 new_table.names.num_entries = 0;
4201 new_table.ids.num_entries = 0;
4202
4203 sec = bfd_get_section_by_name (abfd, ".rsrc");
4204 if (sec == NULL || (size = sec->rawsize) == 0)
4205 return;
4206
4207 pe = pe_data (abfd);
4208 if (pe == NULL)
4209 return;
4210
4211 rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4212
4213 if (! bfd_malloc_and_get_section (abfd, sec, &datastart))
4214 goto end;
4215
4216 /* Step zero: Scan the input bfds looking for .rsrc sections and record
4217 their lengths. Note - we rely upon the fact that the linker script
4218 does *not* sort the input .rsrc sections, so that the order in the
4219 linkinfo list matches the order in the output .rsrc section.
4220
4221 We need to know the lengths because each input .rsrc section has padding
4222 at the end of a variable amount. (It does not appear to be based upon
4223 the section alignment or the file alignment). We need to skip any
4224 padding bytes when parsing the input .rsrc sections. */
4225 data = datastart;
4226 rsrc_sizes = bfd_malloc (max_num_input_rsrc * sizeof (*rsrc_sizes));
4227 if (rsrc_sizes == NULL)
4228 goto end;
4229
4230 for (input = pfinfo->info->input_bfds;
4231 input != NULL;
4232 input = input->link.next)
4233 {
4234 asection * rsrc_sec = bfd_get_section_by_name (input, ".rsrc");
4235
4236 /* PR 18372 - skip discarded .rsrc sections. */
4237 if (rsrc_sec != NULL && !discarded_section (rsrc_sec))
4238 {
4239 if (num_input_rsrc == max_num_input_rsrc)
4240 {
4241 max_num_input_rsrc += 10;
4242 rsrc_sizes = bfd_realloc (rsrc_sizes, max_num_input_rsrc
4243 * sizeof (*rsrc_sizes));
4244 if (rsrc_sizes == NULL)
4245 goto end;
4246 }
4247
4248 BFD_ASSERT (rsrc_sec->size > 0);
4249 rsrc_sizes [num_input_rsrc ++] = rsrc_sec->size;
4250 }
4251 }
4252
4253 if (num_input_rsrc < 2)
4254 goto end;
4255
4256 /* Step one: Walk the section, computing the size of the tables,
4257 leaves and data and decide if we need to do anything. */
4258 dataend = data + size;
4259 num_resource_sets = 0;
4260
4261 while (data < dataend)
4262 {
4263 bfd_byte * p = data;
4264
4265 data = rsrc_count_directory (abfd, data, data, dataend, rva_bias);
4266
4267 if (data > dataend)
4268 {
4269 /* Corrupted .rsrc section - cannot merge. */
4270 _bfd_error_handler (_("%pB: .rsrc merge failure: corrupt .rsrc section"),
4271 abfd);
4272 bfd_set_error (bfd_error_file_truncated);
4273 goto end;
4274 }
4275
4276 if ((data - p) > rsrc_sizes [num_resource_sets])
4277 {
4278 _bfd_error_handler (_("%pB: .rsrc merge failure: unexpected .rsrc size"),
4279 abfd);
4280 bfd_set_error (bfd_error_file_truncated);
4281 goto end;
4282 }
4283 /* FIXME: Should we add a check for "data - p" being much smaller
4284 than rsrc_sizes[num_resource_sets] ? */
4285
4286 data = p + rsrc_sizes[num_resource_sets];
4287 rva_bias += data - p;
4288 ++ num_resource_sets;
4289 }
4290 BFD_ASSERT (num_resource_sets == num_input_rsrc);
4291
4292 /* Step two: Walk the data again, building trees of the resources. */
4293 data = datastart;
4294 rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4295
4296 type_tables = bfd_malloc (num_resource_sets * sizeof (*type_tables));
4297 if (type_tables == NULL)
4298 goto end;
4299
4300 indx = 0;
4301 while (data < dataend)
4302 {
4303 bfd_byte * p = data;
4304
4305 (void) rsrc_parse_directory (abfd, type_tables + indx, data, data,
4306 dataend, rva_bias, NULL);
4307 data = p + rsrc_sizes[indx];
4308 rva_bias += data - p;
4309 ++ indx;
4310 }
4311 BFD_ASSERT (indx == num_resource_sets);
4312
4313 /* Step three: Merge the top level tables (there can be only one).
4314
4315 We must ensure that the merged entries are in ascending order.
4316
4317 We also thread the top level table entries from the old tree onto
4318 the new table, so that they can be pulled off later. */
4319
4320 /* FIXME: Should we verify that all type tables are the same ? */
4321 new_table.characteristics = type_tables[0].characteristics;
4322 new_table.time = type_tables[0].time;
4323 new_table.major = type_tables[0].major;
4324 new_table.minor = type_tables[0].minor;
4325
4326 /* Chain the NAME entries onto the table. */
4327 new_table.names.first_entry = NULL;
4328 new_table.names.last_entry = NULL;
4329
4330 for (indx = 0; indx < num_resource_sets; indx++)
4331 rsrc_attach_chain (& new_table.names, & type_tables[indx].names);
4332
4333 rsrc_sort_entries (& new_table.names, true, & new_table);
4334
4335 /* Chain the ID entries onto the table. */
4336 new_table.ids.first_entry = NULL;
4337 new_table.ids.last_entry = NULL;
4338
4339 for (indx = 0; indx < num_resource_sets; indx++)
4340 rsrc_attach_chain (& new_table.ids, & type_tables[indx].ids);
4341
4342 rsrc_sort_entries (& new_table.ids, false, & new_table);
4343
4344 /* Step four: Create new contents for the .rsrc section. */
4345 /* Step four point one: Compute the size of each region of the .rsrc section.
4346 We do this now, rather than earlier, as the merging above may have dropped
4347 some entries. */
4348 sizeof_leaves = sizeof_strings = sizeof_tables_and_entries = 0;
4349 rsrc_compute_region_sizes (& new_table);
4350 /* We increment sizeof_strings to make sure that resource data
4351 starts on an 8-byte boundary. FIXME: Is this correct ? */
4352 sizeof_strings = (sizeof_strings + 7) & ~ 7;
4353
4354 new_data = bfd_zalloc (abfd, size);
4355 if (new_data == NULL)
4356 goto end;
4357
4358 write_data.abfd = abfd;
4359 write_data.datastart = new_data;
4360 write_data.next_table = new_data;
4361 write_data.next_leaf = new_data + sizeof_tables_and_entries;
4362 write_data.next_string = write_data.next_leaf + sizeof_leaves;
4363 write_data.next_data = write_data.next_string + sizeof_strings;
4364 write_data.rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4365
4366 rsrc_write_directory (& write_data, & new_table);
4367
4368 /* Step five: Replace the old contents with the new.
4369 We don't recompute the size as it's too late here to shrink section.
4370 See PR ld/20193 for more details. */
4371 bfd_set_section_contents (pfinfo->output_bfd, sec, new_data, 0, size);
4372 sec->size = sec->rawsize = size;
4373
4374 end:
4375 /* Step six: Free all the memory that we have used. */
4376 /* FIXME: Free the resource tree, if we have one. */
4377 free (datastart);
4378 free (rsrc_sizes);
4379 }
4380
4381 /* Handle the .idata section and other things that need symbol table
4382 access. */
4383
4384 bool
4385 _bfd_XXi_final_link_postscript (bfd * abfd, struct coff_final_link_info *pfinfo)
4386 {
4387 struct coff_link_hash_entry *h1;
4388 struct bfd_link_info *info = pfinfo->info;
4389 bool result = true;
4390
4391 /* There are a few fields that need to be filled in now while we
4392 have symbol table access.
4393
4394 The .idata subsections aren't directly available as sections, but
4395 they are in the symbol table, so get them from there. */
4396
4397 /* The import directory. This is the address of .idata$2, with size
4398 of .idata$2 + .idata$3. */
4399 h1 = coff_link_hash_lookup (coff_hash_table (info),
4400 ".idata$2", false, false, true);
4401 if (h1 != NULL)
4402 {
4403 /* PR ld/2729: We cannot rely upon all the output sections having been
4404 created properly, so check before referencing them. Issue a warning
4405 message for any sections tht could not be found. */
4406 if ((h1->root.type == bfd_link_hash_defined
4407 || h1->root.type == bfd_link_hash_defweak)
4408 && h1->root.u.def.section != NULL
4409 && h1->root.u.def.section->output_section != NULL)
4410 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress =
4411 (h1->root.u.def.value
4412 + h1->root.u.def.section->output_section->vma
4413 + h1->root.u.def.section->output_offset);
4414 else
4415 {
4416 _bfd_error_handler
4417 (_("%pB: unable to fill in DataDictionary[1] because .idata$2 is missing"),
4418 abfd);
4419 result = false;
4420 }
4421
4422 h1 = coff_link_hash_lookup (coff_hash_table (info),
4423 ".idata$4", false, false, true);
4424 if (h1 != NULL
4425 && (h1->root.type == bfd_link_hash_defined
4426 || h1->root.type == bfd_link_hash_defweak)
4427 && h1->root.u.def.section != NULL
4428 && h1->root.u.def.section->output_section != NULL)
4429 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].Size =
4430 ((h1->root.u.def.value
4431 + h1->root.u.def.section->output_section->vma
4432 + h1->root.u.def.section->output_offset)
4433 - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress);
4434 else
4435 {
4436 _bfd_error_handler
4437 (_("%pB: unable to fill in DataDictionary[1] because .idata$4 is missing"),
4438 abfd);
4439 result = false;
4440 }
4441
4442 /* The import address table. This is the size/address of
4443 .idata$5. */
4444 h1 = coff_link_hash_lookup (coff_hash_table (info),
4445 ".idata$5", false, false, true);
4446 if (h1 != NULL
4447 && (h1->root.type == bfd_link_hash_defined
4448 || h1->root.type == bfd_link_hash_defweak)
4449 && h1->root.u.def.section != NULL
4450 && h1->root.u.def.section->output_section != NULL)
4451 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
4452 (h1->root.u.def.value
4453 + h1->root.u.def.section->output_section->vma
4454 + h1->root.u.def.section->output_offset);
4455 else
4456 {
4457 _bfd_error_handler
4458 (_("%pB: unable to fill in DataDictionary[12] because .idata$5 is missing"),
4459 abfd);
4460 result = false;
4461 }
4462
4463 h1 = coff_link_hash_lookup (coff_hash_table (info),
4464 ".idata$6", false, false, true);
4465 if (h1 != NULL
4466 && (h1->root.type == bfd_link_hash_defined
4467 || h1->root.type == bfd_link_hash_defweak)
4468 && h1->root.u.def.section != NULL
4469 && h1->root.u.def.section->output_section != NULL)
4470 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
4471 ((h1->root.u.def.value
4472 + h1->root.u.def.section->output_section->vma
4473 + h1->root.u.def.section->output_offset)
4474 - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress);
4475 else
4476 {
4477 _bfd_error_handler
4478 (_("%pB: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE (12)] because .idata$6 is missing"),
4479 abfd);
4480 result = false;
4481 }
4482 }
4483 else
4484 {
4485 h1 = coff_link_hash_lookup (coff_hash_table (info),
4486 "__IAT_start__", false, false, true);
4487 if (h1 != NULL
4488 && (h1->root.type == bfd_link_hash_defined
4489 || h1->root.type == bfd_link_hash_defweak)
4490 && h1->root.u.def.section != NULL
4491 && h1->root.u.def.section->output_section != NULL)
4492 {
4493 bfd_vma iat_va;
4494
4495 iat_va =
4496 (h1->root.u.def.value
4497 + h1->root.u.def.section->output_section->vma
4498 + h1->root.u.def.section->output_offset);
4499
4500 h1 = coff_link_hash_lookup (coff_hash_table (info),
4501 "__IAT_end__", false, false, true);
4502 if (h1 != NULL
4503 && (h1->root.type == bfd_link_hash_defined
4504 || h1->root.type == bfd_link_hash_defweak)
4505 && h1->root.u.def.section != NULL
4506 && h1->root.u.def.section->output_section != NULL)
4507 {
4508 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
4509 ((h1->root.u.def.value
4510 + h1->root.u.def.section->output_section->vma
4511 + h1->root.u.def.section->output_offset)
4512 - iat_va);
4513 if (pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size != 0)
4514 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
4515 iat_va - pe_data (abfd)->pe_opthdr.ImageBase;
4516 }
4517 else
4518 {
4519 _bfd_error_handler
4520 (_("%pB: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE(12)]"
4521 " because .idata$6 is missing"), abfd);
4522 result = false;
4523 }
4524 }
4525 }
4526
4527 h1 = coff_link_hash_lookup (coff_hash_table (info),
4528 (bfd_get_symbol_leading_char (abfd) != 0
4529 ? "__tls_used" : "_tls_used"),
4530 false, false, true);
4531 if (h1 != NULL)
4532 {
4533 if ((h1->root.type == bfd_link_hash_defined
4534 || h1->root.type == bfd_link_hash_defweak)
4535 && h1->root.u.def.section != NULL
4536 && h1->root.u.def.section->output_section != NULL)
4537 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].VirtualAddress =
4538 (h1->root.u.def.value
4539 + h1->root.u.def.section->output_section->vma
4540 + h1->root.u.def.section->output_offset
4541 - pe_data (abfd)->pe_opthdr.ImageBase);
4542 else
4543 {
4544 _bfd_error_handler
4545 (_("%pB: unable to fill in DataDictionary[9] because __tls_used is missing"),
4546 abfd);
4547 result = false;
4548 }
4549 /* According to PECOFF sepcifications by Microsoft version 8.2
4550 the TLS data directory consists of 4 pointers, followed
4551 by two 4-byte integer. This implies that the total size
4552 is different for 32-bit and 64-bit executables. */
4553 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
4554 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x18;
4555 #else
4556 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x28;
4557 #endif
4558 }
4559
4560 /* If there is a .pdata section and we have linked pdata finally, we
4561 need to sort the entries ascending. */
4562 #if !defined(COFF_WITH_pep) && (defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64))
4563 {
4564 asection *sec = bfd_get_section_by_name (abfd, ".pdata");
4565
4566 if (sec)
4567 {
4568 bfd_size_type x = sec->rawsize;
4569 bfd_byte *tmp_data;
4570
4571 if (bfd_malloc_and_get_section (abfd, sec, &tmp_data))
4572 {
4573 qsort (tmp_data,
4574 (size_t) (x / 12),
4575 12, sort_x64_pdata);
4576 bfd_set_section_contents (pfinfo->output_bfd, sec,
4577 tmp_data, 0, x);
4578 free (tmp_data);
4579 }
4580 else
4581 result = false;
4582 }
4583 }
4584 #endif
4585
4586 rsrc_process_section (abfd, pfinfo);
4587
4588 /* If we couldn't find idata$2, we either have an excessively
4589 trivial program or are in DEEP trouble; we have to assume trivial
4590 program.... */
4591 return result;
4592 }