Add translations for various sub-directories
[binutils-gdb.git] / bfd / peXXigen.c
blob29012688adfb02ee0e8431abe568f9a13caf422d
1 /* Support for the generic parts of PE/PEI; the common executable parts.
2 Copyright (C) 1995-2025 Free Software Foundation, Inc.
3 Written by Cygnus Solutions.
5 This file is part of BFD, the Binary File Descriptor library.
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.
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.
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. */
23 /* Most of this hacked by Steve Chamberlain <sac@cygnus.com>.
25 PE/PEI rearrangement (and code added): Donn Terry
26 Softway Systems, Inc. */
28 /* Hey look, some documentation [and in a place you expect to find it]!
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.
34 Another reference:
35 "Peering Inside the PE: A Tour of the Win32 Portable Executable
36 File Format", MSJ 1994, Volume 9.
38 The PE/PEI format is also used by .NET. ECMA-335 describes this:
40 "Standard ECMA-335 Common Language Infrastructure (CLI)", 6th Edition, June 2012.
42 This is also available at
43 https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf.
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!)
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.
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. */
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
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>
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
97 #include "coff/pe.h"
98 #include "libcoff.h"
99 #include "libpei.h"
100 #include "safe-ctype.h"
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
108 #define HighBitSet(val) ((val) & 0x80000000)
109 #define SetHighBit(val) ((val) | 0x80000000)
110 #define WithoutHighBit(val) ((val) & 0x7fffffff)
112 void
113 _bfd_XXi_swap_sym_in (bfd * abfd, void * ext1, void * in1)
115 SYMENT *ext = (SYMENT *) ext1;
116 struct internal_syment *in = (struct internal_syment *) in1;
118 if (ext->e.e_name[0] == 0)
120 in->_n._n_n._n_zeroes = 0;
121 in->_n._n_n._n_offset = H_GET_32 (abfd, ext->e.e.e_offset);
123 else
124 memcpy (in->_n._n_name, ext->e.e_name, SYMNMLEN);
126 in->n_value = H_GET_32 (abfd, ext->e_value);
127 in->n_scnum = (short) H_GET_16 (abfd, ext->e_scnum);
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);
134 in->n_sclass = H_GET_8 (abfd, ext->e_sclass);
135 in->n_numaux = H_GET_8 (abfd, ext->e_numaux);
137 #ifndef STRICT_PE_FORMAT
138 /* This is for Gnu-created DLLs. */
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)
148 char namebuf[SYMNMLEN + 1];
149 const char *name = NULL;
151 in->n_value = 0x0;
153 /* Create synthetic empty sections as needed. DJ */
154 if (in->n_scnum == 0)
156 asection *sec;
158 name = _bfd_coff_internal_syment_name (abfd, in, namebuf);
159 if (name == NULL)
161 _bfd_error_handler (_("%pB: unable to find name for empty section"),
162 abfd);
163 bfd_set_error (bfd_error_invalid_target);
164 return;
167 sec = bfd_get_section_by_name (abfd, name);
168 if (sec != NULL)
169 in->n_scnum = sec->target_index;
172 if (in->n_scnum == 0)
174 int unused_section_number = 0;
175 asection *sec;
176 flagword flags;
177 size_t name_len;
178 char *sec_name;
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;
184 name_len = strlen (name) + 1;
185 sec_name = bfd_alloc (abfd, name_len);
186 if (sec_name == NULL)
188 _bfd_error_handler (_("%pB: out of memory creating name "
189 "for empty section"), abfd);
190 return;
192 memcpy (sec_name, name, name_len);
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)
199 _bfd_error_handler (_("%pB: unable to create fake empty section"),
200 abfd);
201 return;
204 sec->alignment_power = 2;
205 sec->target_index = unused_section_number;
207 in->n_scnum = unused_section_number;
209 in->n_sclass = C_STAT;
211 #endif
214 static bool
215 abs_finder (bfd * abfd ATTRIBUTE_UNUSED, asection * sec, void * data)
217 bfd_vma abs_val = * (bfd_vma *) data;
219 return (sec->vma <= abs_val) && ((sec->vma + (1ULL << 32)) > abs_val);
222 unsigned int
223 _bfd_XXi_swap_sym_out (bfd * abfd, void * inp, void * extp)
225 struct internal_syment *in = (struct internal_syment *) inp;
226 SYMENT *ext = (SYMENT *) extp;
228 if (in->_n._n_name[0] == 0)
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);
233 else
234 memcpy (ext->e.e_name, in->_n._n_name, SYMNMLEN);
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)
251 asection * sec;
253 sec = bfd_sections_find_if (abfd, abs_finder, & in->n_value);
254 if (sec)
256 in->n_value -= sec->vma;
257 in->n_scnum = sec->target_index;
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. */
264 H_PUT_32 (abfd, in->n_value, ext->e_value);
265 H_PUT_16 (abfd, in->n_scnum, ext->e_scnum);
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);
272 H_PUT_8 (abfd, in->n_sclass, ext->e_sclass);
273 H_PUT_8 (abfd, in->n_numaux, ext->e_numaux);
275 return SYMESZ;
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)
287 AUXENT *ext = (AUXENT *) ext1;
288 union internal_auxent *in = (union internal_auxent *) in1;
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)
295 case C_FILE:
296 if (ext->x_file.x_fname[0] == 0)
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);
301 else
302 memcpy (in->x_file.x_n.x_fname, ext->x_file.x_fname, FILNMLEN);
303 return;
305 case C_STAT:
306 case C_LEAFSTAT:
307 case C_HIDDEN:
308 if (type == T_NULL)
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;
318 break;
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);
324 if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
325 || ISTAG (in_class))
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);
330 else
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]);
342 if (ISFCN (type))
344 in->x_sym.x_misc.x_fsize = H_GET_32 (abfd, ext->x_sym.x_misc.x_fsize);
346 else
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);
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)
362 union internal_auxent *in = (union internal_auxent *) inp;
363 AUXENT *ext = (AUXENT *) extp;
365 memset (ext, 0, AUXESZ);
367 switch (in_class)
369 case C_FILE:
370 if (in->x_file.x_n.x_fname[0] == 0)
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);
375 else
376 memcpy (ext->x_file.x_fname, in->x_file.x_n.x_fname, sizeof (ext->x_file.x_fname));
378 return AUXESZ;
380 case C_STAT:
381 case C_LEAFSTAT:
382 case C_HIDDEN:
383 if (type == T_NULL)
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;
393 break;
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);
399 if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
400 || ISTAG (in_class))
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);
405 else
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]);
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
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);
425 return AUXESZ;
428 void
429 _bfd_XXi_swap_lineno_in (bfd * abfd, void * ext1, void * in1)
431 LINENO *ext = (LINENO *) ext1;
432 struct internal_lineno *in = (struct internal_lineno *) in1;
434 in->l_addr.l_symndx = H_GET_32 (abfd, ext->l_addr.l_symndx);
435 in->l_lnno = GET_LINENO_LNNO (abfd, ext);
438 unsigned int
439 _bfd_XXi_swap_lineno_out (bfd * abfd, void * inp, void * outp)
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);
445 PUT_LINENO_LNNO (abfd, in->l_lnno, ext);
446 return LINESZ;
449 void
450 _bfd_XXi_swap_aouthdr_in (bfd * abfd,
451 void * aouthdr_ext1,
452 void * aouthdr_int1)
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;
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);
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
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->Win32Version = H_GET_32 (abfd, src->Win32Version);
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);
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++)
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;
522 a->DataDirectory[idx].Size = size;
523 a->DataDirectory[idx].VirtualAddress = vma;
526 while (idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
528 a->DataDirectory[idx].Size = 0;
529 a->DataDirectory[idx].VirtualAddress = 0;
530 idx++;
533 if (aouthdr_int->entry)
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
541 if (aouthdr_int->tsize)
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
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)
553 aouthdr_int->data_start += a->ImageBase;
554 aouthdr_int->data_start &= 0xffffffff;
556 #endif
559 /* A support function for below. */
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)
568 asection *sec = bfd_get_section_by_name (abfd, name);
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))
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;
579 if (size)
581 aout->DataDirectory[idx].VirtualAddress =
582 (sec->vma - base) & 0xffffffff;
583 sec->flags |= SEC_DATA;
588 unsigned int
589 _bfd_XXi_swap_aouthdr_out (bfd * abfd, void * in, void * out)
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;
598 sa = extra->SectionAlignment;
599 fa = extra->FileAlignment;
600 ib = extra->ImageBase;
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];
606 if (aouthdr_in->tsize)
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
614 if (aouthdr_in->dsize)
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
622 if (aouthdr_in->entry)
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
630 #define FA(x) (((x) + fa -1 ) & (- fa))
631 #define SA(x) (((x) + sa -1 ) & (- sa))
633 /* We like to have the sizes aligned. */
634 aouthdr_in->bsize = FA (aouthdr_in->bsize);
636 extra->NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
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);
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.
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;
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);
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);
669 asection *sec;
670 bfd_vma hsize = 0;
671 bfd_vma dsize = 0;
672 bfd_vma isize = 0;
673 bfd_vma tsize = 0;
675 for (sec = abfd->sections; sec; sec = sec->next)
677 int rounded = FA (sec->size);
679 if (rounded == 0)
680 continue;
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.
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 = SA (sec->vma - extra->ImageBase
703 + FA (pei_section_data (abfd, sec)->virt_size));
706 aouthdr_in->dsize = dsize;
707 aouthdr_in->tsize = tsize;
708 extra->SizeOfHeaders = hsize;
709 extra->SizeOfImage = isize;
712 H_PUT_16 (abfd, aouthdr_in->magic, aouthdr_out->standard.magic);
714 if (extra->MajorLinkerVersion || extra->MinorLinkerVersion)
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);
721 else
723 /* e.g. 219510000 is linker version 2.19 */
724 #define LINKER_VERSION ((short) (BFD_VERSION / 1000000))
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);
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);
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
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->Win32Version, aouthdr_out->Win32Version);
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);
776 int idx;
778 for (idx = 0; idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; idx++)
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]);
787 return AOUTSZ;
790 unsigned int
791 _bfd_XXi_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
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;
797 if (pe_data (abfd)->has_reloc_section
798 || pe_data (abfd)->dont_strip_reloc)
799 filehdr_in->f_flags &= ~F_RELFLG;
801 if (pe_data (abfd)->dll)
802 filehdr_in->f_flags |= F_DLL;
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;
819 for (idx = 0; idx < 4; idx++)
820 filehdr_in->pe.e_res[idx] = 0x0;
822 filehdr_in->pe.e_oemid = 0x0;
823 filehdr_in->pe.e_oeminfo = 0x0;
825 for (idx = 0; idx < 10; idx++)
826 filehdr_in->pe.e_res2[idx] = 0x0;
828 filehdr_in->pe.e_lfanew = 0x80;
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));
835 filehdr_in->pe.nt_signature = IMAGE_NT_SIGNATURE;
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);
840 /* Use a real timestamp by default, unless the no-insert-timestamp
841 option was chosen. */
842 if ((pe_data (abfd)->timestamp) == -1)
844 time_t now = bfd_get_current_time (0);
845 H_PUT_32 (abfd, now, filehdr_out->f_timdat);
847 else
848 H_PUT_32 (abfd, pe_data (abfd)->timestamp, filehdr_out->f_timdat);
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);
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);
874 for (idx = 0; idx < 4; idx++)
875 H_PUT_16 (abfd, filehdr_in->pe.e_res[idx], filehdr_out->e_res[idx]);
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);
880 for (idx = 0; idx < 10; idx++)
881 H_PUT_16 (abfd, filehdr_in->pe.e_res2[idx], filehdr_out->e_res2[idx]);
883 H_PUT_32 (abfd, filehdr_in->pe.e_lfanew, filehdr_out->e_lfanew);
885 memcpy (filehdr_out->dos_message, filehdr_in->pe.dos_message,
886 sizeof (filehdr_out->dos_message));
888 /* Also put in the NT signature. */
889 H_PUT_32 (abfd, filehdr_in->pe.nt_signature, filehdr_out->nt_signature);
891 return FILHSZ;
894 unsigned int
895 _bfd_XX_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
897 struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
898 FILHDR *filehdr_out = (FILHDR *) out;
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);
908 return FILHSZ;
911 unsigned int
912 _bfd_XXi_swap_scnhdr_out (bfd * abfd, void * in, void * out)
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;
920 memcpy (scnhdr_ext->s_name, scnhdr_int->s_name, sizeof (scnhdr_int->s_name));
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
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)
940 if (bfd_pei_p (abfd))
942 ps = scnhdr_int->s_size;
943 ss = 0;
945 else
947 ps = 0;
948 ss = scnhdr_int->s_size;
951 else
953 if (bfd_pei_p (abfd))
954 ps = scnhdr_int->s_paddr;
955 else
956 ps = 0;
958 ss = scnhdr_int->s_size;
961 PUT_SCNHDR_SIZE (abfd, ss,
962 scnhdr_ext->s_size);
964 /* s_paddr in PE is really the virtual size. */
965 PUT_SCNHDR_PADDR (abfd, ps, scnhdr_ext->s_paddr);
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);
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. */
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 ? */
989 typedef struct
991 char section_name[SCNNMLEN];
992 unsigned long must_have;
994 pe_required_section_flags;
996 pe_required_section_flags known_sections [] =
998 { ".CRT", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
999 { ".arch", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_ALIGN_8BYTES },
1000 { ".bss", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1001 { ".data", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1002 { ".edata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1003 { ".idata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1004 { ".pdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1005 { ".rdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1006 { ".reloc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE },
1007 { ".rsrc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1008 { ".text" , IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE },
1009 { ".tls", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1010 { ".xdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1013 pe_required_section_flags * p;
1015 /* We have defaulted to adding the IMAGE_SCN_MEM_WRITE flag, but now
1016 we know exactly what this specific section wants so we remove it
1017 and then allow the must_have field to add it back in if necessary.
1018 However, we don't remove IMAGE_SCN_MEM_WRITE flag from .text if the
1019 default WP_TEXT file flag has been cleared. WP_TEXT may be cleared
1020 by ld --enable-auto-import (if auto-import is actually needed),
1021 by ld --omagic, or by obcopy --writable-text. */
1023 for (p = known_sections;
1024 p < known_sections + ARRAY_SIZE (known_sections);
1025 p++)
1026 if (memcmp (scnhdr_int->s_name, p->section_name, SCNNMLEN) == 0)
1028 if (memcmp (scnhdr_int->s_name, ".text", sizeof ".text")
1029 || (bfd_get_file_flags (abfd) & WP_TEXT))
1030 scnhdr_int->s_flags &= ~IMAGE_SCN_MEM_WRITE;
1031 scnhdr_int->s_flags |= p->must_have;
1032 break;
1035 H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
1038 if (coff_data (abfd)->link_info
1039 && ! bfd_link_relocatable (coff_data (abfd)->link_info)
1040 && ! bfd_link_pic (coff_data (abfd)->link_info)
1041 && memcmp (scnhdr_int->s_name, ".text", sizeof ".text") == 0)
1043 /* By inference from looking at MS output, the 32 bit field
1044 which is the combination of the number_of_relocs and
1045 number_of_linenos is used for the line number count in
1046 executables. A 16-bit field won't do for cc1. The MS
1047 document says that the number of relocs is zero for
1048 executables, but the 17-th bit has been observed to be there.
1049 Overflow is not an issue: a 4G-line program will overflow a
1050 bunch of other fields long before this! */
1051 H_PUT_16 (abfd, (scnhdr_int->s_nlnno & 0xffff), scnhdr_ext->s_nlnno);
1052 H_PUT_16 (abfd, (scnhdr_int->s_nlnno >> 16), scnhdr_ext->s_nreloc);
1054 else
1056 if (scnhdr_int->s_nlnno <= 0xffff)
1057 H_PUT_16 (abfd, scnhdr_int->s_nlnno, scnhdr_ext->s_nlnno);
1058 else
1060 /* xgettext:c-format */
1061 _bfd_error_handler (_("%pB: line number overflow: 0x%lx > 0xffff"),
1062 abfd, scnhdr_int->s_nlnno);
1063 bfd_set_error (bfd_error_file_truncated);
1064 H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nlnno);
1065 ret = 0;
1068 /* Although we could encode 0xffff relocs here, we do not, to be
1069 consistent with other parts of bfd. Also it lets us warn, as
1070 we should never see 0xffff here w/o having the overflow flag
1071 set. */
1072 if (scnhdr_int->s_nreloc < 0xffff)
1073 H_PUT_16 (abfd, scnhdr_int->s_nreloc, scnhdr_ext->s_nreloc);
1074 else
1076 /* PE can deal with large #s of relocs, but not here. */
1077 H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nreloc);
1078 scnhdr_int->s_flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
1079 H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
1082 return ret;
1085 void
1086 _bfd_XXi_swap_debugdir_in (bfd * abfd, void * ext1, void * in1)
1088 struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) ext1;
1089 struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) in1;
1091 in->Characteristics = H_GET_32(abfd, ext->Characteristics);
1092 in->TimeDateStamp = H_GET_32(abfd, ext->TimeDateStamp);
1093 in->MajorVersion = H_GET_16(abfd, ext->MajorVersion);
1094 in->MinorVersion = H_GET_16(abfd, ext->MinorVersion);
1095 in->Type = H_GET_32(abfd, ext->Type);
1096 in->SizeOfData = H_GET_32(abfd, ext->SizeOfData);
1097 in->AddressOfRawData = H_GET_32(abfd, ext->AddressOfRawData);
1098 in->PointerToRawData = H_GET_32(abfd, ext->PointerToRawData);
1101 unsigned int
1102 _bfd_XXi_swap_debugdir_out (bfd * abfd, void * inp, void * extp)
1104 struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) extp;
1105 struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) inp;
1107 H_PUT_32(abfd, in->Characteristics, ext->Characteristics);
1108 H_PUT_32(abfd, in->TimeDateStamp, ext->TimeDateStamp);
1109 H_PUT_16(abfd, in->MajorVersion, ext->MajorVersion);
1110 H_PUT_16(abfd, in->MinorVersion, ext->MinorVersion);
1111 H_PUT_32(abfd, in->Type, ext->Type);
1112 H_PUT_32(abfd, in->SizeOfData, ext->SizeOfData);
1113 H_PUT_32(abfd, in->AddressOfRawData, ext->AddressOfRawData);
1114 H_PUT_32(abfd, in->PointerToRawData, ext->PointerToRawData);
1116 return sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1119 CODEVIEW_INFO *
1120 _bfd_XXi_slurp_codeview_record (bfd * abfd, file_ptr where, unsigned long length, CODEVIEW_INFO *cvinfo,
1121 char **pdb)
1123 char buffer[256+1];
1124 bfd_size_type nread;
1126 if (bfd_seek (abfd, where, SEEK_SET) != 0)
1127 return NULL;
1129 if (length <= sizeof (CV_INFO_PDB70) && length <= sizeof (CV_INFO_PDB20))
1130 return NULL;
1131 if (length > 256)
1132 length = 256;
1133 nread = bfd_read (buffer, length, abfd);
1134 if (length != nread)
1135 return NULL;
1137 /* Ensure null termination of filename. */
1138 memset (buffer + nread, 0, sizeof (buffer) - nread);
1140 cvinfo->CVSignature = H_GET_32 (abfd, buffer);
1141 cvinfo->Age = 0;
1143 if ((cvinfo->CVSignature == CVINFO_PDB70_CVSIGNATURE)
1144 && (length > sizeof (CV_INFO_PDB70)))
1146 CV_INFO_PDB70 *cvinfo70 = (CV_INFO_PDB70 *)(buffer);
1148 cvinfo->Age = H_GET_32(abfd, cvinfo70->Age);
1150 /* A GUID consists of 4,2,2 byte values in little-endian order, followed
1151 by 8 single bytes. Byte swap them so we can conveniently treat the GUID
1152 as 16 bytes in big-endian order. */
1153 bfd_putb32 (bfd_getl32 (cvinfo70->Signature), cvinfo->Signature);
1154 bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[4])), &(cvinfo->Signature[4]));
1155 bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[6])), &(cvinfo->Signature[6]));
1156 memcpy (&(cvinfo->Signature[8]), &(cvinfo70->Signature[8]), 8);
1158 cvinfo->SignatureLength = CV_INFO_SIGNATURE_LENGTH;
1159 /* cvinfo->PdbFileName = cvinfo70->PdbFileName; */
1161 if (pdb)
1162 *pdb = xstrdup (cvinfo70->PdbFileName);
1164 return cvinfo;
1166 else if ((cvinfo->CVSignature == CVINFO_PDB20_CVSIGNATURE)
1167 && (length > sizeof (CV_INFO_PDB20)))
1169 CV_INFO_PDB20 *cvinfo20 = (CV_INFO_PDB20 *)(buffer);
1170 cvinfo->Age = H_GET_32(abfd, cvinfo20->Age);
1171 memcpy (cvinfo->Signature, cvinfo20->Signature, 4);
1172 cvinfo->SignatureLength = 4;
1173 /* cvinfo->PdbFileName = cvinfo20->PdbFileName; */
1175 if (pdb)
1176 *pdb = xstrdup (cvinfo20->PdbFileName);
1178 return cvinfo;
1181 return NULL;
1184 unsigned int
1185 _bfd_XXi_write_codeview_record (bfd * abfd, file_ptr where, CODEVIEW_INFO *cvinfo,
1186 const char *pdb)
1188 size_t pdb_len = pdb ? strlen (pdb) : 0;
1189 const bfd_size_type size = sizeof (CV_INFO_PDB70) + pdb_len + 1;
1190 bfd_size_type written;
1191 CV_INFO_PDB70 *cvinfo70;
1192 char * buffer;
1194 if (bfd_seek (abfd, where, SEEK_SET) != 0)
1195 return 0;
1197 buffer = bfd_malloc (size);
1198 if (buffer == NULL)
1199 return 0;
1201 cvinfo70 = (CV_INFO_PDB70 *) buffer;
1202 H_PUT_32 (abfd, CVINFO_PDB70_CVSIGNATURE, cvinfo70->CvSignature);
1204 /* Byte swap the GUID from 16 bytes in big-endian order to 4,2,2 byte values
1205 in little-endian order, followed by 8 single bytes. */
1206 bfd_putl32 (bfd_getb32 (cvinfo->Signature), cvinfo70->Signature);
1207 bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[4])), &(cvinfo70->Signature[4]));
1208 bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[6])), &(cvinfo70->Signature[6]));
1209 memcpy (&(cvinfo70->Signature[8]), &(cvinfo->Signature[8]), 8);
1211 H_PUT_32 (abfd, cvinfo->Age, cvinfo70->Age);
1213 if (pdb == NULL)
1214 cvinfo70->PdbFileName[0] = '\0';
1215 else
1216 memcpy (cvinfo70->PdbFileName, pdb, pdb_len + 1);
1218 written = bfd_write (buffer, size, abfd);
1220 free (buffer);
1222 return written == size ? size : 0;
1225 static char * dir_names[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] =
1227 N_("Export Directory [.edata (or where ever we found it)]"),
1228 N_("Import Directory [parts of .idata]"),
1229 N_("Resource Directory [.rsrc]"),
1230 N_("Exception Directory [.pdata]"),
1231 N_("Security Directory"),
1232 N_("Base Relocation Directory [.reloc]"),
1233 N_("Debug Directory"),
1234 N_("Description Directory"),
1235 N_("Special Directory"),
1236 N_("Thread Storage Directory [.tls]"),
1237 N_("Load Configuration Directory"),
1238 N_("Bound Import Directory"),
1239 N_("Import Address Table Directory"),
1240 N_("Delay Import Directory"),
1241 N_("CLR Runtime Header"),
1242 N_("Reserved")
1245 static bool
1246 get_contents_sanity_check (bfd *abfd, asection *section,
1247 bfd_size_type dataoff, bfd_size_type datasize)
1249 if ((section->flags & SEC_HAS_CONTENTS) == 0)
1250 return false;
1251 if (dataoff > section->size
1252 || datasize > section->size - dataoff)
1253 return false;
1254 ufile_ptr filesize = bfd_get_file_size (abfd);
1255 if (filesize != 0
1256 && ((ufile_ptr) section->filepos > filesize
1257 || dataoff > filesize - section->filepos
1258 || datasize > filesize - section->filepos - dataoff))
1259 return false;
1260 return true;
1263 static bool
1264 pe_print_idata (bfd * abfd, void * vfile)
1266 FILE *file = (FILE *) vfile;
1267 bfd_byte *data;
1268 asection *section;
1269 bfd_signed_vma adj;
1270 bfd_size_type datasize = 0;
1271 bfd_size_type dataoff;
1272 bfd_size_type i;
1273 int onaline = 20;
1275 pe_data_type *pe = pe_data (abfd);
1276 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1278 bfd_vma addr;
1280 addr = extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress;
1282 if (addr == 0 && extra->DataDirectory[PE_IMPORT_TABLE].Size == 0)
1284 /* Maybe the extra header isn't there. Look for the section. */
1285 section = bfd_get_section_by_name (abfd, ".idata");
1286 if (section == NULL || (section->flags & SEC_HAS_CONTENTS) == 0)
1287 return true;
1289 addr = section->vma;
1290 datasize = section->size;
1291 if (datasize == 0)
1292 return true;
1294 else
1296 addr += extra->ImageBase;
1297 for (section = abfd->sections; section != NULL; section = section->next)
1299 datasize = section->size;
1300 if (addr >= section->vma && addr < section->vma + datasize)
1301 break;
1304 if (section == NULL)
1306 fprintf (file,
1307 _("\nThere is an import table, but the section containing it could not be found\n"));
1308 return true;
1310 else if (!(section->flags & SEC_HAS_CONTENTS))
1312 fprintf (file,
1313 _("\nThere is an import table in %s, but that section has no contents\n"),
1314 section->name);
1315 return true;
1319 /* xgettext:c-format */
1320 fprintf (file, _("\nThere is an import table in %s at 0x%lx\n"),
1321 section->name, (unsigned long) addr);
1323 dataoff = addr - section->vma;
1325 fprintf (file,
1326 _("\nThe Import Tables (interpreted %s section contents)\n"),
1327 section->name);
1328 fprintf (file,
1329 _("\
1330 vma: Hint Time Forward DLL First\n\
1331 Table Stamp Chain Name Thunk\n"));
1333 /* Read the whole section. Some of the fields might be before dataoff. */
1334 if (!bfd_malloc_and_get_section (abfd, section, &data))
1336 free (data);
1337 return false;
1340 adj = section->vma - extra->ImageBase;
1342 /* Print all image import descriptors. */
1343 for (i = dataoff; i + onaline <= datasize; i += onaline)
1345 bfd_vma hint_addr;
1346 bfd_vma time_stamp;
1347 bfd_vma forward_chain;
1348 bfd_vma dll_name;
1349 bfd_vma first_thunk;
1350 int idx = 0;
1351 bfd_size_type j;
1352 char *dll;
1354 /* Print (i + extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress). */
1355 fprintf (file, " %08lx\t", (unsigned long) (i + adj));
1356 hint_addr = bfd_get_32 (abfd, data + i);
1357 time_stamp = bfd_get_32 (abfd, data + i + 4);
1358 forward_chain = bfd_get_32 (abfd, data + i + 8);
1359 dll_name = bfd_get_32 (abfd, data + i + 12);
1360 first_thunk = bfd_get_32 (abfd, data + i + 16);
1362 fprintf (file, "%08lx %08lx %08lx %08lx %08lx\n",
1363 (unsigned long) hint_addr,
1364 (unsigned long) time_stamp,
1365 (unsigned long) forward_chain,
1366 (unsigned long) dll_name,
1367 (unsigned long) first_thunk);
1369 if (hint_addr == 0 && first_thunk == 0)
1370 break;
1372 if (dll_name - adj >= section->size)
1373 break;
1375 dll = (char *) data + dll_name - adj;
1376 /* PR 17512 file: 078-12277-0.004. */
1377 bfd_size_type maxlen = (char *)(data + datasize) - dll - 1;
1378 fprintf (file, _("\n\tDLL Name: %.*s\n"), (int) maxlen, dll);
1380 /* PR 21546: When the Hint Address is zero,
1381 we try the First Thunk instead. */
1382 if (hint_addr == 0)
1383 hint_addr = first_thunk;
1385 if (hint_addr != 0 && hint_addr - adj < datasize)
1387 bfd_byte *ft_data;
1388 asection *ft_section;
1389 bfd_vma ft_addr;
1390 bfd_size_type ft_datasize;
1391 int ft_idx;
1392 int ft_allocated;
1394 fprintf (file, _("\tvma: Ordinal Hint Member-Name Bound-To\n"));
1396 idx = hint_addr - adj;
1398 ft_addr = first_thunk + extra->ImageBase;
1399 ft_idx = first_thunk - adj;
1400 ft_data = data + ft_idx;
1401 ft_datasize = datasize - ft_idx;
1402 ft_allocated = 0;
1404 if (first_thunk != hint_addr)
1406 /* Find the section which contains the first thunk. */
1407 for (ft_section = abfd->sections;
1408 ft_section != NULL;
1409 ft_section = ft_section->next)
1411 if (ft_addr >= ft_section->vma
1412 && ft_addr < ft_section->vma + ft_section->size)
1413 break;
1416 if (ft_section == NULL)
1418 fprintf (file,
1419 _("\nThere is a first thunk, but the section containing it could not be found\n"));
1420 continue;
1423 /* Now check to see if this section is the same as our current
1424 section. If it is not then we will have to load its data in. */
1425 if (ft_section != section)
1427 ft_idx = first_thunk - (ft_section->vma - extra->ImageBase);
1428 ft_datasize = ft_section->size - ft_idx;
1429 if (!get_contents_sanity_check (abfd, ft_section,
1430 ft_idx, ft_datasize))
1431 continue;
1432 ft_data = (bfd_byte *) bfd_malloc (ft_datasize);
1433 if (ft_data == NULL)
1434 continue;
1436 /* Read ft_datasize bytes starting at offset ft_idx. */
1437 if (!bfd_get_section_contents (abfd, ft_section, ft_data,
1438 (bfd_vma) ft_idx, ft_datasize))
1440 free (ft_data);
1441 continue;
1443 ft_allocated = 1;
1447 /* Print HintName vector entries. */
1448 #ifdef COFF_WITH_pex64
1449 for (j = 0; idx + j + 8 <= datasize; j += 8)
1451 bfd_size_type amt;
1452 unsigned long member = bfd_get_32 (abfd, data + idx + j);
1453 unsigned long member_high = bfd_get_32 (abfd, data + idx + j + 4);
1455 if (!member && !member_high)
1456 break;
1458 amt = member - adj;
1460 if (HighBitSet (member_high))
1462 /* in low 16 bits is ordinal number, other bits are reserved */
1463 unsigned int ordinal = member & 0xffff;
1464 fprintf (file, "\t%08lx %5u <none> <none>",
1465 (unsigned long)(first_thunk + j), ordinal);
1467 /* PR binutils/17512: Handle corrupt PE data. */
1468 else if (amt >= datasize || amt + 2 >= datasize)
1469 fprintf (file, _("\t<corrupt: 0x%08lx>"), member);
1470 else
1472 unsigned int hint;
1473 char *member_name;
1475 /* First 16 bits is hint name index, rest is the name */
1476 hint = bfd_get_16 (abfd, data + amt);
1477 member_name = (char *) data + amt + 2;
1478 fprintf (file, "\t%08lx <none> %04x %.*s",
1479 (unsigned long)(first_thunk + j), hint,
1480 (int) (datasize - (amt + 2)), member_name);
1483 /* If the time stamp is not zero, the import address
1484 table holds actual addresses. */
1485 if (time_stamp != 0
1486 && first_thunk != 0
1487 && first_thunk != hint_addr
1488 && j + 4 <= ft_datasize)
1489 fprintf (file, "\t%08lx",
1490 (unsigned long) bfd_get_32 (abfd, ft_data + j));
1492 fprintf (file, "\n");
1494 #else
1495 for (j = 0; idx + j + 4 <= datasize; j += 4)
1497 bfd_size_type amt;
1498 unsigned long member = bfd_get_32 (abfd, data + idx + j);
1500 /* Print single IMAGE_IMPORT_BY_NAME vector. */
1501 if (member == 0)
1502 break;
1504 amt = member - adj;
1506 if (HighBitSet (member))
1508 /* in low 16 bits is ordinal number, other bits are reserved */
1509 unsigned int ordinal = member & 0xffff;
1510 fprintf (file, "\t%08lx %5u <none> <none>", (unsigned long)(first_thunk + j), ordinal);
1512 /* PR binutils/17512: Handle corrupt PE data. */
1513 else if (amt >= datasize || amt + 2 >= datasize)
1514 fprintf (file, _("\t<corrupt: 0x%08lx>"), member);
1515 else
1517 unsigned int hint;
1518 char *member_name;
1520 /* First 16 bits is hint name index, rest is the name */
1521 hint = bfd_get_16 (abfd, data + amt);
1522 member_name = (char *) data + amt + 2;
1523 fprintf (file, "\t%08lx <none> %04x %.*s",
1524 (unsigned long)(first_thunk + j), hint,
1525 (int) (datasize - (amt + 2)), member_name);
1528 /* If the time stamp is not zero, the import address
1529 table holds actual addresses. */
1530 if (time_stamp != 0
1531 && first_thunk != 0
1532 && first_thunk != hint_addr
1533 && j + 4 <= ft_datasize)
1534 fprintf (file, "\t%08lx",
1535 (unsigned long) bfd_get_32 (abfd, ft_data + j));
1537 fprintf (file, "\n");
1539 #endif
1540 if (ft_allocated)
1541 free (ft_data);
1544 fprintf (file, "\n");
1547 free (data);
1549 return true;
1552 static bool
1553 pe_print_edata (bfd * abfd, void * vfile)
1555 FILE *file = (FILE *) vfile;
1556 bfd_byte *data;
1557 asection *section;
1558 bfd_size_type datasize = 0;
1559 bfd_size_type dataoff;
1560 bfd_size_type i;
1561 bfd_vma adj;
1562 struct EDT_type
1564 long export_flags; /* Reserved - should be zero. */
1565 long time_stamp;
1566 short major_ver;
1567 short minor_ver;
1568 bfd_vma name; /* RVA - relative to image base. */
1569 long base; /* Ordinal base. */
1570 unsigned long num_functions;/* Number in the export address table. */
1571 unsigned long num_names; /* Number in the name pointer table. */
1572 bfd_vma eat_addr; /* RVA to the export address table. */
1573 bfd_vma npt_addr; /* RVA to the Export Name Pointer Table. */
1574 bfd_vma ot_addr; /* RVA to the Ordinal Table. */
1575 } edt;
1577 pe_data_type *pe = pe_data (abfd);
1578 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1580 bfd_vma addr;
1582 addr = extra->DataDirectory[PE_EXPORT_TABLE].VirtualAddress;
1584 if (addr == 0 && extra->DataDirectory[PE_EXPORT_TABLE].Size == 0)
1586 /* Maybe the extra header isn't there. Look for the section. */
1587 section = bfd_get_section_by_name (abfd, ".edata");
1588 if (section == NULL)
1589 return true;
1591 addr = section->vma;
1592 dataoff = 0;
1593 datasize = section->size;
1594 if (datasize == 0)
1595 return true;
1597 else
1599 addr += extra->ImageBase;
1601 for (section = abfd->sections; section != NULL; section = section->next)
1602 if (addr >= section->vma && addr < section->vma + section->size)
1603 break;
1605 if (section == NULL)
1607 fprintf (file,
1608 _("\nThere is an export table, but the section containing it could not be found\n"));
1609 return true;
1612 dataoff = addr - section->vma;
1613 datasize = extra->DataDirectory[PE_EXPORT_TABLE].Size;
1616 /* PR 17512: Handle corrupt PE binaries. */
1617 if (datasize < 40)
1619 fprintf (file,
1620 /* xgettext:c-format */
1621 _("\nThere is an export table in %s, but it is too small (%d)\n"),
1622 section->name, (int) datasize);
1623 return true;
1626 if (!get_contents_sanity_check (abfd, section, dataoff, datasize))
1628 fprintf (file,
1629 _("\nThere is an export table in %s, but contents cannot be read\n"),
1630 section->name);
1631 return true;
1634 /* xgettext:c-format */
1635 fprintf (file, _("\nThere is an export table in %s at 0x%lx\n"),
1636 section->name, (unsigned long) addr);
1638 data = (bfd_byte *) bfd_malloc (datasize);
1639 if (data == NULL)
1640 return false;
1642 if (! bfd_get_section_contents (abfd, section, data,
1643 (file_ptr) dataoff, datasize))
1645 free (data);
1646 return false;
1649 /* Go get Export Directory Table. */
1650 edt.export_flags = bfd_get_32 (abfd, data + 0);
1651 edt.time_stamp = bfd_get_32 (abfd, data + 4);
1652 edt.major_ver = bfd_get_16 (abfd, data + 8);
1653 edt.minor_ver = bfd_get_16 (abfd, data + 10);
1654 edt.name = bfd_get_32 (abfd, data + 12);
1655 edt.base = bfd_get_32 (abfd, data + 16);
1656 edt.num_functions = bfd_get_32 (abfd, data + 20);
1657 edt.num_names = bfd_get_32 (abfd, data + 24);
1658 edt.eat_addr = bfd_get_32 (abfd, data + 28);
1659 edt.npt_addr = bfd_get_32 (abfd, data + 32);
1660 edt.ot_addr = bfd_get_32 (abfd, data + 36);
1662 adj = section->vma - extra->ImageBase + dataoff;
1664 /* Dump the EDT first. */
1665 fprintf (file,
1666 _("\nThe Export Tables (interpreted %s section contents)\n\n"),
1667 section->name);
1669 fprintf (file,
1670 _("Export Flags \t\t\t%lx\n"), (unsigned long) edt.export_flags);
1672 fprintf (file,
1673 _("Time/Date stamp \t\t%lx\n"), (unsigned long) edt.time_stamp);
1675 fprintf (file,
1676 /* xgettext:c-format */
1677 _("Major/Minor \t\t\t%d/%d\n"), edt.major_ver, edt.minor_ver);
1679 fprintf (file,
1680 _("Name \t\t\t\t"));
1681 bfd_fprintf_vma (abfd, file, edt.name);
1683 if ((edt.name >= adj) && (edt.name < adj + datasize))
1684 fprintf (file, " %.*s\n",
1685 (int) (datasize - (edt.name - adj)),
1686 data + edt.name - adj);
1687 else
1688 fprintf (file, "(outside .edata section)\n");
1690 fprintf (file,
1691 _("Ordinal Base \t\t\t%ld\n"), edt.base);
1693 fprintf (file,
1694 _("Number in:\n"));
1696 fprintf (file,
1697 _("\tExport Address Table \t\t%08lx\n"),
1698 edt.num_functions);
1700 fprintf (file,
1701 _("\t[Name Pointer/Ordinal] Table\t%08lx\n"), edt.num_names);
1703 fprintf (file,
1704 _("Table Addresses\n"));
1706 fprintf (file,
1707 _("\tExport Address Table \t\t"));
1708 bfd_fprintf_vma (abfd, file, edt.eat_addr);
1709 fprintf (file, "\n");
1711 fprintf (file,
1712 _("\tName Pointer Table \t\t"));
1713 bfd_fprintf_vma (abfd, file, edt.npt_addr);
1714 fprintf (file, "\n");
1716 fprintf (file,
1717 _("\tOrdinal Table \t\t\t"));
1718 bfd_fprintf_vma (abfd, file, edt.ot_addr);
1719 fprintf (file, "\n");
1721 /* The next table to find is the Export Address Table. It's basically
1722 a list of pointers that either locate a function in this dll, or
1723 forward the call to another dll. Something like:
1724 typedef union
1726 long export_rva;
1727 long forwarder_rva;
1728 } export_address_table_entry; */
1730 fprintf (file,
1731 _("\nExport Address Table -- Ordinal Base %ld\n"),
1732 edt.base);
1733 fprintf (file, "\t Ordinal Address Type\n");
1735 /* PR 17512: Handle corrupt PE binaries. */
1736 /* PR 17512 file: 140-165018-0.004. */
1737 if (edt.eat_addr - adj >= datasize
1738 /* PR 17512: file: 092b1829 */
1739 || (edt.num_functions + 1) * 4 < edt.num_functions
1740 || edt.eat_addr - adj + (edt.num_functions + 1) * 4 > datasize)
1741 fprintf (file, _("\tInvalid Export Address Table rva (0x%lx) or entry count (0x%lx)\n"),
1742 (long) edt.eat_addr,
1743 (long) edt.num_functions);
1744 else for (i = 0; i < edt.num_functions; ++i)
1746 bfd_vma eat_member = bfd_get_32 (abfd,
1747 data + edt.eat_addr + (i * 4) - adj);
1748 if (eat_member == 0)
1749 continue;
1751 if (eat_member - adj <= datasize)
1753 /* This rva is to a name (forwarding function) in our section. */
1754 /* Should locate a function descriptor. */
1755 fprintf (file,
1756 "\t[%4ld] +base[%4ld] %08lx %s -- %.*s\n",
1757 (long) i,
1758 (long) (i + edt.base),
1759 (unsigned long) eat_member,
1760 _("Forwarder RVA"),
1761 (int)(datasize - (eat_member - adj)),
1762 data + eat_member - adj);
1764 else
1766 /* Should locate a function descriptor in the reldata section. */
1767 fprintf (file,
1768 "\t[%4ld] +base[%4ld] %08lx %s\n",
1769 (long) i,
1770 (long) (i + edt.base),
1771 (unsigned long) eat_member,
1772 _("Export RVA"));
1776 /* The Export Name Pointer Table is paired with the Export Ordinal Table. */
1777 /* Dump them in parallel for clarity. */
1778 fprintf (file,
1779 _("\n[Ordinal/Name Pointer] Table -- Ordinal Base %ld\n"),
1780 edt.base);
1781 fprintf (file, "\t Ordinal Hint Name\n");
1783 /* PR 17512: Handle corrupt PE binaries. */
1784 if (edt.npt_addr + (edt.num_names * 4) - adj >= datasize
1785 /* PR 17512: file: bb68816e. */
1786 || edt.num_names * 4 < edt.num_names
1787 || (data + edt.npt_addr - adj) < data)
1788 /* xgettext:c-format */
1789 fprintf (file, _("\tInvalid Name Pointer Table rva (0x%lx) or entry count (0x%lx)\n"),
1790 (long) edt.npt_addr,
1791 (long) edt.num_names);
1792 /* PR 17512: file: 140-147171-0.004. */
1793 else if (edt.ot_addr + (edt.num_names * 2) - adj >= datasize
1794 || data + edt.ot_addr - adj < data)
1795 /* xgettext:c-format */
1796 fprintf (file, _("\tInvalid Ordinal Table rva (0x%lx) or entry count (0x%lx)\n"),
1797 (long) edt.ot_addr,
1798 (long) edt.num_names);
1799 else for (i = 0; i < edt.num_names; ++i)
1801 bfd_vma name_ptr;
1802 bfd_vma ord;
1804 ord = bfd_get_16 (abfd, data + edt.ot_addr + (i * 2) - adj);
1805 name_ptr = bfd_get_32 (abfd, data + edt.npt_addr + (i * 4) - adj);
1807 if ((name_ptr - adj) >= datasize)
1809 /* xgettext:c-format */
1810 fprintf (file, _("\t[%4ld] +base[%4ld] %04lx <corrupt offset: %lx>\n"),
1811 (long) ord, (long) (ord + edt.base), (long) i, (long) name_ptr);
1813 else
1815 char * name = (char *) data + name_ptr - adj;
1817 fprintf (file,
1818 "\t[%4ld] +base[%4ld] %04lx %.*s\n",
1819 (long) ord, (long) (ord + edt.base), (long) i,
1820 (int)((char *)(data + datasize) - name), name);
1824 free (data);
1826 return true;
1829 /* This really is architecture dependent. On IA-64, a .pdata entry
1830 consists of three dwords containing relative virtual addresses that
1831 specify the start and end address of the code range the entry
1832 covers and the address of the corresponding unwind info data.
1834 On ARM and SH-4, a compressed PDATA structure is used :
1835 _IMAGE_CE_RUNTIME_FUNCTION_ENTRY, whereas MIPS is documented to use
1836 _IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY.
1837 See http://msdn2.microsoft.com/en-us/library/ms253988(VS.80).aspx .
1839 This is the version for uncompressed data. */
1841 static bool
1842 pe_print_pdata (bfd * abfd, void * vfile)
1844 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
1845 # define PDATA_ROW_SIZE (3 * 8)
1846 #else
1847 # define PDATA_ROW_SIZE (5 * 4)
1848 #endif
1849 FILE *file = (FILE *) vfile;
1850 bfd_byte *data = 0;
1851 asection *section = bfd_get_section_by_name (abfd, ".pdata");
1852 bfd_size_type datasize = 0;
1853 bfd_size_type i;
1854 bfd_size_type start, stop;
1855 int onaline = PDATA_ROW_SIZE;
1857 if (section == NULL
1858 || (section->flags & SEC_HAS_CONTENTS) == 0
1859 || coff_section_data (abfd, section) == NULL
1860 || pei_section_data (abfd, section) == NULL)
1861 return true;
1863 stop = pei_section_data (abfd, section)->virt_size;
1864 if ((stop % onaline) != 0)
1865 fprintf (file,
1866 /* xgettext:c-format */
1867 _("warning, .pdata section size (%ld) is not a multiple of %d\n"),
1868 (long) stop, onaline);
1870 fprintf (file,
1871 _("\nThe Function Table (interpreted .pdata section contents)\n"));
1872 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
1873 fprintf (file,
1874 _(" vma:\t\t\tBegin Address End Address Unwind Info\n"));
1875 #else
1876 fprintf (file, _("\
1877 vma:\t\tBegin End EH EH PrologEnd Exception\n\
1878 \t\tAddress Address Handler Data Address Mask\n"));
1879 #endif
1881 datasize = section->size;
1882 if (datasize == 0)
1883 return true;
1885 /* PR 17512: file: 002-193900-0.004. */
1886 if (datasize < stop)
1888 /* xgettext:c-format */
1889 fprintf (file, _("Virtual size of .pdata section (%ld) larger than real size (%ld)\n"),
1890 (long) stop, (long) datasize);
1891 return false;
1894 if (! bfd_malloc_and_get_section (abfd, section, &data))
1896 free (data);
1897 return false;
1900 start = 0;
1902 for (i = start; i < stop; i += onaline)
1904 bfd_vma begin_addr;
1905 bfd_vma end_addr;
1906 bfd_vma eh_handler;
1907 bfd_vma eh_data;
1908 bfd_vma prolog_end_addr;
1909 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64)
1910 int em_data;
1911 #endif
1913 if (i + PDATA_ROW_SIZE > stop)
1914 break;
1916 begin_addr = GET_PDATA_ENTRY (abfd, data + i );
1917 end_addr = GET_PDATA_ENTRY (abfd, data + i + 4);
1918 eh_handler = GET_PDATA_ENTRY (abfd, data + i + 8);
1919 eh_data = GET_PDATA_ENTRY (abfd, data + i + 12);
1920 prolog_end_addr = GET_PDATA_ENTRY (abfd, data + i + 16);
1922 if (begin_addr == 0 && end_addr == 0 && eh_handler == 0
1923 && eh_data == 0 && prolog_end_addr == 0)
1924 /* We are probably into the padding of the section now. */
1925 break;
1927 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64)
1928 em_data = ((eh_handler & 0x1) << 2) | (prolog_end_addr & 0x3);
1929 #endif
1930 eh_handler &= ~(bfd_vma) 0x3;
1931 prolog_end_addr &= ~(bfd_vma) 0x3;
1933 fputc (' ', file);
1934 bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
1935 bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
1936 bfd_fprintf_vma (abfd, file, end_addr); fputc (' ', file);
1937 bfd_fprintf_vma (abfd, file, eh_handler);
1938 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64)
1939 fputc (' ', file);
1940 bfd_fprintf_vma (abfd, file, eh_data); fputc (' ', file);
1941 bfd_fprintf_vma (abfd, file, prolog_end_addr);
1942 fprintf (file, " %x", em_data);
1943 #endif
1944 fprintf (file, "\n");
1947 free (data);
1949 return true;
1950 #undef PDATA_ROW_SIZE
1953 typedef struct sym_cache
1955 int symcount;
1956 asymbol ** syms;
1957 } sym_cache;
1959 static asymbol **
1960 slurp_symtab (bfd *abfd, sym_cache *psc)
1962 asymbol ** sy = NULL;
1963 long storage;
1965 if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
1967 psc->symcount = 0;
1968 return NULL;
1971 storage = bfd_get_symtab_upper_bound (abfd);
1972 if (storage < 0)
1973 return NULL;
1974 if (storage)
1976 sy = (asymbol **) bfd_malloc (storage);
1977 if (sy == NULL)
1978 return NULL;
1981 psc->symcount = bfd_canonicalize_symtab (abfd, sy);
1982 if (psc->symcount < 0)
1983 return NULL;
1984 return sy;
1987 static const char *
1988 my_symbol_for_address (bfd *abfd, bfd_vma func, sym_cache *psc)
1990 int i;
1992 if (psc->syms == 0)
1993 psc->syms = slurp_symtab (abfd, psc);
1995 for (i = 0; i < psc->symcount; i++)
1997 if (psc->syms[i]->section->vma + psc->syms[i]->value == func)
1998 return psc->syms[i]->name;
2001 return NULL;
2004 static void
2005 cleanup_syms (sym_cache *psc)
2007 psc->symcount = 0;
2008 free (psc->syms);
2009 psc->syms = NULL;
2012 /* This is the version for "compressed" pdata. */
2014 bool
2015 _bfd_XX_print_ce_compressed_pdata (bfd * abfd, void * vfile)
2017 # define PDATA_ROW_SIZE (2 * 4)
2018 FILE *file = (FILE *) vfile;
2019 bfd_byte *data = NULL;
2020 asection *section = bfd_get_section_by_name (abfd, ".pdata");
2021 bfd_size_type datasize = 0;
2022 bfd_size_type i;
2023 bfd_size_type start, stop;
2024 int onaline = PDATA_ROW_SIZE;
2025 struct sym_cache cache = {0, 0} ;
2027 if (section == NULL
2028 || (section->flags & SEC_HAS_CONTENTS) == 0
2029 || coff_section_data (abfd, section) == NULL
2030 || pei_section_data (abfd, section) == NULL)
2031 return true;
2033 stop = pei_section_data (abfd, section)->virt_size;
2034 if ((stop % onaline) != 0)
2035 fprintf (file,
2036 /* xgettext:c-format */
2037 _("warning, .pdata section size (%ld) is not a multiple of %d\n"),
2038 (long) stop, onaline);
2040 fprintf (file,
2041 _("\nThe Function Table (interpreted .pdata section contents)\n"));
2043 fprintf (file, _("\
2044 vma:\t\tBegin Prolog Function Flags Exception EH\n\
2045 \t\tAddress Length Length 32b exc Handler Data\n"));
2047 datasize = section->size;
2048 if (datasize == 0)
2049 return true;
2051 if (! bfd_malloc_and_get_section (abfd, section, &data))
2053 free (data);
2054 return false;
2057 start = 0;
2058 if (stop > datasize)
2059 stop = datasize;
2061 for (i = start; i < stop; i += onaline)
2063 bfd_vma begin_addr;
2064 bfd_vma other_data;
2065 bfd_vma prolog_length, function_length;
2066 int flag32bit, exception_flag;
2067 asection *tsection;
2069 if (i + PDATA_ROW_SIZE > stop)
2070 break;
2072 begin_addr = GET_PDATA_ENTRY (abfd, data + i );
2073 other_data = GET_PDATA_ENTRY (abfd, data + i + 4);
2075 if (begin_addr == 0 && other_data == 0)
2076 /* We are probably into the padding of the section now. */
2077 break;
2079 prolog_length = (other_data & 0x000000FF);
2080 function_length = (other_data & 0x3FFFFF00) >> 8;
2081 flag32bit = (int)((other_data & 0x40000000) >> 30);
2082 exception_flag = (int)((other_data & 0x80000000) >> 31);
2084 fputc (' ', file);
2085 bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
2086 bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
2087 bfd_fprintf_vma (abfd, file, prolog_length); fputc (' ', file);
2088 bfd_fprintf_vma (abfd, file, function_length); fputc (' ', file);
2089 fprintf (file, "%2d %2d ", flag32bit, exception_flag);
2091 /* Get the exception handler's address and the data passed from the
2092 .text section. This is really the data that belongs with the .pdata
2093 but got "compressed" out for the ARM and SH4 architectures. */
2094 tsection = bfd_get_section_by_name (abfd, ".text");
2095 if (tsection && coff_section_data (abfd, tsection)
2096 && pei_section_data (abfd, tsection))
2098 bfd_vma eh_off = (begin_addr - 8) - tsection->vma;
2099 bfd_byte *tdata;
2101 tdata = (bfd_byte *) bfd_malloc (8);
2102 if (tdata)
2104 if (bfd_get_section_contents (abfd, tsection, tdata, eh_off, 8))
2106 bfd_vma eh, eh_data;
2108 eh = bfd_get_32 (abfd, tdata);
2109 eh_data = bfd_get_32 (abfd, tdata + 4);
2110 fprintf (file, "%08x ", (unsigned int) eh);
2111 fprintf (file, "%08x", (unsigned int) eh_data);
2112 if (eh != 0)
2114 const char *s = my_symbol_for_address (abfd, eh, &cache);
2116 if (s)
2117 fprintf (file, " (%s) ", s);
2120 free (tdata);
2124 fprintf (file, "\n");
2127 free (data);
2129 cleanup_syms (& cache);
2131 return true;
2132 #undef PDATA_ROW_SIZE
2136 #define IMAGE_REL_BASED_HIGHADJ 4
2137 static const char * const tbl[] =
2139 "ABSOLUTE",
2140 "HIGH",
2141 "LOW",
2142 "HIGHLOW",
2143 "HIGHADJ",
2144 "MIPS_JMPADDR",
2145 "SECTION",
2146 "REL32",
2147 "RESERVED1",
2148 "MIPS_JMPADDR16",
2149 "DIR64",
2150 "HIGH3ADJ",
2151 "UNKNOWN", /* MUST be last. */
2154 static bool
2155 pe_print_reloc (bfd * abfd, void * vfile)
2157 FILE *file = (FILE *) vfile;
2158 bfd_byte *data = 0;
2159 asection *section = bfd_get_section_by_name (abfd, ".reloc");
2160 bfd_byte *p, *end;
2162 if (section == NULL
2163 || section->size == 0
2164 || (section->flags & SEC_HAS_CONTENTS) == 0)
2165 return true;
2167 fprintf (file,
2168 _("\n\nPE File Base Relocations (interpreted .reloc section contents)\n"));
2170 if (! bfd_malloc_and_get_section (abfd, section, &data))
2172 free (data);
2173 return false;
2176 p = data;
2177 end = data + section->size;
2178 while (p + 8 <= end)
2180 int j;
2181 bfd_vma virtual_address;
2182 unsigned long number, size;
2183 bfd_byte *chunk_end;
2185 /* The .reloc section is a sequence of blocks, with a header consisting
2186 of two 32 bit quantities, followed by a number of 16 bit entries. */
2187 virtual_address = bfd_get_32 (abfd, p);
2188 size = bfd_get_32 (abfd, p + 4);
2189 p += 8;
2190 number = (size - 8) / 2;
2192 if (size == 0)
2193 break;
2195 fprintf (file,
2196 /* xgettext:c-format */
2197 _("\nVirtual Address: %08lx Chunk size %ld (0x%lx) Number of fixups %ld\n"),
2198 (unsigned long) virtual_address, size, size, number);
2200 chunk_end = p - 8 + size;
2201 if (chunk_end > end)
2202 chunk_end = end;
2203 j = 0;
2204 while (p + 2 <= chunk_end)
2206 unsigned short e = bfd_get_16 (abfd, p);
2207 unsigned int t = (e & 0xF000) >> 12;
2208 int off = e & 0x0FFF;
2210 if (t >= sizeof (tbl) / sizeof (tbl[0]))
2211 t = (sizeof (tbl) / sizeof (tbl[0])) - 1;
2213 fprintf (file,
2214 /* xgettext:c-format */
2215 _("\treloc %4d offset %4x [%4lx] %s"),
2216 j, off, (unsigned long) (off + virtual_address), tbl[t]);
2218 p += 2;
2219 j++;
2221 /* HIGHADJ takes an argument, - the next record *is* the
2222 low 16 bits of addend. */
2223 if (t == IMAGE_REL_BASED_HIGHADJ && p + 2 <= chunk_end)
2225 fprintf (file, " (%4x)", (unsigned int) bfd_get_16 (abfd, p));
2226 p += 2;
2227 j++;
2230 fprintf (file, "\n");
2234 free (data);
2236 return true;
2239 /* A data structure describing the regions of a .rsrc section.
2240 Some fields are filled in as the section is parsed. */
2242 typedef struct rsrc_regions
2244 bfd_byte * section_start;
2245 bfd_byte * section_end;
2246 bfd_byte * strings_start;
2247 bfd_byte * resource_start;
2248 } rsrc_regions;
2250 static bfd_byte *
2251 rsrc_print_resource_directory (FILE * , bfd *, unsigned int, bfd_byte *,
2252 rsrc_regions *, bfd_vma);
2254 /* Print the resource entry at DATA, with the text indented by INDENT.
2255 Recusively calls rsrc_print_resource_directory to print the contents
2256 of directory entries.
2257 Returns the address of the end of the data associated with the entry
2258 or section_end + 1 upon failure. */
2260 static bfd_byte *
2261 rsrc_print_resource_entries (FILE *file,
2262 bfd *abfd,
2263 unsigned int indent,
2264 bool is_name,
2265 bfd_byte *data,
2266 rsrc_regions *regions,
2267 bfd_vma rva_bias)
2269 unsigned long entry, addr, size;
2270 bfd_byte * leaf;
2272 if (data + 8 >= regions->section_end)
2273 return regions->section_end + 1;
2275 /* xgettext:c-format */
2276 fprintf (file, _("%03x %*.s Entry: "), (int)(data - regions->section_start), indent, " ");
2278 entry = (unsigned long) bfd_get_32 (abfd, data);
2279 if (is_name)
2281 bfd_byte * name;
2283 /* Note - the documentation says that this field is an RVA value
2284 but windres appears to produce a section relative offset with
2285 the top bit set. Support both styles for now. */
2286 if (HighBitSet (entry))
2287 name = regions->section_start + WithoutHighBit (entry);
2288 else
2289 name = regions->section_start + entry - rva_bias;
2291 if (name + 2 < regions->section_end && name > regions->section_start)
2293 unsigned int len;
2295 if (regions->strings_start == NULL)
2296 regions->strings_start = name;
2298 len = bfd_get_16 (abfd, name);
2300 fprintf (file, _("name: [val: %08lx len %d]: "), entry, len);
2302 if (name + 2 + len * 2 < regions->section_end)
2304 /* This strange loop is to cope with multibyte characters. */
2305 while (len --)
2307 char c;
2309 name += 2;
2310 c = * name;
2311 /* Avoid printing control characters. */
2312 if (c > 0 && c < 32)
2313 fprintf (file, "^%c", c + 64);
2314 else
2315 fprintf (file, "%.1s", name);
2318 else
2320 fprintf (file, _("<corrupt string length: %#x>\n"), len);
2321 /* PR binutils/17512: Do not try to continue decoding a
2322 corrupted resource section. It is likely to end up with
2323 reams of extraneous output. FIXME: We could probably
2324 continue if we disable the printing of strings... */
2325 return regions->section_end + 1;
2328 else
2330 fprintf (file, _("<corrupt string offset: %#lx>\n"), entry);
2331 return regions->section_end + 1;
2334 else
2335 fprintf (file, _("ID: %#08lx"), entry);
2337 entry = (long) bfd_get_32 (abfd, data + 4);
2338 fprintf (file, _(", Value: %#08lx\n"), entry);
2340 if (HighBitSet (entry))
2342 data = regions->section_start + WithoutHighBit (entry);
2343 if (data <= regions->section_start || data > regions->section_end)
2344 return regions->section_end + 1;
2346 /* FIXME: PR binutils/17512: A corrupt file could contain a loop
2347 in the resource table. We need some way to detect this. */
2348 return rsrc_print_resource_directory (file, abfd, indent + 1, data,
2349 regions, rva_bias);
2352 leaf = regions->section_start + entry;
2354 if (leaf + 16 >= regions->section_end
2355 /* PR 17512: file: 055dff7e. */
2356 || leaf < regions->section_start)
2357 return regions->section_end + 1;
2359 /* xgettext:c-format */
2360 fprintf (file, _("%03x %*.s Leaf: Addr: %#08lx, Size: %#08lx, Codepage: %d\n"),
2361 (int) (entry), indent, " ",
2362 addr = (long) bfd_get_32 (abfd, leaf),
2363 size = (long) bfd_get_32 (abfd, leaf + 4),
2364 (int) bfd_get_32 (abfd, leaf + 8));
2366 /* Check that the reserved entry is 0. */
2367 if (bfd_get_32 (abfd, leaf + 12) != 0
2368 /* And that the data address/size is valid too. */
2369 || (regions->section_start + (addr - rva_bias) + size > regions->section_end))
2370 return regions->section_end + 1;
2372 if (regions->resource_start == NULL)
2373 regions->resource_start = regions->section_start + (addr - rva_bias);
2375 return regions->section_start + (addr - rva_bias) + size;
2378 #define max(a,b) ((a) > (b) ? (a) : (b))
2379 #define min(a,b) ((a) < (b) ? (a) : (b))
2381 static bfd_byte *
2382 rsrc_print_resource_directory (FILE * file,
2383 bfd * abfd,
2384 unsigned int indent,
2385 bfd_byte * data,
2386 rsrc_regions * regions,
2387 bfd_vma rva_bias)
2389 unsigned int num_names, num_ids;
2390 bfd_byte * highest_data = data;
2392 if (data + 16 >= regions->section_end)
2393 return regions->section_end + 1;
2395 fprintf (file, "%03x %*.s ", (int)(data - regions->section_start), indent, " ");
2396 switch (indent)
2398 case 0: fprintf (file, "Type"); break;
2399 case 2: fprintf (file, "Name"); break;
2400 case 4: fprintf (file, "Language"); break;
2401 default:
2402 fprintf (file, _("<unknown directory type: %d>\n"), indent);
2403 /* FIXME: For now we end the printing here. If in the
2404 future more directory types are added to the RSRC spec
2405 then we will need to change this. */
2406 return regions->section_end + 1;
2409 /* xgettext:c-format */
2410 fprintf (file, _(" Table: Char: %d, Time: %08lx, Ver: %d/%d, Num Names: %d, IDs: %d\n"),
2411 (int) bfd_get_32 (abfd, data),
2412 (long) bfd_get_32 (abfd, data + 4),
2413 (int) bfd_get_16 (abfd, data + 8),
2414 (int) bfd_get_16 (abfd, data + 10),
2415 num_names = (int) bfd_get_16 (abfd, data + 12),
2416 num_ids = (int) bfd_get_16 (abfd, data + 14));
2417 data += 16;
2419 while (num_names --)
2421 bfd_byte * entry_end;
2423 entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, true,
2424 data, regions, rva_bias);
2425 data += 8;
2426 highest_data = max (highest_data, entry_end);
2427 if (entry_end >= regions->section_end)
2428 return entry_end;
2431 while (num_ids --)
2433 bfd_byte * entry_end;
2435 entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, false,
2436 data, regions, rva_bias);
2437 data += 8;
2438 highest_data = max (highest_data, entry_end);
2439 if (entry_end >= regions->section_end)
2440 return entry_end;
2443 return max (highest_data, data);
2446 /* Display the contents of a .rsrc section. We do not try to
2447 reproduce the resources, windres does that. Instead we dump
2448 the tables in a human readable format. */
2450 static bool
2451 rsrc_print_section (bfd * abfd, void * vfile)
2453 bfd_vma rva_bias;
2454 pe_data_type * pe;
2455 FILE * file = (FILE *) vfile;
2456 bfd_size_type datasize;
2457 asection * section;
2458 bfd_byte * data;
2459 rsrc_regions regions;
2461 pe = pe_data (abfd);
2462 if (pe == NULL)
2463 return true;
2465 section = bfd_get_section_by_name (abfd, ".rsrc");
2466 if (section == NULL)
2467 return true;
2468 if (!(section->flags & SEC_HAS_CONTENTS))
2469 return true;
2471 datasize = section->size;
2472 if (datasize == 0)
2473 return true;
2475 rva_bias = section->vma - pe->pe_opthdr.ImageBase;
2477 if (! bfd_malloc_and_get_section (abfd, section, & data))
2479 free (data);
2480 return false;
2483 regions.section_start = data;
2484 regions.section_end = data + datasize;
2485 regions.strings_start = NULL;
2486 regions.resource_start = NULL;
2488 fflush (file);
2489 fprintf (file, "\nThe .rsrc Resource Directory section:\n");
2491 while (data < regions.section_end)
2493 bfd_byte * p = data;
2495 data = rsrc_print_resource_directory (file, abfd, 0, data, & regions, rva_bias);
2497 if (data == regions.section_end + 1)
2498 fprintf (file, _("Corrupt .rsrc section detected!\n"));
2499 else
2501 /* Align data before continuing. */
2502 int align = (1 << section->alignment_power) - 1;
2504 data = (bfd_byte *) (((ptrdiff_t) (data + align)) & ~ align);
2505 rva_bias += data - p;
2507 /* For reasons that are unclear .rsrc sections are sometimes created
2508 aligned to a 1^3 boundary even when their alignment is set at
2509 1^2. Catch that case here before we issue a spurious warning
2510 message. */
2511 if (data == (regions.section_end - 4))
2512 data = regions.section_end;
2513 else if (data < regions.section_end)
2515 /* If the extra data is all zeros then do not complain.
2516 This is just padding so that the section meets the
2517 page size requirements. */
2518 while (++ data < regions.section_end)
2519 if (*data != 0)
2520 break;
2521 if (data < regions.section_end)
2522 fprintf (file, _("\nWARNING: Extra data in .rsrc section - it will be ignored by Windows:\n"));
2527 if (regions.strings_start != NULL)
2528 fprintf (file, _(" String table starts at offset: %#03x\n"),
2529 (int) (regions.strings_start - regions.section_start));
2530 if (regions.resource_start != NULL)
2531 fprintf (file, _(" Resources start at offset: %#03x\n"),
2532 (int) (regions.resource_start - regions.section_start));
2534 free (regions.section_start);
2535 return true;
2538 #define IMAGE_NUMBEROF_DEBUG_TYPES 17
2540 static char * debug_type_names[IMAGE_NUMBEROF_DEBUG_TYPES] =
2542 "Unknown",
2543 "COFF",
2544 "CodeView",
2545 "FPO",
2546 "Misc",
2547 "Exception",
2548 "Fixup",
2549 "OMAP-to-SRC",
2550 "OMAP-from-SRC",
2551 "Borland",
2552 "Reserved",
2553 "CLSID",
2554 "Feature",
2555 "CoffGrp",
2556 "ILTCG",
2557 "MPX",
2558 "Repro",
2561 static bool
2562 pe_print_debugdata (bfd * abfd, void * vfile)
2564 FILE *file = (FILE *) vfile;
2565 pe_data_type *pe = pe_data (abfd);
2566 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
2567 asection *section;
2568 bfd_byte *data = 0;
2569 bfd_size_type dataoff;
2570 unsigned int i, j;
2572 bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress;
2573 bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size;
2575 if (size == 0)
2576 return true;
2578 addr += extra->ImageBase;
2579 for (section = abfd->sections; section != NULL; section = section->next)
2581 if ((addr >= section->vma) && (addr < (section->vma + section->size)))
2582 break;
2585 if (section == NULL)
2587 fprintf (file,
2588 _("\nThere is a debug directory, but the section containing it could not be found\n"));
2589 return true;
2591 else if (!(section->flags & SEC_HAS_CONTENTS))
2593 fprintf (file,
2594 _("\nThere is a debug directory in %s, but that section has no contents\n"),
2595 section->name);
2596 return true;
2598 else if (section->size < size)
2600 fprintf (file,
2601 _("\nError: section %s contains the debug data starting address but it is too small\n"),
2602 section->name);
2603 return false;
2606 fprintf (file, _("\nThere is a debug directory in %s at 0x%lx\n\n"),
2607 section->name, (unsigned long) addr);
2609 dataoff = addr - section->vma;
2611 if (size > (section->size - dataoff))
2613 fprintf (file, _("The debug data size field in the data directory is too big for the section"));
2614 return false;
2617 fprintf (file,
2618 _("Type Size Rva Offset\n"));
2620 /* Read the whole section. */
2621 if (!bfd_malloc_and_get_section (abfd, section, &data))
2623 free (data);
2624 return false;
2627 for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
2629 const char *type_name;
2630 struct external_IMAGE_DEBUG_DIRECTORY *ext
2631 = &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i];
2632 struct internal_IMAGE_DEBUG_DIRECTORY idd;
2634 _bfd_XXi_swap_debugdir_in (abfd, ext, &idd);
2636 if ((idd.Type) >= IMAGE_NUMBEROF_DEBUG_TYPES)
2637 type_name = debug_type_names[0];
2638 else
2639 type_name = debug_type_names[idd.Type];
2641 fprintf (file, " %2ld %14s %08lx %08lx %08lx\n",
2642 idd.Type, type_name, idd.SizeOfData,
2643 idd.AddressOfRawData, idd.PointerToRawData);
2645 if (idd.Type == PE_IMAGE_DEBUG_TYPE_CODEVIEW)
2647 char signature[CV_INFO_SIGNATURE_LENGTH * 2 + 1];
2648 /* PR 17512: file: 065-29434-0.001:0.1
2649 We need to use a 32-bit aligned buffer
2650 to safely read in a codeview record. */
2651 char buffer[256 + 1] ATTRIBUTE_ALIGNED_ALIGNOF (CODEVIEW_INFO);
2652 char *pdb;
2654 CODEVIEW_INFO *cvinfo = (CODEVIEW_INFO *) buffer;
2656 /* The debug entry doesn't have to have to be in a section,
2657 in which case AddressOfRawData is 0, so always use PointerToRawData. */
2658 if (!_bfd_XXi_slurp_codeview_record (abfd, (file_ptr) idd.PointerToRawData,
2659 idd.SizeOfData, cvinfo, &pdb))
2660 continue;
2662 for (j = 0; j < cvinfo->SignatureLength; j++)
2663 sprintf (&signature[j*2], "%02x", cvinfo->Signature[j] & 0xff);
2665 /* xgettext:c-format */
2666 fprintf (file, _("(format %c%c%c%c signature %s age %ld pdb %s)\n"),
2667 buffer[0], buffer[1], buffer[2], buffer[3],
2668 signature, cvinfo->Age, pdb[0] ? pdb : "(none)");
2670 free (pdb);
2674 free(data);
2676 if (size % sizeof (struct external_IMAGE_DEBUG_DIRECTORY) != 0)
2677 fprintf (file,
2678 _("The debug directory size is not a multiple of the debug directory entry size\n"));
2680 return true;
2683 static bool
2684 pe_is_repro (bfd * abfd)
2686 pe_data_type *pe = pe_data (abfd);
2687 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
2688 asection *section;
2689 bfd_byte *data = 0;
2690 bfd_size_type dataoff;
2691 unsigned int i;
2692 bool res = false;
2694 bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress;
2695 bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size;
2697 if (size == 0)
2698 return false;
2700 addr += extra->ImageBase;
2701 for (section = abfd->sections; section != NULL; section = section->next)
2703 if ((addr >= section->vma) && (addr < (section->vma + section->size)))
2704 break;
2707 if ((section == NULL)
2708 || (!(section->flags & SEC_HAS_CONTENTS))
2709 || (section->size < size))
2711 return false;
2714 dataoff = addr - section->vma;
2716 if (size > (section->size - dataoff))
2718 return false;
2721 if (!bfd_malloc_and_get_section (abfd, section, &data))
2723 free (data);
2724 return false;
2727 for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
2729 struct external_IMAGE_DEBUG_DIRECTORY *ext
2730 = &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i];
2731 struct internal_IMAGE_DEBUG_DIRECTORY idd;
2733 _bfd_XXi_swap_debugdir_in (abfd, ext, &idd);
2735 if (idd.Type == PE_IMAGE_DEBUG_TYPE_REPRO)
2737 res = true;
2738 break;
2742 free(data);
2744 return res;
2747 /* Print out the program headers. */
2749 bool
2750 _bfd_XX_print_private_bfd_data_common (bfd * abfd, void * vfile)
2752 FILE *file = (FILE *) vfile;
2753 int j;
2754 pe_data_type *pe = pe_data (abfd);
2755 struct internal_extra_pe_aouthdr *i = &pe->pe_opthdr;
2756 const char *subsystem_name = NULL;
2757 const char *name;
2759 /* The MS dumpbin program reportedly ands with 0xff0f before
2760 printing the characteristics field. Not sure why. No reason to
2761 emulate it here. */
2762 fprintf (file, _("\nCharacteristics 0x%x\n"), pe->real_flags);
2763 #undef PF
2764 #define PF(x, y) if (pe->real_flags & x) { fprintf (file, "\t%s\n", y); }
2765 PF (IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped");
2766 PF (IMAGE_FILE_EXECUTABLE_IMAGE, "executable");
2767 PF (IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped");
2768 PF (IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped");
2769 PF (IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware");
2770 PF (IMAGE_FILE_BYTES_REVERSED_LO, "little endian");
2771 PF (IMAGE_FILE_32BIT_MACHINE, "32 bit words");
2772 PF (IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed");
2773 PF (IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, "copy to swap file if on removable media");
2774 PF (IMAGE_FILE_NET_RUN_FROM_SWAP, "copy to swap file if on network media");
2775 PF (IMAGE_FILE_SYSTEM, "system file");
2776 PF (IMAGE_FILE_DLL, "DLL");
2777 PF (IMAGE_FILE_UP_SYSTEM_ONLY, "run only on uniprocessor machine");
2778 PF (IMAGE_FILE_BYTES_REVERSED_HI, "big endian");
2779 #undef PF
2782 If a PE_IMAGE_DEBUG_TYPE_REPRO entry is present in the debug directory, the
2783 timestamp is to be interpreted as the hash of a reproducible build.
2785 if (pe_is_repro (abfd))
2787 fprintf (file, "\nTime/Date\t\t%08lx", pe->coff.timestamp);
2788 fprintf (file, "\t(This is a reproducible build file hash, not a timestamp)\n");
2790 else
2792 /* ctime implies '\n'. */
2793 time_t t = pe->coff.timestamp;
2794 fprintf (file, "\nTime/Date\t\t%s", ctime (&t));
2797 #ifndef IMAGE_NT_OPTIONAL_HDR_MAGIC
2798 # define IMAGE_NT_OPTIONAL_HDR_MAGIC 0x10b
2799 #endif
2800 #ifndef IMAGE_NT_OPTIONAL_HDR64_MAGIC
2801 # define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
2802 #endif
2803 #ifndef IMAGE_NT_OPTIONAL_HDRROM_MAGIC
2804 # define IMAGE_NT_OPTIONAL_HDRROM_MAGIC 0x107
2805 #endif
2807 switch (i->Magic)
2809 case IMAGE_NT_OPTIONAL_HDR_MAGIC:
2810 name = "PE32";
2811 break;
2812 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
2813 name = "PE32+";
2814 break;
2815 case IMAGE_NT_OPTIONAL_HDRROM_MAGIC:
2816 name = "ROM";
2817 break;
2818 default:
2819 name = NULL;
2820 break;
2822 fprintf (file, "Magic\t\t\t%04x", i->Magic);
2823 if (name)
2824 fprintf (file, "\t(%s)",name);
2825 fprintf (file, "\nMajorLinkerVersion\t%d\n", i->MajorLinkerVersion);
2826 fprintf (file, "MinorLinkerVersion\t%d\n", i->MinorLinkerVersion);
2827 fprintf (file, "SizeOfCode\t\t");
2828 bfd_fprintf_vma (abfd, file, i->SizeOfCode);
2829 fprintf (file, "\nSizeOfInitializedData\t");
2830 bfd_fprintf_vma (abfd, file, i->SizeOfInitializedData);
2831 fprintf (file, "\nSizeOfUninitializedData\t");
2832 bfd_fprintf_vma (abfd, file, i->SizeOfUninitializedData);
2833 fprintf (file, "\nAddressOfEntryPoint\t");
2834 bfd_fprintf_vma (abfd, file, i->AddressOfEntryPoint);
2835 fprintf (file, "\nBaseOfCode\t\t");
2836 bfd_fprintf_vma (abfd, file, i->BaseOfCode);
2837 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
2838 /* PE32+ does not have BaseOfData member! */
2839 fprintf (file, "\nBaseOfData\t\t");
2840 bfd_fprintf_vma (abfd, file, i->BaseOfData);
2841 #endif
2843 fprintf (file, "\nImageBase\t\t");
2844 bfd_fprintf_vma (abfd, file, i->ImageBase);
2845 fprintf (file, "\nSectionAlignment\t%08x\n", i->SectionAlignment);
2846 fprintf (file, "FileAlignment\t\t%08x\n", i->FileAlignment);
2847 fprintf (file, "MajorOSystemVersion\t%d\n", i->MajorOperatingSystemVersion);
2848 fprintf (file, "MinorOSystemVersion\t%d\n", i->MinorOperatingSystemVersion);
2849 fprintf (file, "MajorImageVersion\t%d\n", i->MajorImageVersion);
2850 fprintf (file, "MinorImageVersion\t%d\n", i->MinorImageVersion);
2851 fprintf (file, "MajorSubsystemVersion\t%d\n", i->MajorSubsystemVersion);
2852 fprintf (file, "MinorSubsystemVersion\t%d\n", i->MinorSubsystemVersion);
2853 fprintf (file, "Win32Version\t\t%08x\n", i->Win32Version);
2854 fprintf (file, "SizeOfImage\t\t%08x\n", i->SizeOfImage);
2855 fprintf (file, "SizeOfHeaders\t\t%08x\n", i->SizeOfHeaders);
2856 fprintf (file, "CheckSum\t\t%08x\n", i->CheckSum);
2858 switch (i->Subsystem)
2860 case IMAGE_SUBSYSTEM_UNKNOWN:
2861 subsystem_name = "unspecified";
2862 break;
2863 case IMAGE_SUBSYSTEM_NATIVE:
2864 subsystem_name = "NT native";
2865 break;
2866 case IMAGE_SUBSYSTEM_WINDOWS_GUI:
2867 subsystem_name = "Windows GUI";
2868 break;
2869 case IMAGE_SUBSYSTEM_WINDOWS_CUI:
2870 subsystem_name = "Windows CUI";
2871 break;
2872 case IMAGE_SUBSYSTEM_POSIX_CUI:
2873 subsystem_name = "POSIX CUI";
2874 break;
2875 case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
2876 subsystem_name = "Wince CUI";
2877 break;
2878 /* These are from UEFI Platform Initialization Specification 1.1. */
2879 case IMAGE_SUBSYSTEM_EFI_APPLICATION:
2880 subsystem_name = "EFI application";
2881 break;
2882 case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
2883 subsystem_name = "EFI boot service driver";
2884 break;
2885 case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
2886 subsystem_name = "EFI runtime driver";
2887 break;
2888 case IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
2889 subsystem_name = "SAL runtime driver";
2890 break;
2891 /* This is from revision 8.0 of the MS PE/COFF spec */
2892 case IMAGE_SUBSYSTEM_XBOX:
2893 subsystem_name = "XBOX";
2894 break;
2895 /* Added default case for clarity - subsystem_name is NULL anyway. */
2896 default:
2897 subsystem_name = NULL;
2900 fprintf (file, "Subsystem\t\t%08x", i->Subsystem);
2901 if (subsystem_name)
2902 fprintf (file, "\t(%s)", subsystem_name);
2903 fprintf (file, "\nDllCharacteristics\t%08x\n", i->DllCharacteristics);
2904 if (i->DllCharacteristics)
2906 unsigned short dllch = i->DllCharacteristics;
2907 const char *indent = "\t\t\t\t\t";
2909 if (dllch & IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA)
2910 fprintf (file, "%sHIGH_ENTROPY_VA\n", indent);
2911 if (dllch & IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE)
2912 fprintf (file, "%sDYNAMIC_BASE\n", indent);
2913 if (dllch & IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY)
2914 fprintf (file, "%sFORCE_INTEGRITY\n", indent);
2915 if (dllch & IMAGE_DLL_CHARACTERISTICS_NX_COMPAT)
2916 fprintf (file, "%sNX_COMPAT\n", indent);
2917 if (dllch & IMAGE_DLLCHARACTERISTICS_NO_ISOLATION)
2918 fprintf (file, "%sNO_ISOLATION\n", indent);
2919 if (dllch & IMAGE_DLLCHARACTERISTICS_NO_SEH)
2920 fprintf (file, "%sNO_SEH\n", indent);
2921 if (dllch & IMAGE_DLLCHARACTERISTICS_NO_BIND)
2922 fprintf (file, "%sNO_BIND\n", indent);
2923 if (dllch & IMAGE_DLLCHARACTERISTICS_APPCONTAINER)
2924 fprintf (file, "%sAPPCONTAINER\n", indent);
2925 if (dllch & IMAGE_DLLCHARACTERISTICS_WDM_DRIVER)
2926 fprintf (file, "%sWDM_DRIVER\n", indent);
2927 if (dllch & IMAGE_DLLCHARACTERISTICS_GUARD_CF)
2928 fprintf (file, "%sGUARD_CF\n", indent);
2929 if (dllch & IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE)
2930 fprintf (file, "%sTERMINAL_SERVICE_AWARE\n", indent);
2932 fprintf (file, "SizeOfStackReserve\t");
2933 bfd_fprintf_vma (abfd, file, i->SizeOfStackReserve);
2934 fprintf (file, "\nSizeOfStackCommit\t");
2935 bfd_fprintf_vma (abfd, file, i->SizeOfStackCommit);
2936 fprintf (file, "\nSizeOfHeapReserve\t");
2937 bfd_fprintf_vma (abfd, file, i->SizeOfHeapReserve);
2938 fprintf (file, "\nSizeOfHeapCommit\t");
2939 bfd_fprintf_vma (abfd, file, i->SizeOfHeapCommit);
2940 fprintf (file, "\nLoaderFlags\t\t%08lx\n", (unsigned long) i->LoaderFlags);
2941 fprintf (file, "NumberOfRvaAndSizes\t%08lx\n",
2942 (unsigned long) i->NumberOfRvaAndSizes);
2944 fprintf (file, "\nThe Data Directory\n");
2945 for (j = 0; j < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; j++)
2947 fprintf (file, "Entry %1x ", j);
2948 bfd_fprintf_vma (abfd, file, i->DataDirectory[j].VirtualAddress);
2949 fprintf (file, " %08lx ", (unsigned long) i->DataDirectory[j].Size);
2950 fprintf (file, "%s\n", dir_names[j]);
2953 pe_print_idata (abfd, vfile);
2954 pe_print_edata (abfd, vfile);
2955 if (bfd_coff_have_print_pdata (abfd))
2956 bfd_coff_print_pdata (abfd, vfile);
2957 else
2958 pe_print_pdata (abfd, vfile);
2959 pe_print_reloc (abfd, vfile);
2960 pe_print_debugdata (abfd, file);
2962 rsrc_print_section (abfd, vfile);
2964 return true;
2967 static bool
2968 is_vma_in_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj)
2970 bfd_vma addr = * (bfd_vma *) obj;
2971 return (addr >= sect->vma) && (addr < (sect->vma + sect->size));
2974 static asection *
2975 find_section_by_vma (bfd *abfd, bfd_vma addr)
2977 return bfd_sections_find_if (abfd, is_vma_in_section, (void *) & addr);
2980 /* Copy any private info we understand from the input bfd
2981 to the output bfd. */
2983 bool
2984 _bfd_XX_bfd_copy_private_bfd_data_common (bfd * ibfd, bfd * obfd)
2986 pe_data_type *ipe, *ope;
2987 bfd_size_type size;
2989 /* One day we may try to grok other private data. */
2990 if (ibfd->xvec->flavour != bfd_target_coff_flavour
2991 || obfd->xvec->flavour != bfd_target_coff_flavour)
2992 return true;
2994 ipe = pe_data (ibfd);
2995 ope = pe_data (obfd);
2997 /* pe_opthdr is copied in copy_object. */
2998 ope->dll = ipe->dll;
3000 /* Don't copy input subsystem if output is different from input. */
3001 if (obfd->xvec != ibfd->xvec)
3002 ope->pe_opthdr.Subsystem = IMAGE_SUBSYSTEM_UNKNOWN;
3004 /* For strip: if we removed .reloc, we'll make a real mess of things
3005 if we don't remove this entry as well. */
3006 if (! pe_data (obfd)->has_reloc_section)
3008 pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].VirtualAddress = 0;
3009 pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].Size = 0;
3012 /* For PIE, if there is .reloc, we won't add IMAGE_FILE_RELOCS_STRIPPED.
3013 But there is no .reloc, we make sure that IMAGE_FILE_RELOCS_STRIPPED
3014 won't be added. */
3015 if (! pe_data (ibfd)->has_reloc_section
3016 && ! (pe_data (ibfd)->real_flags & IMAGE_FILE_RELOCS_STRIPPED))
3017 pe_data (obfd)->dont_strip_reloc = 1;
3019 memcpy (ope->dos_message, ipe->dos_message, sizeof (ope->dos_message));
3021 /* The file offsets contained in the debug directory need rewriting. */
3022 size = ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size;
3023 if (size != 0)
3025 bfd_vma addr = ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
3026 + ope->pe_opthdr.ImageBase;
3027 /* In particular a .buildid section may overlap (in VA space) with
3028 whatever section comes ahead of it (largely because of section->size
3029 representing s_size, not virt_size). Therefore don't look for the
3030 section containing the first byte, but for that covering the last
3031 one. */
3032 bfd_vma last = addr + size - 1;
3033 asection *section = find_section_by_vma (obfd, last);
3035 if (section != NULL)
3037 bfd_byte *data;
3038 bfd_vma dataoff = addr - section->vma;
3040 /* PR 17512: file: 0f15796a. */
3041 if (addr < section->vma
3042 || section->size < dataoff
3043 || section->size - dataoff < size)
3045 /* xgettext:c-format */
3046 _bfd_error_handler
3047 (_("%pB: Data Directory (%lx bytes at %" PRIx64 ") "
3048 "extends across section boundary at %" PRIx64),
3049 obfd, ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size,
3050 (uint64_t) addr, (uint64_t) section->vma);
3051 return false;
3054 if ((section->flags & SEC_HAS_CONTENTS) != 0
3055 && bfd_malloc_and_get_section (obfd, section, &data))
3057 unsigned int i;
3058 struct external_IMAGE_DEBUG_DIRECTORY *dd =
3059 (struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff);
3061 for (i = 0; i < ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
3062 / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
3064 asection *ddsection;
3065 struct external_IMAGE_DEBUG_DIRECTORY *edd = &(dd[i]);
3066 struct internal_IMAGE_DEBUG_DIRECTORY idd;
3067 bfd_vma idd_vma;
3069 _bfd_XXi_swap_debugdir_in (obfd, edd, &idd);
3071 /* RVA 0 means only offset is valid, not handled yet. */
3072 if (idd.AddressOfRawData == 0)
3073 continue;
3075 idd_vma = idd.AddressOfRawData + ope->pe_opthdr.ImageBase;
3076 ddsection = find_section_by_vma (obfd, idd_vma);
3077 if (!ddsection)
3078 continue; /* Not in a section! */
3080 idd.PointerToRawData
3081 = ddsection->filepos + idd_vma - ddsection->vma;
3082 _bfd_XXi_swap_debugdir_out (obfd, &idd, edd);
3085 if (!bfd_set_section_contents (obfd, section, data, 0,
3086 section->size))
3088 _bfd_error_handler (_("failed to update file offsets"
3089 " in debug directory"));
3090 free (data);
3091 return false;
3093 free (data);
3095 else
3097 _bfd_error_handler (_("%pB: failed to read "
3098 "debug data section"), obfd);
3099 return false;
3104 return true;
3107 /* Copy private section data. */
3109 bool
3110 _bfd_XX_bfd_copy_private_section_data (bfd *ibfd,
3111 asection *isec,
3112 bfd *obfd,
3113 asection *osec)
3115 if (bfd_get_flavour (ibfd) != bfd_target_coff_flavour
3116 || bfd_get_flavour (obfd) != bfd_target_coff_flavour)
3117 return true;
3119 if (coff_section_data (ibfd, isec) != NULL
3120 && pei_section_data (ibfd, isec) != NULL)
3122 if (coff_section_data (obfd, osec) == NULL)
3124 size_t amt = sizeof (struct coff_section_tdata);
3125 osec->used_by_bfd = bfd_zalloc (obfd, amt);
3126 if (osec->used_by_bfd == NULL)
3127 return false;
3130 if (pei_section_data (obfd, osec) == NULL)
3132 size_t amt = sizeof (struct pei_section_tdata);
3133 coff_section_data (obfd, osec)->tdata = bfd_zalloc (obfd, amt);
3134 if (coff_section_data (obfd, osec)->tdata == NULL)
3135 return false;
3138 pei_section_data (obfd, osec)->virt_size =
3139 pei_section_data (ibfd, isec)->virt_size;
3140 pei_section_data (obfd, osec)->pe_flags =
3141 pei_section_data (ibfd, isec)->pe_flags;
3144 return true;
3147 void
3148 _bfd_XX_get_symbol_info (bfd * abfd, asymbol *symbol, symbol_info *ret)
3150 coff_get_symbol_info (abfd, symbol, ret);
3153 #if !defined(COFF_WITH_pep) && (defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64))
3154 static int
3155 sort_x64_pdata (const void *l, const void *r)
3157 const char *lp = (const char *) l;
3158 const char *rp = (const char *) r;
3159 bfd_vma vl, vr;
3160 vl = bfd_getl32 (lp); vr = bfd_getl32 (rp);
3161 if (vl != vr)
3162 return (vl < vr ? -1 : 1);
3163 /* We compare just begin address. */
3164 return 0;
3166 #endif
3168 /* Functions to process a .rsrc section. */
3170 static unsigned int sizeof_leaves;
3171 static unsigned int sizeof_strings;
3172 static unsigned int sizeof_tables_and_entries;
3174 static bfd_byte *
3175 rsrc_count_directory (bfd *, bfd_byte *, bfd_byte *, bfd_byte *, bfd_vma);
3177 static bfd_byte *
3178 rsrc_count_entries (bfd *abfd,
3179 bool is_name,
3180 bfd_byte *datastart,
3181 bfd_byte *data,
3182 bfd_byte *dataend,
3183 bfd_vma rva_bias)
3185 unsigned long entry, addr, size;
3187 if (data + 8 >= dataend)
3188 return dataend + 1;
3190 if (is_name)
3192 bfd_byte * name;
3194 entry = (long) bfd_get_32 (abfd, data);
3196 if (HighBitSet (entry))
3197 name = datastart + WithoutHighBit (entry);
3198 else
3199 name = datastart + entry - rva_bias;
3201 if (name + 2 >= dataend || name < datastart)
3202 return dataend + 1;
3204 unsigned int len = bfd_get_16 (abfd, name);
3205 if (len == 0 || len > 256)
3206 return dataend + 1;
3209 entry = (long) bfd_get_32 (abfd, data + 4);
3211 if (HighBitSet (entry))
3213 data = datastart + WithoutHighBit (entry);
3215 if (data <= datastart || data >= dataend)
3216 return dataend + 1;
3218 return rsrc_count_directory (abfd, datastart, data, dataend, rva_bias);
3221 if (datastart + entry + 16 >= dataend)
3222 return dataend + 1;
3224 addr = (long) bfd_get_32 (abfd, datastart + entry);
3225 size = (long) bfd_get_32 (abfd, datastart + entry + 4);
3227 return datastart + addr - rva_bias + size;
3230 static bfd_byte *
3231 rsrc_count_directory (bfd * abfd,
3232 bfd_byte * datastart,
3233 bfd_byte * data,
3234 bfd_byte * dataend,
3235 bfd_vma rva_bias)
3237 unsigned int num_entries, num_ids;
3238 bfd_byte * highest_data = data;
3240 if (data + 16 >= dataend)
3241 return dataend + 1;
3243 num_entries = (int) bfd_get_16 (abfd, data + 12);
3244 num_ids = (int) bfd_get_16 (abfd, data + 14);
3246 num_entries += num_ids;
3248 data += 16;
3250 while (num_entries --)
3252 bfd_byte * entry_end;
3254 entry_end = rsrc_count_entries (abfd, num_entries >= num_ids,
3255 datastart, data, dataend, rva_bias);
3256 data += 8;
3257 highest_data = max (highest_data, entry_end);
3258 if (entry_end >= dataend)
3259 break;
3262 return max (highest_data, data);
3265 typedef struct rsrc_dir_chain
3267 unsigned int num_entries;
3268 struct rsrc_entry * first_entry;
3269 struct rsrc_entry * last_entry;
3270 } rsrc_dir_chain;
3272 typedef struct rsrc_directory
3274 unsigned int characteristics;
3275 unsigned int time;
3276 unsigned int major;
3277 unsigned int minor;
3279 rsrc_dir_chain names;
3280 rsrc_dir_chain ids;
3282 struct rsrc_entry * entry;
3283 } rsrc_directory;
3285 typedef struct rsrc_string
3287 unsigned int len;
3288 bfd_byte * string;
3289 } rsrc_string;
3291 typedef struct rsrc_leaf
3293 unsigned int size;
3294 unsigned int codepage;
3295 bfd_byte * data;
3296 } rsrc_leaf;
3298 typedef struct rsrc_entry
3300 bool is_name;
3301 union
3303 unsigned int id;
3304 struct rsrc_string name;
3305 } name_id;
3307 bool is_dir;
3308 union
3310 struct rsrc_directory * directory;
3311 struct rsrc_leaf * leaf;
3312 } value;
3314 struct rsrc_entry * next_entry;
3315 struct rsrc_directory * parent;
3316 } rsrc_entry;
3318 static bfd_byte *
3319 rsrc_parse_directory (bfd *, rsrc_directory *, bfd_byte *,
3320 bfd_byte *, bfd_byte *, bfd_vma, rsrc_entry *);
3322 static bfd_byte *
3323 rsrc_parse_entry (bfd *abfd,
3324 bool is_name,
3325 rsrc_entry *entry,
3326 bfd_byte *datastart,
3327 bfd_byte * data,
3328 bfd_byte *dataend,
3329 bfd_vma rva_bias,
3330 rsrc_directory *parent)
3332 unsigned long val, addr, size;
3334 val = bfd_get_32 (abfd, data);
3336 entry->parent = parent;
3337 entry->is_name = is_name;
3339 if (is_name)
3341 bfd_byte * address;
3343 if (HighBitSet (val))
3345 val = WithoutHighBit (val);
3347 address = datastart + val;
3349 else
3351 address = datastart + val - rva_bias;
3354 if (address + 3 > dataend)
3355 return dataend;
3357 entry->name_id.name.len = bfd_get_16 (abfd, address);
3358 entry->name_id.name.string = address + 2;
3360 else
3361 entry->name_id.id = val;
3363 val = bfd_get_32 (abfd, data + 4);
3365 if (HighBitSet (val))
3367 entry->is_dir = true;
3368 entry->value.directory = bfd_malloc (sizeof (*entry->value.directory));
3369 if (entry->value.directory == NULL)
3370 return dataend;
3372 return rsrc_parse_directory (abfd, entry->value.directory,
3373 datastart,
3374 datastart + WithoutHighBit (val),
3375 dataend, rva_bias, entry);
3378 entry->is_dir = false;
3379 entry->value.leaf = bfd_malloc (sizeof (*entry->value.leaf));
3380 if (entry->value.leaf == NULL)
3381 return dataend;
3383 data = datastart + val;
3384 if (data < datastart || data + 12 > dataend)
3385 return dataend;
3387 addr = bfd_get_32 (abfd, data);
3388 size = entry->value.leaf->size = bfd_get_32 (abfd, data + 4);
3389 entry->value.leaf->codepage = bfd_get_32 (abfd, data + 8);
3390 /* FIXME: We assume that the reserved field (data + 12) is OK. */
3392 if (size > dataend - datastart - (addr - rva_bias))
3393 return dataend;
3394 entry->value.leaf->data = bfd_malloc (size);
3395 if (entry->value.leaf->data == NULL)
3396 return dataend;
3398 memcpy (entry->value.leaf->data, datastart + addr - rva_bias, size);
3399 return datastart + (addr - rva_bias) + size;
3402 static bfd_byte *
3403 rsrc_parse_entries (bfd *abfd,
3404 rsrc_dir_chain *chain,
3405 bool is_name,
3406 bfd_byte *highest_data,
3407 bfd_byte *datastart,
3408 bfd_byte *data,
3409 bfd_byte *dataend,
3410 bfd_vma rva_bias,
3411 rsrc_directory *parent)
3413 unsigned int i;
3414 rsrc_entry * entry;
3416 if (chain->num_entries == 0)
3418 chain->first_entry = chain->last_entry = NULL;
3419 return highest_data;
3422 entry = bfd_malloc (sizeof (*entry));
3423 if (entry == NULL)
3424 return dataend;
3426 chain->first_entry = entry;
3428 for (i = chain->num_entries; i--;)
3430 bfd_byte * entry_end;
3432 entry_end = rsrc_parse_entry (abfd, is_name, entry, datastart,
3433 data, dataend, rva_bias, parent);
3434 data += 8;
3435 highest_data = max (entry_end, highest_data);
3436 if (entry_end > dataend)
3437 return dataend;
3439 if (i)
3441 entry->next_entry = bfd_malloc (sizeof (*entry));
3442 entry = entry->next_entry;
3443 if (entry == NULL)
3444 return dataend;
3446 else
3447 entry->next_entry = NULL;
3450 chain->last_entry = entry;
3452 return highest_data;
3455 static bfd_byte *
3456 rsrc_parse_directory (bfd * abfd,
3457 rsrc_directory * table,
3458 bfd_byte * datastart,
3459 bfd_byte * data,
3460 bfd_byte * dataend,
3461 bfd_vma rva_bias,
3462 rsrc_entry * entry)
3464 bfd_byte * highest_data = data;
3466 if (table == NULL)
3467 return dataend;
3469 table->characteristics = bfd_get_32 (abfd, data);
3470 table->time = bfd_get_32 (abfd, data + 4);
3471 table->major = bfd_get_16 (abfd, data + 8);
3472 table->minor = bfd_get_16 (abfd, data + 10);
3473 table->names.num_entries = bfd_get_16 (abfd, data + 12);
3474 table->ids.num_entries = bfd_get_16 (abfd, data + 14);
3475 table->entry = entry;
3477 data += 16;
3479 highest_data = rsrc_parse_entries (abfd, & table->names, true, data,
3480 datastart, data, dataend, rva_bias, table);
3481 data += table->names.num_entries * 8;
3483 highest_data = rsrc_parse_entries (abfd, & table->ids, false, highest_data,
3484 datastart, data, dataend, rva_bias, table);
3485 data += table->ids.num_entries * 8;
3487 return max (highest_data, data);
3490 typedef struct rsrc_write_data
3492 bfd * abfd;
3493 bfd_byte * datastart;
3494 bfd_byte * next_table;
3495 bfd_byte * next_leaf;
3496 bfd_byte * next_string;
3497 bfd_byte * next_data;
3498 bfd_vma rva_bias;
3499 } rsrc_write_data;
3501 static void
3502 rsrc_write_string (rsrc_write_data * data,
3503 rsrc_string * string)
3505 bfd_put_16 (data->abfd, string->len, data->next_string);
3506 memcpy (data->next_string + 2, string->string, string->len * 2);
3507 data->next_string += (string->len + 1) * 2;
3510 static inline unsigned int
3511 rsrc_compute_rva (rsrc_write_data * data,
3512 bfd_byte * addr)
3514 return (addr - data->datastart) + data->rva_bias;
3517 static void
3518 rsrc_write_leaf (rsrc_write_data * data,
3519 rsrc_leaf * leaf)
3521 bfd_put_32 (data->abfd, rsrc_compute_rva (data, data->next_data),
3522 data->next_leaf);
3523 bfd_put_32 (data->abfd, leaf->size, data->next_leaf + 4);
3524 bfd_put_32 (data->abfd, leaf->codepage, data->next_leaf + 8);
3525 bfd_put_32 (data->abfd, 0 /*reserved*/, data->next_leaf + 12);
3526 data->next_leaf += 16;
3528 memcpy (data->next_data, leaf->data, leaf->size);
3529 /* An undocumented feature of Windows resources is that each unit
3530 of raw data is 8-byte aligned... */
3531 data->next_data += ((leaf->size + 7) & ~7);
3534 static void rsrc_write_directory (rsrc_write_data *, rsrc_directory *);
3536 static void
3537 rsrc_write_entry (rsrc_write_data * data,
3538 bfd_byte * where,
3539 rsrc_entry * entry)
3541 if (entry->is_name)
3543 bfd_put_32 (data->abfd,
3544 SetHighBit (data->next_string - data->datastart),
3545 where);
3546 rsrc_write_string (data, & entry->name_id.name);
3548 else
3549 bfd_put_32 (data->abfd, entry->name_id.id, where);
3551 if (entry->is_dir)
3553 bfd_put_32 (data->abfd,
3554 SetHighBit (data->next_table - data->datastart),
3555 where + 4);
3556 rsrc_write_directory (data, entry->value.directory);
3558 else
3560 bfd_put_32 (data->abfd, data->next_leaf - data->datastart, where + 4);
3561 rsrc_write_leaf (data, entry->value.leaf);
3565 static void
3566 rsrc_compute_region_sizes (rsrc_directory * dir)
3568 struct rsrc_entry * entry;
3570 if (dir == NULL)
3571 return;
3573 sizeof_tables_and_entries += 16;
3575 for (entry = dir->names.first_entry; entry != NULL; entry = entry->next_entry)
3577 sizeof_tables_and_entries += 8;
3579 sizeof_strings += (entry->name_id.name.len + 1) * 2;
3581 if (entry->is_dir)
3582 rsrc_compute_region_sizes (entry->value.directory);
3583 else
3584 sizeof_leaves += 16;
3587 for (entry = dir->ids.first_entry; entry != NULL; entry = entry->next_entry)
3589 sizeof_tables_and_entries += 8;
3591 if (entry->is_dir)
3592 rsrc_compute_region_sizes (entry->value.directory);
3593 else
3594 sizeof_leaves += 16;
3598 static void
3599 rsrc_write_directory (rsrc_write_data * data,
3600 rsrc_directory * dir)
3602 rsrc_entry * entry;
3603 unsigned int i;
3604 bfd_byte * next_entry;
3605 bfd_byte * nt;
3607 bfd_put_32 (data->abfd, dir->characteristics, data->next_table);
3608 bfd_put_32 (data->abfd, 0 /*dir->time*/, data->next_table + 4);
3609 bfd_put_16 (data->abfd, dir->major, data->next_table + 8);
3610 bfd_put_16 (data->abfd, dir->minor, data->next_table + 10);
3611 bfd_put_16 (data->abfd, dir->names.num_entries, data->next_table + 12);
3612 bfd_put_16 (data->abfd, dir->ids.num_entries, data->next_table + 14);
3614 /* Compute where the entries and the next table will be placed. */
3615 next_entry = data->next_table + 16;
3616 data->next_table = next_entry + (dir->names.num_entries * 8)
3617 + (dir->ids.num_entries * 8);
3618 nt = data->next_table;
3620 /* Write the entries. */
3621 for (i = dir->names.num_entries, entry = dir->names.first_entry;
3622 i > 0 && entry != NULL;
3623 i--, entry = entry->next_entry)
3625 BFD_ASSERT (entry->is_name);
3626 rsrc_write_entry (data, next_entry, entry);
3627 next_entry += 8;
3629 BFD_ASSERT (i == 0);
3630 BFD_ASSERT (entry == NULL);
3632 for (i = dir->ids.num_entries, entry = dir->ids.first_entry;
3633 i > 0 && entry != NULL;
3634 i--, entry = entry->next_entry)
3636 BFD_ASSERT (! entry->is_name);
3637 rsrc_write_entry (data, next_entry, entry);
3638 next_entry += 8;
3640 BFD_ASSERT (i == 0);
3641 BFD_ASSERT (entry == NULL);
3642 BFD_ASSERT (nt == next_entry);
3645 #if ! defined __CYGWIN__ && ! defined __MINGW32__
3646 /* Return the length (number of units) of the first character in S,
3647 putting its 'ucs4_t' representation in *PUC. */
3649 static unsigned int
3650 u16_mbtouc (wint_t * puc, const unsigned short * s, unsigned int n)
3652 unsigned short c = * s;
3654 if (c < 0xd800 || c >= 0xe000)
3656 *puc = c;
3657 return 1;
3660 if (c < 0xdc00)
3662 if (n >= 2)
3664 if (s[1] >= 0xdc00 && s[1] < 0xe000)
3666 *puc = 0x10000 + ((c - 0xd800) << 10) + (s[1] - 0xdc00);
3667 return 2;
3670 else
3672 /* Incomplete multibyte character. */
3673 *puc = 0xfffd;
3674 return n;
3678 /* Invalid multibyte character. */
3679 *puc = 0xfffd;
3680 return 1;
3682 #endif /* not Cygwin/Mingw */
3684 /* Perform a comparison of two entries. */
3685 static signed int
3686 rsrc_cmp (bool is_name, rsrc_entry * a, rsrc_entry * b)
3688 signed int res;
3689 bfd_byte * astring;
3690 unsigned int alen;
3691 bfd_byte * bstring;
3692 unsigned int blen;
3694 if (! is_name)
3695 return a->name_id.id - b->name_id.id;
3697 /* We have to perform a case insenstive, unicode string comparison... */
3698 astring = a->name_id.name.string;
3699 alen = a->name_id.name.len;
3700 bstring = b->name_id.name.string;
3701 blen = b->name_id.name.len;
3703 #if defined __CYGWIN__ || defined __MINGW32__
3704 /* Under Windows hosts (both Cygwin and Mingw types),
3705 unicode == UTF-16 == wchar_t. The case insensitive string comparison
3706 function however goes by different names in the two environments... */
3708 #undef rscpcmp
3709 #ifdef __CYGWIN__
3710 #define rscpcmp wcsncasecmp
3711 #endif
3712 #ifdef __MINGW32__
3713 #define rscpcmp wcsnicmp
3714 #endif
3716 res = rscpcmp ((const wchar_t *) astring, (const wchar_t *) bstring,
3717 min (alen, blen));
3719 #else
3721 unsigned int i;
3723 res = 0;
3724 for (i = min (alen, blen); i--; astring += 2, bstring += 2)
3726 wint_t awc;
3727 wint_t bwc;
3729 /* Convert UTF-16 unicode characters into wchar_t characters
3730 so that we can then perform a case insensitive comparison. */
3731 unsigned int Alen = u16_mbtouc (& awc, (const unsigned short *) astring, 2);
3732 unsigned int Blen = u16_mbtouc (& bwc, (const unsigned short *) bstring, 2);
3734 if (Alen != Blen)
3735 return Alen - Blen;
3737 awc = towlower (awc);
3738 bwc = towlower (bwc);
3740 res = awc - bwc;
3741 if (res)
3742 break;
3745 #endif
3747 if (res == 0)
3748 res = alen - blen;
3750 return res;
3753 static void
3754 rsrc_print_name (char * buffer, rsrc_string string)
3756 unsigned int i;
3757 bfd_byte * name = string.string;
3759 for (i = string.len; i--; name += 2)
3760 sprintf (buffer + strlen (buffer), "%.1s", name);
3763 static const char *
3764 rsrc_resource_name (rsrc_entry *entry, rsrc_directory *dir, char *buffer)
3766 bool is_string = false;
3768 buffer[0] = 0;
3770 if (dir != NULL && dir->entry != NULL && dir->entry->parent != NULL
3771 && dir->entry->parent->entry != NULL)
3773 strcpy (buffer, "type: ");
3774 if (dir->entry->parent->entry->is_name)
3775 rsrc_print_name (buffer + strlen (buffer),
3776 dir->entry->parent->entry->name_id.name);
3777 else
3779 unsigned int id = dir->entry->parent->entry->name_id.id;
3781 sprintf (buffer + strlen (buffer), "%x", id);
3782 switch (id)
3784 case 1: strcat (buffer, " (CURSOR)"); break;
3785 case 2: strcat (buffer, " (BITMAP)"); break;
3786 case 3: strcat (buffer, " (ICON)"); break;
3787 case 4: strcat (buffer, " (MENU)"); break;
3788 case 5: strcat (buffer, " (DIALOG)"); break;
3789 case 6: strcat (buffer, " (STRING)"); is_string = true; break;
3790 case 7: strcat (buffer, " (FONTDIR)"); break;
3791 case 8: strcat (buffer, " (FONT)"); break;
3792 case 9: strcat (buffer, " (ACCELERATOR)"); break;
3793 case 10: strcat (buffer, " (RCDATA)"); break;
3794 case 11: strcat (buffer, " (MESSAGETABLE)"); break;
3795 case 12: strcat (buffer, " (GROUP_CURSOR)"); break;
3796 case 14: strcat (buffer, " (GROUP_ICON)"); break;
3797 case 16: strcat (buffer, " (VERSION)"); break;
3798 case 17: strcat (buffer, " (DLGINCLUDE)"); break;
3799 case 19: strcat (buffer, " (PLUGPLAY)"); break;
3800 case 20: strcat (buffer, " (VXD)"); break;
3801 case 21: strcat (buffer, " (ANICURSOR)"); break;
3802 case 22: strcat (buffer, " (ANIICON)"); break;
3803 case 23: strcat (buffer, " (HTML)"); break;
3804 case 24: strcat (buffer, " (MANIFEST)"); break;
3805 case 240: strcat (buffer, " (DLGINIT)"); break;
3806 case 241: strcat (buffer, " (TOOLBAR)"); break;
3811 if (dir != NULL && dir->entry != NULL)
3813 strcat (buffer, " name: ");
3814 if (dir->entry->is_name)
3815 rsrc_print_name (buffer + strlen (buffer), dir->entry->name_id.name);
3816 else
3818 unsigned int id = dir->entry->name_id.id;
3820 sprintf (buffer + strlen (buffer), "%x", id);
3822 if (is_string)
3823 sprintf (buffer + strlen (buffer), " (resource id range: %d - %d)",
3824 (id - 1) << 4, (id << 4) - 1);
3828 if (entry != NULL)
3830 strcat (buffer, " lang: ");
3832 if (entry->is_name)
3833 rsrc_print_name (buffer + strlen (buffer), entry->name_id.name);
3834 else
3835 sprintf (buffer + strlen (buffer), "%x", entry->name_id.id);
3838 return buffer;
3841 /* *sigh* Windows resource strings are special. Only the top 28-bits of
3842 their ID is stored in the NAME entry. The bottom four bits are used as
3843 an index into unicode string table that makes up the data of the leaf.
3844 So identical type-name-lang string resources may not actually be
3845 identical at all.
3847 This function is called when we have detected two string resources with
3848 match top-28-bit IDs. We have to scan the string tables inside the leaves
3849 and discover if there are any real collisions. If there are then we report
3850 them and return FALSE. Otherwise we copy any strings from B into A and
3851 then return TRUE. */
3853 static bool
3854 rsrc_merge_string_entries (rsrc_entry * a ATTRIBUTE_UNUSED,
3855 rsrc_entry * b ATTRIBUTE_UNUSED)
3857 unsigned int copy_needed = 0;
3858 unsigned int i;
3859 bfd_byte * astring;
3860 bfd_byte * bstring;
3861 bfd_byte * new_data;
3862 bfd_byte * nstring;
3864 /* Step one: Find out what we have to do. */
3865 BFD_ASSERT (! a->is_dir);
3866 astring = a->value.leaf->data;
3868 BFD_ASSERT (! b->is_dir);
3869 bstring = b->value.leaf->data;
3871 for (i = 0; i < 16; i++)
3873 unsigned int alen = astring[0] + (astring[1] << 8);
3874 unsigned int blen = bstring[0] + (bstring[1] << 8);
3876 if (alen == 0)
3878 copy_needed += blen * 2;
3880 else if (blen == 0)
3882 else if (alen != blen)
3883 /* FIXME: Should we continue the loop in order to report other duplicates ? */
3884 break;
3885 /* alen == blen != 0. We might have two identical strings. If so we
3886 can ignore the second one. There is no need for wchar_t vs UTF-16
3887 theatrics here - we are only interested in (case sensitive) equality. */
3888 else if (memcmp (astring + 2, bstring + 2, alen * 2) != 0)
3889 break;
3891 astring += (alen + 1) * 2;
3892 bstring += (blen + 1) * 2;
3895 if (i != 16)
3897 if (a->parent != NULL
3898 && a->parent->entry != NULL
3899 && !a->parent->entry->is_name)
3900 _bfd_error_handler (_(".rsrc merge failure: duplicate string resource: %d"),
3901 ((a->parent->entry->name_id.id - 1) << 4) + i);
3902 return false;
3905 if (copy_needed == 0)
3906 return true;
3908 /* If we reach here then A and B must both have non-colliding strings.
3909 (We never get string resources with fully empty string tables).
3910 We need to allocate an extra COPY_NEEDED bytes in A and then bring
3911 in B's strings. */
3912 new_data = bfd_malloc (a->value.leaf->size + copy_needed);
3913 if (new_data == NULL)
3914 return false;
3916 nstring = new_data;
3917 astring = a->value.leaf->data;
3918 bstring = b->value.leaf->data;
3920 for (i = 0; i < 16; i++)
3922 unsigned int alen = astring[0] + (astring[1] << 8);
3923 unsigned int blen = bstring[0] + (bstring[1] << 8);
3925 if (alen != 0)
3927 memcpy (nstring, astring, (alen + 1) * 2);
3928 nstring += (alen + 1) * 2;
3930 else if (blen != 0)
3932 memcpy (nstring, bstring, (blen + 1) * 2);
3933 nstring += (blen + 1) * 2;
3935 else
3937 * nstring++ = 0;
3938 * nstring++ = 0;
3941 astring += (alen + 1) * 2;
3942 bstring += (blen + 1) * 2;
3945 BFD_ASSERT (nstring - new_data == (signed) (a->value.leaf->size + copy_needed));
3947 free (a->value.leaf->data);
3948 a->value.leaf->data = new_data;
3949 a->value.leaf->size += copy_needed;
3951 return true;
3954 static void rsrc_merge (rsrc_entry *, rsrc_entry *);
3956 /* Sort the entries in given part of the directory.
3957 We use an old fashioned bubble sort because we are dealing
3958 with lists and we want to handle matches specially. */
3960 static void
3961 rsrc_sort_entries (rsrc_dir_chain *chain,
3962 bool is_name,
3963 rsrc_directory *dir)
3965 rsrc_entry * entry;
3966 rsrc_entry * next;
3967 rsrc_entry ** points_to_entry;
3968 bool swapped;
3970 if (chain->num_entries < 2)
3971 return;
3975 swapped = false;
3976 points_to_entry = & chain->first_entry;
3977 entry = * points_to_entry;
3978 next = entry->next_entry;
3982 signed int cmp = rsrc_cmp (is_name, entry, next);
3984 if (cmp > 0)
3986 entry->next_entry = next->next_entry;
3987 next->next_entry = entry;
3988 * points_to_entry = next;
3989 points_to_entry = & next->next_entry;
3990 next = entry->next_entry;
3991 swapped = true;
3993 else if (cmp == 0)
3995 if (entry->is_dir && next->is_dir)
3997 /* When we encounter identical directory entries we have to
3998 merge them together. The exception to this rule is for
3999 resource manifests - there can only be one of these,
4000 even if they differ in language. Zero-language manifests
4001 are assumed to be default manifests (provided by the
4002 Cygwin/MinGW build system) and these can be silently dropped,
4003 unless that would reduce the number of manifests to zero.
4004 There should only ever be one non-zero lang manifest -
4005 if there are more it is an error. A non-zero lang
4006 manifest takes precedence over a default manifest. */
4007 if (!entry->is_name
4008 && entry->name_id.id == 1
4009 && dir != NULL
4010 && dir->entry != NULL
4011 && !dir->entry->is_name
4012 && dir->entry->name_id.id == 0x18)
4014 if (next->value.directory->names.num_entries == 0
4015 && next->value.directory->ids.num_entries == 1
4016 && !next->value.directory->ids.first_entry->is_name
4017 && next->value.directory->ids.first_entry->name_id.id == 0)
4018 /* Fall through so that NEXT is dropped. */
4020 else if (entry->value.directory->names.num_entries == 0
4021 && entry->value.directory->ids.num_entries == 1
4022 && !entry->value.directory->ids.first_entry->is_name
4023 && entry->value.directory->ids.first_entry->name_id.id == 0)
4025 /* Swap ENTRY and NEXT. Then fall through so that the old ENTRY is dropped. */
4026 entry->next_entry = next->next_entry;
4027 next->next_entry = entry;
4028 * points_to_entry = next;
4029 points_to_entry = & next->next_entry;
4030 next = entry->next_entry;
4031 swapped = true;
4033 else
4035 _bfd_error_handler (_(".rsrc merge failure: multiple non-default manifests"));
4036 bfd_set_error (bfd_error_file_truncated);
4037 return;
4040 /* Unhook NEXT from the chain. */
4041 /* FIXME: memory loss here. */
4042 entry->next_entry = next->next_entry;
4043 chain->num_entries --;
4044 if (chain->num_entries < 2)
4045 return;
4046 next = next->next_entry;
4048 else
4049 rsrc_merge (entry, next);
4051 else if (entry->is_dir != next->is_dir)
4053 _bfd_error_handler (_(".rsrc merge failure: a directory matches a leaf"));
4054 bfd_set_error (bfd_error_file_truncated);
4055 return;
4057 else
4059 /* Otherwise with identical leaves we issue an error
4060 message - because there should never be duplicates.
4061 The exception is Type 18/Name 1/Lang 0 which is the
4062 defaul manifest - this can just be dropped. */
4063 if (!entry->is_name
4064 && entry->name_id.id == 0
4065 && dir != NULL
4066 && dir->entry != NULL
4067 && !dir->entry->is_name
4068 && dir->entry->name_id.id == 1
4069 && dir->entry->parent != NULL
4070 && dir->entry->parent->entry != NULL
4071 && !dir->entry->parent->entry->is_name
4072 && dir->entry->parent->entry->name_id.id == 0x18 /* RT_MANIFEST */)
4074 else if (dir != NULL
4075 && dir->entry != NULL
4076 && dir->entry->parent != NULL
4077 && dir->entry->parent->entry != NULL
4078 && !dir->entry->parent->entry->is_name
4079 && dir->entry->parent->entry->name_id.id == 0x6 /* RT_STRING */)
4081 /* Strings need special handling. */
4082 if (! rsrc_merge_string_entries (entry, next))
4084 /* _bfd_error_handler should have been called inside merge_strings. */
4085 bfd_set_error (bfd_error_file_truncated);
4086 return;
4089 else
4091 if (dir == NULL
4092 || dir->entry == NULL
4093 || dir->entry->parent == NULL
4094 || dir->entry->parent->entry == NULL)
4095 _bfd_error_handler (_(".rsrc merge failure: duplicate leaf"));
4096 else
4098 char buff[256];
4100 _bfd_error_handler (_(".rsrc merge failure: duplicate leaf: %s"),
4101 rsrc_resource_name (entry, dir, buff));
4103 bfd_set_error (bfd_error_file_truncated);
4104 return;
4108 /* Unhook NEXT from the chain. */
4109 entry->next_entry = next->next_entry;
4110 chain->num_entries --;
4111 if (chain->num_entries < 2)
4112 return;
4113 next = next->next_entry;
4115 else
4117 points_to_entry = & entry->next_entry;
4118 entry = next;
4119 next = next->next_entry;
4122 while (next);
4124 chain->last_entry = entry;
4126 while (swapped);
4129 /* Attach B's chain onto A. */
4130 static void
4131 rsrc_attach_chain (rsrc_dir_chain * achain, rsrc_dir_chain * bchain)
4133 if (bchain->num_entries == 0)
4134 return;
4136 achain->num_entries += bchain->num_entries;
4138 if (achain->first_entry == NULL)
4140 achain->first_entry = bchain->first_entry;
4141 achain->last_entry = bchain->last_entry;
4143 else
4145 achain->last_entry->next_entry = bchain->first_entry;
4146 achain->last_entry = bchain->last_entry;
4149 bchain->num_entries = 0;
4150 bchain->first_entry = bchain->last_entry = NULL;
4153 static void
4154 rsrc_merge (struct rsrc_entry * a, struct rsrc_entry * b)
4156 rsrc_directory * adir;
4157 rsrc_directory * bdir;
4159 BFD_ASSERT (a->is_dir);
4160 BFD_ASSERT (b->is_dir);
4162 adir = a->value.directory;
4163 bdir = b->value.directory;
4165 if (adir->characteristics != bdir->characteristics)
4167 _bfd_error_handler (_(".rsrc merge failure: dirs with differing characteristics"));
4168 bfd_set_error (bfd_error_file_truncated);
4169 return;
4172 if (adir->major != bdir->major || adir->minor != bdir->minor)
4174 _bfd_error_handler (_(".rsrc merge failure: differing directory versions"));
4175 bfd_set_error (bfd_error_file_truncated);
4176 return;
4179 /* Attach B's name chain to A. */
4180 rsrc_attach_chain (& adir->names, & bdir->names);
4182 /* Attach B's ID chain to A. */
4183 rsrc_attach_chain (& adir->ids, & bdir->ids);
4185 /* Now sort A's entries. */
4186 rsrc_sort_entries (& adir->names, true, adir);
4187 rsrc_sort_entries (& adir->ids, false, adir);
4190 /* Check the .rsrc section. If it contains multiple concatenated
4191 resources then we must merge them properly. Otherwise Windows
4192 will ignore all but the first set. */
4194 static void
4195 rsrc_process_section (bfd * abfd,
4196 struct coff_final_link_info * pfinfo)
4198 rsrc_directory new_table;
4199 bfd_size_type size;
4200 asection * sec;
4201 pe_data_type * pe;
4202 bfd_vma rva_bias;
4203 bfd_byte * data;
4204 bfd_byte * datastart;
4205 bfd_byte * dataend;
4206 bfd_byte * new_data;
4207 unsigned int num_resource_sets;
4208 rsrc_directory * type_tables;
4209 rsrc_write_data write_data;
4210 unsigned int indx;
4211 bfd * input;
4212 unsigned int num_input_rsrc = 0;
4213 unsigned int max_num_input_rsrc = 4;
4214 ptrdiff_t * rsrc_sizes = NULL;
4216 new_table.names.num_entries = 0;
4217 new_table.ids.num_entries = 0;
4219 sec = bfd_get_section_by_name (abfd, ".rsrc");
4220 if (sec == NULL || (size = sec->rawsize) == 0)
4221 return;
4223 pe = pe_data (abfd);
4224 if (pe == NULL)
4225 return;
4227 rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4229 if (! bfd_malloc_and_get_section (abfd, sec, &datastart))
4230 goto end;
4232 /* Step zero: Scan the input bfds looking for .rsrc sections and record
4233 their lengths. Note - we rely upon the fact that the linker script
4234 does *not* sort the input .rsrc sections, so that the order in the
4235 linkinfo list matches the order in the output .rsrc section.
4237 We need to know the lengths because each input .rsrc section has padding
4238 at the end of a variable amount. (It does not appear to be based upon
4239 the section alignment or the file alignment). We need to skip any
4240 padding bytes when parsing the input .rsrc sections. */
4241 data = datastart;
4242 rsrc_sizes = bfd_malloc (max_num_input_rsrc * sizeof (*rsrc_sizes));
4243 if (rsrc_sizes == NULL)
4244 goto end;
4246 for (input = pfinfo->info->input_bfds;
4247 input != NULL;
4248 input = input->link.next)
4250 asection * rsrc_sec = bfd_get_section_by_name (input, ".rsrc");
4252 /* PR 18372 - skip discarded .rsrc sections. */
4253 if (rsrc_sec != NULL && !discarded_section (rsrc_sec))
4255 if (num_input_rsrc == max_num_input_rsrc)
4257 max_num_input_rsrc += 10;
4258 rsrc_sizes = bfd_realloc (rsrc_sizes, max_num_input_rsrc
4259 * sizeof (*rsrc_sizes));
4260 if (rsrc_sizes == NULL)
4261 goto end;
4264 BFD_ASSERT (rsrc_sec->size > 0);
4265 rsrc_sizes [num_input_rsrc ++] = rsrc_sec->size;
4269 if (num_input_rsrc < 2)
4270 goto end;
4272 /* Step one: Walk the section, computing the size of the tables,
4273 leaves and data and decide if we need to do anything. */
4274 dataend = data + size;
4275 num_resource_sets = 0;
4277 while (data < dataend)
4279 bfd_byte * p = data;
4281 data = rsrc_count_directory (abfd, data, data, dataend, rva_bias);
4283 if (data > dataend)
4285 /* Corrupted .rsrc section - cannot merge. */
4286 _bfd_error_handler (_("%pB: .rsrc merge failure: corrupt .rsrc section"),
4287 abfd);
4288 bfd_set_error (bfd_error_file_truncated);
4289 goto end;
4292 if ((data - p) > rsrc_sizes [num_resource_sets])
4294 _bfd_error_handler (_("%pB: .rsrc merge failure: unexpected .rsrc size"),
4295 abfd);
4296 bfd_set_error (bfd_error_file_truncated);
4297 goto end;
4299 /* FIXME: Should we add a check for "data - p" being much smaller
4300 than rsrc_sizes[num_resource_sets] ? */
4302 data = p + rsrc_sizes[num_resource_sets];
4303 rva_bias += data - p;
4304 ++ num_resource_sets;
4306 BFD_ASSERT (num_resource_sets == num_input_rsrc);
4308 /* Step two: Walk the data again, building trees of the resources. */
4309 data = datastart;
4310 rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4312 type_tables = bfd_malloc (num_resource_sets * sizeof (*type_tables));
4313 if (type_tables == NULL)
4314 goto end;
4316 indx = 0;
4317 while (data < dataend)
4319 bfd_byte * p = data;
4321 (void) rsrc_parse_directory (abfd, type_tables + indx, data, data,
4322 dataend, rva_bias, NULL);
4323 data = p + rsrc_sizes[indx];
4324 rva_bias += data - p;
4325 ++ indx;
4327 BFD_ASSERT (indx == num_resource_sets);
4329 /* Step three: Merge the top level tables (there can be only one).
4331 We must ensure that the merged entries are in ascending order.
4333 We also thread the top level table entries from the old tree onto
4334 the new table, so that they can be pulled off later. */
4336 /* FIXME: Should we verify that all type tables are the same ? */
4337 new_table.characteristics = type_tables[0].characteristics;
4338 new_table.time = type_tables[0].time;
4339 new_table.major = type_tables[0].major;
4340 new_table.minor = type_tables[0].minor;
4342 /* Chain the NAME entries onto the table. */
4343 new_table.names.first_entry = NULL;
4344 new_table.names.last_entry = NULL;
4346 for (indx = 0; indx < num_resource_sets; indx++)
4347 rsrc_attach_chain (& new_table.names, & type_tables[indx].names);
4349 rsrc_sort_entries (& new_table.names, true, & new_table);
4351 /* Chain the ID entries onto the table. */
4352 new_table.ids.first_entry = NULL;
4353 new_table.ids.last_entry = NULL;
4355 for (indx = 0; indx < num_resource_sets; indx++)
4356 rsrc_attach_chain (& new_table.ids, & type_tables[indx].ids);
4358 rsrc_sort_entries (& new_table.ids, false, & new_table);
4360 /* Step four: Create new contents for the .rsrc section. */
4361 /* Step four point one: Compute the size of each region of the .rsrc section.
4362 We do this now, rather than earlier, as the merging above may have dropped
4363 some entries. */
4364 sizeof_leaves = sizeof_strings = sizeof_tables_and_entries = 0;
4365 rsrc_compute_region_sizes (& new_table);
4366 /* We increment sizeof_strings to make sure that resource data
4367 starts on an 8-byte boundary. FIXME: Is this correct ? */
4368 sizeof_strings = (sizeof_strings + 7) & ~ 7;
4370 new_data = bfd_zalloc (abfd, size);
4371 if (new_data == NULL)
4372 goto end;
4374 write_data.abfd = abfd;
4375 write_data.datastart = new_data;
4376 write_data.next_table = new_data;
4377 write_data.next_leaf = new_data + sizeof_tables_and_entries;
4378 write_data.next_string = write_data.next_leaf + sizeof_leaves;
4379 write_data.next_data = write_data.next_string + sizeof_strings;
4380 write_data.rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4382 rsrc_write_directory (& write_data, & new_table);
4384 /* Step five: Replace the old contents with the new.
4385 We don't recompute the size as it's too late here to shrink section.
4386 See PR ld/20193 for more details. */
4387 bfd_set_section_contents (pfinfo->output_bfd, sec, new_data, 0, size);
4388 sec->size = sec->rawsize = size;
4390 end:
4391 /* Step six: Free all the memory that we have used. */
4392 /* FIXME: Free the resource tree, if we have one. */
4393 free (datastart);
4394 free (rsrc_sizes);
4397 /* Handle the .idata section and other things that need symbol table
4398 access. */
4400 bool
4401 _bfd_XXi_final_link_postscript (bfd * abfd, struct coff_final_link_info *pfinfo)
4403 struct coff_link_hash_entry *h1;
4404 struct bfd_link_info *info = pfinfo->info;
4405 bool result = true;
4407 /* There are a few fields that need to be filled in now while we
4408 have symbol table access.
4410 The .idata subsections aren't directly available as sections, but
4411 they are in the symbol table, so get them from there. */
4413 /* The import directory. This is the address of .idata$2, with size
4414 of .idata$2 + .idata$3. */
4415 h1 = coff_link_hash_lookup (coff_hash_table (info),
4416 ".idata$2", false, false, true);
4417 if (h1 != NULL)
4419 /* PR ld/2729: We cannot rely upon all the output sections having been
4420 created properly, so check before referencing them. Issue a warning
4421 message for any sections tht could not be found. */
4422 if ((h1->root.type == bfd_link_hash_defined
4423 || h1->root.type == bfd_link_hash_defweak)
4424 && h1->root.u.def.section != NULL
4425 && h1->root.u.def.section->output_section != NULL)
4426 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress =
4427 (h1->root.u.def.value
4428 + h1->root.u.def.section->output_section->vma
4429 + h1->root.u.def.section->output_offset);
4430 else
4432 _bfd_error_handler
4433 (_("%pB: unable to fill in DataDictionary[1] because .idata$2 is missing"),
4434 abfd);
4435 result = false;
4438 h1 = coff_link_hash_lookup (coff_hash_table (info),
4439 ".idata$4", false, false, true);
4440 if (h1 != NULL
4441 && (h1->root.type == bfd_link_hash_defined
4442 || h1->root.type == bfd_link_hash_defweak)
4443 && h1->root.u.def.section != NULL
4444 && h1->root.u.def.section->output_section != NULL)
4445 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].Size =
4446 ((h1->root.u.def.value
4447 + h1->root.u.def.section->output_section->vma
4448 + h1->root.u.def.section->output_offset)
4449 - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress);
4450 else
4452 _bfd_error_handler
4453 (_("%pB: unable to fill in DataDictionary[1] because .idata$4 is missing"),
4454 abfd);
4455 result = false;
4458 /* The import address table. This is the size/address of
4459 .idata$5. */
4460 h1 = coff_link_hash_lookup (coff_hash_table (info),
4461 ".idata$5", false, false, true);
4462 if (h1 != NULL
4463 && (h1->root.type == bfd_link_hash_defined
4464 || h1->root.type == bfd_link_hash_defweak)
4465 && h1->root.u.def.section != NULL
4466 && h1->root.u.def.section->output_section != NULL)
4467 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
4468 (h1->root.u.def.value
4469 + h1->root.u.def.section->output_section->vma
4470 + h1->root.u.def.section->output_offset);
4471 else
4473 _bfd_error_handler
4474 (_("%pB: unable to fill in DataDictionary[12] because .idata$5 is missing"),
4475 abfd);
4476 result = false;
4479 h1 = coff_link_hash_lookup (coff_hash_table (info),
4480 ".idata$6", false, false, true);
4481 if (h1 != NULL
4482 && (h1->root.type == bfd_link_hash_defined
4483 || h1->root.type == bfd_link_hash_defweak)
4484 && h1->root.u.def.section != NULL
4485 && h1->root.u.def.section->output_section != NULL)
4486 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
4487 ((h1->root.u.def.value
4488 + h1->root.u.def.section->output_section->vma
4489 + h1->root.u.def.section->output_offset)
4490 - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress);
4491 else
4493 _bfd_error_handler
4494 (_("%pB: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE (12)] because .idata$6 is missing"),
4495 abfd);
4496 result = false;
4499 else
4501 h1 = coff_link_hash_lookup (coff_hash_table (info),
4502 "__IAT_start__", false, false, true);
4503 if (h1 != NULL
4504 && (h1->root.type == bfd_link_hash_defined
4505 || h1->root.type == bfd_link_hash_defweak)
4506 && h1->root.u.def.section != NULL
4507 && h1->root.u.def.section->output_section != NULL)
4509 bfd_vma iat_va;
4511 iat_va =
4512 (h1->root.u.def.value
4513 + h1->root.u.def.section->output_section->vma
4514 + h1->root.u.def.section->output_offset);
4516 h1 = coff_link_hash_lookup (coff_hash_table (info),
4517 "__IAT_end__", false, false, true);
4518 if (h1 != NULL
4519 && (h1->root.type == bfd_link_hash_defined
4520 || h1->root.type == bfd_link_hash_defweak)
4521 && h1->root.u.def.section != NULL
4522 && h1->root.u.def.section->output_section != NULL)
4524 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
4525 ((h1->root.u.def.value
4526 + h1->root.u.def.section->output_section->vma
4527 + h1->root.u.def.section->output_offset)
4528 - iat_va);
4529 if (pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size != 0)
4530 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
4531 iat_va - pe_data (abfd)->pe_opthdr.ImageBase;
4533 else
4535 _bfd_error_handler
4536 (_("%pB: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE(12)]"
4537 " because .idata$6 is missing"), abfd);
4538 result = false;
4543 h1 = coff_link_hash_lookup (coff_hash_table (info),
4544 (bfd_get_symbol_leading_char (abfd) != 0
4545 ? "__tls_used" : "_tls_used"),
4546 false, false, true);
4547 if (h1 != NULL)
4549 if ((h1->root.type == bfd_link_hash_defined
4550 || h1->root.type == bfd_link_hash_defweak)
4551 && h1->root.u.def.section != NULL
4552 && h1->root.u.def.section->output_section != NULL)
4553 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].VirtualAddress =
4554 (h1->root.u.def.value
4555 + h1->root.u.def.section->output_section->vma
4556 + h1->root.u.def.section->output_offset
4557 - pe_data (abfd)->pe_opthdr.ImageBase);
4558 else
4560 _bfd_error_handler
4561 (_("%pB: unable to fill in DataDictionary[9] because __tls_used is missing"),
4562 abfd);
4563 result = false;
4565 /* According to PECOFF sepcifications by Microsoft version 8.2
4566 the TLS data directory consists of 4 pointers, followed
4567 by two 4-byte integer. This implies that the total size
4568 is different for 32-bit and 64-bit executables. */
4569 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64) && !defined (COFF_WITH_peRiscV64)
4570 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x18;
4571 #else
4572 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x28;
4573 #endif
4576 /* If there is a .pdata section and we have linked pdata finally, we
4577 need to sort the entries ascending. */
4578 #if !defined(COFF_WITH_pep) && (defined(COFF_WITH_pex64) || defined(COFF_WITH_peAArch64) || defined(COFF_WITH_peLoongArch64) || defined (COFF_WITH_peRiscV64))
4580 asection *sec = bfd_get_section_by_name (abfd, ".pdata");
4582 if (sec)
4584 bfd_size_type x = sec->rawsize;
4585 bfd_byte *tmp_data;
4587 if (bfd_malloc_and_get_section (abfd, sec, &tmp_data))
4589 qsort (tmp_data,
4590 (size_t) (x / 12),
4591 12, sort_x64_pdata);
4592 bfd_set_section_contents (pfinfo->output_bfd, sec,
4593 tmp_data, 0, x);
4594 free (tmp_data);
4596 else
4597 result = false;
4600 #endif
4602 rsrc_process_section (abfd, pfinfo);
4604 /* If we couldn't find idata$2, we either have an excessively
4605 trivial program or are in DEEP trouble; we have to assume trivial
4606 program.... */
4607 return result;